System.Collections.Generic.HashSet.Contains(int)

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

808 Examples 7

19 View Source File : MeshSkin.cs
License : MIT License
Project Creator : ansel86castro

unsafe private bool AddTriangleBones(int* indices)
            {
                /*
                * First of all you need to check if all the triangle's bones can be added
                * if the test preplaced then add the 
                */
                int boneCount = 0;
                _tempBonesSet.Clear();

                //First of all you need to check if all the triangle's bones can be added
                for (int k = 0; k < 3; k++)
                {
                    float* bones = GetVertexBones(indices[k]);
                    float* weights = GetVertexWeights(indices[k]);

                    for (int ibone = 0; ibone < 4; ibone++)
                    {
                        //check all the bones 
                        int boneIdx = (int)bones[ibone];
                        if (weights[ibone] > 0 && _boneLookup[boneIdx] < 0 && !_tempBonesSet.Contains(boneIdx))
                        {
                            boneCount++;
                            //if the bones is valid and its not in the layer check if there is space for it
                            if (_layerBonesCount + boneCount > _maxPalleteEntries)
                                return false;

                            //add the bone to the layer                        
                            _tempBonesSet.Add(boneIdx);
                        }
                    }
                }
                return true;
            }

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

public void Render(Rect rect, IEnumerable<T> itemList, float elementHeight = 20f, float elementPadding = 1f)
        {
            var totalElementHeight = elementHeight + elementPadding;
            var width = rect.width;
            var height = rect.height;

            if (!object.ReferenceEquals(itemList, _itemList))
            {
                _itemList = itemList;
                _filteredList = null;
            }

            GUI.BeginGroup(rect);

            // Search Field
            var searchFieldRect = new Rect(5f, 5f, width - 25f, elementHeight);
            var lastSearchString = _searchString;
            GUI.SetNextControlName("Apex_ListView_Search");
            _searchString = EditorGUI.TextField(searchFieldRect, _searchString, SharedStyles.BuiltIn.searchFieldStyle);
            EditorGUI.FocusTextInControl("Apex_ListView_Search");

            var searchCancelRect = new Rect(searchFieldRect.x + searchFieldRect.width, 5f, 10f, elementHeight);
            if (GUI.Button(searchCancelRect, GUIContent.none, string.IsNullOrEmpty(_searchString) ? SharedStyles.BuiltIn.searchCancelButtonEmpty : SharedStyles.BuiltIn.searchCancelButton))
            {
                _searchString = string.Empty;
                GUIUtility.keyboardControl = 0;
            }

            // filter list based on search string
            if (_filteredList == null || !string.Equals(lastSearchString, _searchString, StringComparison.OrdinalIgnoreCase))
            {
                if (string.IsNullOrEmpty(_searchString))
                {
                    _filteredList = _itemList as T[];
                    if (_filteredList == null)
                    {
                        _filteredList = _itemList.ToArray();
                    }
                }
                else
                {
                    _filteredList = _itemList.Where(t => _searchPredicate(t, _searchString)).ToArray();
                }

                _selectRangeStart = _selectRangeEnd = -1;
                _selectedIndexes.Clear();
            }

            // Scroll View
            var noneItemAdjust = _allowNoneSelect ? 1 : 0;
            float listStartY = searchFieldRect.y + searchFieldRect.height + 5f;
            var scrollViewRect = new Rect(0f, listStartY, width, height - listStartY);
            var innerScrollView = new Rect(0f, 0f, scrollViewRect.width - 20f, (_filteredList.Length + noneItemAdjust) * totalElementHeight);

            //Do preselect if applicable
            var evt = Event.current;
            if (evt != null && evt.type == EventType.Repaint && _selectPredicate != null)
            {
                _selectedIndexes.AddRange(_filteredList.Select((item, idx) => _selectPredicate(item) ? idx : -1).Where(idx => idx >= 0));
                if (_selectedIndexes.Count > 0)
                {
                    _selectRangeStart = _selectRangeEnd = _selectedIndexes.Min();
                    EnsureInView(_selectRangeStart, totalElementHeight, scrollViewRect.height);
                }

                _selectPredicate = null;
            }

            _scrollPos = GUI.BeginScrollView(scrollViewRect, _scrollPos, innerScrollView);

            // Element List
            int startIdx = Math.Max(Mathf.FloorToInt(_scrollPos.y / totalElementHeight) - noneItemAdjust, 0);
            int endIdx = Math.Min(startIdx + Mathf.CeilToInt(Mathf.Min(scrollViewRect.height, innerScrollView.height) / totalElementHeight), _filteredList.Length);

            if (_allowNoneSelect && _scrollPos.y < totalElementHeight)
            {
                var itemRect = new Rect(2f, 0f, innerScrollView.width, elementHeight);

                var style = _noneSelected ? SharedStyles.BuiltIn.objectSelectorBoxActive : SharedStyles.BuiltIn.objectSelectorBoxNormal;
                GUI.Box(itemRect, "None", style);
            }

            var currentY = (startIdx + noneItemAdjust) * totalElementHeight;
            for (var i = startIdx; i < endIdx; i++)
            {
                var item = _filteredList[i];
                var itemRect = new Rect(2f, currentY, innerScrollView.width, elementHeight);

                var style = _selectedIndexes.Contains(i) ? SharedStyles.BuiltIn.objectSelectorBoxActive : SharedStyles.BuiltIn.objectSelectorBoxNormal;
                GUI.Box(itemRect, _itemRenderer(item), style);

                currentY += totalElementHeight;
            }

            GUI.EndScrollView();

            //Handle mouse clicks and key presses
            if (evt.type == EventType.MouseDown && evt.button == MouseButton.left)
            {
                evt.Use();
                float adjustedMouseY = evt.mousePosition.y + (_scrollPos.y - listStartY);
                var index = Mathf.FloorToInt(adjustedMouseY / totalElementHeight) - noneItemAdjust;

                if (_allowNoneSelect && index < 0)
                {
                    SelectNone();
                }
                else if (_allowMultiSelect)
                {
                    if (evt.command || evt.control)
                    {
                        SingleToggle(index);
                    }
                    else if (evt.shift)
                    {
                        RangeSelect(index);
                    }
                    else
                    {
                        SingleSelect(index);
                    }
                }
                else
                {
                    SingleSelect(index);
                }

                //We allow double-click selection under all cirreplacedstances
                _singleSelected = (_onSelect != null) && (evt.clickCount == 2) && (_selectedIndexes.Count == 1 || _noneSelected);
                if (!_singleSelected)
                {
                    _owner.Repaint();
                }
            }
            else if (evt.type == EventType.MouseUp && evt.button == MouseButton.left)
            {
                evt.Use();

                if (_singleSelected)
                {
                    // double click detected
                    DoSelect();
                }
            }
            else if (evt.type == EventType.KeyUp)
            {
                if (evt.keyCode == KeyCode.DownArrow)
                {
                    evt.Use();

                    if (_selectRangeStart < 0 && _allowNoneSelect && !_noneSelected)
                    {
                        SelectNone();
                    }
                    else if (_allowMultiSelect && evt.shift)
                    {
                        RangeSelect(_selectRangeEnd + 1);
                    }
                    else
                    {
                        SingleSelect(_selectRangeStart + 1);
                    }

                    EnsureInView(_selectRangeEnd, totalElementHeight, scrollViewRect.height);
                }
                else if (evt.keyCode == KeyCode.UpArrow)
                {
                    evt.Use();

                    if (_selectRangeStart == 0 && _selectRangeEnd == 0 && _allowNoneSelect)
                    {
                        SelectNone();
                    }
                    else if (_selectRangeEnd < 0 && !_noneSelected)
                    {
                        SingleSelect(_filteredList.Length - 1);
                    }
                    else if (_allowMultiSelect && evt.shift)
                    {
                        RangeSelect(_selectRangeEnd - 1);
                    }
                    else
                    {
                        SingleSelect(_selectRangeStart - 1);
                    }

                    EnsureInView(_selectRangeStart, totalElementHeight, scrollViewRect.height);
                }
                else if (evt.keyCode == KeyCode.A && (evt.control || evt.command))
                {
                    evt.Use();
                    _noneSelected = false;
                    AddSelected(0, _filteredList.Length - 1);
                }
                else if (evt.keyCode == KeyCode.Return || evt.keyCode == KeyCode.KeypadEnter)
                {
                    evt.Use();

                    if (_onSelect != null && (_selectedIndexes.Count > 0 || _noneSelected))
                    {
                        DoSelect();
                    }
                }
            }

            GUI.EndGroup();
        }

19 View Source File : Fixture.cs
License : MIT License
Project Creator : Alan-FGR

public void IgnoreCollisionWith(Fixture fixture)
        {
            if (!_collisionIgnores.Contains(fixture.FixtureId))
            {
                _collisionIgnores.Add(fixture.FixtureId);
                Refilter();
            }
        }

19 View Source File : RemoveSurfaceVertices.cs
License : MIT License
Project Creator : anderm

