System.Collections.Generic.List.Exists(System.Predicate)

Here are the examples of the csharp api System.Collections.Generic.List.Exists(System.Predicate) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

725 Examples 7

19 View Source File : FactoriesManager.cs
License : MIT License
Project Creator : Analogy-LogViewer

public replacedembly GetreplacedemblyOfFactory(IreplacedogyFactory factory)
            => BuiltInFactories.Exists(f => f.Factory == factory)
                ? BuiltInFactories.First(f => f.Factory == factory).replacedembly
                : Factories.Single(f => f.Factory == factory).replacedembly;

19 View Source File : ControllerConnectionHandler.cs
License : MIT License
Project Creator : aornelas

private void HandleOnControllerConnected(byte controllerId)
        {
            MLInputController newController = MLInput.GetController(controllerId);
            if (IsDeviceAllowed(newController))
            {
                if(_allowedConnectedDevices.Exists((device) => device.Id == controllerId))
                {
                    Debug.LogWarning(string.Format("Connected controller with id {0} already connected.", controllerId));
                    return;
                }

                _allowedConnectedDevices.Add(newController);
            }
        }

19 View Source File : Creature.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public void Gereplacedem(Point itemPos)
        {
            Block[] blocks = currentFloor >= 0 ? Program.WorldMap[worldIndex.X, worldIndex.Y].Dungeon.Floors[currentFloor].Blocks : Program.WorldMap[worldIndex.X, worldIndex.Y].Blocks;
            int width = Program.WorldMap.TileWidth;
            bool itemAdded = false;
            string itemName = "";
            string containerName = "inventory";

            if (blocks[itemPos.X * width + itemPos.Y] is Item item) {
                // handle various cases of items which must be managed uniquely
                itemName = item.Name;
                if (item is Arrow && inventory.Exists(i => i is Quiver)) {
                    Quiver q = (Quiver)inventory.Find(i => i is Quiver);
                    if (q.Arrows.Count <= 20) {
                        q.Arrows.Add(item);
                        itemAdded = true;
                        containerName = q.Name;
                    }
                }
                else if (item is Quiver q1 && inventory.Exists(i => i is Quiver)) {
                    Quiver q2 = (Quiver)inventory.Find(i => i is Quiver);
                    foreach (Arrow a in q1.Arrows) {
                        if (q2.Arrows.Count <= 20)
                            q2.Arrows.Add(a);
                        else inventory.Add(a);
                    }
                    itemAdded = true;
                    itemName += "'s arrows";
                    containerName = q2.Name;
                }
                else if (item is Blueprint && inventory.Exists(i => i is BlueprintPouch)) {
                    BlueprintPouch bp = (BlueprintPouch)inventory.Find(i => i is BlueprintPouch);
                    bp.Blueprints.Add(item);
                    itemAdded = true;
                    containerName = bp.Name;
                }
                else if (item is CraftingRecipe && inventory.Exists(i => i is RecipePouch))
                {
                    RecipePouch rp = (RecipePouch)inventory.Find(i => i is RecipePouch);
                    rp.Recipes.Add(item);
                    itemAdded = true;
                    containerName = rp.Name;
                }
                // normal case
                if (!itemAdded) itemAdded = AddItem(item);

                // apply action cost, update map, write to msg console
                if (itemAdded) {
                    Block replacementBlock = item.BlockPlacedOn ?? new Air();
                    blocks[itemPos.X * width + itemPos.Y] = replacementBlock;
                    if (currentFloor == Program.Player.CurrentFloor && worldIndex.Equals(Program.Player.WorldIndex))
                        Program.WorldMap[worldIndex.X, worldIndex.Y].DijkstraMaps.CallItemPosChanged(this);
                    if (this.Visible)
                        Program.MsgConsole.WriteLine($"{Name} put the {itemName} in their {containerName}.");
                    ApplyActionCost(6);
                }
                else if (this.Visible)
                    Program.MsgConsole.WriteLine($"{Name} tried to get the {itemName} but didn't have enough space.");
            }
        }

19 View Source File : TemplateInterpData.cs
License : MIT License
Project Creator : alexismorin

public bool HasRawInterpolatorOfName( string name )
		{
			return RawInterpolators.Exists( ( x ) => x.VarName.Equals( name ));
		}

19 View Source File : StringExtension.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static IEnumerable<string> Except(this IEnumerable<string> first, IEnumerable<string> second, bool ignoreCase)
		{
			if (first == null)
				throw new ArgumentNullException("first");
			if (second == null)
				throw new ArgumentNullException("second");

			var list = new List<string>(second);
			foreach (var elem in first)
			{
				bool skip;
				if (ignoreCase)
					skip = list.Exists(s => string.Equals(s, elem, StringComparison.OrdinalIgnoreCase));
				else
					skip = list.Contains(elem);

				if (!skip)
					yield return elem;
			}
		}

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private void Input_ButtonPressed(object sender, StardewModdingAPI.Events.ButtonPressedEventArgs e)
        {
            if (!Config.Enabled || !Context.IsWorldReady)
                return;

            Dictionary<string, string> npcDic;
            List<string> npcKeys;

            // check for click on dialogue

            if (Game1.activeClickableMenu != null && Game1.player?.currentLocation?.lastQuestionKey?.StartsWith("DialogueTrees_") == true)
            {
                IClickableMenu menu = Game1.activeClickableMenu;
                if (menu == null || menu.GetType() != typeof(DialogueBox))
                    return;

                DialogueBox db = menu as DialogueBox;
                int resp = db.selectedResponse;
                List<Response> resps = db.responses;

                if (resp < 0 || resps == null || resp >= resps.Count || resps[resp] == null)
                    return;

                string[] parts = resps[resp].responseKey.Split('#');
                string npcName = parts[1];
                string topicID = parts[2];
                string responseID = parts[3];
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npcName}", ContentSource.GameContent);
                npcKeys = npcDic.Keys.ToList();

                if (Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_Player_Question")
                {
                    Monitor.Log($"asking {npcName} about {loadedTopicNames[topicID]}");
                    var possibleResponses = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_response_" + topicID + "_"));
                    NPC n = Game1.getCharacterFromName(npcName);
                    Game1.drawDialogue(n, npcDic[possibleResponses[myRand.Next(possibleResponses.Count)]]);

                    string nextTopicID = GetNextTopicID(topicID, "any");

                    if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID) && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + nextTopicID + "_")))
                    {
                        if (responseData != null)
                        {
                            responseData.lastTopic = loadedDialogues[topicID];
                            responseData.nextTopic = loadedDialogues[nextTopicID];
                            responseData.npc = n;
                            responseData.topicResponses[topicID] = responseID;
                        }
                        else
                            responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                    }
                }
                else if(Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_NPC_Question")
                {
                    Monitor.Log($"{npcName} is asking player about {loadedTopicNames[topicID]}, player response: {loadedResponseStrings[responseID]}");

                    var possibleReactions = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_reaction_" + topicID + "_" + responseID + "_"));

                    if (!possibleReactions.Any())
                    {
                        Monitor.Log($"{npcName} has no reaction to {loadedTopicNames[topicID]} response {loadedResponseStrings[responseID]}! Check the [DT] content pack.", LogLevel.Warn);
                    }
                    else
                    {
                        NPC n = Game1.getCharacterFromName(npcName);
                        Game1.drawDialogue(n, npcDic[possibleReactions[myRand.Next(possibleReactions.Count)]]);
                        if (npcDic.ContainsKey("DialogueTrees_friendship_" + topicID + "_" + responseID) && int.TryParse(npcDic["DialogueTrees_friendship_" + topicID + "_" + responseID], out int amount))
                        {
                            Monitor.Log($"changing friendship with {n.Name} by {amount}");
                            Game1.player.changeFriendship(amount, n);
                        }

                        string nextTopicID = GetNextTopicID(topicID, responseID);

                        if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID))
                        {
                            Monitor.Log($"Preparing followup dialogue {nextTopicID}");
                            if (responseData != null)
                            {
                                Monitor.Log($"Adding to existing responseData");

                                responseData.lastTopic = loadedDialogues[topicID];
                                responseData.nextTopic = loadedDialogues[nextTopicID];
                                responseData.npc = n;
                                responseData.topicResponses[topicID] = responseID;
                            }
                            else
                                responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                        }
                        else
                        {
                            if(responseData != null)
                                Monitor.Log("No next topic, erasing response data");
                            responseData = null;
                        }
                    }
                }
                
                Game1.player.currentLocation.lastQuestionKey = "";
                return;
            }

            // check for click on NPC

            if (Game1.activeClickableMenu != null || !Context.CanPlayerMove || (Config.ModButton != SButton.None && !Helper.Input.IsDown(Config.ModButton)) || (e.Button != Config.AskButton && e.Button != Config.AnswerButton))
                return;

            Monitor.Log($"Pressed modkey + {e.Button}");

            Rectangle tileRect = new Rectangle((int)Game1.currentCursorTile.X * 64, (int)Game1.currentCursorTile.Y * 64, 64, 64);

            NPC npc = null;

            foreach (NPC i in Game1.currentLocation.characters)
            {
                if (i != null && !i.IsMonster && (!Game1.player.isRidingHorse() || !(i is Horse)) && i.GetBoundingBox().Intersects(tileRect) && !i.IsInvisible && !i.checkAction(Game1.player, Game1.currentLocation))
                {
                    npc = i;
                    break;
                }
            }

            if (npc == null)
                return;
            try
            {
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npc.Name}", ContentSource.GameContent);

            }
            catch
            {
                Monitor.Log($"No dialogue file for {npc.Name}", LogLevel.Warn);

                return;
            }
            npcKeys = npcDic.Keys.ToList();

            if (e.Button == Config.AskButton)
            {

                Monitor.Log($"Asking question of {npc.Name}");

                var shuffled = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && d.playerCanAsk && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + d.topicID+"_")));

                if(!shuffled.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} has a response to! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }
                Monitor.Log($"{shuffled.Count} questions that {npc.Name} has a response to.");

                ShuffleList(shuffled);
                var questions = shuffled.Take(Config.MaxPlayerQuestions);
                List<Response> responses = new List<Response>();
                foreach(var q in questions)
                {
                    Monitor.Log(q.topicID);
                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{q.topicID}", string.Format(loadedQuestionStrings[q.questionIDs[myRand.Next(q.questionIDs.Count)]], loadedTopicNames[q.topicID])));
                }

                Game1.player.currentLocation.createQuestionDialogue(string.Format(Helper.Translation.Get("ask-npc"), npc.Name), responses.ToArray(), "DialogueTrees_Player_Question");
            }
            else if (e.Button == Config.AnswerButton)
            {
                Monitor.Log($"Answering {npc.Name}'s question");

                var possibleQuestions = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && npcKeys.Exists(k => k.StartsWith("DialogueTrees_reaction_" + d.topicID+"_")));

                if (!possibleQuestions.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} can ask (no reactions)! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }

                DialogueTree p = possibleQuestions[myRand.Next(possibleQuestions.Count)];

                Monitor.Log($"Asking about {loadedTopicNames[p.topicID]}");

                List<Response> responses = new List<Response>();
                foreach(var r in p.responseIDs)
                {
                    Monitor.Log(r);

                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{p.topicID}#{r}", string.Format(loadedResponseStrings[r], loadedTopicNames[p.topicID])));
                }
                string qid = p.questionIDs[myRand.Next(p.questionIDs.Count)];

                List<string> possibleQuestionStrings = npcDic.Keys.ToList().FindAll(k => k.StartsWith("DialogueTrees_question_" + qid + "_"));
                string questionString = possibleQuestionStrings.Any() ? npcDic[possibleQuestionStrings[myRand.Next(possibleQuestionStrings.Count)]] : loadedQuestionStrings[qid];

                Game1.player.currentLocation.createQuestionDialogue(string.Format(questionString, loadedTopicNames[p.topicID]), responses.ToArray(), "DialogueTrees_NPC_Question");
                Game1.objectDialoguePortraitPerson = npc;
            }
        }

