private static bool RecoursiveCheckGraph(Task root, ImmutableList<Guid> previousTasks) { Contract.Requires(root != null); Contract.Requires(root.Inputs != null); Contract.Requires(previousTasks != null); if (previousTasks.Contains(root.Id)) { Logger.Write( LogCategories.Error(string.Format( "{0} is cycled.", root), LogCategories.TaskServices)); return false; } foreach (var task in root.Inputs) { if (previousTasks.Contains(task.Id)) { Logger.Write( LogCategories.Error(string.Format( "{0} is cycled.", task), LogCategories.TaskServices)); return false; } if (!RecoursiveCheckGraph(task, previousTasks.Add(root.Id))) return false; } return true; }
public void ImmutableListAndObject() { var list = new ImmutableList<ImmutableObject>(); list.Add(new ImmutableObject(1)).Add(new ImmutableObject(2)); Assert.Equal(2, list.Count); list[0].CalculateDummyValue(); Assert.Equal(1, list[0].CallCount); }
public void Add_ReturnsNewListWithNewItemAppended() { var subject = new ImmutableList<int>(); var result = subject.Add(12); Assert.AreEqual(0, subject.Count); Assert.AreEqual(1, result.Count); }
/// <summary> /// Registers a <see cref="ITagAdapter"/> implemented adapter with the host. /// </summary> public void RegisterAdapter(Func <IAdapterHost, ITagAdapter> loadAdapter) { var adapter = loadAdapter.Invoke(this); if (adapter == null) { return; } _adapters = _adapters.Add(adapter); }
public static ImmutableList <T> UpsertWhere <T>(this ImmutableList <T> source, Func <T, bool> predicate, T item) { var index = source.IndexOf(predicate); if (index < 0) { return(source.Add(item)); } return(source.SetItem(index, item)); }
private ManualSolverModel ToggleHighlighted(int index) { if (SelectedSegmentIndices.Contains(index)) { return(With(Segments, HighlightedSegmentIndex, SelectedSegmentIndices.Remove(index), PendingOperationType.None, mirrors)); } else { return(With(Segments, HighlightedSegmentIndex, SelectedSegmentIndices.Add(index), PendingOperationType.None, mirrors)); } }
public CH_Polygon Flip() { int iEnd = vertices.Count; ImmutableList <Vertex3> v2 = ImmutableList <Vertex3> .Empty; for (int i = 0; i < iEnd; ++i) { v2 = v2.Add(vertices[iEnd - i - 1]); } return(new CH_Polygon(v2)); }
/// <summary> /// Converts the children of a node into a string representation /// </summary> /// <param name="lastChild">Whether or not the node is the last child at each parent level of the tree</param> /// <param name="children">The children of the node</param> /// <returns>A string representation of the children of a node</returns> private static string ChildrenToString(ImmutableList <bool> lastChild, IAbstractSyntaxTreeNode[] children) { StringBuilder sb = new StringBuilder(); int numChildren = children.Length; for (int i = 0; i < numChildren; i++) { sb.Append(ToString(lastChild.Add(i == numChildren - 1), children[i])); } return(sb.ToString()); }
public IDisposable Subscribe(IObserver <T> observer) { lock (subscriberListMutex) { Observers = Observers.Add(observer); } return(Disposable.Create(() => { lock (subscriberListMutex) { Observers = Observers.Remove(observer); } })); }
private Task PushHandler(IContextualProvider <THandler> handlerFactory) { _handlerStack = _handlerStack.Add(handlerFactory); if (handlerFactory is IActivationNotifyable notifyable) { return(notifyable.NotifyActivationAsync()); } return(Task.CompletedTask); }
public ServerEnterPacketHandler() : base() { ImmutableList <IPEndPoint> .Builder builder = ImmutableList.CreateBuilder <IPEndPoint>(); string ipAddress = Environment.GetEnvironmentVariable("IP"); int port = int.Parse(Environment.GetEnvironmentVariable("LOGIN_PORT")); builder.Add(new IPEndPoint(IPAddress.Parse(ipAddress), port)); ServerIPs = builder.ToImmutable(); ServerName = Environment.GetEnvironmentVariable("NAME"); }
/// <summary> /// Adds provider. Composite metamodel will be built in that order, in which providers were added /// </summary> public CompositeMetamodelProvider AddProvider(IMetamodelProvider provider) { if (provider == null) { throw new ArgumentNullException(nameof(provider)); } _builders = _builders.Add(provider); return(this); }
//TODO: account for Member.MemberId public void AddMember(Member member) { // Avoid adding the same member twice if (_members.Any(x => x.Address == member.Address)) { return; } _members = _members.Add(member); _rdv.UpdateMembers(_members); }
public void AddInstruction(InterInst inst) { Instructions = Instructions.Add(inst); inst.SetOwner(this); if (!LabelManager.LabelNext) { return; } inst.Label = LabelManager.NextLabel; }
public RoleName Role(string name) { if (_roles.Exists(r => r.Name == name)) { throw new ArgumentException("non-unique role name " + name); } var roleName = new RoleName(name); _roles = _roles.Add(roleName); return(roleName); }
private void CollectObjectInstances(ImmutableObject obj, ImmutableList <ImmutableObject> .Builder result) { if (!(obj is MetaRootNamespace)) { result.Add(obj); } foreach (var child in obj.MChildren) { this.CollectObjectInstances(child, result); } }
public void Add(IContact contactToAdd) { var info = new ContactDB.UpdateInfo() { _contacts = new[] { contactToAdd }, _reason = ContactDB.UpdateReason.Add }; _sender.OnNext(info); _mylist = _mylist.Add(contactToAdd); }
public static async Task <IEnumerable <IEntityValue> > CreateUIPropertyValueValuesAsync( IQueryExecutionContext queryExecutionContext, IEntityValue parent, IProjectState cache, Rule schema, QueryProjectPropertiesContext propertiesContext, string propertyName, IUIPropertyValuePropertiesAvailableStatus requestedProperties) { BaseProperty?unboundProperty = schema.GetProperty(propertyName); if (unboundProperty is null) { return(ImmutableList <IEntityValue> .Empty); } ImmutableList <IEntityValue> .Builder builder = ImmutableList.CreateBuilder <IEntityValue>(); IEnumerable <ProjectConfiguration> configurations; if (unboundProperty.IsConfigurationDependent()) { // Return the values across all configurations. configurations = await cache.GetKnownConfigurationsAsync() ?? Enumerable.Empty <ProjectConfiguration>(); } else { // Return the value from any one configuration. if (await cache.GetSuggestedConfigurationAsync() is ProjectConfiguration defaultConfiguration) { configurations = CreateSingleItemEnumerable(defaultConfiguration); } else { configurations = Enumerable.Empty <ProjectConfiguration>(); } } foreach (ProjectConfiguration configuration in configurations) { (string versionKey, long versionNumber) = await cache.GetConfiguredProjectVersionAsync(configuration); queryExecutionContext.ReportInputDataVersion(versionKey, versionNumber); if (await cache.BindToRule(configuration, schema.Name, propertiesContext) is IRule rule && rule.GetProperty(propertyName) is ProjectSystem.Properties.IProperty property) { IEntityValue propertyValue = await CreateUIPropertyValueValueAsync(parent, configuration, property, requestedProperties); builder.Add(propertyValue); } } return(builder.ToImmutable());
public void ImmutableList_RemoveAfterAdd() { var items = new[] { 1, 2, 3, 1, 2, 3 }; var sut = new ImmutableList <int>(items); var result = sut.Add(12).Remove(12); sut.Should().BeEquivalentTo(new[] { 1, 2, 3, 1, 2, 3 }); result.Should().BeEquivalentTo(new[] { 1, 2, 3, 1, 2, 3 }); result.Should().NotBeSameAs(sut); }
private Reachability Change(UniqueAddress observer, UniqueAddress subject, ReachabilityStatus status) { var v = NextVersion(observer); var newVersions = _versions.SetItem(observer, v); var newRecord = new Record(observer, subject, status, v); var oldObserverRows = ObserverRows(observer); if (oldObserverRows == null && status == ReachabilityStatus.Reachable) { return(this); } if (oldObserverRows == null) { return(new Reachability(_records.Add(newRecord), newVersions)); } if (!oldObserverRows.TryGetValue(subject, out var oldRecord)) { if (status == ReachabilityStatus.Reachable && oldObserverRows.Values.All(r => r.Status == ReachabilityStatus.Reachable)) { return(new Reachability(_records.FindAll(r => !r.Observer.Equals(observer)), newVersions)); } return(new Reachability(_records.Add(newRecord), newVersions)); } if (oldRecord.Status == ReachabilityStatus.Terminated || oldRecord.Status == status) { return(this); } if (status == ReachabilityStatus.Reachable && oldObserverRows.Values.All(r => r.Status == ReachabilityStatus.Reachable || r.Subject.Equals(subject))) { return(new Reachability(_records.FindAll(r => !r.Observer.Equals(observer)), newVersions)); } var newRecords = _records.SetItem(_records.IndexOf(oldRecord), newRecord); return(new Reachability(newRecords, newVersions)); }
protected void CleanEntities() { while (_toRemove.Count > 0) { Entities = Entities.Remove(_toRemove.Pop()); } while (_toAdd.Count > 0) { Entities = Entities.Add(_toAdd.Pop()); } }
private static void AddMemberAndAttributes(ImmutableList <SyntaxNode> .Builder elements, SyntaxNode member) { switch (member.Kind()) { case SyntaxKind.ClassDeclaration: case SyntaxKind.StructDeclaration: case SyntaxKind.InterfaceDeclaration: case SyntaxKind.EnumDeclaration: case SyntaxKindEx.RecordDeclaration: elements.AddRange(((BaseTypeDeclarationSyntax)member).AttributeLists); break; case SyntaxKind.FieldDeclaration: case SyntaxKind.EventFieldDeclaration: elements.AddRange(((BaseFieldDeclarationSyntax)member).AttributeLists); break; case SyntaxKind.PropertyDeclaration: case SyntaxKind.EventDeclaration: case SyntaxKind.IndexerDeclaration: elements.AddRange(((BasePropertyDeclarationSyntax)member).AttributeLists); break; case SyntaxKind.MethodDeclaration: case SyntaxKind.ConstructorDeclaration: case SyntaxKind.DestructorDeclaration: case SyntaxKind.OperatorDeclaration: case SyntaxKind.ConversionOperatorDeclaration: elements.AddRange(((BaseMethodDeclarationSyntax)member).AttributeLists); break; case SyntaxKind.GetAccessorDeclaration: case SyntaxKind.SetAccessorDeclaration: case SyntaxKind.AddAccessorDeclaration: case SyntaxKind.RemoveAccessorDeclaration: case SyntaxKind.UnknownAccessorDeclaration: elements.AddRange(((AccessorDeclarationSyntax)member).AttributeLists); break; case SyntaxKind.TypeParameter: elements.AddRange(((TypeParameterSyntax)member).AttributeLists); break; case SyntaxKind.Parameter: elements.AddRange(((ParameterSyntax)member).AttributeLists); break; default: break; } elements.Add(member); }
public override Shopping Arrange(object evt) { switch (evt) { default: return(this); case ProductChosen e: return(new Shopping( _products.Add(e.ProductId) )); } }
public static Document GetDocument(string code, string languageName, ImmutableList <MetadataReference> references = null) { references = references ?? ImmutableList <MetadataReference> .Empty; references = references .Add(References.Core) .Add(References.Linq); return(new AdhocWorkspace() .AddProject("TestProject", languageName) .AddMetadataReferences(references) .AddDocument("TestDocument", code)); }
/// <summary> /// Link the copied data stream to another block /// </summary> private void LinkCopyTo(IDataflow <T> other) { //first, create a new copy block Dataflow <T, T> copyBuffer = new BufferBlock <T>(m_dataflowOptions.ToGroupingBlockOption()).ToDataflow(m_dataflowOptions); RegisterChild(copyBuffer); copyBuffer.RegisterDependency(m_transformBlock); m_copyBuffers = m_copyBuffers.Add(copyBuffer); copyBuffer.Name = "Buffer" + m_copyBuffers.Count; copyBuffer.LinkTo(other); }
public (Game game, Turn turn) Turn(User user, int cell, int number) { var isSkipped = Field[cell] != null; var field = this.Field.SetItem(cell, number); isSkipped |= !Check(field); var turn = new Domains.Turn(Turns.Count, user, cell, number, DateTime.UtcNow, isSkipped); var game = this.With(turns: Turns.Add(turn)); return(isSkipped ? game : game.With(field: field), turn); }
public FactGraph Add(Fact fact) { if (factsByReference.ContainsKey(fact.Reference)) { return(this); } return(new FactGraph( factsByReference.Add(fact.Reference, fact), topologicalOrder.Add(fact.Reference) )); }
public static ImmutableList <Symbol> WithoutDuplicates(this ImmutableList <Symbol> steps) { return(steps.Count <= 1 ? steps : steps.Skip(1).Aggregate( (Steps: ImmutableList <Symbol> .Empty.Add(steps.First()), steps.First()), (tuple, symbol) => { var(steps, last) = tuple; return (symbol.Equals(last) ? steps : steps.Add(symbol), symbol); } ).Steps); }
public void RemoveTest() { ImmutableList <int> list = ImmutableList <int> .Empty; for (int i = 1; i <= 10; i++) { list = list.Add(i * 10); } list = list.Remove(30); Assert.Equal(9, list.Count); Assert.False(list.Contains(30)); list = list.Remove(100); Assert.Equal(8, list.Count); Assert.False(list.Contains(100)); list = list.Remove(10); Assert.Equal(7, list.Count); Assert.False(list.Contains(10)); var removeList = new int[] { 20, 70 }; list = list.RemoveAll(removeList.Contains); Assert.Equal(5, list.Count); Assert.False(list.Contains(20)); Assert.False(list.Contains(70)); IImmutableList <int> list2 = ImmutableList <int> .Empty; for (int i = 1; i <= 10; i++) { list2 = list2.Add(i * 10); } list2 = list2.Remove(30); Assert.Equal(9, list2.Count); Assert.False(list2.Contains(30)); list2 = list2.Remove(100); Assert.Equal(8, list2.Count); Assert.False(list2.Contains(100)); list2 = list2.Remove(10); Assert.Equal(7, list2.Count); Assert.False(list2.Contains(10)); list2 = list2.RemoveAll(removeList.Contains); Assert.Equal(5, list2.Count); Assert.False(list2.Contains(20)); Assert.False(list2.Contains(70)); }
public ImmutableList <I> GetMatchedItems(ImmutableHashSet <string> globsToIgnore) { ImmutableList <I> .Builder items = ImmutableList.CreateBuilder <I>(); foreach (ItemData data in GetItemData(globsToIgnore)) { if (data.ConditionResult) { items.Add(data.Item); } } return(items.ToImmutable()); }
public void Register(ChangeTypeFactory converterFactory) { if (converterFactory == null) { throw new ArgumentNullException(nameof(converterFactory)); } lock (_sync) { _converterFactories = _converterFactories.Add(converterFactory); _hasFactories = true; } }
public HandshakeData(JObject data) { var upgrades = data.GetValue("upgrades"); foreach (var e in upgrades) { Upgrades = Upgrades.Add(e.ToString()); } Sid = data.GetValue("sid").Value <string>(); PingInterval = data.GetValue("pingInterval").Value <long>(); PingTimeout = data.GetValue("pingTimeout").Value <long>(); }
public void Add_1() { //Arrange var list = ImmutableList.Create(3, 5, 1, 85); //Act ImmutableList <int> .Builder builder = list.ToBuilder(); builder.Add(100); //Assert CollectionAssert.Contents(list, "Original list", 3, 5, 1, 85); CollectionAssert.Contents(builder, "Resulting list", 3, 5, 1, 85, 100); }
private static bool RecoursiveCheckGraph(TaskRequest root, ImmutableList<Guid> previousTasks) { if (previousTasks.Contains(root.Id)) return false; foreach (var task in root.Dependencies) { if (previousTasks.Contains(task.Id)) return false; if (!RecoursiveCheckGraph(task, previousTasks.Add(root.Id))) return false; } return true; }
private static bool RecoursiveCheckGraph(Japi.Task root, ImmutableList<Japi.Task> previousTasks) { if(previousTasks.Contains(root)) { Console.WriteLine("1: {0}", root); return false; } foreach(var task in root.Dependencies) { if(previousTasks.Contains(task)) { Console.WriteLine("2: {0}", root); return false; } if(!RecoursiveCheckGraph(task, previousTasks.Add(root))) return false; } return true; }
static ReferenceFinders() { DefaultRenameReferenceFinders = ImmutableList.Create( Constructor, Destructor, Event, ExplicitInterfaceMethod, Field, Label, Local, MethodTypeParameter, NamedType, Namespace, Operator, OrdinaryMethod, Parameter, Property, PropertyAccessor, RangeVariable, TypeParameter); DefaultReferenceFinders = DefaultRenameReferenceFinders.Add(ConstructorInitializer); }
private IProperty VerifyRootPrincipal( IProperty principalProperty, Dictionary<IProperty, IProperty> verifiedProperties, ImmutableList<IForeignKey> visitedForeignKeys, out string errorMessage) { errorMessage = null; IProperty rootPrincipal; if (verifiedProperties.TryGetValue(principalProperty, out rootPrincipal)) { return rootPrincipal; } var rootPrincipals = new Dictionary<IProperty, IForeignKey>(); foreach (var foreignKey in principalProperty.DeclaringEntityType.GetForeignKeys()) { for (var index = 0; index < foreignKey.Properties.Count; index++) { if (principalProperty == foreignKey.Properties[index]) { var nextPrincipalProperty = foreignKey.PrincipalKey.Properties[index]; if (visitedForeignKeys.Contains(foreignKey)) { var cycleStart = visitedForeignKeys.IndexOf(foreignKey); var cycle = visitedForeignKeys.GetRange(cycleStart, visitedForeignKeys.Count - cycleStart); errorMessage = Strings.CircularDependency(cycle.Select(fk => fk.ToString()).Join()); continue; } rootPrincipal = VerifyRootPrincipal(nextPrincipalProperty, verifiedProperties, visitedForeignKeys.Add(foreignKey), out errorMessage); if (rootPrincipal == null) { if (principalProperty.RequiresValueGenerator) { rootPrincipals[principalProperty] = foreignKey; } continue; } if (principalProperty.RequiresValueGenerator) { ShowError(Strings.ForeignKeyValueGenerationOnAdd( principalProperty.Name, principalProperty.DeclaringEntityType.DisplayName(), Property.Format(foreignKey.Properties))); return principalProperty; } rootPrincipals[rootPrincipal] = foreignKey; } } } if (rootPrincipals.Count == 0) { if (errorMessage != null) { return null; } if (!principalProperty.RequiresValueGenerator) { ShowError(Strings.PrincipalKeyNoValueGenerationOnAdd(principalProperty.Name, principalProperty.DeclaringEntityType.DisplayName())); return null; } return principalProperty; } if (rootPrincipals.Count > 1) { var firstRoot = rootPrincipals.Keys.ElementAt(0); var secondRoot = rootPrincipals.Keys.ElementAt(1); ShowWarning(Strings.MultipleRootPrincipals( rootPrincipals[firstRoot].DeclaringEntityType.DisplayName(), Property.Format(rootPrincipals[firstRoot].Properties), firstRoot.DeclaringEntityType.DisplayName(), firstRoot.Name, Property.Format(rootPrincipals[secondRoot].Properties), secondRoot.DeclaringEntityType.DisplayName(), secondRoot.Name)); return firstRoot; } errorMessage = null; rootPrincipal = rootPrincipals.Keys.Single(); verifiedProperties[principalProperty] = rootPrincipal; return rootPrincipal; }
//TODO with the rollback information that's now being stored, rollback could be down without needing the block public void RollbackUtxo(IChainStateCursor chainStateCursor, Chain chain, ChainedHeader chainedHeader, IEnumerable<BlockTx> blockTxes, ImmutableList<UnmintedTx>.Builder unmintedTxes) { //TODO don't reverse here, storage should be read in reverse foreach (var blockTx in blockTxes.Reverse()) { var tx = blockTx.Decode().Transaction; var txIndex = blockTx.Index; // remove transaction's outputs from utxo, except for the genesis block and the duplicate coinbases var isDupeCoinbase = IsDupeCoinbase(chainedHeader, tx); if (chainedHeader.Height > 0 && !isDupeCoinbase) { this.Unmint(chainStateCursor, tx, chainedHeader); // decrease unspent output count chainStateCursor.UnspentOutputCount -= tx.Outputs.Length; // decrement unspent tx count chainStateCursor.UnspentTxCount--; chainStateCursor.TotalTxCount--; chainStateCursor.TotalInputCount -= tx.Inputs.Length; chainStateCursor.TotalOutputCount -= tx.Outputs.Length; } var prevTxOutputs = ImmutableArray.CreateBuilder<PrevTxOutput>(!tx.IsCoinbase ? tx.Inputs.Length : 0); if (!tx.IsCoinbase) { // remove inputs in reverse order for (var inputIndex = tx.Inputs.Length - 1; inputIndex >= 0; inputIndex--) { var input = tx.Inputs[inputIndex]; var prevTxOutput = this.Unspend(chainStateCursor, input, chainedHeader); // store rollback replay information prevTxOutputs.Add(prevTxOutput); } } // reverse output keys to match original input order, as the inputs were read in reverse here prevTxOutputs.Reverse(); // store rollback replay information unmintedTxes.Add(new UnmintedTx(tx.Hash, prevTxOutputs.MoveToImmutable())); } }
public GuildBank(Guild guild, bool isNew) { Guild = guild; BankTabs = new ImmutableList<GuildBankTab>(5); if (isNew) { var tab = new GuildBankTab(this) { BankSlot = 0, Icon = "", Name = "Slot 0", Text = "" }; BankTabs.Add(tab); } else { var tabs = GuildBankTab.FindAllByProperty("_guildId", (int) guild.Id); foreach (var tab in tabs) { BankTabs.Add(tab); } } }
public override ImmutableList<char> FreeVariableNames(ImmutableList<Symbol> boundVariables) { return _body.FreeVariableNames(boundVariables.Add(_variable)); }