private IEnumerator RemoveSurfaceVerticesWithinBoundsRoutine()
        {
            List<MeshFilter> meshFilters = SpatialMappingManager.Instance.GetMeshFilters();
            float start = Time.realtimeSinceStartup;

            while (boundingObjectsQueue.Count > 0)
            {
                // Get the current boundingObject.
                Bounds bounds = boundingObjectsQueue.Dequeue();

                foreach (MeshFilter filter in meshFilters)
                {
                    // Since this is amortized across frames, the filter can be destroyed by the time
                    // we get here.
                    if (filter == null)
                    {
                        continue;
                    }

                    Mesh mesh = filter.sharedMesh;
                    MeshRenderer meshRenderer = filter.GetComponent<MeshRenderer>();
                    
                    // The mesh renderer bounds are in world space.
                    // If the mesh is null there is nothing to process
                    // If the renderer is null we can't get the renderer bounds
                    // If the renderer's bounds aren't contained inside of the current
                    // bounds from the bounds queue there is no reason to process
                    // If any of the above conditions are met, then we should go to the next meshfilter. 
                    if (mesh == null || meshRenderer == null || !meshRenderer.bounds.Intersects(bounds))
                    {
                        // We don't need to do anything to this mesh, move to the next one.
                        continue;
                    }

                    // Remove vertices from any mesh that intersects with the bounds.
                    Vector3[] verts = mesh.vertices;
                    HashSet<int> vertsToRemove = new HashSet<int>();

                    // Find which mesh vertices are within the bounds.
                    for (int i = 0; i < verts.Length; ++i)
                    {
                        if (bounds.Contains(filter.transform.TransformPoint(verts[i])))
                        {
                            // These vertices are within bounds, so mark them for removal.
                            vertsToRemove.Add(i);
                        }

                        // If too much time has preplaceded, we need to return control to the main game loop.
                        if ((Time.realtimeSinceStartup - start) > FrameTime)
                        {
                            // Pause our work here, and continue finding vertices to remove on the next frame.
                            yield return null;
                            start = Time.realtimeSinceStartup;
                        }
                    }

                    if (vertsToRemove.Count == 0)
                    {
                        // We did not find any vertices to remove, so move to the next mesh.
                        continue;
                    }

                    // We found vertices to remove, so now we need to remove any triangles that reference these vertices.
                    int[] indices = mesh.GetTriangles(0);
                    List<int> updatedIndices = new List<int>();

                    for (int index = 0; index < indices.Length; index += 3)
                    {
                        // Each triangle utilizes three slots in the index buffer, check to see if any of the
                        // triangle indices contain a vertex that should be removed.
                        if (vertsToRemove.Contains(indices[index]) ||
                            vertsToRemove.Contains(indices[index + 1]) ||
                            vertsToRemove.Contains(indices[index + 2]))
                        {
                            // Do nothing, we don't want to save this triangle...
                        }
                        else
                        {
                            // Every vertex in this triangle is good, so let's save it.
                            updatedIndices.Add(indices[index]);
                            updatedIndices.Add(indices[index + 1]);
                            updatedIndices.Add(indices[index + 2]);
                        }

                        // If too much time has preplaceded, we need to return control to the main game loop.
                        if ((Time.realtimeSinceStartup - start) > FrameTime)
                        {
                            // Pause our work, and continue making additional planes on the next frame.
                            yield return null;
                            start = Time.realtimeSinceStartup;
                        }
                    }

                    if (indices.Length == updatedIndices.Count)
                    {
                        // None of the verts to remove were being referenced in the triangle list.
                        continue;
                    }

                    // Update mesh to use the new triangles.
                    mesh.SetTriangles(updatedIndices.ToArray(), 0);
                    mesh.RecalculateBounds();
                    yield return null;
                    start = Time.realtimeSinceStartup;

                    // Reset the mesh collider to fit the new mesh.
                    MeshCollider meshCollider = filter.gameObject.GetComponent<MeshCollider>();
                    if (meshCollider != null)
                    {
                        meshCollider.sharedMesh = null;
                        meshCollider.sharedMesh = mesh;
                    }
                }
            }

            Debug.Log("Finished removing vertices.");

            // We are done removing vertices, trigger an event.
            EventHandler handler = RemoveVerticesComplete;
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }

            removingVerts = false;
        }

19 View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna

public List<Block> GetStoredAndNewBlocks(Block newBlock)
        {
            var list = new List<Block>(storedBlocks.Count + 1);
            list.AddRange(storedBlocks);

            if (storedBlockIndices.Contains(newBlock.Index) is false)
                list.Add(newBlock);

            list.Sort((a, b) => a.Index - b.Index);

            return list;
        }

19 View Source File : ChunkData.cs
License : The Unlicense
Project Creator : aeroson

static Vector3[] RecalculateNormals(ref NativeArray<Vector3> vertices, int[] triangleIndicies, Vector2[] uvs, HashSet<int> ignoreIndicies = null)
	{
		int verticesNum = vertices.Length;
		int indiciesNum = triangleIndicies.Length;

		var outNormals = new Vector3[verticesNum];
		int[] counts = new int[verticesNum];

		for (int i = 0; i <= indiciesNum - 3; i += 3)
		{
			int ai = triangleIndicies[i];
			int bi = triangleIndicies[i + 1];
			int ci = triangleIndicies[i + 2];

			if (ai < verticesNum && bi < verticesNum && ci < verticesNum)
			{
				if (ignoreIndicies != null && (ignoreIndicies.Contains(ai) || ignoreIndicies.Contains(bi) || ignoreIndicies.Contains(ci))) continue;

				Vector3 av = vertices[ai];
				Vector3 n = Vector3.Normalize(Vector3.Cross(
					vertices[bi] - av,
					vertices[ci] - av
				));

				outNormals[ai] += n;
				outNormals[bi] += n;
				outNormals[ci] += n;

				counts[ai]++;
				counts[bi]++;
				counts[ci]++;
			}
		}

		for (int i = 0; i < verticesNum; i++)
		{
			outNormals[i] /= counts[i];
		}

		return outNormals;
	}

19 View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett

public int RemoveUnderlining(Database database)
        {
            if (database == null)
            {
                throw new ArgumentNullException(nameof(database));
            }

            if (!database.Notes.Any())
            {
                var count = database.UserMarks.Count;
                database.UserMarks.Clear();
                return count;
            }

            // we must retain user marks that are replacedociated with notes...
            HashSet<int> userMarksToRetain = new HashSet<int>();
            foreach (var note in database.Notes)
            {
                if (note.UserMarkId != null)
                {
                    userMarksToRetain.Add(note.UserMarkId.Value);
                }
            }

            var countRemoved = 0;
            foreach (var userMark in Enumerable.Reverse(database.UserMarks))
            {
                if (!userMarksToRetain.Contains(userMark.UserMarkId))
                {
                    database.UserMarks.Remove(userMark);
                    ++countRemoved;
                }
            }

            return countRemoved;
        }