19 View Source File : ICultureExtensionsTest.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void Exists_When_CultureCode_Exists_Returns_True()
        {
            // Arrange
            var expected = new CultureStub();

            // Act & replacedert
            new List<ICulture> { expected }.Exists(expected.Code).ShouldBeTrue();
        }

19 View Source File : PlayerEventHandler.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826

public async Task Handle(QuestTriggerEvent message, CancellationToken cancellationToken)
        {
            var player = message.Player;
            var questTriggerType = message.QuestTriggerType;

            //已经领取的所有任务
            var myQuests = (await _playerQuestDomainService.GetPlayerQuests(player.Id));
            //正在进行的任务
            var myQuestsNotComplete = myQuests.Where(x => x.Status== QuestStateEnum.已领取进行中);
            //所有未完成任务
            var quests = (await _questDomainService.GetAll()).Where(x => myQuestsNotComplete.Select(y => y.QuestId).Contains(x.Id));


            foreach(var quest in quests)
            {
                List<QuestTarget> questTargets = new List<QuestTarget>();
                try
                {
                    questTargets = JsonConvert.DeserializeObject<List<QuestTarget>>(quest.Target);
                }
                catch (Exception ex)
                {
                    _logger.LogError($"Convert QuestTarget:{ex}");
                }

                if (questTargets == null || questTargets.Count == 0)
                {
                    continue;
                }

                if (!questTargets.Exists(x => x.Target == questTriggerType.ToString()))
                {
                    continue;
                }

                foreach (var questTarget in questTargets)
                {
                    var npcId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "NpcId")?.Val;
                    var questId = questTarget.Attrs.FirstOrDefault(x => x.Attr == "QuestId")?.Val;
                    int.TryParse(questTarget.Attrs.FirstOrDefault(x => x.Attr == "RoomId")?.Val, out int roomId);

                    var targetEnum = (QuestTargetEnum)Enum.Parse(typeof(QuestTargetEnum), questTarget.Target, true);
                    switch (targetEnum)
                    {

                        case QuestTargetEnum.与某个Npc对话:
    
                            break;

                        case QuestTargetEnum.所在房间:
                            if (player.RoomId != roomId)
                            {
                                continue;
                            }


                            break;

                    }
                }


            }


        }

19 View Source File : ExcelVBAModuleCollection.cs
License : Apache License 2.0
Project Creator : Appdynamics

public bool Exists(string Name)
        {
            return _list.Exists((f) => TypeCompat.GetPropertyValue(f,"Name").ToString().Equals(Name,StringComparison.OrdinalIgnoreCase));
        }

19 View Source File : GraphSceneComponents.cs
License : Apache License 2.0
Project Creator : activey

public bool HasNodeComponent(AbstractGraphNode graphNode)
		{
			return nodeComponents.Exists (nodeComponent => {
				return nodeComponent.GetGraphNode().GetId() == graphNode.GetId();
			});
		}

19 View Source File : NodeParametersWindow.cs
License : MIT License
Project Creator : alexismorin

public void DrawFunctionProperties()
		{
			List<PropertyNode> nodes = UIUtils.PropertyNodesList();
			if ( m_propertyReordableList == null || nodes.Count != m_lastCount )
			{
				m_propertyReordableNodes.Clear();

				for ( int i = 0; i < nodes.Count; i++ )
				{
					ReordenatorNode rnode = nodes[ i ] as ReordenatorNode;
					if ( ( rnode == null || !rnode.IsInside ) && ( !m_propertyReordableNodes.Exists( x => x.PropertyName.Equals( nodes[ i ].PropertyName ) ) ) )
						m_propertyReordableNodes.Add( nodes[ i ] );
				}

				m_propertyReordableNodes.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } );

				m_propertyReordableList = new ReorderableList( m_propertyReordableNodes, typeof( PropertyNode ), true, false, false, false );
				m_propertyReordableList.headerHeight = 0;
				m_propertyReordableList.footerHeight = 0;
				m_propertyReordableList.showDefaultBackground = false;

				m_propertyReordableList.drawElementCallback = ( Rect rect, int index, bool isActive, bool isFocused ) =>
				{
					EditorGUI.LabelField( rect, /*m_propertyReordableNodes[ index ].OrderIndex + " " + */m_propertyReordableNodes[ index ].PropertyInspectorName );
				};

				m_propertyReordableList.onChangedCallback = ( list ) =>
				{
					ReorderList( ref nodes );
				};

				ReorderList( ref nodes );

				m_lastCount = m_propertyReordableList.count;
			}

			if ( m_propertyReordableList != null )
			{
				if ( m_propertyAdjustment == null )
				{
					m_propertyAdjustment = new GUIStyle();
					m_propertyAdjustment.padding.left = 17;
				}
				EditorGUILayout.BeginVertical( m_propertyAdjustment );
				m_propertyReordableList.DoLayoutList();
				EditorGUILayout.EndVertical();
			}
		}

19 View Source File : StringExtension.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static IEnumerable<string> Merge(this IEnumerable<string> first, IEnumerable<string> second, bool ignoreCase)
		{
			if (first == null)
				throw new ArgumentNullException("first");
			if (second == null)
				throw new ArgumentNullException("second");

			foreach (var elem in first)
				yield return elem;

			var list = new List<string>(first);
			foreach (var elem in second)
			{
				bool skip;
				if (ignoreCase)
					skip = list.Exists(s => string.Equals(s, elem, StringComparison.OrdinalIgnoreCase));
				else
					skip = list.Contains(elem);

				if (!skip)
					yield return elem;
			}
		}

19 View Source File : DmnDefinitionFactory.cs
License : MIT License
Project Creator : adamecr

protected static void AddNewRequiredInputs(IReadOnlyCollection<DmnVariableDefinition> newInputs, List<DmnVariableDefinition> requiredInputs)
        {
            if (requiredInputs == null) throw Logger.Fatal<ArgumentNullException>($"{nameof(requiredInputs)} is null.");
            if (newInputs == null || !newInputs.Any()) return;

            foreach (var requiredInput in newInputs)
            {
                if (!requiredInputs.Exists(i => i.Name == requiredInput.Name))
                    requiredInputs.Add(requiredInput);
            }
        }

19 View Source File : PlottingDataManager.cs
License : MIT License
Project Creator : Analogy-LogViewer

public void ClearSeriesData(string seriesNameToClear)
        {
            var exist = GraphsData.Exists(s => s.seriesName.Equals(seriesNameToClear));
            if (exist)
            {
                var series = GraphsData.First(s => s.seriesName.Equals(seriesNameToClear));
                series.data.Clear();
            }
        }

19 View Source File : BookListAndBookRelationshipManager.cs
License : MIT License
Project Creator : 52ABP

public async Task CreateRelationship(long? bookListId, List<long> bookIds)
        {
            // 删除原有的关联
            await _repository.DeleteAsync(o => o.BookListId == bookListId.Value);
            await CurrentUnitOfWork.SaveChangesAsync();


            // 创建关联
            var insertdBookIds = new List<long>();
            foreach (var bookId in bookIds)
            {
                // 已经插入过了
                if (insertdBookIds.Exists(o => o == bookId))
                {
                    continue;
                }

                await _repository.InsertAsync(new BookListAndBookRelationship()
                {
                    BookId = bookId,
                    BookListId = bookListId.Value
                });
                insertdBookIds.Add(bookId);
            }
        }

19 View Source File : ICultureExtensionsTest.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void Exists_When_Cultures_IsEmpty_Returns_False()
        {
            new List<ICulture>().Exists(cultureCode: "does-not-matter").ShouldBeFalse();
        }

19 View Source File : BlocksHelper.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

internal static Creature GetCreatureAtPosition(this List<Creature> creatures, Point position)
        {
            if (Program.Player.Position.Equals(position) && creatures.Exists(c => c.ID == Program.Player.ID))
                return Program.Player;

            foreach (Creature creature in creatures)
                if (creature.Position.Equals(position))
                    return creature;
            return null;
        }

19 View Source File : ControllerConnectionHandler.cs
License : MIT License
Project Creator : aornelas

private void GetAllowedInput()
        {
            for (int i = 0; i < 2; ++i)
            {
                MLInputController controller = MLInput.GetController(i);
                if (IsDeviceAllowed(controller) && !_allowedConnectedDevices.Exists((device) => device.Id == controller.Id))
                {
                    _allowedConnectedDevices.Add(controller);
                }
            }
        }

19 View Source File : Statistics.cs
License : MIT License
Project Creator : 1ZouLTReX1

private void StopSentTimer(int recvTickAck, long idleTime)
    {
        if (tickBuffer.Exists(x => x.tickNum == recvTickAck))
        {
            var item = tickBuffer.Find(x => x.tickNum == recvTickAck);
            long now = m_StopWatch.ElapsedTicks;

            m_currentRtt = (int) ((now - item.sentTime - idleTime) / m_FrequencyMS);
            m_currentLag = (int) ((now - item.sentTime) / m_FrequencyMS);
            
            // Debug printing
            // Debug.Log("Pure RTT: " + m_currentRtt);
            // Debug.Log("Over all Lag: " + m_currentLag);

            // Since we got the Ack back we don't have to store the tick anymore and every tick until that tick (Because of tcp).
            // A better approach would a 4 bytes mask where every bit is whether we got the tick or not.
            tickBuffer.RemoveRange(0, tickBuffer.LastIndexOf(item));
        }
    }

19 View Source File : FormulaDependency.cs
License : Apache License 2.0
Project Creator : Appdynamics

public virtual void AddReferenceTo(RangeAddress rangeAddress)
        {
            if (Address.CollidesWith(rangeAddress) || _referencedBy.Exists(x => x.CollidesWith(rangeAddress)))
            {
                throw new CircularReferenceException("Circular reference detected at " + rangeAddress.ToString());
            }
            _references.Add(rangeAddress);
        }

19 View Source File : PeriodTask.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void AddTask(string name, Action<object> action, int intervalSeconds, int waitSeconds = 0)
		{
			if (IsRunning)
				throw new InvalidOperationException("Task is running.");
			if (_tasks.Exists(t => t.Name == name))
				throw new ArgumentException("Task name exist.");

			_tasks.Add(new Task()
			{
				Name = name,
				Action = action,
				Wait = waitSeconds,
				Interval = intervalSeconds,
				LastEndTime = DateTime.MinValue
			});
		}

19 View Source File : PeriodTask.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void AddTask(string name, Action<object> action, object state, int intervalSeconds, int waitSeconds)
		{
			if (IsRunning)
				throw new InvalidOperationException("Task is running.");
			if (_tasks.Exists(t => t.Name == name))
				throw new ArgumentException("Task name has existed.");

			_tasks.Add(new Task()
			{
				Name = name,
				Action = action,
				State = state,
				Wait = waitSeconds,
				Interval = intervalSeconds,
				LastEndTime = DateTime.MinValue
			});
		}

19 View Source File : Utils.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static void DedupServerList(List<Mode.VmessItem> source, out List<Mode.VmessItem> result, bool keepOlder)
        {
            List<Mode.VmessItem> list = new List<Mode.VmessItem>();
            if (!keepOlder) source.Reverse(); // Remove the early items first

            bool _isAdded(Mode.VmessItem o, Mode.VmessItem n)
            {
                return o.configVersion == n.configVersion &&
                    o.configType == n.configType &&
                    o.address == n.address &&
                    o.port == n.port &&
                    o.id == n.id &&
                    o.alterId == n.alterId &&
                    o.security == n.security &&
                    o.network == n.network &&
                    o.headerType == n.headerType &&
                    o.requestHost == n.requestHost &&
                    o.path == n.path &&
                    o.streamSecurity == n.streamSecurity;
                // skip (will remove) different remarks
            }
            foreach (Mode.VmessItem item in source)
            {
                if (!list.Exists(i => _isAdded(i, item)))
                {
                    list.Add(item);
                }
            }
            if (!keepOlder) list.Reverse();
            result = list;
        }

19 View Source File : HttpRoute.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public bool IsMatch(HttpListenerRequest Request, string prefix)
		{
			string url = Request.GetFilePath(prefix);
			return _rules.Exists(r => Regex.IsMatch(url, r.Pattern));
		}

19 View Source File : GraphSceneComponents.cs
License : Apache License 2.0
Project Creator : activey