public static List<PropertiesEnchantmentRegistry> GetEnchantmentsTopLayerByStatModType(this ICollection<PropertiesEnchantmentRegistry> value, EnchantmentTypeFlags statModType, ReaderWriterLockSlim rwLock, HashSet<int> setSpells)
        {
            if (value == null)
                return null;

            rwLock.EnterReadLock();
            try
            {
                var valuesByStatModType = value.Where(e => (e.StatModType & statModType) == statModType);

                var results = from e in valuesByStatModType
                    group e by e.SpellCategory
                    into categories
                    //select categories.OrderByDescending(c => c.LayerId).First();
                    select categories.OrderByDescending(c => c.PowerLevel)
                        .ThenByDescending(c => Level8AuraSelfSpells.Contains(c.SpellId))
                        .ThenByDescending(c => setSpells.Contains(c.SpellId) ? c.SpellId : c.StartTime).First();

                return results.ToList();
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

19 View Source File : PhotonViewHandler.cs
License : MIT License
Project Creator : ArcturusZhang

internal static void HierarchyChange()
		{
			if (Application.isPlaying)
			{
				//Debug.Log("HierarchyChange ignored, while running.");
				CheckSceneForStuckHandlers = true;  // done once AFTER play mode.
				return;
			}

			if (CheckSceneForStuckHandlers)
			{
				CheckSceneForStuckHandlers = false;
				PhotonNetwork.InternalCleanPhotonMonoFromSceneIfStuck();
			}

			HashSet<PhotonView> pvInstances = new HashSet<PhotonView>();
			HashSet<int> usedInstanceViewNumbers = new HashSet<int>();
			bool fixedSomeId = false;

			//// the following code would be an option if we only checked scene objects (but we can check all PVs)
			//PhotonView[] pvObjects = GameObject.FindSceneObjectsOfType(typeof(PhotonView)) as PhotonView[];
			//Debug.Log("HierarchyChange. PV Count: " + pvObjects.Length);

			string levelName = SceneManagerHelper.ActiveSceneName;
			#if UNITY_EDITOR
			levelName = SceneManagerHelper.EditorActiveSceneName;
			#endif
			int minViewIdInThisScene = PunSceneSettings.MinViewIdForScene(levelName);
			//Debug.Log("Level '" + Application.loadedLevelName + "' has a minimum ViewId of: " + minViewIdInThisScene);

			PhotonView[] pvObjects = Resources.FindObjectsOfTypeAll(typeof(PhotonView)) as PhotonView[];

			foreach (PhotonView view in pvObjects)
			{
		
				// first preplaced: fix prefabs to viewID 0 if they got a view number replacedigned (cause they should not have one!)
				if (PhotonEditorUtils.IsPrefab(view.gameObject))
				{
					if (view.ViewID != 0 || view.prefixField != -1)
					{
						#if !UNITY_2018_3_OR_NEWER
							Debug.LogWarning("PhotonView on persistent object being fixed (id and prefix must be 0). Was: " + view);
						#endif
						view.ViewID = 0;
						view.prefixField = -1;
						EditorUtility.SetDirty(view);   // even in Unity 5.3+ it's OK to SetDirty() for non-scene objects.
						fixedSomeId = true;
					}
				}
				else
				{
					// keep all scene-instanced PVs for later re-check
					pvInstances.Add(view);
				}
			}

			Dictionary<GameObject, int> idPerObject = new Dictionary<GameObject, int>();

			// second preplaced: check all used-in-scene viewIDs for duplicate viewIDs (only checking anything non-prefab)
			// scene-PVs must have user == 0 (scene/room) and a subId != 0
			foreach (PhotonView view in pvInstances)
			{
				if (view.OwnerActorNr > 0)
				{
					Debug.Log("Re-Setting Owner ID of: " + view);
				}

				view.Prefix = -1;   // TODO: prefix could be settable via inspector per scene?!

				if (view.ViewID != 0)
				{
					if (view.ViewID < minViewIdInThisScene || usedInstanceViewNumbers.Contains(view.ViewID))
					{
						view.ViewID = 0; // avoid duplicates and negative values by replacedigning 0 as (temporary) number to be fixed in next preplaced
					}
					else
					{
						usedInstanceViewNumbers.Add(view.ViewID); // builds a list of currently used viewIDs

						int instId = 0;
						if (idPerObject.TryGetValue(view.gameObject, out instId))
						{
							view.InstantiationId = instId;
						}
						else
						{
							view.InstantiationId = view.ViewID;
							idPerObject[view.gameObject] = view.InstantiationId;
						}
					}
				}

			}

			// third preplaced: anything that's now 0 must get a new (not yet used) ID (starting at 0)
			int lastUsedId = (minViewIdInThisScene > 0) ? minViewIdInThisScene - 1 : 0;

			foreach (PhotonView view in pvInstances)
			{
				if (view.ViewID == 0)
				{
					Undo.RecordObject(view, "Automatic viewID change for: "+view.gameObject.name);

					// Debug.LogWarning("setting scene ID: " + view.gameObject.name + " ID: " + view.subId.ID + " scene ID: " + view.GetSceneID() + " IsPersistent: " + EditorUtility.IsPersistent(view.gameObject) + " IsSceneViewIDFree: " + IsSceneViewIDFree(view.subId.ID, view));
					int nextViewId = PhotonViewHandler.GetID(lastUsedId, usedInstanceViewNumbers);

					view.ViewID = nextViewId;

					int instId = 0;
					if (idPerObject.TryGetValue(view.gameObject, out instId))
					{
						view.InstantiationId = instId;
					}
					else
					{
						view.InstantiationId = view.ViewID;
						idPerObject[view.gameObject] = nextViewId;
					}

					lastUsedId = nextViewId;
					fixedSomeId = true;
				}
			}


			if (fixedSomeId)
			{
				//Debug.LogWarning("Some subId was adjusted."); // this log is only interesting for Exit Games
			}
		}

19 View Source File : LootGenerationFactory_Rare.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static int GetRareTier(uint rareWCID)
        {
            var wcid = (int)rareWCID;

            foreach (var kvp in RareWCIDs)
                if (kvp.Value.Contains(wcid))
                    return kvp.Key;

            return 0;
        }

19 View Source File : InstructorsController.cs
License : MIT License
Project Creator : alimon808

private void PopulatereplacedignedCourseData(Instructor instructor)
        {
            var allCourses = _courseRepo.GetAll();
            var instructorCourses = new HashSet<int>(instructor.Coursereplacedignments.Select(c => c.CourseID));
            var viewModel = new List<replacedignedCourseData>();
            foreach (var course in allCourses)
            {
                viewModel.Add(new replacedignedCourseData
                {
                    CourseID = course.ID,
                    replacedle = course.replacedle,
                    replacedigned = instructorCourses.Contains(course.ID)
                });
            }
            ViewData["Courses"] = viewModel;
        }

19 View Source File : _217_ContainsDuplicate.cs
License : MIT License
Project Creator : AlexChesser

public bool ContainsDuplicate(int[] nums)
        {
            HashSet<int> dupeCheck = new HashSet<int>();
            for (int i = 0; i < nums.Length; i++)
            {
                if (dupeCheck.Contains(nums[i]))
                {
                    return true;
                }
                dupeCheck.Add(nums[i]);
            }
            return false;
        }

19 View Source File : Client.cs
License : MIT License
Project Creator : Aerion

private JsonElement DeserializeJsonElementFromStream(Stream stream)
        {
            using var sr = new StreamReader(stream);
            var strData = sr.ReadToEnd();
            DebugWriteLine($"Deserialized data: {strData}");
            var data = JsonSerializer.Deserialize<ResponseBase>(strData, JsonSerializerOptions);

            if (InvalidStatusCodes.Contains(data.StatusCode))
            {
                throw new ClientException(data.Data.GetString());
            }

            return data.Data;
        }

19 View Source File : MultiSearchMerger.cs
License : Apache License 2.0
Project Creator : AnkiUniversal

private List<MergeBuilder> MergeStep(List<MergeBuilder> builders, List<MultiSearchResult> results, int currentIndex)
        {
            MultiSearchResult nextResult = results[currentIndex];
            PriorityQueue<MergePair> pairHeap = new PriorityQueue<MergePair>();
            List<MergeBuilder> ret = new List<MultiSearchMerger.MergeBuilder>();

            if ((builders.Count == 0) || (nextResult.Count == 0))
            {
                return ret;
            }

            pairHeap.Add(new MergePair(0, 0, builders[0].Cost + nextResult.GetCost(0)));

            HashSet<int> visited = new HashSet<int>();

            while (ret.Count < maxCount && pairHeap.Count > 0)
            {
                MergePair top = pairHeap.Poll();

                if (GetCostLowerBound(top.Cost, currentIndex) - baseCost > costSlack)
                {
                    break;
                }

                int i = top.LeftIndex;
                int j = top.RightIndex;

                MergeBuilder nextBuilder = new MergeBuilder(results, builders[i].Indices);
                nextBuilder.Add(j);
                ret.Add(nextBuilder);

                if (i + 1 < builders.Count)
                {
                    MergePair newMergePair = new MergePair(i + 1, j, builders[i + 1].Cost + nextResult.GetCost(j));
                    int positionValue = GetPositionValue(i + 1, j);
                    if (!visited.Contains(positionValue))
                    {
                        pairHeap.Add(newMergePair);
                        visited.Add(positionValue);
                    }
                }
                if (j + 1 < nextResult.Count)
                {
                    MergePair newMergePair = new MergePair(i, j + 1, builders[i].Cost + nextResult.GetCost(j + 1));
                    int positionValue = GetPositionValue(i, j + 1);
                    if (!visited.Contains(positionValue))
                    {
                        pairHeap.Add(newMergePair);
                        visited.Add(positionValue);
                    }
                }
            }

            return ret;
        }

19 View Source File : BiotaExtensions.cs
License : GNU Affero General Public License v3.0
Project Creator : ACEmulator

public static Dictionary<int, float> GetMatchingSpells(this Biota biota, HashSet<int> match, ReaderWriterLockSlim rwLock)
        {
            if (biota.PropertiesSpellBook == null)
                return new Dictionary<int, float>();

            rwLock.EnterReadLock();
            try
            {
                var results = new Dictionary<int, float>();

                foreach (var value in biota.PropertiesSpellBook)
                {
                    if (match.Contains(value.Key))
                        results[value.Key] = value.Value;
                }

                return results;
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

19 View Source File : Cleaner.cs
License : MIT License
Project Creator : AntonyCorbett

private int CleanLocations()
        {
            int removed = 0;
            
            var locations = _database.Locations;
            if (locations.Any())
            {
                var locationIds = GetLocationIdsInUse();

                foreach (var location in Enumerable.Reverse(locations))
                {
                    if (!locationIds.Contains(location.LocationId))
                    {
                        Log.Logger.Debug($"Removing redundant location id: {location.LocationId}");
                        locations.Remove(location);
                        ++removed;
                    }
                }
            }

            return removed;
        }

19 View Source File : AtomicQueues.cs
License : MIT License
Project Creator : aksyr

[Test]
    [TestCase(AllocationMode.Ephemeral)]
    [TestCase(AllocationMode.Pooled)]
    public void PreservesItems(AllocationMode allocationMode)
    {
        using (var queue = AtomicQueue<int>.Create(allocationMode))
        {
            var count = 0;
            var items = new HashSet<int>();
            var threads = new List<Thread>();

            for (int i = 0; i < kWorkerCount; ++i)
            {
                var thread = new Thread((o) =>
                {
                    var item = Interlocked.Increment(ref count);
                    queue.Enqueue((int*)item);
                });
                items.Add(i + 1);
                thread.Start();
                threads.Add(thread);
            }

            foreach (var thread in threads)
                thread.Join();
            replacedert.That(!queue.IsEmpty);

            for (int i = 0; i < kWorkerCount; ++i)
            {
                var item = (int)queue.Dequeue();
                replacedert.That(items.Contains(item), $"Missing item {item} (iteration {i})");
                items.Remove(item);
            }

            replacedert.That(queue.IsEmpty);
            replacedert.That(items.Count == 0);
        }
    }

19 View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett

private static int RemoveUnderlining(Database database, HashSet<int> userMarkIdsToRemove, bool removereplacedociatedNotes)
        {
            var noteIdsToRemove = new HashSet<int>();
            var tagMapIdsToRemove = new HashSet<int>();

            if (userMarkIdsToRemove.Any())
            {
                foreach (var note in database.Notes)
                {
                    if (note.UserMarkId == null)
                    {
                        continue;
                    }

                    if (userMarkIdsToRemove.Contains(note.UserMarkId.Value))
                    {
                        if (removereplacedociatedNotes)
                        {
                            noteIdsToRemove.Add(note.NoteId);
                        }
                        else
                        {
                            note.UserMarkId = null;
                        }
                    }
                }

                foreach (var tagMap in database.TagMaps)
                {
                    if (tagMap.NoteId == null)
                    {
                        continue;
                    }

                    if (noteIdsToRemove.Contains(tagMap.NoteId.Value))
                    {
                        tagMapIdsToRemove.Add(tagMap.TagMapId);
                    }
                }
            }

            database.UserMarks.RemoveAll(x => userMarkIdsToRemove.Contains(x.UserMarkId));
            database.Notes.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId));
            database.TagMaps.RemoveAll(x => tagMapIdsToRemove.Contains(x.TagMapId));

            return userMarkIdsToRemove.Count;
        }

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

public static bool GetKeyDown(KeyBinding kb)
        {
            if (kb.TryGetMouseButton(out int mouseButton))
            {
                if (isSimulated)
                    return SimulatedMouseDownSet.Contains(mouseButton);
                else
                    return UnityEngine.Input.GetMouseButtonDown(mouseButton);
            }
            if (kb.TryGetKeyCode(out KeyCode keyCode))
            {
                if (isSimulated)
                    return SimulatedKeyDownSet.Contains(keyCode);
                else
                    return UnityEngine.Input.GetKeyDown(keyCode);
            }
            return false;
        }

19 View Source File : APILegality.cs
License : MIT License
Project Creator : architdate

public static void ValidateGender(PKM pkm)
        {
            bool genderValid = pkm.IsGenderValid();
            if (!genderValid)
            {
                if (pkm.Format == 4 && pkm.Species == 292) // Shedinja glitch
                {
                    // should match original gender
                    var gender = PKX.GetGenderFromPIDAndRatio(pkm.PID, 0x7F); // 50-50
                    if (gender == pkm.Gender)
                        genderValid = true;
                }
                else if (pkm.Format > 5 && (pkm.Species == 183 || pkm.Species == 184))
                {
                    var gv = pkm.PID & 0xFF;
                    if (gv > 63 && pkm.Gender == 1) // evolved from azurill after transferring to keep gender
                        genderValid = true;
                }
            }
            else
            {
                // check for mixed->fixed gender incompatibility by checking the gender of the original species
                if (new HashSet<int>{290, 292, 412, 413, 414, 280, 475, 361, 478, 677, 678}.Contains(pkm.Species) && pkm.Gender != 2) // shedinja
                {
                    var gender = PKX.GetGenderFromPID(new LegalInfo(pkm).EncounterMatch.Species, pkm.EncryptionConstant);
                    pkm.Gender = gender;
                    genderValid = true;
                }
            }

            if (genderValid)
                return;
            else
            {
                if (pkm.Gender == 0) pkm.Gender = 1;
                else if (pkm.Gender == 1) pkm.Gender = 0;
                else pkm.GetSaneGender();
            }
        }

19 View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna

public void StoreReceivedBlocks(Block block)
        {
            if (storedBlockIndices.Contains(block.Index))
                return;

            storedBlockIndices.Add(block.Index);
            storedBlocks.Add(block);
        }

19 View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna

public void StoreReceivedBlocks(IList<Block> blocks)
        {
            for (int i = 0, c = blocks.Count; i < c; ++i)
            {
                var block = blocks[i];
                if (storedBlockIndices.Contains(block.Index))
                    continue;

                storedBlockIndices.Add(block.Index);
                storedBlocks.Add(block);
            }
        }

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

public static bool GetKeyUp(KeyBinding kb)
        {
            if (kb.TryGetMouseButton(out int mouseButton))
            {
                if (isSimulated)
                    return SimulatedMouseUpSet.Contains(mouseButton);
                else
                    return UnityEngine.Input.GetMouseButtonUp(mouseButton);
            }
            if (kb.TryGetKeyCode(out KeyCode keyCode))
            {
                if (isSimulated)
                    return SimulatedKeyUpSet.Contains(keyCode);
                else
                    return UnityEngine.Input.GetKeyUp(keyCode);
            }
            return false;
        }

19 View Source File : Context.cs
License : MIT License
Project Creator : alexanderdna

public List<Block> GetStoredAndNewBlocks(IList<Block> newBlocks)
        {
            var list = new List<Block>(storedBlocks.Count + newBlocks.Count);
            list.AddRange(storedBlocks);

            for (int i = 0, c = newBlocks.Count; i < c; ++i)
            {
                var block = newBlocks[i];
                if (storedBlockIndices.Contains(block.Index))
                    continue;

                list.Add(block);
            }
            list.Sort((a, b) => a.Index - b.Index);

            return list;
        }

19 View Source File : KeyboardHookManager.cs
License : MIT License
Project Creator : adainrivers

private async Task HandleSingleKeyboardInput(object keyboardParamsObj)
        {
            var keyboardParams = (KeyboardParams)keyboardParamsObj;
            var wParam = keyboardParams.wParam;
            var vkCode = keyboardParams.vkCode;

            var modifierKey = ModifierKeysUtilities.GetModifierKeyFromCode(vkCode);

            // If the keyboard event is a KeyDown event (i.e. key pressed)
            if (wParam == (IntPtr)WM_KEYDOWN || wParam == (IntPtr)WM_SYSKEYDOWN)
            {
                // In this case, we only care about modifier keys
                if (modifierKey != null)
                {
                    lock (_modifiersLock)
                    {
                        _downModifierKeys.Add(modifierKey.Value);
                    }
                }

                // Trigger callbacks that are registered for this key, but only once per key press
                if (!_downKeys.Contains(vkCode))
                {
                    _downKeys.Add(vkCode);
                }
            }

            // If the keyboard event is a KeyUp event (i.e. key released)
            if (wParam == (IntPtr)WM_KEYUP || wParam == (IntPtr)WM_SYSKEYUP)
            {
                await HandleKeyPress(vkCode);
                // If the released key is a modifier key, remove it from the HashSet of modifier keys
                if (modifierKey != null)
                {
                    lock (_modifiersLock)
                    {
                        _downModifierKeys.Remove(modifierKey.Value);
                    }
                }

                _downKeys.Remove(vkCode);
            }
        }

19 View Source File : InstructorsController.cs
License : MIT License
Project Creator : alimon808

private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate)
        {
            if (selectedCourses == null)
            {
                instructorToUpdate.Coursereplacedignments = new List<Coursereplacedignment>();
                return;
            }

            var selectedCoursesHS = new HashSet<string>(selectedCourses);
            var instructorCourses = new HashSet<int>(instructorToUpdate.Coursereplacedignments.Select(c => c.Course.ID));
            foreach (var course in _courseRepo.GetAll())
            {
                if (selectedCoursesHS.Contains(course.ID.ToString()))
                {
                    if (!instructorCourses.Contains(course.ID))
                    {
                        instructorToUpdate.Coursereplacedignments.Add(new Coursereplacedignment { InstructorID = instructorToUpdate.ID, CourseID = course.ID });
                    }
                }
                else
                {
                    if (instructorCourses.Contains(course.ID))
                    {
                        Coursereplacedignment courseToRemove = instructorToUpdate.Coursereplacedignments.SingleOrDefault(i => i.CourseID == course.ID);
                        _coursereplacedignmentRepo.Delete(courseToRemove);
                    }
                }
            }
        }

19 View Source File : CommandLineAnalyzer.cs
License : MIT License
Project Creator : AlexGhiondea

private static void ValidateArguments(List<Argument> args, SymbolreplacedysisContext context)
        {
            HashSet<string> namesOfAllArgs = new HashSet<string>();
            HashSet<int> positionsOrRequiredArgs = new HashSet<int>();
            int numberOfPositionalArgs = 0;
            int indexOfCollectionArg = -1;
            RequiredArgument collectionArg = null;
            foreach (var item in args)
            {
                if (item is OptionalArgument)

                {
                    OptionalArgument oag = item as OptionalArgument;

                    // Validate that the same name is not used across required and optional arguments.
                    if (namesOfAllArgs.Contains(oag.Name))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, oag.Symbol.Locations.First(), oag.Name));
                    }

                    namesOfAllArgs.Add(oag.Name);
                }
                else if (item is RequiredArgument)
                {
                    RequiredArgument rag = item as RequiredArgument;
                    numberOfPositionalArgs++;

                    // Validate that the same position is not used twice 
                    if (positionsOrRequiredArgs.Contains(rag.Position))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DuplicatePositionalArgumentPositionRule, rag.Symbol.Locations.First(), rag.Position));
                    }

                    // Validate that the same name is not used across required and optional arguments.
                    if (namesOfAllArgs.Contains(rag.Name))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, rag.Symbol.Locations.First(), rag.Name));
                    }

                    // is the required collection argument the last one AND do we only have one of them?
                    if (indexOfCollectionArg >= 0 && rag.Position > indexOfCollectionArg)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(OnlyOneRequiredCollection, rag.Symbol.Locations.First(), collectionArg.Name, rag.Name));
                    }

                    // do we have a collection argument specified?
                    if (rag.IsCollection)
                    {
                        indexOfCollectionArg = rag.Position;
                        collectionArg = rag;
                    }

                    namesOfAllArgs.Add(rag.Name);
                    positionsOrRequiredArgs.Add(rag.Position);
                }
            }

            int checkedPositions = 0;
            //validate that the positional arguments are in a continuous sequence, starting at 0
            for (checkedPositions = 0; checkedPositions < numberOfPositionalArgs; checkedPositions++)
            {
                if (!positionsOrRequiredArgs.Contains(checkedPositions))
                {
                    // at this point, we could not find the required positional argument 'i'
                    // we should give the error at the type level.
                    context.ReportDiagnostic(Diagnostic.Create(RequiredPositionalArgumentNotFound, args.First().Symbol.ContainingType.Locations.First(), numberOfPositionalArgs, checkedPositions));
                    break;
                }
            }

            // Ensure that the required collection argument (if present) is last.
            if (indexOfCollectionArg >= 0 && indexOfCollectionArg != numberOfPositionalArgs - 1)
            {
                context.ReportDiagnostic(Diagnostic.Create(CollectionArgumentShouldBeLast, collectionArg.Symbol.Locations.First(), collectionArg.Name));
            }
        }

19 View Source File : CrossChainIndexingDataService.cs
License : MIT License
Project Creator : AElfProject

private async Task<List<SideChainBlockData>> GetNonIndexedSideChainBlockDataAsync(Hash blockHash,
            long blockHeight, HashSet<int> excludeChainIdList)
        {
            var crossChainContractAddress = await GetCrossChainContractAddressAsync(new ChainContext
            {
                BlockHash = blockHash,
                BlockHeight = blockHeight
            });
            var sideChainBlockDataList = new List<SideChainBlockData>();
            var sideChainIndexingInformationList = await _contractReaderFactory
                .Create(new ContractReaderContext
                {
                    BlockHash = blockHash,
                    BlockHeight = blockHeight,
                    ContractAddress = crossChainContractAddress
                })
                .GetSideChainIndexingInformationList.CallAsync(new Empty());
            foreach (var sideChainIndexingInformation in sideChainIndexingInformationList.IndexingInformationList)
            {
                var libDto = await _irreversibleBlockStateProvider.GetLastIrreversibleBlockHashAndHeightAsync();
                var sideChainId = sideChainIndexingInformation.ChainId;
                if (excludeChainIdList.Contains(sideChainId))
                    continue;
                var sideChainHeightInLibValue = await _contractReaderFactory
                    .Create(new ContractReaderContext
                    {
                        BlockHash = libDto.BlockHash,
                        BlockHeight = libDto.BlockHeight,
                        ContractAddress = crossChainContractAddress
                    })
                    .GetSideChainHeight.CallAsync(new Int32Value {Value = sideChainId});

                long toBeIndexedCount;
                long targetHeight;
                var sideChainHeightInLib = sideChainHeightInLibValue?.Value ?? 0;
                if (sideChainHeightInLib > 0)
                {
                    targetHeight = sideChainIndexingInformation.IndexedHeight + 1;
                    toBeIndexedCount = CrossChainConstants.DefaultBlockCacheEnreplacedyCount;
                    Logger.LogDebug(
                        $"Target height {targetHeight} of side chain " +
                        $"{ChainHelper.ConvertChainIdToBase58(sideChainId)}.");
                }
                else if (sideChainIndexingInformation.IndexedHeight > 0)
                {
                    toBeIndexedCount = 0;
                    targetHeight = sideChainIndexingInformation.IndexedHeight + 1;
                }
                else
                {
                    toBeIndexedCount = 1;
                    targetHeight = AElfConstants.GenesisBlockHeight;
                    Logger.LogDebug(
                        $"Target height {targetHeight} of side chain " +
                        $"{ChainHelper.ConvertChainIdToBase58(sideChainId)}.");
                }

                var sideChainBlockDataFromCache = new List<SideChainBlockData>();

                var i = 0;
                while (i < toBeIndexedCount)
                {
                    var sideChainBlockData =
                        _blockCacheEnreplacedyConsumer.Take<SideChainBlockData>(sideChainIndexingInformation.ChainId,
                            targetHeight, targetHeight == AElfConstants.GenesisBlockHeight);
                    if (sideChainBlockData == null || sideChainBlockData.Height != targetHeight)
                    {
                        // no more available side chain block info
                        break;
                    }

                    sideChainBlockDataFromCache.Add(sideChainBlockData);
                    targetHeight++;
                    i++;
                }

                if (sideChainBlockDataFromCache.Count > 0)
                {
                    Logger.LogDebug(
                        $"Got height [{sideChainBlockDataFromCache.First().Height} - {sideChainBlockDataFromCache.Last().Height} ]" +
                        $" from side chain {ChainHelper.ConvertChainIdToBase58(sideChainIndexingInformation.ChainId)}.");
                    sideChainBlockDataList.AddRange(sideChainBlockDataFromCache);
                }
            }

            return sideChainBlockDataList;
        }