public bool HasEdgeComponent(AbstractGraphEdge graphEdge)
		{
			return edgeComponents.Exists (edgeComponent => {
				return edgeComponent.GetGraphEdge().GetId() == graphEdge.GetId();
			});
		}

19 View Source File : WmiProvider.cs
License : MIT License
Project Creator : AlexGyver

private bool Exists(string identifier) {
      return activeInstances.Exists(h => h.Identifier == identifier);
    }

19 View Source File : BaseGraphView.cs
License : MIT License
Project Creator : alelievr

public void AddSelectionsToGroup(GroupView view)
        {
            foreach (var selectedNode in selection)
            {
                if (selectedNode is BaseNodeView)
                {
                    if (groupViews.Exists(x => x.ContainsElement(selectedNode as BaseNodeView)))
                        continue;

                    view.AddElement(selectedNode as BaseNodeView);
                }
            }
        }

19 View Source File : GenerateNuSpecFileTask.cs
License : MIT License
Project Creator : adamecr

public override bool Execute()
        {
            if (DebugTasks)
            {
                //Wait for debugger
                Log.LogMessage(
                    MessageImportance.High,
                    $"Debugging task {GetType().Name}, set the breakpoint and attach debugger to process with PID = {System.Diagnostics.Process.GetCurrentProcess().Id}");

                while (!System.Diagnostics.Debugger.IsAttached)
                {
                    Thread.Sleep(1000);
                }
            }

            var replacedle = !string.IsNullOrEmpty(replacedle) ? replacedle : PackageId;

            var sb = new System.Text.StringBuilder(); //TODO refactor to LINQ XML
            sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
            sb.AppendLine($"<package xmlns=\"http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd\">");
            sb.AppendLine($" <metadata>");
            sb.AppendLine($"  <id>{PackageId}</id>");
            sb.AppendLine($"  <version>{PackageVersionFull}</version>");
            sb.AppendLine($"  <authors>{Authors}</authors>");
            sb.AppendLine($"  <replacedle>{replacedle}</replacedle>");
            sb.AppendLine($"  <owners>{Authors}</owners>");
            sb.AppendLine($"  <requireLicenseAcceptance>{PackageRequireLicenseAcceptance}</requireLicenseAcceptance>");
            // ReSharper disable once ConvertIfStatementToConditionalTernaryExpression
            if (!string.IsNullOrEmpty(PackageLicense))
            {
                sb.AppendLine($"  <license type=\"expression\">{PackageLicense}</license>");
            }
            else
            {
                sb.AppendLine($"  <licenseUrl>{PackageLicenseUrl}</licenseUrl>");
            }
            sb.AppendLine($"  <projectUrl>{PackageProjectUrl}</projectUrl>");
            sb.AppendLine($"  <iconUrl>{PackageIconUrl}</iconUrl>");
            sb.AppendLine($"  <description>{Description}</description>");
            sb.AppendLine($"  <releaseNotes>{PackageReleaseNotes}</releaseNotes>");
            sb.AppendLine($"  <copyright>{Copyright}</copyright>");
            sb.AppendLine($"  <tags>{PackageTags}</tags>");
            sb.AppendLine(
                $"  <repository url=\"{RepositoryUrl}\" type=\"git\" branch=\"{GitBranch}\" commit=\"{GitCommit}\" />");
            sb.AppendLine($"  <dependencies>");
            sb.AppendLine($"   <group targetFramework=\"{TargetFramework}\">");

            if (PackageReferences != null)
            {
                foreach (var r in PackageReferences)
                {
                    var item = r.ItemSpec;
                    if (item != "NETStandard.Library")
                        sb.AppendLine(
                            $"    <dependency id=\"{r.ItemSpec}\" version=\"{r.GetMetadata("Version")}\" exclude=\"Build,replacedyzers\" />");
                }
            }

            var resolvedProjectReferences =
                new List<string>(); //project references that has been resolved as NuGet packages
            if (ProjectReferences != null)
            {
                foreach (var src in ProjectReferences)
                {
                    var refPackageDependencyFile = Path.Combine(src.GetMetadata("RelativeDir"), IntermediateOutputPath,
                        Configuration, "package_dependency.txt");
                    if (!File.Exists(refPackageDependencyFile)) continue;

                    var refPackageDependency = File.ReadAllText(refPackageDependencyFile);

                    resolvedProjectReferences.Add(refPackageDependency);
                    sb.AppendLine(refPackageDependency);
                }
            }

            sb.AppendLine($"   </group>");
            sb.AppendLine($"  </dependencies>");
            sb.AppendLine($" </metadata>");

            sb.AppendLine($"  <files>");
            var dllFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.dll");
            sb.AppendLine([email protected]"    <file src=""{dllFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.dll"" />");

            var pdbFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.pdb");
            if (File.Exists(pdbFile))
            {
                sb.AppendLine([email protected]"    <file src=""{pdbFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.pdb"" />");
            }

            var xmlDocFile = Path.Combine(ProjectDirectory, OutputPath, $"{replacedemblyName}.xml");
            if (File.Exists(xmlDocFile))
            {
                sb.AppendLine(
                    [email protected]"    <file src=""{xmlDocFile}"" target=""lib\{TargetFramework}\{replacedemblyName}.xml"" />");
            }

            if (SourceFiles != null && Configuration.ToLower() != "release")
            {
                sb.AppendLine("");

                foreach (var src in SourceFiles)
                {
                    var srcFileOriginal = src.GetMetadata("OriginalItemSpec");
                    var srcFileRel = srcFileOriginal.Replace([email protected]"{ProjectDirectory}\", "");
                    if (Path.IsPathRooted(srcFileRel)) continue; //not a project file (probably source-only package) - project files have the relative path in srcFileRel, non project files have full path in srcFileRel 

                    var targetFile = Path.Combine("src", ProjectName, srcFileRel);
                    sb.AppendLine([email protected]"    <file src=""{src}"" target=""{targetFile}"" />");
                }
            }

            //include project references that has NOT been resolved as NuGet packages
            if (ProjectReferences != null && ReferenceCopyLocalPaths != null)
            {
                foreach (var rf in ReferenceCopyLocalPaths)
                {
                    if (rf.GetMetadata("ReferenceSourceTarget") == "ProjectReference")
                    {
                        var fileName = rf.GetMetadata("FileName");
                        if (!resolvedProjectReferences.Exists(s => s.Contains($"id=\"{fileName}\"")))
                        {
                            sb.AppendLine(
                                [email protected]"    <file src=""{rf.GetMetadata("FullPath")}"" target=""lib\{TargetFramework}\{rf.GetMetadata("FileName")}{rf.GetMetadata("Extension")}"" />");
                        }
                    }
                }
            }

            sb.AppendLine($"  </files>");

            sb.AppendLine($"</package>  ");

            //Write NuSpec file to /obj directory
            NuSpecFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
                PackageVersionShort + ".nuspec");
            File.WriteAllText(NuSpecFile, sb.ToString());

            Log.LogMessage(sb.ToString());

            //Create dependency file for package in /obj directory
            var dep =
                [email protected]"<dependency id=""{PackageId}"" version=""{PackageVersionFull}"" exclude=""Build,replacedyzers"" />";
            var dependencyFile = Path.Combine(ProjectDirectory, IntermediateOutputPath, Configuration,
                "package_dependency.txt");
            File.WriteAllText(dependencyFile, dep);

            return true;
        }

19 View Source File : MasterNode.cs
License : MIT License
Project Creator : alexismorin

private void RefreshVisibleList( ref List<PropertyNode> allNodes )
		{
			// temp reference for lambda expression
			List<PropertyNode> nodes = allNodes;
			m_propertyNodesVisibleList.Clear();

			for( int i = 0; i < nodes.Count; i++ )
			{
				ReordenatorNode rnode = nodes[ i ] as ReordenatorNode;
				if( ( rnode == null || !rnode.IsInside ) && ( !m_propertyNodesVisibleList.Exists( x => x.PropertyName.Equals( nodes[ i ].PropertyName ) ) ) )
					m_propertyNodesVisibleList.Add( nodes[ i ] );
			}

			m_propertyNodesVisibleList.Sort( ( x, y ) => { return x.OrderIndex.CompareTo( y.OrderIndex ); } );
		}