19 View Source File : ConvexHullAlgorithm.Initialize.cs
License : Apache License 2.0
Project Creator : allenai

internal void GetConvexHull()
        {
            // accessing a 1D array is quicker than a jagged array, so the first step is to make this array
            SerializeVerticesToPositions();
            // next the bounding box extremes are found. This is used to shift, scale and find the starting simplex.
            FindBoundingBoxPoints();
            // the positions are shifted to avoid divide by zero problems
            // and if Delaunay or Voronoi, then the parabola terms are scaled back to match the size of the other coords
            ShiftAndScalePositions();
            // Find the (dimension+1) initial points and create the simplexes.
            CreateInitialSimplex();

            // Now, the main loop. These initial faces of a simplex are replaced and expanded 
            // outwards to make the convex hull and faces.
            while (UnprocessedFaces.First != null)
            {
                var currentFace = UnprocessedFaces.First;
                CurrentVertex = currentFace.FurthestVertex;

                UpdateCenter();

                // The affected faces get tagged
                TagAffectedFaces(currentFace);

                // Create the cone from the currentVertex and the affected faces horizon.
                if (!SingularVertices.Contains(CurrentVertex) && CreateCone()) CommitCone();
                else HandleSingular();

                // Need to reset the tags
                var count = AffectedFaceBuffer.Count;
                for (var i = 0; i < count; i++) AffectedFaceFlags[AffectedFaceBuffer[i]] = false;
            }
        }

19 View Source File : TabControlHelper.cs
License : MIT License
Project Creator : Accelerider

private static void OnRightToLeftAnimationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TabControl tabControl &&
                !_initializedTabControlSet.Contains(tabControl.GetHashCode()))
            {
                ModifyTabControl(tabControl);
            }
        }

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

public static List<SongMap> Search(string SearchKey)
            {
                if (!DatabaseImported && RequestBotConfig.Instance.LocalSearch )
                {
                    LoadCustomSongs();                  
                }

                List<SongMap> result = new List<SongMap>();

                if (RequestBot.Instance.GetBeatSaverId(SearchKey) != "")
                {
                    SongMap song;
                    if (MapDatabase.MapLibrary.TryGetValue(normalize.RemoveSymbols(ref SearchKey,normalize._SymbolsNoDash), out song))
                    {
                        result.Add(song);
                        return result;
                    }
                }

                List<HashSet<int>> resultlist = new List<HashSet<int>>();

                string[] SearchParts = normalize.Split(SearchKey);

                foreach (var part in SearchParts)
                {
                     HashSet<int>  idset;

                    if (!SearchDictionary.TryGetValue(part, out idset)) return result; // Keyword must be found
                    resultlist.Add(idset);
                }

                // We now have n lists of candidates

                resultlist.Sort((L1, L2) => L1.Count.CompareTo(L2.Count));

                // We now have an optimized query

                // Compute all matches
                foreach (var map in resultlist[0])
                {
                    for (int i = 1; i < resultlist.Count; i++)
                    {
                        if (!resultlist[i].Contains(map)) goto next; // We can't continue from here :(    
                    }


                    try
                    {
                        result.Add(MapDatabase.MapLibrary[map.ToString("x")]);
                    }
                catch
                    {
                        RequestBot.Instance.QueueChatMessage($"map fail = {map}");
                    }

                next:
                    ;
                }

                return result;
            }

19 View Source File : TriangleMeshConvexContactManifold.cs
License : The Unlicense
Project Creator : aeroson

public override void Update(float dt)
        {
            //First, refresh all existing contacts.  This is an incremental manifold.
            var transform = MeshTransform;
            ContactRefresher.ContactRefresh(contacts, supplementData, ref convex.worldTransform, ref transform, contactIndicesToRemove);

            RemoveQueuedContacts();


            CleanUpOverlappingTriangles();
            //Get all the overlapped triangle indices.
            int triangleCount = FindOverlappingTriangles(dt);

            Matrix3x3 orientation;
            Matrix3x3.CreateFromQuaternion(ref convex.worldTransform.Orientation, out orientation);
            var guaranteedContacts = 0;
            for (int i = 0; i < triangleCount; i++)
            {
                //Initialize the local triangle.
                TriangleIndices indices;
                if (ConfigureTriangle(i, out indices))
                {

                    //Find a pairtester for the triangle.
                    TrianglePairTester pairTester;
                    if (!activePairTesters.TryGetValue(indices, out pairTester))
                    {
                        pairTester = GetTester();
                        pairTester.Initialize(convex.Shape, localTriangleShape);
                        activePairTesters.Add(indices, pairTester);
                    }
                    pairTester.Updated = true;


                    //Put the triangle into the local space of the convex.
                    Vector3.Subtract(ref localTriangleShape.vA, ref convex.worldTransform.Position, out localTriangleShape.vA);
                    Vector3.Subtract(ref localTriangleShape.vB, ref convex.worldTransform.Position, out localTriangleShape.vB);
                    Vector3.Subtract(ref localTriangleShape.vC, ref convex.worldTransform.Position, out localTriangleShape.vC);
                    Matrix3x3.TransformTranspose(ref localTriangleShape.vA, ref orientation, out localTriangleShape.vA);
                    Matrix3x3.TransformTranspose(ref localTriangleShape.vB, ref orientation, out localTriangleShape.vB);
                    Matrix3x3.TransformTranspose(ref localTriangleShape.vC, ref orientation, out localTriangleShape.vC);

                    //Now, generate a contact between the two shapes.
                    ContactData contact;
                    TinyStructList<ContactData> contactList;
                    if (pairTester.GenerateContactCandidate(out contactList))
                    {
                        for (int j = 0; j < contactList.Count; j++)
                        {
                            contactList.Get(j, out contact);


                            if (UseImprovedBoundaryHandling)
                            {
                                if (replacedyzeCandidate(ref indices, pairTester, ref contact))
                                {
                                    //This is let through if there's a face contact. Face contacts cannot be blocked.
                                    guaranteedContacts++;
                                    AddLocalContact(ref contact, ref orientation);
                                }
                            }
                            else
                            {
                                AddLocalContact(ref contact, ref orientation);
                            }

                        }
                    }

                    //Get the voronoi region from the contact candidate generation.  Possibly just recalculate, since most of the systems don't calculate it.
                    //Depending on which voronoi region it is in (Switch on enumeration), identify the indices composing that region.  For face contacts, don't bother- just add it if unique.
                    //For AB, AC, or BC, add an Edge to the blockedEdgeRegions set with the corresponding indices.
                    //For A, B, or C, add the index of the vertex to the blockedVertexRegions set.
                    //If the edge/vertex is already present in the set, then DO NOT add the contact.
                    //When adding a contact, add ALL other voronoi regions to the blocked sets. 
                }

            }



            if (UseImprovedBoundaryHandling)
            {

                //If there were no face contacts that absolutely must be included, we may get into a very rare situation
                //where absolutely no contacts get created.  For example, a sphere falling directly on top of a vertex in a flat terrain.
                //It will generally get locked out of usage by belonging only to restricted regions (numerical issues make it visible by both edges and vertices).
                //In some cases, the contacts will be ignored instead of corrected (e.g. spheres).
                //To prevent objects from just falling through the ground in such a situation, force-correct the contacts regardless of the pair tester's desires.
                //Sure, it might not be necessary under normal cirreplacedstances, but it's a better option than having no contacts.
                //TODO: There is another option: Changing restricted regions so that a vertex only restricts the other two vertices and the far edge,
                //and an edge only restricts the far vertex and other two edges.  This introduces an occasional bump though...

                //It's possible, in very specific instances, for an object to wedge itself between two adjacent triangles.
                //For this state to continue beyond a brief instant generally requires the object be orientation locked and slender.
                //However, some characters fit this description, so it can't be ignored!

                //Conceptually, this issue can occur at either a vertex junction or a shared edge (usually on extremely flat surfaces only).
                //However, an object stuck between multiple triangles is not in a stable state.  In the edge case, the object gets shoved to one side
                //as one contact 'wins' the solver war.  That's not enough to escape, unfortunately.
                //The vertex case, on the other hand, is degenerate and decays into an edge case rapidly thanks to this lack of stability.
                //So, we don't have to explicitly handle the somewhat more annoying and computationally expensive vertex unstucking case, because the edge case handles both! :)

                //This isn't a completely free operation, but it's guarded behind pretty rare conditions.
                //Essentially, we will check to see if there's just edge contacts fighting against each other.
                //If they are, then we will correct any stuck-contributing normals to the triangle normal.
                if (vertexContacts.Count == 0 && guaranteedContacts == 0 && edgeContacts.Count > 1)
                {
                    //There are only edge contacts, check to see if:
                    //all normals are coplanar, and
                    //at least one normal faces against the other normals (meaning it's probably stuck, as opposed to just colliding on a corner).

                    bool allNormalsInSamePlane = true;
                    bool atLeastOneNormalAgainst = false;

                    var firstNormal = edgeContacts.Elements[0].ContactData.Normal;
                    edgeContacts.Elements[0].CorrectedNormal.Normalize();
                    float dot;
                    Vector3.Dot(ref firstNormal, ref edgeContacts.Elements[0].CorrectedNormal, out dot);
                    if (Math.Abs(dot) > .01f)
                    {
                        //Go ahead and test the first contact separately, since we're using its contact normal to determine coplanarity.
                        allNormalsInSamePlane = false;
                    }
                    else
                    {
                        //TODO: Note that we're only checking the new edge contacts, not the existing contacts.
                        //It's possible that some existing contacts could interfere and cause issues, but for the sake of simplicity and due to rarity
                        //we'll ignore that possibility for now.
                        for (int i = 1; i < edgeContacts.Count; i++)
                        {
                            Vector3.Dot(ref edgeContacts.Elements[i].ContactData.Normal, ref firstNormal, out dot);
                            if (dot < 0)
                            {
                                atLeastOneNormalAgainst = true;
                            }
                            //Check to see if the normal is outside the plane.
                            Vector3.Dot(ref edgeContacts.Elements[i].ContactData.Normal, ref edgeContacts.Elements[0].CorrectedNormal, out dot);

                            if (Math.Abs(dot) > .01f)
                            {

                                //We are not stuck!
                                allNormalsInSamePlane = false;
                                break;
                            }
                        }
                    }

                    if (allNormalsInSamePlane && atLeastOneNormalAgainst)
                    {
                        //Uh oh! all the normals are parallel... The object is probably in a weird situation.
                        //Let's correct the normals!

                        //Already normalized the first contact above.
                        //We don't need to perform the perpendicularity test here- we did that before! We know it's perpendicular already.
                        edgeContacts.Elements[0].ContactData.Normal = edgeContacts.Elements[0].CorrectedNormal;
                        edgeContacts.Elements[0].ShouldCorrect = true;

                        for (int i = 1; i < edgeContacts.Count; i++)
                        {
                            //Must normalize the corrected normal before using it.
                            edgeContacts.Elements[i].CorrectedNormal.Normalize();
                            Vector3.Dot(ref edgeContacts.Elements[i].CorrectedNormal, ref edgeContacts.Elements[i].ContactData.Normal, out dot);
                            if (dot < .01)
                            {
                                //Only bother doing the correction if the normal appears to be pointing nearly horizontally- implying that it's a contributor to the stuckness!
                                //If it's blocked, the next section will use the corrected normal- if it's not blocked, the next section will use the direct normal.
                                //Make them the same thing :)
                                edgeContacts.Elements[i].ContactData.Normal = edgeContacts.Elements[i].CorrectedNormal;
                                edgeContacts.Elements[i].ShouldCorrect = true;
                                //Note that the penetration depth is NOT corrected.  The contact's depth no longer represents the true depth.
                                //However, we only need to have some penetration depth to get the object to escape the rut.
                                //Furthermore, the depth computed from the horizontal opposing contacts is known to be less than the depth in the perpendicular direction.
                                //If the current depth was NOT less than the true depth along the corrected normal, then the collision detection system 
                                //would have picked a different depth, as it finds a reasonable approximation of the minimum penetration!
                                //As a consequence, this contact will not be active beyond the object's destuckification, because its contact depth will be negative (or very close to it).

                            }
                        }
                    }
                }


              


                for (int i = 0; i < edgeContacts.Count; i++)
                {
                    //Only correct if it's allowed AND it's blocked.
                    //If it's not blocked, the contact being created is necessary!
                    //The normal generated by the triangle-convex tester is already known not to
                    //violate the triangle sidedness.
                    if (!blockedEdgeRegions.Contains(edgeContacts.Elements[i].Edge))
                    {
                        //If it's not blocked, use the contact as-is without correcting it.
                        AddLocalContact(ref edgeContacts.Elements[i].ContactData, ref orientation);

                    }
                    else if (edgeContacts.Elements[i].ShouldCorrect || guaranteedContacts == 0)
                    {
                        //If it is blocked, we can still make use of the contact.  But first, we need to change the contact normal to ensure that
                        //it will not interfere (and cause a bump or something).
                        float dot;
                        edgeContacts.Elements[i].CorrectedNormal.Normalize();
                        Vector3.Dot(ref edgeContacts.Elements[i].CorrectedNormal, ref edgeContacts.Elements[i].ContactData.Normal, out dot);
                        edgeContacts.Elements[i].ContactData.Normal = edgeContacts.Elements[i].CorrectedNormal;
                        edgeContacts.Elements[i].ContactData.PenetrationDepth *= MathHelper.Max(0, dot); //Never cause a negative penetration depth.
                        AddLocalContact(ref edgeContacts.Elements[i].ContactData, ref orientation);
                    }
                    //If it's blocked AND it doesn't allow correction, ignore its existence.



                }




                for (int i = 0; i < vertexContacts.Count; i++)
                {

                    if (!blockedVertexRegions.Contains(vertexContacts.Elements[i].Vertex))
                    {
                        //If it's not blocked, use the contact as-is without correcting it.
                        AddLocalContact(ref vertexContacts.Elements[i].ContactData, ref orientation);
                    }
                    else if (vertexContacts.Elements[i].ShouldCorrect || guaranteedContacts == 0)
                    {
                        //If it is blocked, we can still make use of the contact.  But first, we need to change the contact normal to ensure that
                        //it will not interfere (and cause a bump or something).
                        float dot;
                        vertexContacts.Elements[i].CorrectedNormal.Normalize();
                        Vector3.Dot(ref vertexContacts.Elements[i].CorrectedNormal, ref vertexContacts.Elements[i].ContactData.Normal, out dot);
                        vertexContacts.Elements[i].ContactData.Normal = vertexContacts.Elements[i].CorrectedNormal;
                        vertexContacts.Elements[i].ContactData.PenetrationDepth *= MathHelper.Max(0, dot); //Never cause a negative penetration depth.
                        AddLocalContact(ref vertexContacts.Elements[i].ContactData, ref orientation);
                    }
                    //If it's blocked AND it doesn't allow correction, ignore its existence.


                }



                blockedEdgeRegions.Clear();
                blockedVertexRegions.Clear();
                vertexContacts.Clear();
                edgeContacts.Clear();


            }



            //Remove stale pair testers.
            //This will only remove 8 stale ones per frame, but it doesn't really matter.
            //VERY rarely will there be more than 8 in a single frame, and they will be immediately taken care of in the subsequent frame.
            var toRemove = new TinyList<TriangleIndices>();
            foreach (KeyValuePair<TriangleIndices, TrianglePairTester> pair in activePairTesters)
            {
                if (!pair.Value.Updated)
                {
                    if (!toRemove.Add(pair.Key))
                        break;
                }
                else
                    pair.Value.Updated = false;
            }



            for (int i = toRemove.Count - 1; i >= 0; i--)
            {
                var pairTester = activePairTesters[toRemove[i]];
                pairTester.CleanUp();
                GiveBackTester(pairTester);
                activePairTesters.Remove(toRemove[i]);
            }


            //Some child types will want to do some extra post processing on the manifold.        
            ProcessCandidates(candidatesToAdd);


            //Check if adding the new contacts would overflow the manifold.
            if (contacts.Count + candidatesToAdd.Count > 4)
            {
                //Adding all the contacts would overflow the manifold.  Reduce to the best subset.
                ContactReducer.ReduceContacts(contacts, candidatesToAdd, contactIndicesToRemove, reducedCandidates);
                RemoveQueuedContacts();
                for (int i = reducedCandidates.Count - 1; i >= 0; i--)
                {
                    Add(ref reducedCandidates.Elements[i]);
                    reducedCandidates.RemoveAt(i);
                }
            }
            else if (candidatesToAdd.Count > 0)
            {
                //Won't overflow the manifold, so just toss it in PROVIDED that it isn't too close to something else.
                for (int i = 0; i < candidatesToAdd.Count; i++)
                {
                    Add(ref candidatesToAdd.Elements[i]);
                }
            }



            candidatesToAdd.Clear();

        }

19 View Source File : NavMeshExporter.cs
License : MIT License
Project Creator : AnotherEnd15