19 View Source File : BookAndBookTagRelationshipManager.cs
License : MIT License
Project Creator : 52ABP

public async Task CreateRelationship(long? bookId, List<long> bookTagIds)
        {
            // 删除原有的关联
            await _repository.DeleteAsync(o => o.BookId == bookId.Value);
            await CurrentUnitOfWork.SaveChangesAsync();


            // 创建关联
            var insertdBookTagIds = new List<long>();
            foreach (var bookTagId in bookTagIds)
            {
                // 已经插入过了
                if (insertdBookTagIds.Exists(o => o == bookTagId))
                {
                    continue;
                }

                await _repository.InsertAsync(new BookAndBookTagRelationship()
                {
                    BookId = bookId.Value,
                    BookTagId = bookTagId,
                });
                insertdBookTagIds.Add(bookTagId);
            }
        }

19 View Source File : EntityCollection.cs
License : MIT License
Project Creator : amolines

public bool Exists(Predicate<TEnreplacedy> match)
        {
            return _enreplacedies.Exists(match);
        }

19 View Source File : FixedFacetsConfiguration.cs
License : MIT License
Project Creator : Adoxio

public bool IsFacetConfigured(string facetName)
		{
			return this.facetConfigs.Exists(facetConfig => { return facetConfig.FieldName == facetName; });
		}

19 View Source File : FactoriesManager.cs
License : MIT License
Project Creator : Analogy-LogViewer

public bool IsBuiltInFactory(Guid factoryId) =>
            BuiltInFactories.Exists(fc => fc.Factory.FactoryId == factoryId);

19 View Source File : DbQuery.cs
License : Apache License 2.0
Project Creator : 1448376744

private string ResolveUpdate()
        {
            var table = GetTableMetaInfo().TableName;
            var builder = new StringBuilder();
            if (_setExpressions.Count > 0)
            {
                var where = ResolveWhere();
                foreach (var item in _setExpressions)
                {
                    var column = new BooleanExpressionResovle(item.Column).Resovle();
                    var expression = new BooleanExpressionResovle(item.Expression, _parameters).Resovle();
                    builder.Append($"{column} = {expression},");
                }
                var sql = $"UPDATE {table} SET {builder.ToString().Trim(',')}{where}";
                return sql;
            }
            else
            {
                var filters = new GroupExpressionResovle(_filterExpression).Resovle().Split(',');
                var where = ResolveWhere();
                var columns = GetColumnMetaInfos();
                var updcolumns = columns
                    .Where(a => !filters.Contains(a.ColumnName))
                    .Where(a => !a.IsComplexType)
                    .Where(a => !a.IsIdenreplacedy && !a.IsPrimaryKey && !a.IsNotMapped)
                    .Where(a => !a.IsConcurrencyCheck)
                    .Select(s => $"{s.ColumnName} = @{s.CsharpName}");
                if (string.IsNullOrEmpty(where))
                {
                    var primaryKey = columns.Where(a => a.IsPrimaryKey).FirstOrDefault()
                        ?? columns.First();
                    where = $" WHERE {primaryKey.ColumnName} = @{primaryKey.CsharpName}";
                    if (columns.Exists(a => a.IsConcurrencyCheck))
                    {
                        var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                        where += $" AND {checkColumn.ColumnName} = @{checkColumn.CsharpName}";
                    }
                }
                var sql = $"UPDATE {table} SET {string.Join(",", updcolumns)}";
                if (columns.Exists(a => a.IsConcurrencyCheck))
                {
                    var checkColumn = columns.Where(a => a.IsConcurrencyCheck).FirstOrDefault();
                    sql += $",{checkColumn.ColumnName} = @New{checkColumn.CsharpName}";
                    if (checkColumn.CsharpType.IsValueType)
                    {
                        var version = Convert.ToInt32((DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0)).TotalSeconds);
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                    else
                    {
                        var version = Guid.NewGuid().ToString("N");
                        _parameters.Add($"New{checkColumn.CsharpName}", version);
                    }
                }
                sql += where;
                return sql;
            }
        }

19 View Source File : LocalizationUtils.cs
License : Apache License 2.0
Project Creator : AndcultureCode

public static bool CultureExists(string cultureCode) => Cultures.Exists(cultureCode);

19 View Source File : LocationPatches.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