private static void InputTriangles(int[] indices, int[] areas)
        {
            Face face = null;
            var faceIndices = new HashSet<int>();
            for (int i = 0, n = areas.Length; i < n; i++)
            {
                var triangleIndexList = new int[3];
                var triangleVertList = new Vert[3];
                for (var j = 0; j < 3; j++)
                {
                    triangleIndexList[j] = indices[i * 3 + j];
                    triangleVertList[j] = indexVertDict[triangleIndexList[j]];
                }

                var vert0 = triangleVertList[0];
                var vert1 = triangleVertList[1];
                var vert2 = triangleVertList[2];
                if (vert0 == vert1 || vert1 == vert2 || vert2 == vert0)
                {
                    continue;
                }

                var newFace = true;
                var area = areas[i] >= 3? areas[i] - 2 : 0;
                if (face != null && face.area == area)
                {
                    for (var j = 0; j < 3; j++)
                    {
                        if (faceIndices.Contains(triangleIndexList[j]))
                        {
                            newFace = false;
                            break;
                        }
                    }
                }

                if (newFace)
                {
                    if (face != null)
                    {
                        InitFace(face);
                        faceIndices.Clear();
                    }

                    face = new Face();
                    face.area = area;
                }

                double x1 = vert1.x - vert0.x;
                double y1 = vert1.y - vert0.y;
                double z1 = vert1.z - vert0.z;
                double x2 = vert2.x - vert0.x;
                double y2 = vert2.y - vert0.y;
                double z2 = vert2.z - vert0.z;
                double normalA = y1 * z2 - z1 * y2;
                double normalB = z1 * x2 - x1 * z2;
                double normalC = x1 * y2 - y1 * x2;
                if (normalB < -0.000001 || 0.000001 < normalB)
                {
                    var normalD = normalA + normalB + normalC;
                    if (normalD > face.normalD)
                    {
                        face.normalA = normalA;
                        face.normalB = normalB;
                        face.normalC = normalC;
                        face.normalD = normalD;
                    }
                }

                for (var j = 0; j < 3; j++)
                {
                    if (!faceIndices.Contains(triangleIndexList[j]))
                    {
                        faceIndices.Add(triangleIndexList[j]);
                        face.verts.Add(triangleVertList[j]);
                    }
                }
            }

            if (face != null)
            {
                InitFace(face);
            }

            foreach (var pair in pairList)
            {
                var firstFace = pair.firstEdgeFace;
                var secondFace = pair.secondEdgeFace;
                var firstDistance = GetDistance(firstFace.centerX - pair.centerX, firstFace.centerZ - pair.centerZ);
                var secondDistance = GetDistance(secondFace.centerX - pair.centerX, secondFace.centerZ - pair.centerZ);
                pair.distance = firstDistance + secondDistance;
            }
        }

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

public static bool GetKey(KeyBinding kb)
        {
            if (kb.TryGetMouseButton(out int mouseButton))
            {
                if (isSimulated)
                    return SimulatedMouseSet.Contains(mouseButton);
                else
                    return UnityEngine.Input.GetMouseButton(mouseButton);
            }
            if (kb.TryGetKeyCode(out KeyCode keyCode))
            {
                if (isSimulated)
                    return SimulatedKeySet.Contains(keyCode);
                else
                    return UnityEngine.Input.GetKey(keyCode);
            }
            return false;
        }

19 View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett

public int RemoveNotesByTag(
            BackupFile backup, 
            int[]? tagIds, 
            bool removeUntaggedNotes, 
            bool removereplacedociatedUnderlining,
            bool removereplacedociatedTags)
        {
            if (backup == null)
            {
                throw new ArgumentNullException(nameof(backup));
            }

            tagIds ??= Array.Empty<int>();

            var tagIdsHash = tagIds.ToHashSet();

            var tagMapIdsToRemove = new HashSet<int>();
            var noteIdsToRemove = new HashSet<int>();
            var candidateUserMarks = new HashSet<int>();

            if (removeUntaggedNotes)
            {
                // notes without a tag
                foreach (var i in GetNotesWithNoTag(backup))
                {
                    noteIdsToRemove.Add(i);
                }
            }

            foreach (var tagMap in backup.Database.TagMaps)
            {
                if (tagIdsHash.Contains(tagMap.TagId) && tagMap.NoteId != null && tagMap.NoteId > 0)
                {
                    tagMapIdsToRemove.Add(tagMap.TagMapId);
                    noteIdsToRemove.Add(tagMap.NoteId.Value);

                    var note = backup.Database.FindNote(tagMap.NoteId.Value);
                    if (note?.UserMarkId != null)
                    {
                        candidateUserMarks.Add(note.UserMarkId.Value);
                    }
                }
            }

            backup.Database.TagMaps.RemoveAll(x => tagMapIdsToRemove.Contains(x.TagMapId));
            backup.Database.TagMaps.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId ?? 0));
            backup.Database.Notes.RemoveAll(x => noteIdsToRemove.Contains(x.NoteId));

            if (removereplacedociatedUnderlining)
            {
                RemoveUnderlining(backup.Database, candidateUserMarks);
            }

            if (removereplacedociatedTags)
            {
                RemoveSelectedTags(backup.Database, tagIdsHash);
            }

            return noteIdsToRemove.Count;
        }

19 View Source File : ChunkData.cs
License : The Unlicense
Project Creator : aeroson

static Vector4[] RecalculateTangents(ref NativeArray<Vector3> vertices, int[] triangleIndicies, Vector2[] uvs, HashSet<int> ignoreIndicies = null)
	{
		// inspired by http://www.opengl-tutorial.org/intermediate-tutorials/tutorial-13-normal-mapping/

		int verticesNum = vertices.Length;
		int indiciesNum = triangleIndicies.Length;

		var outTangents = new Vector4[verticesNum];
		int[] counts = new int[verticesNum];

		for (int i = 0; i <= indiciesNum - 3; i += 3)
		{
			int ai = triangleIndicies[i];
			int bi = triangleIndicies[i + 1];
			int ci = triangleIndicies[i + 2];

			if (ai < verticesNum && bi < verticesNum && ci < verticesNum)
			{
				if (ignoreIndicies != null && (ignoreIndicies.Contains(ai) || ignoreIndicies.Contains(bi) || ignoreIndicies.Contains(ci))) continue;

				Vector3 av = vertices[ai];
				Vector3 deltaPos1 = vertices[bi] - av;
				Vector3 deltaPos2 = vertices[ci] - av;

				Vector2 auv = uvs[ai];
				Vector2 deltaUV1 = uvs[bi] - auv;
				Vector2 deltaUV2 = uvs[ci] - auv;

				float r = 1.0f / (deltaUV1.x * deltaUV2.y - deltaUV1.y * deltaUV2.x);
				Vector4 t = (deltaPos1 * deltaUV2.y - deltaPos2 * deltaUV1.y) * r;

				outTangents[ai] += t;
				outTangents[bi] += t;
				outTangents[ci] += t;

				counts[ai]++;
				counts[bi]++;
				counts[ci]++;
			}
		}

		for (int i = 0; i < verticesNum; i++)
		{
			outTangents[i] /= counts[i];
		}

		return outTangents;
	}

19 View Source File : Cleaner.cs
License : MIT License
Project Creator : AntonyCorbett

private int CleanBlockRanges()
        {
            int removed = 0;

            var ranges = _database.BlockRanges;
            if (ranges.Any())
            {
                var userMarkIdsFound = new HashSet<int>();
                var userMarkIds = GetUserMarkIdsInUse();
                
                foreach (var range in Enumerable.Reverse(ranges))
                {
                    if (!userMarkIds.Contains(range.UserMarkId))
                    {
                        Log.Logger.Debug($"Removing redundant range: {range.BlockRangeId}");
                        ranges.Remove(range);
                        ++removed;
                    }
                    else
                    {
                        if (userMarkIdsFound.Contains(range.UserMarkId))
                        {
                            // don't know how to handle this situation - we are expecting 
                            // a unique constraint on the UserMarkId column but have found 
                            // occasional duplication!
                            Log.Logger.Debug($"Removing redundant range (duplicate UserMarkId): {range.BlockRangeId}");
                            ranges.Remove(range);
                            ++removed;
                        }
                        else
                        {
                            userMarkIdsFound.Add(range.UserMarkId);
                        }
                    }
                }
            }

            return removed;
        }