public static void FarmHouse_performTenMinuteUpdate_Postfix(FarmHouse __instance, int timeOfDay)
        {
            try
            {
                if (__instance.owner == null)
                    return;

                List<string> mySpouses = Misc.GetSpouses(__instance.owner, 1).Keys.ToList();
                if (Game1.IsMasterGame && Game1.timeOfDay >= 2200 && Game1.IsMasterGame)
                {
                    int upgradeLevel = __instance.upgradeLevel;
                    List<string> roomSpouses = mySpouses.FindAll((s) => Maps.roomIndexes.ContainsKey(s) || Maps.tmxSpouseRooms.ContainsKey(s));
                    List<string> bedSpouses = mySpouses.FindAll((s) => ModEntry.config.RoommateRomance || !__instance.owner.friendshipData[s].RoommateMarriage);
                    foreach (NPC c in __instance.characters)
                    {
                        if (c.isMarried())
                        {
                            string spouseName = c.Name;

                            if (Misc.GetSpouses(Game1.player,1).ContainsKey(spouseName))
                            {
                                c.checkForMarriageDialogue(timeOfDay, __instance);
                            }

                            Point bedSpot;
                            if (timeOfDay >= 2200)
                            {
                                if (!bedSpouses.Contains(c.Name))
                                {
                                    if (!roomSpouses.Exists((n) => n == spouseName))
                                    {
                                        bedSpot = __instance.getRandomOpenPointInHouse(ModEntry.myRand);
                                    }
                                    else
                                    {
                                        int offset = roomSpouses.IndexOf(spouseName) * 7;
                                        Vector2 spot = (upgradeLevel == 1) ? new Vector2(32f, 5f) : new Vector2(38f, 14f);
                                        bedSpot = new Point((int)spot.X + offset, (int)spot.Y);
                                    }

                                }
                                else
                                {
                                    int bedWidth = Misc.GetBedWidth(__instance);
                                    bool up = upgradeLevel > 1;

                                    Point bedStart = __instance.GetSpouseBed().GetBedSpot();
                                    int x = 1 + (int)(bedSpouses.IndexOf(spouseName) / (float)(bedSpouses.Count) * (bedWidth - 1));
                                    bedSpot = new Point(bedStart.X + x, bedStart.Y);

                                }

                                c.controller = null;
                                if (c.Position != Misc.GetSpouseBedPosition(__instance, bedSpouses, c.Name) && (!Misc.IsInBed(__instance,c.GetBoundingBox()) || !Kissing.kissingSpouses.Contains(c.Name)))
                                {
                                    c.controller = new PathFindController(c, __instance, bedSpot, 0, new PathFindController.endBehavior(FarmHouse.spouseSleepEndFunction));
                                    if (c.controller.pathToEndPoint == null || !__instance.isTileOnMap(c.controller.pathToEndPoint.Last<Point>().X, c.controller.pathToEndPoint.Last<Point>().Y))
                                    {
                                        c.controller = null;
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Monitor.Log($"Failed in {nameof(FarmHouse_performTenMinuteUpdate_Postfix)}:\n{ex}", LogLevel.Error);
            }
        }

19 View Source File : ICultureExtensionsTest.cs
License : Apache License 2.0
Project Creator : AndcultureCode

[Fact]
        public void Exists_When_CultureCode_DoesNotExist_Returns_False()
        {
            new List<ICulture> { new CultureStub() }.Exists("404").ShouldBeFalse();
        }

19 View Source File : Settings.cs
License : MIT License
Project Creator : 71

public static void Load()
        {
            int defaultKeycode;
            List<InputDevice> inputDevices = new List<InputDevice>();
            InputDevices.GetDevices(inputDevices);

            if (inputDevices.Exists(x => x.name.IndexOf("rift", StringComparison.InvariantCultureIgnoreCase) != -1))
                defaultKeycode = (int)ConInput.Oculus.LeftThumbstickPress;
            else if (inputDevices.Exists(x => x.name.IndexOf("vive", StringComparison.InvariantCultureIgnoreCase) != -1))
                defaultKeycode = (int)ConInput.Vive.LeftTrackpadPress;
            else
                defaultKeycode = (int)ConInput.WinMR.LeftThumbstickPress;

            DisplayLyrics = ModPrefs.GetBool(PrefsSection, "Enabled"            , true);
            ToggleKeyCode = ModPrefs.GetInt (PrefsSection, nameof(ToggleKeyCode), defaultKeycode);

            DisplayDelay = ModPrefs.GetFloat(PrefsSection, nameof(DisplayDelay), -.1f);
            HideDelay    = ModPrefs.GetFloat(PrefsSection, nameof(HideDelay)   , 0f);

            VerboseLogging = ModPrefs.GetBool(PrefsSection, nameof(VerboseLogging), false);
        }

19 View Source File : LeanPool.cs
License : Apache License 2.0
Project Creator : AnotherEnd15

public void FastDespawn(GameObject clone, float delay = 0.0f)
		{
			if (clone != null)
			{
				// Delay the despawn?
				if (delay > 0.0f)
				{
					// Make sure we only add it to the marked object list once
					if (delayedDestructions.Exists(m => m.Clone == clone) == false)
					{
						var delayedDestruction = LeanClreplacedPool<DelayedDestruction>.Spawn() ?? new DelayedDestruction();
						
						delayedDestruction.Clone = clone;
						delayedDestruction.Life  = delay;
						
						delayedDestructions.Add(delayedDestruction);
					}
				}
				// Despawn now?
				else
				{
					// Add it to the cache
					cache.Add(clone);
					
					// Messages?
					SendNotification(clone, "OnDespawn");
					
					// Deactivate it
					clone.SetActive(false);
					
					// Move it under this GO
					clone.transform.SetParent(transform, false);
				}
			}
			else
			{
				//Debug.LogWarning("Attempting to despawn a null clone");
			}
		}

19 View Source File : CraftingManager.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static bool DetermineIfCanCraft(CraftingRecipe craftingRecipe)
        {
            // does the player have enough skill?
            if (craftingRecipe.MinCraftingSkill > Program.Player.Stats.Skills[Skill.Crafting])
                return false;

            List<RecipeComponent> recipe = new List<RecipeComponent>();
            // copy recipe to variable
            foreach (RecipeComponent r in craftingRecipe.Recipe)
                recipe.Add(r);

            // determine if the player has the required components

            for (int i = Program.Player.Inventory.Count - 1; i >= 0; i--)
            {
                Item item = Program.Player.Inventory[i];
                if ( recipe.Exists(rc => rc == item.ToComponent() ))
                    recipe.RemoveAt( recipe.FindLastIndex( rc => rc == item.ToComponent() ) );
            }
            
            if (recipe.Count > 0)
                return false;

            return true;
        }

19 View Source File : ControllerConnectionHandler.cs
License : MIT License
Project Creator : aornelas

public bool IsControllerValid(byte controllerId)
        {
            return _allowedConnectedDevices.Exists((device) => device.Id == controllerId);
        }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void OrderModules() {
            List<ModuleDefinition> ordered = new List<ModuleDefinition>(Modules);

            Log("[OrderModules] Unordered: ");
            for (int i = 0; i < Modules.Count; i++)
                Log($"[OrderModules] #{i + 1}: {Modules[i].replacedembly.Name.Name}");

            ModuleDefinition dep = null;
            foreach (ModuleDefinition mod in Modules)
                foreach (replacedemblyNameReference depName in mod.replacedemblyReferences)
                    if (Modules.Exists(other => (dep = other).replacedembly.Name.Name == depName.Name) &&
                        ordered.IndexOf(dep) > ordered.IndexOf(mod)) {
                        Log($"[OrderModules] Reordering {mod.replacedembly.Name.Name} dependency {dep.Name}");
                        ordered.Remove(mod);
                        ordered.Insert(ordered.IndexOf(dep) + 1, mod);
                    }

            Modules = ordered;

            Log("[OrderModules] Reordered: ");
            for (int i = 0; i < Modules.Count; i++)
                Log($"[OrderModules] #{i + 1}: {Modules[i].replacedembly.Name.Name}");
        }

19 View Source File : FormulaDependency.cs
License : Apache License 2.0
Project Creator : Appdynamics

public virtual void AddReferenceFrom(RangeAddress rangeAddress)
        {
            if (Address.CollidesWith(rangeAddress) || _references.Exists(x => x.CollidesWith(rangeAddress)))
            {
                throw new CircularReferenceException("Circular reference detected at " + rangeAddress.ToString());
            }
            _referencedBy.Add(rangeAddress);
        }

19 View Source File : Pathfinder.cs
License : GNU General Public License v3.0
Project Creator : aenemenate

public static List<Point> FindPath( Point start, Point end, float[,] heightMap )
        {
            List<Point> path       = new List<Point>();
            List<Node>  openList   = new List<Node>() { new Node( start, 0, 0 ) };
            List<Node>  closedList = new List<Node>();

            Point startIndex = new Point(start.X / 100, start.Y / 100), 
                    endIndex = new Point( end.X / 100, end.Y / 100 ); //world map indexes
            Point currentPoint = new Point(start.X, start.Y);
            Point GetNextTempGoal()
            {
                Point currentIndex = new Point( currentPoint.X / 100, currentPoint.Y / 100 );
                Point tempIndex = new Point();
                if (currentIndex.Equals( endIndex ))
                    return end;
                for (int i = Math.Max(0, currentIndex.X - 1); i <= Math.Min( 3, currentIndex.X + 1 ); i++)
                    for (int j = Math.Max( 0, currentIndex.Y - 1 ); j <= Math.Min( 3, currentIndex.Y + 1 ); j++) {
                        if (new Point( i, j ).DistFrom( endIndex ) < tempIndex.DistFrom( endIndex ))
                            tempIndex = new Point( i, j );
                    }
                bool xDeltaNon0 = (tempIndex.X - currentIndex.X) == 1 || (tempIndex.X - currentIndex.X) == -1;
                bool yDeltaNon0 = (tempIndex.Y - currentIndex.Y) == 1 || (tempIndex.Y - currentIndex.Y) == -1;
                if (xDeltaNon0 && yDeltaNon0) {
                    if (Program.RNG.Next( 0, 100 ) < 50) xDeltaNon0 = false;
                    else yDeltaNon0 = false;
                }
                Point tempGoal = 
                    new Point( currentPoint.X + (( (tempIndex.X - currentIndex.X) == 1 ? 100 : -1) - currentPoint.X % 100) * (xDeltaNon0 ? 1 : 0),
                                currentPoint.Y + (( ( tempIndex.Y - currentIndex.Y ) == 1 ? 100 : -1) - currentPoint.Y % 100) * (yDeltaNon0 ? 1 : 0));
                Point returnGoal = new Point(tempGoal.X, tempGoal.Y);
                if (xDeltaNon0) {
                    for (int j = ( tempGoal.Y / 100 ) * 100 + 10; j < ( tempGoal.Y / 100 ) * 100 + 90; j++) {
                        if (new Point( tempGoal.X, j ).DistFrom( end ) + heightMap[tempGoal.X, j] < returnGoal.DistFrom( end ) + heightMap[end.X, end.Y] && false == heightMap[tempGoal.X, j] >= WorldMapGeneration.StoneCutoff)
                            returnGoal = new Point( tempGoal.X, j );
                    }
                } else if (yDeltaNon0) {
                    for (int i = ( tempGoal.X / 100 ) * 100 + 10; i < ( tempGoal.X / 100 ) * 100 + 90; i++) {
                        if (new Point( i, tempGoal.Y ).DistFrom( end ) + heightMap[i, tempGoal.Y] < returnGoal.DistFrom( end ) + heightMap[end.X, end.Y] && false == heightMap[i, tempGoal.Y] >= WorldMapGeneration.StoneCutoff)
                            returnGoal = new Point( i, tempGoal.Y);
                    }
                }
                
                return returnGoal;
            }

            bool CheckOpenList( Node node )
            {
                foreach (Node otherNode in openList)
                    if (otherNode.Pos.Equals( node.Pos ))
                        if (otherNode.F <= node.F)
                            return true;
                return false;
            }
            bool CheckClosedList( Node node )
            {
                foreach (Node otherNode in closedList)
                    if (otherNode.Pos.Equals( node.Pos ))
                        if (otherNode.F <= node.F)
                            return true;
                return false;
            }

            while (path.Exists(point => point.Equals(end)) == false)
            {
                Point nextGoal = GetNextTempGoal();
                while (openList.Count > 0)
                {
                    Node currentNode = GetSmallestNode( openList );
                    List<Node> adjacentNodes = GetAdjacentNodes( currentNode, new Point(currentPoint.X / 100, currentPoint.Y / 100) );
                    for (int i = adjacentNodes.Count - 1; i >= 0; i--)
                    {
                        Node node = adjacentNodes[i];
                        if (heightMap[node.Pos.X, node.Pos.Y] >= WorldMapGeneration.StoneCutoff && !( heightMap[currentNode.Pos.X, currentNode.Pos.Y] >= WorldMapGeneration.StoneCutoff ))
                            continue;
                        if (node.Pos.Equals( nextGoal ))
                        {
                            Node pathNode = node;
                            while (pathNode.Pos.Equals( currentPoint ) == false)
                            {
                                path.Insert( 0, pathNode.Pos );
                                pathNode = pathNode.ParentNode;
                            }
                            goto Finish;
                        } else
                        {
                            node.G = currentNode.G + node.Pos.DistFrom( currentNode.Pos )
                                + Math.Max( -2, Math.Min( 2, .3 * ( heightMap[node.Pos.X, node.Pos.Y] - heightMap[currentNode.Pos.X, currentNode.Pos.Y] ) ) );
                            node.H = Math.Abs( node.Pos.X - nextGoal.X ) + Math.Abs( node.Pos.Y - nextGoal.Y );
                            if (CheckOpenList( node ))
                                continue;

                            if (CheckClosedList( node ))
                                continue;

                            openList.Add( node );
                        }
                    }
                    closedList.Add( currentNode );
                }

                Finish:
                closedList = new List<Node>();
                openList = new List<Node>() { new Node( nextGoal, 0, 0 ) };
                currentPoint = new Point(nextGoal.X, nextGoal.Y);
            }
            return path;
        }

19 View Source File : ThemeDefinition.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

void ISerializationCallbackReceiver.OnBeforeSerialize()
        {
            // Backward compatibility at runtime in case some custom properties have been added in code after first serialization
            ThemeDefinition defaultDefinition = GetDefaultThemeDefinition(ThemeType).Value;

            if (defaultDefinition.CustomProperties.Count > CustomProperties.Count)
            {
                foreach (ThemeProperty prop in defaultDefinition.CustomProperties)
                {
                    if (!CustomProperties.Exists(p => p.Name == prop.Name))
                    {
                        CustomProperties.Add(new ThemeProperty()
                        {
                            Name = prop.Name,
                            Tooltip = prop.Tooltip,
                            Type = prop.Type,
                            Value = prop.Value,
                        });
                    }
                }
            }
        }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void ScanPath(string path) {
            if (Directory.Exists(path)) {
                // Use the directory as "dependency directory" and scan in it.
                if (Directories.Contains(path))
                    // No need to scan the dir if the dir is scanned...
                    return;

                RestoreBackup(path);

                Log($"[ScanPath] Scanning directory {path}");
                Directories.Add(path);
                replacedemblyResolver.AddSearchDirectory(path); // Needs to be added manually as DependencyDirs was already added

                // Most probably the actual game directory - let's just copy XnaToFna.exe to there to be referenced properly.
                string xtfPath = Path.Combine(path, Path.GetFileName(Thisreplacedembly.Location));
                if (Path.GetDirectoryName(Thisreplacedembly.Location) != path) {
                    Log($"[ScanPath] Found separate game directory - copying XnaToFna.exe and FNA.dll");
                    File.Copy(Thisreplacedembly.Location, xtfPath, true);

                    string dbExt = null;
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "pdb")))
                        dbExt = "pdb";
                    if (File.Exists(Path.ChangeExtension(Thisreplacedembly.Location, "mdb")))
                        dbExt = "mdb";
                    if (dbExt != null)
                        File.Copy(Path.ChangeExtension(Thisreplacedembly.Location, dbExt), Path.ChangeExtension(xtfPath, dbExt), true);

                    if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll"), Path.Combine(path, "FNA.dll"), true);
                    else if (File.Exists(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp")))
                        File.Copy(Path.Combine(Path.GetDirectoryName(Thisreplacedembly.Location), "FNA.dll.tmp"), Path.Combine(path, "FNA.dll"), true);

                }

                ScanPaths(Directory.GetFiles(path));
                return;
            }

            if (File.Exists(path + ".xex")) {
                if (!ExtractedXEX.Contains(path)) {
                    // Remove the original file - let XnaToFna unpack and handle it later.
                    File.Delete(path);
                } else {
                    // XnaToFna will handle the .xex instead.
                }
                return;
            }

            if (path.EndsWith(".xex")) {
                string pathTarget = path.Substring(0, path.Length - 4);
                if (string.IsNullOrEmpty(Path.GetExtension(pathTarget)))
                    return;

                using (Stream streamXEX = File.OpenRead(path))
                using (BinaryReader reader = new BinaryReader(streamXEX))
                using (Stream streamRAW = File.OpenWrite(pathTarget)) {
                    XEXImageData data = new XEXImageData(reader);

                    int offset = 0;
                    int size = data.m_memorySize;

                    // Check if this file is a PE containing an embedded PE.
                    if (data.m_memorySize > 0x10000) { // One default segment alignment.
                        using (MemoryStream streamMEM = new MemoryStream(data.m_memoryData))
                        using (BinaryReader mem = new BinaryReader(streamMEM)) {
                            if (mem.ReadUInt32() != 0x00905A4D) // MZ
                                goto WriteRaw;
                            // This is horrible.
                            streamMEM.Seek(0x00000280, SeekOrigin.Begin);
                            if (mem.ReadUInt64() != 0x000061746164692E) // ".idata\0\0"
                                goto WriteRaw;
                            streamMEM.Seek(0x00000288, SeekOrigin.Begin);
                            mem.ReadInt32(); // Virtual size; It's somewhat incorrect?
                            offset = mem.ReadInt32(); // Virtual offset.
                            // mem.ReadInt32(); // Raw size; Still incorrect.
                            // Let's just write everything...
                            size = data.m_memorySize - offset;
                        }
                    }

                    WriteRaw:
                    streamRAW.Write(data.m_memoryData, offset, size);
                }

                path = pathTarget;
                ExtractedXEX.Add(pathTarget);
            } else if (!path.EndsWith(".dll") && !path.EndsWith(".exe"))
                return;

            // Check if .dll is CLR replacedembly
            replacedemblyName name;
            try {
                name = replacedemblyName.GetreplacedemblyName(path);
            } catch {
                return;
            }

            ReaderParameters modReaderParams = Modder.GenReaderParameters(false);
            // Don't ReadWrite if the module being read is XnaToFna or a relink target.
            bool isReadWrite =
#if !CECIL0_9
            modReaderParams.ReadWrite =
#endif
                path != Thisreplacedembly.Location &&
                !Mappings.Exists(mappings => name.Name == mappings.Target);
            // Only read debug info if it exists
            if (!File.Exists(path + ".mdb") && !File.Exists(Path.ChangeExtension(path, "pdb")))
                modReaderParams.ReadSymbols = false;
            Log($"[ScanPath] Checking replacedembly {name.Name} ({(isReadWrite ? "rw" : "r-")})");
            ModuleDefinition mod;
            try {
                mod = MonoModExt.ReadModule(path, modReaderParams);
            } catch (Exception e) {
                Log($"[ScanPath] WARNING: Cannot load replacedembly: {e}");
                return;
            }
            bool add = !isReadWrite || name.Name == ThisreplacedemblyName;

            if ((mod.Attributes & ModuleAttributes.ILOnly) != ModuleAttributes.ILOnly) {
                // Mono.Cecil can't handle mixed mode replacedemblies.
                Log($"[ScanPath] WARNING: Cannot handle mixed mode replacedembly {name.Name}");
                if (MixedDeps == MixedDepAction.Stub) {
                    ModulesToStub.Add(mod);
                    add = true;
                } else {
                    if (MixedDeps == MixedDepAction.Remove) {
                        RemoveDeps.Add(name.Name);
                    }
#if !CECIL0_9
                    mod.Dispose();
#endif
                    return;
                }
            }

            if (add && !isReadWrite) { // XNA replacement
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (name.Name == mapping.Target) {
                        mapping.IsActive = true;
                        mapping.Module = mod;
                        foreach (string from in mapping.Sources) {
                            Log($"[ScanPath] Mapping {from} -> {name.Name}");
                            Modder.RelinkModuleMap[from] = mod;
                        }
                    }
            } else if (!add) {
                foreach (XnaToFnaMapping mapping in Mappings)
                    if (mod.replacedemblyReferences.Any(dep => mapping.Sources.Contains(dep.Name))) {
                        add = true;
                        Log($"[ScanPath] XnaToFna-ing {name.Name}");
                        goto BreakMappings;
                    }
            }
            BreakMappings:

            if (add) {
                Modules.Add(mod);
                ModulePaths[mod] = path;
            } else {
#if !CECIL0_9
                mod.Dispose();
#endif
            }

        }

19 View Source File : XnaToFnaUtil.cs
License : zlib License
Project Creator : 0x0ade

public void Relink(ModuleDefinition mod) {
            // Don't relink the relink targets!
            if (Mappings.Exists(mappings => mod.replacedembly.Name.Name == mappings.Target))
                return;

            // Don't relink stubbed targets again!
            if (ModulesToStub.Contains(mod))
                return;

            // Don't relink XnaToFna itself!
            if (mod.replacedembly.Name.Name == ThisreplacedemblyName)
                return;

            Log($"[Relink] Relinking {mod.replacedembly.Name.Name}");
            Modder.Module = mod;

            ApplyCommonChanges(mod);

            Log("[Relink] Pre-processing");
            foreach (TypeDefinition type in mod.Types)
                PreProcessType(type);

            Log("[Relink] Relinking (MonoMod PatchRefs preplaced)");
            Modder.PatchRefs();

            Log("[Relink] Post-processing");
            foreach (TypeDefinition type in mod.Types)
                PostProcessType(type);

            if (HookEntryPoint && mod.EntryPoint != null) {
                Log("[Relink] Injecting XnaToFna entry point hook");
                ILProcessor il = mod.EntryPoint.Body.GetILProcessor();
                Instruction call = il.Create(OpCodes.Call, mod.ImportReference(m_XnaToFnaHelper_MainHook));
                il.InsertBefore(mod.EntryPoint.Body.Instructions[0], call);
                il.InsertBefore(call, il.Create(OpCodes.Ldarg_0));
            }

            Log("[Relink] Rewriting and disposing module\n");
#if !CECIL0_9
            Modder.Module.Write(Modder.WriterParameters);
#else
            Modder.Module.Write(ModulePaths[Modder.Module], Modder.WriterParameters);
#endif
            // Dispose the module so other modules can read it as a dependency again.
#if !CECIL0_9
            Modder.Module.Dispose();
#endif
            Modder.Module = null;
            Modder.ClearCaches(moduleSpecific: true);
        }

19 View Source File : BookApplicationService.cs
License : MIT License
Project Creator : 52ABP

[AbpAuthorize(BookPermissions.Create, BookPermissions.Edit)]
        public async Task<GetBookForEditOutput> GetForEdit(NullableIdDto<long> input)
        {
            var output = new GetBookForEditOutput();
            BookEditDto editDto;
            // 已选中的标签Id
            List<long> bookTagIds = null;
            // 所有标签
            var allbookTag = (await _bookTagManager.GetAll()).MapTo<List<BookTagSelectListDto>>();

            if (input.Id.HasValue)
            {
                var enreplacedy = await _enreplacedyRepository.GetAsync(input.Id.Value);

                editDto = enreplacedy.MapTo<BookEditDto>();


                bookTagIds = (await _bookAndBookTagRelationshipManager.GetByBookId(input.Id.Value))
                     .Select(o => o.BookTagId)
                     .ToList();


                foreach (var bookTag in allbookTag)
                {
                    if (bookTagIds.Exists(o => o == bookTag.Id))
                    {
                        bookTag.IsSelected = true;
                    }
                }
            }
            else
            {
                editDto = new BookEditDto();
            }

            output.Book = editDto;
            output.BookTags = allbookTag;

            return output;
        }

19 View Source File : SubscriberWorker.cs
License : MIT License
Project Creator : ad313

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            Console.WriteLine($"{DateTime.Now} ----------------------------------------");

            foreach (var channel in AopSubscriberAttribute.ChannelList)
            {
                Console.WriteLine($"{DateTime.Now} AopCache:生产者频道:{channel}");

                var methodList = AopSubscriberAttribute.MethodList.Where(d =>
                    d.GetCustomAttributes<AopSubscriberAttribute>().ToList().Exists(t => t.Channel == channel)).ToList();

                var subscribers = new List<(AopCacheAttribute, AopSubscriberAttribute)>();

                foreach (var method in methodList)
                {
                    var cacheAttribute = method.GetCustomAttribute<AopCacheAttribute>();
                    if (cacheAttribute == null)
                        continue;

                    Console.WriteLine($"{DateTime.Now} AopCache:消费者订阅方法:{method.DeclaringType?.FullName}.{method.Name}");

                    var subscriberTag = method.GetCustomAttributes<AopSubscriberAttribute>().First(d => d.Channel == channel);

                    subscribers.Add((cacheAttribute, subscriberTag));
                }

                ChannelSubscribersDictionary.Add(channel, subscribers);

                Console.WriteLine($"{DateTime.Now} ----------------------------------------");
            }

            //开始订阅
            foreach (var keyValuePair in ChannelSubscribersDictionary)
            {
                _eventBusProvider.Subscribe<Dictionary<string, object>>(keyValuePair.Key, msg =>
                {
                    foreach ((AopCacheAttribute cache, AopSubscriberAttribute sub) item in keyValuePair.Value)
                    {
                        var cacheAttribute = item.cache;
                        var subscriberTag = item.sub;

                        switch (subscriberTag.ActionType)
                        {
                            case ActionType.DeleteByKey:

                                var key = subscriberTag.GetKey(cacheAttribute.Key, msg.Data);
                                key = cacheAttribute.FormatPrefix(key);
                                _cacheProvider.Remove(key);
                                Console.WriteLine($"{DateTime.Now} Key:{msg.Key}:清除缓存:{key}");
                                break;
                            //case ActionType.DeleteByGroup:
                            //    break;
                            default:
                                throw new ArgumentOutOfRangeException();
                        }
                    }
                }, true);
            }

            await Task.CompletedTask;
        }

19 View Source File : PostProcessLayer.cs
License : MIT License
Project Creator : alelievr

void UpdateBundleSortList(List<SerializedBundleRef> sortedList, PostProcessEvent evt)
        {
            // First get all effects replacedociated with the injection point
            var effects = m_Bundles.Where(kvp => kvp.Value.attribute.eventType == evt && !kvp.Value.attribute.builtinEffect)
                                   .Select(kvp => kvp.Value)
                                   .ToList();

            // Remove types that don't exist anymore
            sortedList.RemoveAll(x =>
            {
                string searchStr = x.replacedemblyQualifiedName;
                return !effects.Exists(b => b.settings.GetType().replacedemblyQualifiedName == searchStr);
            });

            // Add new ones
            foreach (var effect in effects)
            {
                string typeName = effect.settings.GetType().replacedemblyQualifiedName;

                if (!sortedList.Exists(b => b.replacedemblyQualifiedName == typeName))
                {
                    var sbr = new SerializedBundleRef { replacedemblyQualifiedName = typeName };
                    sortedList.Add(sbr);
                }
            }

            // Link internal references
            foreach (var effect in sortedList)
            {
                string typeName = effect.replacedemblyQualifiedName;
                var bundle = effects.Find(b => b.settings.GetType().replacedemblyQualifiedName == typeName);
                effect.bundle = bundle;
            }
        }

See More Examples