public static List<PropertiesEnchantmentRegistry> GetEnchantmentsTopLayer(this ICollection<PropertiesEnchantmentRegistry> value, ReaderWriterLockSlim rwLock, HashSet<int> setSpells)
        {
            if (value == null)
                return null;

            rwLock.EnterReadLock();
            try
            {
                var results = from e in value
                    group e by e.SpellCategory
                    into categories
                    //select categories.OrderByDescending(c => c.LayerId).First();
                    select categories.OrderByDescending(c => c.PowerLevel)
                        .ThenByDescending(c => Level8AuraSelfSpells.Contains(c.SpellId))
                        .ThenByDescending(c => setSpells.Contains(c.SpellId) ? c.SpellId : c.StartTime).First();

                return results.ToList();
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

19 View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett

private static void RemoveSelectedTags(Database database, HashSet<int> tagIds)
        {
            database.Tags.RemoveAll(x => tagIds.Contains(x.TagId));
            database.TagMaps.RemoveAll(x => tagIds.Contains(x.TagMapId));
        }

19 View Source File : Fixture.cs
License : MIT License
Project Creator : Alan-FGR

public void RestoreCollisionWith(Fixture fixture)
        {
            if (_collisionIgnores.Contains(fixture.FixtureId))
            {
                _collisionIgnores.Remove(fixture.FixtureId);
                Refilter();
            }
        }

19 View Source File : BackupFileService.cs
License : MIT License
Project Creator : AntonyCorbett

private static void RemoveUnderlining(Database database, HashSet<int> userMarksToRemove)
        {
            foreach (var note in database.Notes)
            {
                if (note.UserMarkId != null && userMarksToRemove.Contains(note.UserMarkId.Value))
                {
                    // we can't delete this user mark because it is still in use (a user mark
                    // may have multiple replacedociated notes).
                    userMarksToRemove.Remove(note.UserMarkId.Value);
                }
            }

            database.UserMarks.RemoveAll(x => userMarksToRemove.Contains(x.UserMarkId));
        }

19 View Source File : UdpClient.cs
License : MIT License
Project Creator : a11s

void ioLoop()
        {
            var tid = Thread.CurrentThread.ManagedThreadId;
            debug?.Invoke($"Thread {tid} start");
            SpinWait sw = new SpinWait();
            while (IOThreads.Contains(tid))
            {
                DoWork();
                sw.SpinOnce();
            }
            debug?.Invoke($"Thread {tid} exit");
        }

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

internal bool IsPermaBlocked(int idx)
            {
                return _blockedLookup.Contains(idx);
            }

19 View Source File : Fixture.cs
License : MIT License
Project Creator : Alan-FGR

public bool IsFixtureIgnored(Fixture fixture)
        {
            return _collisionIgnores.Contains(fixture.FixtureId);
        }

public static List<PropertiesEnchantmentRegistry> GetEnchantmentsTopLayerByStatModType(this ICollection<PropertiesEnchantmentRegistry> value, EnchantmentTypeFlags statModType, uint statModKey, ReaderWriterLockSlim rwLock, HashSet<int> setSpells, bool handleMultiple = false)
        {
            if (value == null)
                return null;

            rwLock.EnterReadLock();
            try
            {
                var multipleStat = EnchantmentTypeFlags.Undef;

                if (handleMultiple)
                {
                    // todo: this is starting to get a bit messy here, EnchantmentTypeFlags handling should be more adaptable
                    // perhaps the enchantment registry in acclient should be investigated for reference logic

                    multipleStat = statModType | EnchantmentTypeFlags.MultipleStat;

                    statModType |= EnchantmentTypeFlags.SingleStat;
                }

                var valuesByStatModTypeAndKey = value.Where(e => (e.StatModType & statModType) == statModType && e.StatModKey == statModKey || (handleMultiple && (e.StatModType & multipleStat) == multipleStat && (e.StatModType & EnchantmentTypeFlags.Vitae) == 0 && e.StatModKey == 0));

                // 3rd spell id sort added for Gauntlet Damage Boost I / Gauntlet Damage Boost II, which is contained in multiple sets, and can overlap
                // without this sorting criteria, it's already matched up to the client, but produces logically incorrect results for server spell stacking
                // confirmed this bug still exists in acclient Enchantment.Duel(), unknown if it existed in retail server

                var results = from e in valuesByStatModTypeAndKey
                    group e by e.SpellCategory
                    into categories
                    //select categories.OrderByDescending(c => c.LayerId).First();
                    select categories.OrderByDescending(c => c.PowerLevel)
                        .ThenByDescending(c => Level8AuraSelfSpells.Contains(c.SpellId))
                        .ThenByDescending(c => setSpells.Contains(c.SpellId) ? c.SpellId : c.StartTime).First();

                return results.ToList();
            }
            finally
            {
                rwLock.ExitReadLock();
            }
        }

19 View Source File : AvifWriter.AvifWriterState.cs
License : MIT License
Project Creator : 0xC0000054

private static IArrayPoolBuffer<int> GetDuplicateTileSearchSpace(IReadOnlyList<CompressedAV1Image> images,
                                                                             HashSet<int> replacedgeneousTiles,
                                                                             IArrayPoolService arrayPool)
            {
                IArrayPoolBuffer<int> buffer = arrayPool.Rent<int>(images.Count - replacedgeneousTiles.Count);

                int[] searchSpace = buffer.Array;
                int index = 0;

                for (int i = 0; i < images.Count; i++)
                {
                    if (!replacedgeneousTiles.Contains(i))
                    {
                        searchSpace[index] = i;
                        index++;
                    }
                }

                return buffer;
            }

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

public static void TryCreateMaterialCopy(Graphic targetGraphic)
        {
            int targetId = targetGraphic.GetInstanceID();
            if (!targetInstances.Contains(targetId))
            {
                targetInstances.Add(targetId);
                targetGraphic.material = new Material(targetGraphic.material);
            }
        }

19 View Source File : TabControlHelper.cs
License : MIT License
Project Creator : Accelerider

private static void OnLeftToRightAnimationChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            if (d is TabControl tabControl &&
                !_initializedTabControlSet.Contains(tabControl.GetHashCode()))
            {
                ModifyTabControl(tabControl);
            }
        }

19 View Source File : CrossChainIndexingDataService.cs
License : MIT License
Project Creator : AElfProject

private async Task<List<ParentChainBlockData>> GetNonIndexedParentChainBlockDataAsync(Hash blockHash,
            long blockHeight, HashSet<int> excludeChainIdList)
        {
            var parentChainBlockDataList = new List<ParentChainBlockData>();
            var libExists = await _irreversibleBlockStateProvider.ValidateIrreversibleBlockExistingAsync();
            if (!libExists)
                return parentChainBlockDataList;

            var crossChainContractAddress = await GetCrossChainContractAddressAsync(new ChainContext
            {
                BlockHash = blockHash,
                BlockHeight = blockHeight
            });

            var returnValue = await _contractReaderFactory.Create(new ContractReaderContext
                {
                    BlockHash = blockHash,
                    BlockHeight = blockHeight,
                    ContractAddress = crossChainContractAddress
                }).GetParentChainId
                .CallAsync(new Empty());
            var parentChainId = returnValue?.Value ?? 0;
            if (parentChainId == 0 || excludeChainIdList.Contains(parentChainId))
            {
                // no configured parent chain
                return parentChainBlockDataList;
            }

            int length = CrossChainConstants.DefaultBlockCacheEnreplacedyCount;
            var heightInState = (await _contractReaderFactory
                .Create(new ContractReaderContext
                {
                    BlockHash = blockHash,
                    BlockHeight = blockHeight,
                    ContractAddress = crossChainContractAddress
                }).GetParentChainHeight
                .CallAsync(new Empty())).Value;

            var targetHeight = heightInState + 1;
            Logger.LogDebug($"Target height {targetHeight}");

            var i = 0;
            while (i < length)
            {
                var parentChainBlockData =
                    _blockCacheEnreplacedyConsumer.Take<ParentChainBlockData>(parentChainId, targetHeight, false);
                if (parentChainBlockData == null || parentChainBlockData.Height != targetHeight)
                {
                    // no more available parent chain block info
                    break;
                }

                parentChainBlockDataList.Add(parentChainBlockData);
                targetHeight++;
                i++;
            }

            if (parentChainBlockDataList.Count > 0)
                Logger.LogDebug(
                    $"Got height [{parentChainBlockDataList.First().Height} - {parentChainBlockDataList.Last().Height} ]" +
                    $" from parent chain {ChainHelper.ConvertChainIdToBase58(parentChainId)}.");
            return parentChainBlockDataList;
        }

19 View Source File : CommandLineAnalyzer.cs
License : MIT License
Project Creator : AlexGhiondea

private static void ValidateArguments(List<Argument> args, SymbolreplacedysisContext context)
        {
            HashSet<string> namesOfAllArgs = new HashSet<string>();
            HashSet<int> positionsOrRequiredArgs = new HashSet<int>();
            int numberOfPositionalArgs = 0;
            int indexOfCollectionArg = -1;
            RequiredArgument collectionArg = null;
            foreach (var item in args)
            {
                if (item is OptionalArgument)

                {
                    OptionalArgument oag = item as OptionalArgument;

                    // Validate that the same name is not used across required and optional arguments.
                    if (namesOfAllArgs.Contains(oag.Name))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, oag.Symbol.Locations.First(), oag.Name));
                    }

                    namesOfAllArgs.Add(oag.Name);
                }
                else if (item is RequiredArgument)
                {
                    RequiredArgument rag = item as RequiredArgument;
                    numberOfPositionalArgs++;

                    // Validate that the same position is not used twice 
                    if (positionsOrRequiredArgs.Contains(rag.Position))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DuplicatePositionalArgumentPositionRule, rag.Symbol.Locations.First(), rag.Position));
                    }

                    // Validate that the same name is not used across required and optional arguments.
                    if (namesOfAllArgs.Contains(rag.Name))
                    {
                        context.ReportDiagnostic(Diagnostic.Create(DuplicateArgumentNameRule, rag.Symbol.Locations.First(), rag.Name));
                    }

                    // is the required collection argument the last one AND do we only have one of them?
                    if (indexOfCollectionArg >= 0 && rag.Position > indexOfCollectionArg)
                    {
                        context.ReportDiagnostic(Diagnostic.Create(OnlyOneRequiredCollection, rag.Symbol.Locations.First(), collectionArg.Name, rag.Name));
                    }

                    // do we have a collection argument specified?
                    if (rag.IsCollection)
                    {
                        indexOfCollectionArg = rag.Position;
                        collectionArg = rag;
                    }

                    namesOfAllArgs.Add(rag.Name);
                    positionsOrRequiredArgs.Add(rag.Position);
                }
            }

            int checkedPositions = 0;
            //validate that the positional arguments are in a continuous sequence, starting at 0
            for (checkedPositions = 0; checkedPositions < numberOfPositionalArgs; checkedPositions++)
            {
                if (!positionsOrRequiredArgs.Contains(checkedPositions))
                {
                    // at this point, we could not find the required positional argument 'i'
                    // we should give the error at the type level.
                    context.ReportDiagnostic(Diagnostic.Create(RequiredPositionalArgumentNotFound, args.First().Symbol.ContainingType.Locations.First(), numberOfPositionalArgs, checkedPositions));
                    break;
                }
            }

            // Ensure that the required collection argument (if present) is last.
            if (indexOfCollectionArg >= 0 && indexOfCollectionArg != numberOfPositionalArgs - 1)
            {
                context.ReportDiagnostic(Diagnostic.Create(CollectionArgumentShouldBeLast, collectionArg.Symbol.Locations.First(), collectionArg.Name));
            }
        }

See More Examples