System.Collections.Generic.Dictionary.TryGetValue(string, out int)

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

598 Examples 7

19 View Source File : StringMap.cs
License : MIT License
Project Creator : 0x0ade

public void CountRead(string value) {
            if (value.Length <= MinLength)
                return;

            lock (Pending) {
                if (MappedRead.Contains(value) || Pending.Contains(value))
                    return;

                if (!Counting.TryGetValue(value, out int count))
                    count = 0;
                if (++count >= PromotionCount) {
                    Counting.Remove(value);
                    Pending.Add(value);
                } else {
                    Counting[value] = count;
                }

                if (Counting.Count >= MaxCounting)
                    Cleanup();
            }
        }

19 View Source File : NetObjectCache.cs
License : MIT License
Project Creator : 404Lcc

internal int AddObjectKey(object value, out bool existing)
        {
            if (value == null) throw new ArgumentNullException("value");

            if ((object)value == (object)rootObject) // (object) here is no-op, but should be
            {                                        // preserved even if this was typed - needs ref-check
                existing = true;
                return Root;
            }

            string s = value as string;
            BasicList list = List;
            int index;

#if NO_GENERICS
            
            if(s == null)
            {
                if (objectKeys == null)
                {
                    objectKeys = new ReferenceHashtable();
                    index = -1;
                }
                else
                {
                    object tmp = objectKeys[value];
                    index = tmp == null ? -1 : (int) tmp;
                }
            }
            else
            {
                if (stringKeys == null)
                {
                    stringKeys = new Hashtable();
                    index = -1;
                }
                else
                {
                    object tmp = stringKeys[s];
                    index = tmp == null ? -1 : (int) tmp;
                }
            }
#else

            if(s == null)
            {
#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way
                index = list.IndexOfReference(value);
#else
                if (objectKeys == null) 
                {
                    objectKeys = new System.Collections.Generic.Dictionary<object, int>(ReferenceComparer.Default);
                    index = -1;
                }
                else
                {
                    if (!objectKeys.TryGetValue(value, out index)) index = -1;
                }
#endif
            }
            else
            {
                if (stringKeys == null)
                {
                    stringKeys = new System.Collections.Generic.Dictionary<string, int>();
                    index = -1;
                } 
                else
                {
                    if (!stringKeys.TryGetValue(s, out index)) index = -1;
                }
            }
#endif

            if (!(existing = index >= 0))
            {
                index = list.Add(value);

                if (s == null)
                {
#if !CF && !PORTABLE // CF can't handle the object keys very well
                    objectKeys.Add(value, index);
#endif
                }
                else
                {
                    stringKeys.Add(s, index);
                }
            }
            return index + 1;
        }

19 View Source File : RiskFunct.cs
License : GNU General Public License v3.0
Project Creator : 9E4ECDDE

internal static System.Collections.IEnumerator CheckWorld()
        {
            if (alreadyCheckingWorld)
            {
                MelonLogger.Error("Attempted to check for world multiple times");
                yield break;
            }

            // Wait for RoomManager to exist before continuing.
            ApiWorld currentWorld = null;
            while (currentWorld == null)
            {
                currentWorld = RoomManager.field_Internal_Static_ApiWorld_0;
                yield return new WaitForSecondsRealtime(1);
            }
            var worldId = currentWorld.id;
            //MelonLogger.Msg($"Checking World with Id {worldId}");

            // Check cache for world, so we keep the number of API calls lower.
            //if (checkedWorlds.ContainsKey(worldId))
            if (checkedWorlds.TryGetValue(worldId, out int outres))
            {
                //checkedWorlds.TryGetValue(worldId, out int outres);
                NDB.WorldType = outres;
                //checkedWorlds[worldId];
                //MelonLogger.Msg($"Using cached check {Main.WorldType} for world '{worldId}'");
                yield break;
            }

            // Check for Game Objects first, as it's the lowest cost check.
            if (GameObject.Find("eVRCRiskFuncEnable") != null || GameObject.Find("UniversalRiskyFuncEnable") != null || GameObject.Find("ModCompatRiskyFuncEnable ") != null)
            {
                NDB.WorldType = 0;
                checkedWorlds.Add(worldId, 0);
                yield break;
            }
            else if (GameObject.Find("eVRCRiskFuncDisable") != null || GameObject.Find("UniversalRiskyFuncDisable") != null || GameObject.Find("ModCompatRiskyFuncDisable ") != null)
            {
                NDB.WorldType = 4;
                checkedWorlds.Add(worldId, 4);
                yield break;
            }

            alreadyCheckingWorld = true;
            // Check if black/whitelisted from EmmVRC - thanks Emilia and the rest of EmmVRC Staff
            var uwr = UnityWebRequest.Get($"https://dl.emmvrc.com/riskyfuncs.php?worldid={worldId}");
            uwr.SendWebRequest();
            while (!uwr.isDone)
                yield return new WaitForEndOfFrame();

            var result = uwr.downloadHandler.text?.Trim().ToLower();
            uwr.Dispose();
            if (!string.IsNullOrWhiteSpace(result))
            {
                switch (result)
                {
                    case "allowed":
                        NDB.WorldType = 0;
                        checkedWorlds.Add(worldId, 0);
                        alreadyCheckingWorld = false;
                        //MelonLogger.Msg($"EmmVRC allows world '{worldId}'");
                        yield break;

                    case "denied":
                        NDB.WorldType = 3;
                        checkedWorlds.Add(worldId, 3);
                        alreadyCheckingWorld = false;
                        //MelonLogger.Msg($"EmmVRC denies world '{worldId}'");
                        yield break;
                }
            }

            // No result from server or they're currently down
            // Check tags then. should also be in cache as it just got downloaded
            API.Fetch<ApiWorld>(
                worldId,
                new Action<ApiContainer>(
                    container =>
                    {
                        ApiWorld apiWorld;
                        if ((apiWorld = container.Model.TryCast<ApiWorld>()) != null)
                        {
                            short tagResult = 0;
                            foreach (var worldTag in apiWorld.tags)
                            {
                                if (worldTag.IndexOf("game", StringComparison.OrdinalIgnoreCase) != -1 && worldTag.IndexOf("games", StringComparison.OrdinalIgnoreCase) == -1)
                                {
                                    tagResult = 2;
                                    //MelonLogger.Msg($"Found game tag in world world '{worldId}'");
                                    break;
                                }
                                else if (worldTag.IndexOf("club", StringComparison.OrdinalIgnoreCase) != -1)
                                    tagResult = 1;
                            }
                            NDB.WorldType = tagResult;
                            checkedWorlds.Add(worldId, tagResult);
                            alreadyCheckingWorld = false;
                            //MelonLogger.Msg($"Tag search result: '{tagResult}' for '{worldId}'");
                        }
                        else
                        {
                            MelonLogger.Error("Failed to cast ApiModel to ApiWorld");
                        }
                    }),
                disableCache: false);

        }

19 View Source File : UMAData.cs
License : Apache License 2.0
Project Creator : A7ocin

public SlotData MergeSlot(SlotData slot, bool dontSerialize)
			{
				if ((slot == null) || (slot.replacedet == null))
					return null;

				int overlayCount = 0;
				for (int i = 0; i < slotDataList.Length; i++)
				{
					if (slotDataList[i] == null)
						continue;
					if (slot.replacedet == slotDataList[i].replacedet)
					{
						SlotData originalSlot = slotDataList[i];
						overlayCount = slot.OverlayCount;
						for (int j = 0; j < overlayCount; j++)
						{
							OverlayData overlay = slot.GetOverlay(j);
							//DynamicCharacterSystem:: Needs to use alternative methods that find equivalent overlays since they may not be Equal if they were in an replacedetBundle
							OverlayData originalOverlay = originalSlot.GetEquivalentUsedOverlay(overlay);
							if (originalOverlay != null)
							{
								originalOverlay.CopyColors(overlay);//also copies textures
								if (overlay.colorData.HasName())
								{
									int sharedIndex;
									if (mergedSharedColors.TryGetValue(overlay.colorData.name, out sharedIndex))
									{
										originalOverlay.colorData = sharedColors[sharedIndex];
									}
								}
							}
							else
							{
								OverlayData overlayCopy = overlay.Duplicate();
								if (overlayCopy.colorData.HasName())
								{
									int sharedIndex;
									if (mergedSharedColors.TryGetValue(overlayCopy.colorData.name, out sharedIndex))
									{
										overlayCopy.colorData = sharedColors[sharedIndex];
									}
								}
								originalSlot.AddOverlay(overlayCopy);
							}
						}
						originalSlot.dontSerialize = dontSerialize;
						return originalSlot;
					}
				}

				int insertIndex = slotDataList.Length;
				System.Array.Resize<SlotData>(ref slotDataList, slotDataList.Length + 1);

				SlotData slotCopy = slot.Copy();
				slotCopy.dontSerialize = dontSerialize;
				overlayCount = slotCopy.OverlayCount;
				for (int j = 0; j < overlayCount; j++)
				{
					OverlayData overlay = slotCopy.GetOverlay(j);
					if (overlay.colorData.HasName())
					{
						int sharedIndex;
						if (mergedSharedColors.TryGetValue(overlay.colorData.name, out sharedIndex))
						{
							overlay.colorData = sharedColors[sharedIndex];
						}
					}
				}
				slotDataList[insertIndex] = slotCopy;
				MergeMatchingOverlays();
                return slotCopy;
			}

19 View Source File : UMAData.cs
License : Apache License 2.0
Project Creator : A7ocin

public void Merge(UMARecipe recipe, bool dontSerialize)
			{
				if (recipe == null)
					return;

				if ((recipe.raceData != null) && (recipe.raceData != raceData))
				{
					Debug.LogWarning("Merging recipe with conflicting race data: " + recipe.raceData.name);
				}

				foreach (var dnaEntry in recipe.umaDna)
				{
					var destDNA = GetOrCreateDna(dnaEntry.Value.GetType(), dnaEntry.Key);
					destDNA.Values = dnaEntry.Value.Values;
				}

				mergedSharedColors.Clear();
				if (sharedColors == null)
					sharedColors = new OverlayColorData[0];
				if (recipe.sharedColors != null)
				{
					for (int i = 0; i < sharedColors.Length; i++)
					{
						if (sharedColors[i] != null && sharedColors[i].HasName())
						{
							while (mergedSharedColors.ContainsKey(sharedColors[i].name))
							{
								sharedColors[i].name = sharedColors[i].name + ".";
							}
							mergedSharedColors.Add(sharedColors[i].name, i);
						}
					}

					for (int i = 0; i < recipe.sharedColors.Length; i++)
					{
						OverlayColorData sharedColor = recipe.sharedColors[i];
						if (sharedColor != null && sharedColor.HasName())
						{
							int sharedIndex;
							if (!mergedSharedColors.TryGetValue(sharedColor.name, out sharedIndex))
							{
								int index = sharedColors.Length;
								mergedSharedColors.Add(sharedColor.name, index);
								Array.Resize<OverlayColorData>(ref sharedColors, index + 1);
								sharedColors[index] = sharedColor.Duplicate();
							}
						}
					}
				}

				if (slotDataList == null)
					slotDataList = new SlotData[0];
				if (recipe.slotDataList != null)
				{
					for (int i = 0; i < recipe.slotDataList.Length; i++)
					{
						MergeSlot(recipe.slotDataList[i], dontSerialize);
					}
				}
			}

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

public static void OnPostprocessAllreplacedets(string[] importedreplacedets, string[] deletedreplacedets, string[] movedreplacedets, string[] movedFromreplacedetPaths)
        {
            foreach (string replacedet in importedreplacedets)
            {
                string extension = Path.GetExtension(replacedet);
                if (extension == ".room" || extension == ".glb" || extension == ".gltf")
                {
                    Type replacedetType = replacedetDatabase.GetMainreplacedetTypeAtPath(replacedet);
                    if (replacedetType == typeof(Defaultreplacedet))
                    {
                        if (!replacedetsAttemptedToReimport.TryGetValue(replacedet, out int numAttempts))
                        {
                            numAttempts = 0;
                        }

                        replacedetsAttemptedToReimport[replacedet] = ++numAttempts;

                        if (numAttempts <= 3)
                        {
                            Debug.LogWarning($"replacedet '{replacedet}' appears to have failed importing, will attempt to re-import. Attempt: {numAttempts}");
                            replacedetDatabase.Importreplacedet(replacedet);
                        }
                        else
                        {
                            Debug.LogWarning($"replacedet '{replacedet}' appears to have failed the re-import 3 times, will not try again.");
                        }
                    }
                }
            }
        }

19 View Source File : CaseSensitiveDictionaryContextData.cs
License : MIT License
Project Creator : actions

public Boolean TryGetValue(
            String key,
            out PipelineContextData value)
        {
            if (m_list?.Count > 0 &&
                IndexLookup.TryGetValue(key, out var index))
            {
                value = m_list[index].Value;
                return true;
            }

            value = null;
            return false;
        }

19 View Source File : TemplateEvaluator.cs
License : MIT License
Project Creator : actions

private void HandleMappingWithWellKnownProperties(
            DefinitionInfo definition,
            List<MappingDefinition> mappingDefinitions,
            MappingToken mapping)
        {
            // Check if loose properties are allowed
            String looseKeyType = null;
            String looseValueType = null;
            DefinitionInfo? looseKeyDefinition = null;
            DefinitionInfo? looseValueDefinition = null;
            if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
            {
                looseKeyType = mappingDefinitions[0].LooseKeyType;
                looseValueType = mappingDefinitions[0].LooseValueType;
            }

            var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
            var hasExpressionKey = false;

            while (m_unraveler.AllowScalar(definition.Expand, out ScalarToken nextKeyScalar))
            {
                // Expression
                if (nextKeyScalar is ExpressionToken)
                {
                    hasExpressionKey = true;
                    var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
                    mapping.Add(nextKeyScalar, Evaluate(anyDefinition));
                    continue;
                }

                // Not a string, convert
                if (!(nextKeyScalar is StringToken nextKey))
                {
                    nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
                }

                // Duplicate
                if (!keys.Add(nextKey.Value))
                {
                    m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
                    m_unraveler.SkipMappingValue();
                    continue;
                }

                // Well known
                if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
                {
                    var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
                    var nextValue = Evaluate(nextValueDefinition);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Loose
                if (looseKeyType != null)
                {
                    if (looseKeyDefinition == null)
                    {
                        looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
                        looseValueDefinition = new DefinitionInfo(definition, looseValueType);
                    }

                    Validate(nextKey, looseKeyDefinition.Value);
                    var nextValue = Evaluate(looseValueDefinition.Value);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Error
                m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
                m_unraveler.SkipMappingValue();
            }

            // Only one
            if (mappingDefinitions.Count > 1)
            {
                var hitCount = new Dictionary<String, Int32>();
                foreach (MappingDefinition mapdef in mappingDefinitions)
                {
                    foreach (String key in mapdef.Properties.Keys)
                    {
                        if (!hitCount.TryGetValue(key, out Int32 value))
                        {
                            hitCount.Add(key, 1);
                        }
                        else
                        {
                            hitCount[key] = value + 1;
                        }
                    }
                }

                List<String> nonDuplicates = new List<String>();
                foreach (String key in hitCount.Keys)
                {
                    if (hitCount[key] == 1)
                    {
                        nonDuplicates.Add(key);
                    }
                }
                nonDuplicates.Sort();

                String listToDeDuplicate = String.Join(", ", nonDuplicates);
                m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
            }
            else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
            {
                foreach (var property in mappingDefinitions[0].Properties)
                {
                    if (property.Value.Required)
                    {
                        if (!keys.Contains(property.Key))
                        {
                            m_context.Error(mapping, $"Required property is missing: {property.Key}");
                        }
                    }
                }
            }

            m_unraveler.ReadMappingEnd();
        }

19 View Source File : TemplateReader.cs
License : MIT License
Project Creator : actions

private void HandleMappingWithWellKnownProperties(
            DefinitionInfo definition,
            List<MappingDefinition> mappingDefinitions,
            MappingToken mapping)
        {
            // Check if loose properties are allowed
            String looseKeyType = null;
            String looseValueType = null;
            DefinitionInfo? looseKeyDefinition = null;
            DefinitionInfo? looseValueDefinition = null;
            if (!String.IsNullOrEmpty(mappingDefinitions[0].LooseKeyType))
            {
                looseKeyType = mappingDefinitions[0].LooseKeyType;
                looseValueType = mappingDefinitions[0].LooseValueType;
            }

            var keys = new HashSet<String>(StringComparer.OrdinalIgnoreCase);
            var hasExpressionKey = false;

            while (m_objectReader.AllowLiteral(out LiteralToken rawLiteral))
            {
                var nextKeyScalar = ParseScalar(rawLiteral, definition.AllowedContext);
                // Expression
                if (nextKeyScalar is ExpressionToken)
                {
                    hasExpressionKey = true;
                    // Legal
                    if (definition.AllowedContext.Length > 0)
                    {
                        m_memory.AddBytes(nextKeyScalar);
                        var anyDefinition = new DefinitionInfo(definition, TemplateConstants.Any);
                        mapping.Add(nextKeyScalar, ReadValue(anyDefinition));
                    }
                    // Illegal
                    else
                    {
                        m_context.Error(nextKeyScalar, TemplateStrings.ExpressionNotAllowed());
                        SkipValue();
                    }

                    continue;
                }

                // Not a string, convert
                if (!(nextKeyScalar is StringToken nextKey))
                {
                    nextKey = new StringToken(nextKeyScalar.FileId, nextKeyScalar.Line, nextKeyScalar.Column, nextKeyScalar.ToString());
                }

                // Duplicate
                if (!keys.Add(nextKey.Value))
                {
                    m_context.Error(nextKey, TemplateStrings.ValueAlreadyDefined(nextKey.Value));
                    SkipValue();
                    continue;
                }

                // Well known
                if (m_schema.TryMatchKey(mappingDefinitions, nextKey.Value, out String nextValueType))
                {
                    m_memory.AddBytes(nextKey);
                    var nextValueDefinition = new DefinitionInfo(definition, nextValueType);
                    var nextValue = ReadValue(nextValueDefinition);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Loose
                if (looseKeyType != null)
                {
                    if (looseKeyDefinition == null)
                    {
                        looseKeyDefinition = new DefinitionInfo(definition, looseKeyType);
                        looseValueDefinition = new DefinitionInfo(definition, looseValueType);
                    }

                    Validate(nextKey, looseKeyDefinition.Value);
                    m_memory.AddBytes(nextKey);
                    var nextValue = ReadValue(looseValueDefinition.Value);
                    mapping.Add(nextKey, nextValue);
                    continue;
                }

                // Error
                m_context.Error(nextKey, TemplateStrings.UnexpectedValue(nextKey.Value));
                SkipValue();
            }

            // Only one
            if (mappingDefinitions.Count > 1)
            {
                var hitCount = new Dictionary<String, Int32>();
                foreach (MappingDefinition mapdef in mappingDefinitions)
                {
                    foreach (String key in mapdef.Properties.Keys)
                    {
                        if (!hitCount.TryGetValue(key, out Int32 value))
                        {
                            hitCount.Add(key, 1);
                        }
                        else
                        {
                            hitCount[key] = value + 1;
                        }
                    }
                }

                List<String> nonDuplicates = new List<String>();
                foreach (String key in hitCount.Keys)
                {
                    if(hitCount[key] == 1)
                    {
                        nonDuplicates.Add(key);
                    }
                }
                nonDuplicates.Sort();

                String listToDeDuplicate = String.Join(", ", nonDuplicates);
                m_context.Error(mapping, TemplateStrings.UnableToDetermineOneOf(listToDeDuplicate));
            }
            else if (mappingDefinitions.Count == 1 && !hasExpressionKey)
            {
                foreach (var property in mappingDefinitions[0].Properties)
                {
                    if (property.Value.Required)
                    {
                        if (!keys.Contains(property.Key))
                        {
                            m_context.Error(mapping, $"Required property is missing: {property.Key}");
                        }
                    }
                }
            }
            ExpectMappingEnd();
        }

19 View Source File : SimpleLexer.cs
License : MIT License
Project Creator : Actipro

protected virtual int ParseIdentifier(ITextBufferReader reader, char ch) {
			// Get the entire word
			int startOffset = reader.Offset - 1;
			while (!reader.IsAtEnd) {
				char ch2 = reader.Read();
				// NOTE: This could be improved by supporting \u escape sequences
				if ((!char.IsLetterOrDigit(ch2)) && (ch2 != '_')) {
					reader.ReadReverse();
					break;
				}
			}

			// Determine if the word is a keyword
			if (Char.IsLetter(ch)) {
				int value;
				String subString = reader.GetSubstring(startOffset, reader.Offset - startOffset);
				if (!caseSensitive)
					subString = subString.ToLowerInvariant();

				return keywords.TryGetValue(subString, out value) ? value : SimpleTokenId.Identifier;
			}
			else
				return SimpleTokenId.Identifier;
		}

19 View Source File : Versions.cs
License : Apache License 2.0
Project Creator : adamralph

[Fact]
        public static async Task RepoWithHistory()
        {
            // arrange
            var historicalCommands =
@"git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.0.0-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.0.0
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.1.0-beta.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 0.1.0
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.0-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.0-rc.1
git tag 1.0.0
git checkout -b foo
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.1-alpha.1
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.0.1
git commit --allow-empty -m '.'
git checkout main
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.1.0-alpha.1
git commit --allow-empty -m '.'
git merge foo --no-edit
git commit --allow-empty -m '.'
git tag 1.1.0-beta.2
git tag 1.1.0-beta.10
git commit --allow-empty -m '.'
git commit --allow-empty -m '.'
git tag 1.1.0-rc.1
git tag 1.1.0 -a -m '.'";

            var path = MethodBase.GetCurrentMethod().GetTestDirectory();

            await EnsureEmptyRepositoryAndCommit(path);

            foreach (var command in historicalCommands.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var nameAndArgs = command.Split(" ", 2);
                _ = await ReadAsync(nameAndArgs[0], nameAndArgs[1], path);
                await Task.Delay(200);
            }

            // act
            var versionCounts = new Dictionary<string, int>();
            foreach (var sha in await GetCommitShas(path))
            {
                await Checkout(path, sha);

                var version = Versioner.GetVersion(path, default, default, default, default, default, default);
                var versionString = version.ToString();
                var tagName = $"v/{versionString}";

                _ = versionCounts.TryGetValue(versionString, out var oldVersionCount);
                var versionCount = oldVersionCount + 1;
                versionCounts[versionString] = versionCount;

                tagName = versionCount > 1 ? $"v({versionCount})/{versionString}" : tagName;

                await Tag(path, tagName, sha);
            }

            await Checkout(path, "main");

            // replacedert
            await replacedertFile.Contains("../../../versions.txt", await GetGraph(path));
        }

19 View Source File : RTConstants.cs
License : GNU General Public License v3.0
Project Creator : Aekras1a

public int? GetConstant(string name)
        {
            int ret;
            if(!constants.TryGetValue(name, out ret))
                return null;
            return ret;
        }

19 View Source File : ConfigFile.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public int GetInt(string key)
        {
            int result;
            if (integers.TryGetValue(key, out result))
            {
                return result;
            }
            string val;
            if (allValues.TryGetValue(key, out val))
            {
                if (int.TryParse(val, out result))
                {
                    integers.Add(key, result);
                }
            }
            return result;
        }

19 View Source File : ReplayAnimationRecorder.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public void RecordAnimationCall(ReplayGameObject go, AnimationType type, string animation, float time = 0f)
        {
            int animationId;
            if(!animationsDictionary.TryGetValue(animation, out animationId))
            {
                animationId = nextAnimId;
                animationsDictionary.Add(animation, nextAnimId++);
            }

            playedAnimations.Add(new AnimationPlayInformation(
                animationId,
                type,
                go.Id,
                FengGameManagerMKII.FGM.logic.RoundTime,
                time));
        }

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

int FindOrAddObjVertex(ref string faceParamater, ref Vector3 vertex, ref Vector2 texCoord, ref Vector3 normal)
        {
            int index;
            if (objFaceToMeshIndicie.TryGetValue(faceParamater, out index)) {
                return index;
            } else {

                verticesMesh.Add(vertex);
                uvsMesh.Add(texCoord);
                normalsMesh.Add(normal);

                index = verticesMesh.Count - 1;
                objFaceToMeshIndicie[faceParamater]=index;

                return index;
            }
        }

19 View Source File : ExcelImporter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

protected virtual string Write(TData data, int line)
        {
            var info = data.Validate();
            if (info.Succeed)
                return !Write(data, out var msg2) ? msg2 : null;

            foreach (var item in info.Items)
                if (ColumnFields2.TryGetValue(item.Name, out var col))
                    WriteCellState(line, col, item.Message, true);
            return info.ToString();
        }

19 View Source File : ExcelImporter.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu

public bool ImportExcel()
        {
            var success = true;
            var emptyRow = 0;
            for (var line = 1; line < short.MaxValue; line++)
            {
                bool nowSuccess = true;
                var msg = new StringBuilder();
                switch (ReadRow(line, out var data, out var row))
                {
                    case -1:
                        if (++emptyRow > 2)
                            return success;
                        continue;
                    case 1:
                        nowSuccess = false;
                        break;
                }

                var info = data.Validate();
                if (!info.Succeed)
                {
                    nowSuccess = false;
                    foreach (var item in info.Items)
                    {
                        if (ColumnFields2.TryGetValue(item.Name, out var col))
                        {
                            WriteCellState(line, col, item.Message, true);
                            msg.AppendFormat("{0}:{1}", item.Caption, item.Message);
                        }
                        else
                        {
                            msg.AppendFormat("�ֶ�{0}δ�ṩ����������У�鲻ͨ��:{1}", item.Caption, item.Message);
                        }
                        msg.AppendLine();
                    }
                }
                if (!OnRead(data, row, !nowSuccess, out var msg2))
                {
                    nowSuccess = false;
                    msg.AppendLine();
                    msg.Append(msg2);
                }

                if (nowSuccess)
                {
                    continue;
                }
                success = false;
                row.SafeGetCell(MaxColumn).SetCellValue("����");
                row.SafeGetCell(MaxColumn + 1).SetCellValue(msg.ToString());
            }
            return success;
        }

19 View Source File : Prefetch.cs
License : MIT License
Project Creator : AkiniKites

public bool Rebuild(Patch patch)
        {
            var sizeChanged = false;
            var linksChanged = false;
            var links = GetLinks();
            
            foreach (var file in patch.Files)
            {
                //only operate on .core files
                var fileName = HzdCore.NormalizeSource(file);

                if (Files.TryGetValue(fileName, out int idx))
                {
                    var filePath = Path.Combine(patch.WorkingDir, HzdCore.EnsureExt(file));
                    var length = (int)new FileInfo(filePath).Length;

                    if (Data.Sizes[idx] != length)
                    {
                        sizeChanged = true;
                        Data.Sizes[idx] = length;
                    }

                    if (UpdateLinks(links, filePath, fileName))
                        linksChanged = true;
                }
            }

            if (linksChanged)
                RebuildLinks(links);

            return sizeChanged || linksChanged;
        }

19 View Source File : JsonSerializer.cs
License : MIT License
Project Creator : AlenToma

private void WriteObject(object obj)
        {
            int i = 0;
            if (_cirobj.TryGetValue(obj, out i) == false)
                _cirobj.Add(obj, _cirobj.Count + 1);
            else
            {
                if (_current_depth > 0 && _params.InlineCircularReferences == false)
                {
                    //_circular = true;
                    _output.Append("{\"$i\":");
                    _output.Append(i.ToString());
                    _output.Append("}");
                    return;
                }
            }
            if (_params.UsingGlobalTypes == false)
                _output.Append('{');
            else
            {
                if (_TypesWritten == false)
                {
                    _output.Append('{');
                    _before = _output.Length;
                    //_output = new StringBuilder();
                }
                else
                    _output.Append('{');
            }
            _TypesWritten = true;
            _current_depth++;
            if (_current_depth > _MAX_DEPTH)
                throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);


            Dictionary<string, string> map = new Dictionary<string, string>();
            Type t = obj.GetType();
            bool append = false;
            if (_params.UseExtensions)
            {
                if (_params.UsingGlobalTypes == false)
                    WritePairFast("$type", Reflection.Instance.GetTypereplacedemblyName(t));
                else
                {
                    int dt = 0;
                    string ct = Reflection.Instance.GetTypereplacedemblyName(t);
                    if (_globalTypes.TryGetValue(ct, out dt) == false)
                    {
                        dt = _globalTypes.Count + 1;
                        _globalTypes.Add(ct, dt);
                    }
                    WritePairFast("$type", dt.ToString());
                }
                append = true;
            }

            Getters[] g = Reflection.Instance.GetGetters(t, _params.IgnoreAttributes);
            int c = g.Length;
            for (int ii = 0; ii < c; ii++)
            {
                var p = g[ii];
                object o = p.Property.GetValue(obj);
                if (_params.SerializeNullValues == false && (o == null || o is DBNull))
                {
                    //append = false;
                }
                else
                {
                    if (append)
                        _output.Append(',');
                    if (p.memberName != null)
                        WritePair(p.memberName, o);
                    else
                    {
                        WritePair(JsonHelper.SerializaName(_params.JsonFormatting, p.Name), o);
                    }

                    if (o != null && _params.UseExtensions)
                    {
                        Type tt = o.GetType();
                        if (tt == typeof(System.Object))
                            map.Add(p.Name, tt.ToString());
                    }
                    append = true;
                }
            }
            if (map.Count > 0 && _params.UseExtensions)
            {
                _output.Append(",\"$map\":");
                WriteStringDictionary(map);
            }
            _output.Append('}');
            _current_depth--;
        }

19 View Source File : MenuItemId.cs
License : MIT License
Project Creator : AlexanderPro

public static int GetId(string name)
        {
            if (NameToId.TryGetValue(name.ToLower(), out int id))
            {
                return id;
            }

            return 0;
        }

19 View Source File : Model.cs
License : Apache License 2.0
Project Creator : Algoryx

public Material GetMaterial( string name )
    {
      if ( m_materialTable.TryGetValue( name, out var materialIndex ) )
        return m_materials[ materialIndex ];
      return null;
    }

19 View Source File : Model.cs
License : Apache License 2.0
Project Creator : Algoryx

public Link GetLink( string name )
    {
      if ( m_linkTable.TryGetValue( name, out var linkIndex ) )
        return m_links[ linkIndex ];
      return null;
    }

19 View Source File : Model.cs
License : Apache License 2.0
Project Creator : Algoryx

public UJoint GetJoint( string name )
    {
      if ( m_jointTable.TryGetValue( name, out var jointIndex ) )
        return m_joints[ jointIndex ];
      return null;
    }

19 View Source File : Model.cs
License : Apache License 2.0
Project Creator : Algoryx

private UnityEngine.Material GetRenderMaterial( string name )
    {
      if ( m_renderMaterialsTable.TryGetValue( name, out var renderMaterialIndex ) )
        return m_renderMaterials[ renderMaterialIndex ];
      return null;
    }

19 View Source File : GltfModelLoader.cs
License : MIT License
Project Creator : Aminator

private VertexBufferView[] GetVertexBufferViews(GltfLoader.Schema.Mesh mesh, Span<byte> indexBuffer = default, bool is32BitIndex = false)
        {
            VertexBufferView[] vertexBufferViews = new VertexBufferView[4];

            Dictionary<string, int> attributes = mesh.Primitives[0].Attributes;

            bool hasPosition = attributes.TryGetValue("POSITION", out int positionIndex);
            bool hasNormal = attributes.TryGetValue("NORMAL", out int normalIndex);
            bool hasTangent = attributes.TryGetValue("TANGENT", out int tangentIndex);
            bool hasTexCoord0 = attributes.TryGetValue("TEXCOORD_0", out int texCoord0Index);

            if (hasPosition)
            {
                Span<byte> positionBuffer = GetVertexBuffer(positionIndex, out int positionStride);
                vertexBufferViews[0] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, positionBuffer, ResourceFlags.None), positionStride);

                if (hasNormal)
                {
                    Span<byte> normalBuffer = GetVertexBuffer(normalIndex, out int normalStride);
                    vertexBufferViews[1] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, normalBuffer, ResourceFlags.None), normalStride);
                }

                if (hasTangent)
                {
                    Span<byte> tangentBuffer = GetVertexBuffer(tangentIndex, out int tangentStride);
                    vertexBufferViews[2] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, tangentBuffer, ResourceFlags.None), tangentStride);
                }

                if (hasTexCoord0)
                {
                    Span<byte> texCoord0Buffer = GetVertexBuffer(texCoord0Index, out int texCoord0Stride);
                    vertexBufferViews[3] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, texCoord0Buffer, ResourceFlags.None), texCoord0Stride);

                    if (!hasTangent)
                    {
                        Span<Vector4> tangentBuffer = VertexHelper.GenerateTangents(positionBuffer, texCoord0Buffer, indexBuffer, is32BitIndex);
                        vertexBufferViews[2] = new VertexBufferView(GraphicsResource.CreateBuffer(GraphicsDevice, tangentBuffer, ResourceFlags.None), Unsafe.SizeOf<Vector4>());
                    }
                }
            }

            return vertexBufferViews;
        }

19 View Source File : SqlMapper.DapperTable.cs
License : MIT License
Project Creator : anet-team

internal int IndexOfName(string name)
            {
                return (name != null && fieldNameLookup.TryGetValue(name, out int result)) ? result : -1;
            }

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

internal int AddObjectKey(object value, out bool existing)
        {
            if (value == null) throw new ArgumentNullException(nameof(value));

            if ((object)value == (object)rootObject) // (object) here is no-op, but should be
            {                                        // preserved even if this was typed - needs ref-check
                existing = true;
                return Root;
            }

            string s = value as string;
            BasicList list = List;
            int index;

            if (s == null)
            {
#if CF || PORTABLE // CF has very limited proper object ref-tracking; so instead, we'll search it the hard way
                index = list.IndexOfReference(value);
#else
                if (objectKeys == null)
                {
                    objectKeys = new Dictionary<object, int>(ReferenceComparer.Default);
                    index = -1;
                }
                else
                {
                    if (!objectKeys.TryGetValue(value, out index)) index = -1;
                }
#endif
            }
            else
            {
                if (stringKeys == null)
                {
                    stringKeys = new Dictionary<string, int>();
                    index = -1;
                }
                else
                {
                    if (!stringKeys.TryGetValue(s, out index)) index = -1;
                }
            }

            if (!(existing = index >= 0))
            {
                index = list.Add(value);

                if (s == null)
                {
#if !CF && !PORTABLE // CF can't handle the object keys very well
                    objectKeys.Add(value, index);
#endif
                }
                else
                {
                    stringKeys.Add(s, index);
                }
            }
            return index + 1;
        }

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

public bool Remove(T item)
        {
            int index;
            if (_lookup.TryGetValue(item.Name, out index))
            {
                UnHookNameChanged(item);
                _lookup.Remove(item.Name);
                _items.RemoveAt(index);
                return true;
            }
            return false;
        }

19 View Source File : StringGenerator.cs
License : GNU General Public License v3.0
Project Creator : anydream

public int AddString(string str)
		{
			if (!StringMap.TryGetValue(str, out int idx))
			{
				idx = ++Counter;
				StringMap.Add(str, idx);
			}
			return idx;
		}

19 View Source File : EthornellScript.cs
License : MIT License
Project Creator : arcusmaximus

private void SerializeStrings(Stream inputStream, IEnumerable<ScriptString> scriptStrings, out MemoryStream stringStream, out List<EthornellScriptString> newStrings)
        {
            BinaryReader inputReader = new BinaryReader(inputStream);

            stringStream = new MemoryStream();
            BinaryWriter stringWriter = new BinaryWriter(stringStream);
            Dictionary<string, int> stringOffsets = new Dictionary<string, int>();
            newStrings = new List<EthornellScriptString>();

            using (IEnumerator<ScriptString> scriptStringEnumerator = scriptStrings.GetEnumerator())
            {
                foreach (EthornellScriptString ethString in _strings)
                {
                    string text;
                    if (ethString.Type == ScriptStringType.Internal)
                    {
                        text = ReadString(inputReader, ethString.TextOffset);
                    }
                    else
                    {
                        if (!scriptStringEnumerator.MoveNext())
                            throw new InvalidDataException("Not enough strings in script file");

                        text = scriptStringEnumerator.Current.Text;
                        //text = ProportionalWordWrapper.Default.Wrap(text);
                    }

                    int offset;
                    if (!stringOffsets.TryGetValue(text, out offset))
                    {
                        offset = _codeOffset + _codeLength + (int)stringStream.Length;
                        stringWriter.WriteZeroTerminatedSjisString(text);
                        stringOffsets.Add(text, offset);
                    }

                    newStrings.Add(new EthornellScriptString(ethString.OperandOffset, offset, ethString.Type));
                }
                if (scriptStringEnumerator.MoveNext())
                    throw new InvalidDataException("Too many strings in script file");
            }

            stringStream.Position = 0;
        }

19 View Source File : EditGradientWindow.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : arklumpus

private void SortGradientStopControls(bool skipTransitions = false)
        {
            List<Grid> controls = new List<Grid>();

            Grid container = this.FindControl<Grid>("GradientStopContainer");

            for (int i = 0; i < container.Children.Count; i++)
            {
                controls.Add((Grid)container.Children[i]);
            }

            controls.Sort((a, b) =>
            {
                return ((NumericUpDown)a.Children[0]).Value.CompareTo(((NumericUpDown)b.Children[0]).Value);
            });

            for (int i = 0; i < controls.Count; i++)
            {
                string tag = (string)controls[i].Tag;

                if (!stopIndices.TryGetValue(tag, out int index) || index != i)
                {
                    TransformOperations.Builder builder = new TransformOperations.Builder(1);
                    builder.AppendTranslate(0, 30 * i);

                    if (!skipTransitions)
                    {
                        controls[i].RenderTransform = builder.Build();
                    }
                    else
                    {
                        Transitions prevTransitions = controls[i].Transitions;
                        controls[i].Transitions = null;
                        controls[i].RenderTransform = builder.Build();
                        controls[i].Transitions = prevTransitions;
                    }
                    stopIndices[tag] = i;
                }
            }

            container.Height = 30 * controls.Count;
        }

19 View Source File : Journal.cs
License : GNU General Public License v3.0
Project Creator : arycama

public bool AddOrUpdateEntry(string entry, int index)
	{
		if(entries.TryGetValue(entry, out index))
		{
			entries[entry] = index;
			return true;
		}

		entries.Add(entry, index);
		return false;
	}

19 View Source File : Worker.cs
License : GNU General Public License v3.0
Project Creator : asimmon

private void FixPlayerNames(ConcurrentDictionary<string, string> playerNames)
        {
            var playerIdsWithNameWarnings = new HashSet<string>();

            foreach (var playerId in playerNames.Keys.ToList())
            {
                var playerName = playerNames[playerId];

                if (string.IsNullOrWhiteSpace(playerName))
                {
                    playerIdsWithNameWarnings.Add(playerId);
                    playerName = GetDefaultPlayerName(playerId);
                }

                // Player name is overriden by program options
                if (this._opts.PlayerNames.TryGetValue(playerId, out var playerNameOverride) && !string.IsNullOrWhiteSpace(playerNameOverride))
                {
                    playerName = SanitizePlayerName(playerId, playerNameOverride);
                }

                playerNames[playerId] = playerName;
            }

            var playerNameUses = playerNames.Aggregate(new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase), (acc, kvp) =>
            {
                var (_, playerName) = kvp;
                acc[playerName] = acc.TryGetValue(playerName, out var uses) ? uses + 1 : 1;
                return acc;
            });

            var uniquePlayerNames = new HashSet<string>(playerNameUses.Keys);

            foreach (var uniquePlayerName in uniquePlayerNames)
            {
                if (playerNameUses.TryGetValue(uniquePlayerName, out var uses) && uses == 1)
                {
                    playerNameUses.Remove(uniquePlayerName);
                }
            }

            foreach (var (playerId, playerName) in playerNames.OrderBy(kvp => kvp.Key, StringComparer.Ordinal))
            {
                string suffixedUniquePlayerName;
                if (playerNameUses.TryGetValue(playerName, out var uses))
                {
                    suffixedUniquePlayerName = $"{playerName} ({uses})";
                    playerNameUses[playerName]--;
                }
                else
                {
                    suffixedUniquePlayerName = playerName;
                }

                Guid? websitePlayerId = this._opts.PlayerWebsiteIds.TryGetValue(playerId, out var id) ? id : null;
                this._simulator.AddPlayer(playerId.ToString(CultureInfo.InvariantCulture), suffixedUniquePlayerName, websitePlayerId);
                this._playerIds.Add(playerId);

                if (playerIdsWithNameWarnings.Contains(playerId))
                {
                    this.AddPlayerError(playerId, "An invalid bot name has been provided");
                }
            }
        }

19 View Source File : EndpointActor.cs
License : Apache License 2.0
Project Creator : asynkron

private Task RemoteDeliver(IEnumerable<RemoteDeliver> m, IContext context)
        {
            var envelopes = new List<MessageEnvelope>();
            var typeNames = new Dictionary<string, int>();
            var targetNames = new Dictionary<string, int>();
            var typeNameList = new List<string>();
            var targetNameList = new List<string>();
            var counter = context.System.Metrics.Get<RemoteMetrics>().RemoteSerializedMessageCount;

            foreach (var rd in m)
            {
                var targetName = rd.Target.Id;

                if (!targetNames.TryGetValue(targetName, out var targetId))
                {
                    targetId = targetNames[targetName] = targetNames.Count;
                    targetNameList.Add(targetName);
                }

                var message = rd.Message;
                //if the message can be translated to a serialization representation, we do this here
                //this only apply to root level messages and never to nested child objects inside the message
                if (message is IRootSerializable deserialized) message = deserialized.Serialize(context.System);

                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                if (message is null)
                {
                    Logger.LogError("Null message preplaceded to EndpointActor, ignoring message");
                    continue;
                }

                ByteString bytes;
                string typeName;
                int serializerId;

                try
                {
                    bytes = SerializeMessage(_remoteConfig.Serialization, message, out typeName, out serializerId);
                }
                catch (CodedOutputStream.OutOfSpaceException oom)
                {
                    Logger.LogError(oom, "Message is too large {Message}",message.GetType().Name);
                    throw;
                }
                catch(Exception x)
                {
                    Logger.LogError(x, "Serialization failed for message {Message}",message.GetType().Name);
                    throw;
                }

                if (!context.System.Metrics.IsNoop) counter.Inc(new[] {context.System.Id, context.System.Address, typeName});

                if (!typeNames.TryGetValue(typeName, out var typeId))
                {
                    typeId = typeNames[typeName] = typeNames.Count;
                    typeNameList.Add(typeName);
                }

                MessageHeader? header = null;
                
                if (rd.Header is {Count: > 0})
                {
                    header = new MessageHeader();
                    header.HeaderData.Add(rd.Header.ToDictionary());
                }

                var envelope = new MessageEnvelope
                {
                    MessageData = bytes,
                    Sender = rd.Sender,
                    Target = targetId,
                    TypeId = typeId,
                    SerializerId = serializerId,
                    MessageHeader = header,
                    RequestId = rd.Target.RequestId
                };

                context.System.Logger()?.LogDebug("EndpointActor adding Envelope {Envelope}", envelope);

                envelopes.Add(envelope);
            }

            var batch = new MessageBatch();
            batch.TargetNames.AddRange(targetNameList);
            batch.TypeNames.AddRange(typeNameList);
            batch.Envelopes.AddRange(envelopes);

            // Logger.LogDebug("[EndpointActor] Sending {Count} envelopes for {Address}", envelopes.Count, _address);

            return SendEnvelopesAsync(batch, context);
        }

19 View Source File : EndpointActor.cs
License : Apache License 2.0
Project Creator : asynkron

private Task RemoteDeliver(IEnumerable<RemoteDeliver> m, IContext context)
        {
            var envelopes = new List<MessageEnvelope>();
            var typeNames = new Dictionary<string, int>();
            var targetNames = new Dictionary<string, int>();
            var typeNameList = new List<string>();
            var targetNameList = new List<string>();
            var counter = context.System.Metrics.Get<RemoteMetrics>().RemoteSerializedMessageCount;

            foreach (var rd in m)
            {
                var targetName = rd.Target.Id;

                if (!targetNames.TryGetValue(targetName, out var targetId))
                {
                    targetId = targetNames[targetName] = targetNames.Count;
                    targetNameList.Add(targetName);
                }

                var message = rd.Message;
                //if the message can be translated to a serialization representation, we do this here
                //this only apply to root level messages and never to nested child objects inside the message
                if (message is IRootSerializable deserialized) message = deserialized.Serialize(context.System);

                // ReSharper disable once ConditionIsAlwaysTrueOrFalse
                if (message is null)
                {
                    Logger.LogError("Null message preplaceded to EndpointActor, ignoring message");
                    continue;
                }

                ByteString bytes;
                string typeName;
                int serializerId;

                try
                {
                    bytes = SerializeMessage(_remoteConfig.Serialization, message, out typeName, out serializerId);
                }
                catch (CodedOutputStream.OutOfSpaceException oom)
                {
                    Logger.LogError(oom, "Message is too large {Message}",message.GetType().Name);
                    throw;
                }
                catch(Exception x)
                {
                    Logger.LogError(x, "Serialization failed for message {Message}",message.GetType().Name);
                    throw;
                }

                if (!context.System.Metrics.IsNoop) counter.Inc(new[] {context.System.Id, context.System.Address, typeName});

                if (!typeNames.TryGetValue(typeName, out var typeId))
                {
                    typeId = typeNames[typeName] = typeNames.Count;
                    typeNameList.Add(typeName);
                }

                MessageHeader? header = null;
                
                if (rd.Header is {Count: > 0})
                {
                    header = new MessageHeader();
                    header.HeaderData.Add(rd.Header.ToDictionary());
                }

                var envelope = new MessageEnvelope
                {
                    MessageData = bytes,
                    Sender = rd.Sender,
                    Target = targetId,
                    TypeId = typeId,
                    SerializerId = serializerId,
                    MessageHeader = header,
                    RequestId = rd.Target.RequestId
                };

                context.System.Logger()?.LogDebug("EndpointActor adding Envelope {Envelope}", envelope);

                envelopes.Add(envelope);
            }

            var batch = new MessageBatch();
            batch.TargetNames.AddRange(targetNameList);
            batch.TypeNames.AddRange(typeNameList);
            batch.Envelopes.AddRange(envelopes);

            // Logger.LogDebug("[EndpointActor] Sending {Count} envelopes for {Address}", envelopes.Count, _address);

            return SendEnvelopesAsync(batch, context);
        }

19 View Source File : OrderedDeliveryTests.cs
License : Apache License 2.0
Project Creator : asynkron

private void HandleOrderedRequest(SequentialIdRequest request, IContext context)
            {
                _seqRequests++;
                _senders.Add(request.Sender);
                var outOfOrder = _lastReceivedSeq.TryGetValue(request.SequenceKey, out var last) &&
                                 last + 1 != request.SequenceId;
                _lastReceivedSeq[request.SequenceKey] = request.SequenceId;
                if (outOfOrder) _outOfOrderErrors++;

                context.Respond(new Ack());
            }

19 View Source File : EtherScanApi.cs
License : GNU General Public License v3.0
Project Creator : atomex-me

private IEnumerable<IBlockchainTransaction> ParseTransactions(
            string responseContent,
            string txId,
            bool isInternal)
        {
            var result = new List<IBlockchainTransaction>();

            var txs = JsonConvert.DeserializeObject<Response<List<Transaction>>>(responseContent);

            var internalCounters = new Dictionary<string, int>();

            foreach (var tx in txs.Result)
            {
                if (txId == null && tx.Hash == null)
                {
                    Log.Warning("Tx with null hash received");
                    continue;
                }

                var id = tx.Hash ?? txId;

                var internalIndex = 0;

                if (isInternal)
                {
                    if (internalCounters.TryGetValue(id, out var index))
                    {
                        internalIndex = ++index;
                        internalCounters[id] = internalIndex;
                    }
                    else
                    {
                        internalCounters.Add(id, internalIndex);
                    }
                }

                var state = tx.ReceiptStatus != null
                    ? tx.ReceiptStatus.Equals("1")
                        ? BlockchainTransactionState.Confirmed
                        : BlockchainTransactionState.Failed
                    : isInternal
                        ? tx.IsError.Equals("0")
                            ? BlockchainTransactionState.Confirmed
                            : BlockchainTransactionState.Failed
                        : BlockchainTransactionState.Unconfirmed;

                result.Add(new EthereumTransaction
                {
                    Id            = id,
                    Currency      = Currency.Name,
                    Type          = BlockchainTransactionType.Unknown,
                    State         = state,
                    CreationTime  = DateTimeExtensions.UnixStartTime.AddSeconds(double.Parse(tx.TimeStamp)),

                    From          = tx.From.ToLowerInvariant(),
                    To            = tx.To.ToLowerInvariant(),
                    Input         = tx.Input,
                    Amount        = BigInteger.Parse(tx.Value),
                    Nonce         = tx.Nonce != null
                        ? BigInteger.Parse(tx.Nonce)
                        : 0,
                    GasPrice      = tx.GasPrice != null
                        ? BigInteger.Parse(tx.GasPrice)
                        : 0,
                    GasLimit      = BigInteger.Parse(tx.Gas),
                    GasUsed       = BigInteger.Parse(tx.GasUsed),
                    ReceiptStatus = state == BlockchainTransactionState.Confirmed,
                    IsInternal    = isInternal,
                    InternalIndex = internalIndex,

                    BlockInfo = new BlockInfo
                    {
                        Confirmations = tx.Confirmations != null
                            ? int.Parse(tx.Confirmations)
                            : 1,
                        BlockHash   = tx.BlockHash,
                        BlockHeight = long.Parse(tx.BlockNumber),
                        BlockTime   = DateTimeExtensions.UnixStartTime.AddSeconds(double.Parse(tx.TimeStamp)),
                        FirstSeen   = DateTimeExtensions.UnixStartTime.AddSeconds(double.Parse(tx.TimeStamp))
                    }
                });
            }

            return result;
        }

19 View Source File : UseDracoTestFileCaseAttribute.cs
License : Apache License 2.0
Project Creator : atteneder

IEnumerable<TestMethod> ITestBuilder.BuildFrom(IMethodInfo method, Test suite) {
            List<TestMethod> results = new List<TestMethod>();
            var nameCounts = new Dictionary<string, int>();

            if (m_sampleSet == null) {
                throw new Exception("SampleSet not set");
            }

            try {
                foreach (var testCase in m_sampleSet) {
                    var data = new TestCaseData(new object[] { testCase });

                    var uri = new Uri(testCase);

                    string origName = System.IO.Path.GetFileName(uri.LocalPath);
                    string name;
                    if (nameCounts.TryGetValue(origName, out int count)) {
                        name = string.Format("{0}-{1}", origName, count);
                        nameCounts[origName] = count + 1;
                    }
                    else {
                        name = origName;
                        nameCounts[origName] = 1;
                    }

                    data.SetName(name);
                    data.ExpectedResult = new UnityEngine.Object();
                    data.HasExpectedResult = true;

                    var test = this._builder.BuildTestMethod(method, suite, data);
                    if (test.parms != null)
                        test.parms.HasExpectedResult = false;

                    test.Name = name;

                    results.Add(test);
                }
            }
            catch (Exception ex) {
                Console.WriteLine("Failed to generate glTF testcases!");
                Debug.LogException(ex);
                throw;
            }

            Console.WriteLine("Generated {0} glTF test cases.", results.Count);
            return results;
        }

19 View Source File : CdcConfig.cs
License : MIT License
Project Creator : Avanade

private void PrepareJoins()
        {
            if (Joins == null)
                Joins = new List<CdcJoinConfig>();

            // Prepare the Join and also make sure the alias is unique.
            var dict = new Dictionary<string, int> { { Alias!, 1 } };
            foreach (var join in Joins)
            {
                join.Alias = DefaultWhereNull(join.Alias, () => DbTable.CreateAlias(join.Name!));

                if (dict.TryGetValue(join.Alias!, out var val))
                {
                    dict[join.Alias!] = ++val;
                    join.Alias = $"{join.Alias}{val}";
                }
                else
                    dict.Add(join.Alias!, 1);

                join.Prepare(Root!, this);
            }

            // Do some further validation.
            if (Joins.Any(x => x.Name == Name))
                throw new CodeGenException(this, nameof(Name), $"The Name '{Name}' is ambiguous (not unique); please make 'Name' unique and set 'TableName' to the actual table name to correct.");

            foreach (var j in Joins)
            {
                if (Joins.Any(x => x != j && x.Name == j.Name))
                    throw new CodeGenException(this, nameof(Joins), $"The Name '{j.Name}' is ambiguous (not unique); please make 'Name' unique and set 'TableName' to the actual table name to correct.");
            }
        }

19 View Source File : QueryConfig.cs
License : MIT License
Project Creator : Avanade

private void PrepareJoins()
        {
            if (Joins == null)
                Joins = new List<QueryJoinConfig>();

            // Prepare the Join and also make sure the alias is unique.
            var dict = new Dictionary<string, int> { { Alias!, 1 } };
            foreach (var join in Joins)
            {
                join.Prepare(Root!, this);
                if (dict.TryGetValue(join.Alias!, out var val))
                {
                    dict[join.Alias!] = val++;
                    join.Alias = $"{join.Alias}{val}";
                }
                else
                    dict.Add(join.Alias!, 1);
            }

            // Now that the alias has been updated we can prepare accordingly.
            foreach (var join in Joins)
            {
                join.PrepareJoinOn();
            }
        }

19 View Source File : PersistentConfigFileIdMap.cs
License : Apache License 2.0
Project Creator : awslabs

public bool TryGetValue(string key, out int value) => _memoryMap.TryGetValue(key, out value);

19 View Source File : RendererShader.cs
License : MIT License
Project Creator : AximoGames

private bool SetInternal<T>(string name, T value, Action<int, T> setter)
        {
            if (!_uniformLocations.TryGetValue(name, out var location))
                return false;

            LocalUniformValues.Set(location, value);

            if (CurrentHandle != Handle)
                return false;

            if (SharedUniformValues.TryGetValue(location, out var v))
            {
                if (Equals(value, v))
                    return false;

                SharedUniformValues[location] = value;
            }
            else
            {
                SharedUniformValues.Add(location, value);
            }

            Bind();
            setter(location, value);

            return true;
        }

19 View Source File : RendererShader.cs
License : MIT License
Project Creator : AximoGames

public void BindBlock(string blockName, BindingPoint bindingPoint)
        {
            if (_uniformBlockLocations.TryGetValue(blockName, out var location))
            {
                GL.UniformBlockBinding(Handle, location, bindingPoint.Number);
            }
        }

19 View Source File : GLSLLinkProgramManager.cs
License : GNU Lesser General Public License v2.1
Project Creator : axiom3d

public void ExtractConstantDefs(String src, GpuProgramParameters.GpuNamedConstants defs, String filename)
        {
            // Parse the output string and collect all uniforms
            // NOTE this relies on the source already having been preprocessed
            // which is done in GLSLProgram::loadFromSource

            string line;

            var currPos = src.IndexOf("uniform");
            while (currPos != -1)
            {
                var def = new GpuProgramParameters.GpuConstantDefinition();
                var paramName = "";

                // Now check for using the word 'uniform' in a larger string & ignore
                bool inLargerString = false;
                if (currPos != 0)
                {
                    var prev = src[currPos - 1];
                    if (prev != ' ' && prev != '\t' && prev != '\r' && prev != '\n' && prev != ';')
                    {
                        inLargerString = true;
                    }
                }
                if (!inLargerString && currPos + 7 < src.Length)
                {
                    var next = src[currPos + 7];
                    if (next != ' ' && next != '\t' && next != '\r' && next != '\n')
                    {
                        inLargerString = true;
                    }
                }

                // skip 'uniform'
                currPos += 7;

                if (!inLargerString)
                {
                    // find terminating semicolon
                    var endPos = src.IndexOf(';', currPos);
                    if (endPos == -1)
                    {
                        // problem, missing semicolon, abort
                        break;
                    }
                    line = src.Substring(currPos, endPos - currPos);

                    // Remove spaces before opening square braces, otherwise
                    // the following split() can split the line at inappropriate
                    // places (e.g. "vec3 something [3]" won't work).
                    for (var sqp = line.IndexOf(" ["); sqp != -1; sqp = line.IndexOf(" ["))
                    {
                        line.Remove(sqp, 1);
                    }

                    // Split into tokens
                    var parts = line.Split(", \t\r\n".ToCharArray());
                    foreach (var _i in parts)
                    {
                        var i = _i;
                        int typei;
                        if (this.typeEnumMap.TryGetValue(i, out typei))
                        {
                            CompleteDefInfo(typei, def);
                        }
                        else
                        {
                            // if this is not a type, and not empty, it should be a name
                            i = i.Trim();
                            if (i == string.Empty)
                            {
                                continue;
                            }

                            var arrayStart = i.IndexOf('[');
                            if (arrayStart != -1)
                            {
                                // potential name (if butted up to array)
                                var name = i.Substring(0, arrayStart);
                                name = name.Trim();
                                if (name != string.Empty)
                                {
                                    paramName = name;
                                }

                                var arrayEnd = i.IndexOf(']', arrayStart);
                                var arrayDimTerm = i.Substring(arrayStart + 1, arrayEnd - arrayStart - 1);
                                arrayDimTerm = arrayDimTerm.Trim();
                                // the array term might be a simple number or it might be
                                // an expression (e.g. 24*3) or refer to a constant expression
                                // we'd have to evaluate the expression which could get nasty
                                // TODO
                                def.ArraySize = int.Parse(arrayDimTerm);
                            }
                            else
                            {
                                paramName = i;
                                def.ArraySize = 1;
                            }

                            // Name should be after the type, so complete def and add
                            // We do this now so that comma-separated params will do
                            // this part once for each name mentioned 
                            if (def.ConstantType == GpuProgramParameters.GpuConstantType.Unknown)
                            {
                                LogManager.Instance.Write("Problem parsing the following GLSL Uniform: '" + line + "' in file " + filename);
                                // next uniform
                                break;
                            }

                            // Complete def and add
                            // increment physical buffer location
                            def.LogicalIndex = 0; // not valid in GLSL
                            if (def.IsFloat)
                            {
                                def.PhysicalIndex = defs.FloatBufferSize;
                                defs.FloatBufferSize += def.ArraySize * def.ElementSize;
                            }
                            else
                            {
                                def.PhysicalIndex = defs.IntBufferSize;
                                defs.IntBufferSize += def.ArraySize * def.ElementSize;
                            }

                            defs.Map.Add(paramName, def);

#warning this aint working properly yet (fix this as soon we need array support for GLSL!)
                            //defs.GenerateConstantDefinitionArrayEntries(paramName, def);
                        }
                    }
                }
                // Find next one
                currPos = src.IndexOf("uniform", currPos);
            }
        }

19 View Source File : ELink.cs
License : MIT License
Project Creator : azist

private void decode() //link -> props
    {
      var data = new List<byte>(32);

      char pc = (char)0;
      for (var i = 0; i < m_Link.Length; i++)
      {
        char c = m_Link[i];
        if (c == '-' || c == ' ') continue;
        if (pc != (char)0)
        {
          var seg = string.Concat(pc, c).ToUpperInvariant();
          pc = (char)0;
          if (!RALPHABET.TryGetValue(seg, out int sid))
            throw new DataException(StringConsts.ELINK_CHAR_COMBINATION_ERROR.Args(m_Link, seg));
          data.Add((byte)sid);
        }
        else
          pc = c;
      }

      if (data.Count < 4 || pc != (char)0)
        throw new DataException(StringConsts.ELINK_CHAR_LENGTH_ERROR.Args(m_Link));

      //2 control bytes
      var lead1 = data[0];
      var rnd = (lead1 & 0xf0) >> 4;
      rnd |= rnd << 4;
      var authority = lead1 & 0x0f;

      var lead2 = data[1] ^ rnd;
      var eraLength = (lead2 & 0xf0) >> 4;
      var idLength = lead2 & 0x0f;

      var csum = data[2] ^ rnd;

      if (eraLength > 4 || idLength < 1 || idLength > 8)
        throw new DataException(StringConsts.ELINK_SEGMENT_LENGTH_ERROR.Args(m_Link));

      if (data.Count - 3 < eraLength + idLength)
        throw new DataException(StringConsts.ELINK_CHAR_LENGTH_ERROR.Args(m_Link));

      uint era = 0;
      var idx = 3;
      if (eraLength > 0)
      {
        for (var i = 0; i < eraLength; i++, idx++)
          era |= (uint)((byte)(data[idx] ^ rnd)) << (8 * i);
      }

      ulong id = 0;
      if (idLength > 0)
      {
        for (var i = 0; i < idLength; i++, idx++)
          id |= (ulong)((byte)(data[idx] ^ rnd)) << (8 * i);
      }

      id |= ((ulong)authority << 60);

      byte[] metadata = null;
      if (idx < data.Count)
      {
        metadata = new byte[data.Count - idx];
        for (var j = 0; idx < data.Count; idx++, j++)
          metadata[j] = (byte)(data[idx] ^ rnd);
      }

      var thiscsum = crc(era, id, metadata);
      if (csum != thiscsum)
        throw new DataException(StringConsts.ELINK_CSUM_MISMATCH_ERROR.Args(m_Link));

      m_GDID = new GDID(era, id);
      m_Metadata = metadata;
    }

19 View Source File : BSONDocument.cs
License : MIT License
Project Creator : azist

public int IndexOfName(string name)
      {
        if (name==null) return -1;

        if (m_Dict==null) //linear search
        {
          var cnt = m_List.Count;
          for(var i=0; i<cnt; i++)
          {
            var elm = m_List[i];
            if (isSameName(name, elm.Name)) return i;
          }
          return -1;
        }

        //else use index
        int result;
        if (m_Dict.TryGetValue(name, out result)) return result;
        return -1;
      }

19 View Source File : ZoneGovernorService.cs
License : MIT License
Project Creator : azist

public int SendTelemetry(string host, Azos.Instrumentation.Datum[] data)
    {
      if (!Running || data==null) return 0;
      var sis = m_SubInstr;
      if (sis==null) return 0;

      for(var i=0; i<data.Length; i++)
      {
        var datum = data[i];
        var tpn = datum.GetType().FullName;
        int reductionLevel;

        if (!m_SubInstrReductionLevels.TryGetValue(tpn, out reductionLevel)) reductionLevel = -1;

        datum.ReduceSourceDetail(reductionLevel);
        sis.Record(datum);
      }


      if (host==null) host = string.Empty;

      m_SubInstrCallers[host] = App.TimeSource.UTCNow;

      //How many slots are available in memory
      var freeSpace = sis.MaxRecordCount - sis.RecordCount;
      var freePerClient = freeSpace / m_SubInstrCallerCount;

      var canTake = freePerClient * m_CPULoadFactor;

      return (int)canTake;
    }

19 View Source File : EqualPartitionsBalancingStrategy.cs
License : MIT License
Project Creator : Azure

private void CategorizeLeases(
            IEnumerable<DoreplacedentServiceLease> allLeases,
            Dictionary<string, DoreplacedentServiceLease> allParreplacedions,
            List<DoreplacedentServiceLease> expiredLeases,
            Dictionary<string, int> workerToParreplacedionCount)
        {
            foreach (DoreplacedentServiceLease lease in allLeases)
            {
                Debug.replacedert(lease.CurrentLeaseToken != null, "TakeLeasesAsync: lease.CurrentLeaseToken cannot be null.");

                allParreplacedions.Add(lease.CurrentLeaseToken, lease);
                if (string.IsNullOrWhiteSpace(lease.Owner) || this.IsExpired(lease))
                {
                    DefaultTrace.TraceVerbose("Found unused or expired lease: {0}", lease);
                    expiredLeases.Add(lease);
                }
                else
                {
                    string replacedignedTo = lease.Owner;
                    if (workerToParreplacedionCount.TryGetValue(replacedignedTo, out int count))
                    {
                        workerToParreplacedionCount[replacedignedTo] = count + 1;
                    }
                    else
                    {
                        workerToParreplacedionCount.Add(replacedignedTo, 1);
                    }
                }
            }

            if (!workerToParreplacedionCount.ContainsKey(this.hostName))
            {
                workerToParreplacedionCount.Add(this.hostName, 0);
            }
        }

19 View Source File : IntrinsicsGenerator.cs
License : MIT License
Project Creator : badamczewski

public string Generate(IEnumerable<CSharpToIntrinsicMethod> methods, string rootClreplacedName, string destinationClreplacedName)
        {
            Dictionary<string, int> conflictinSignatures = new Dictionary<string, int>();

            StringBuilder clreplacedBuilder = new StringBuilder();
            clreplacedBuilder.AppendLine("using System.Runtime.CompilerServices;");
            clreplacedBuilder.AppendLine("using System.Runtime.Intrinsics;");
            clreplacedBuilder.AppendLine("using System.Runtime.Intrinsics.X86;");
            clreplacedBuilder.AppendLine();

            clreplacedBuilder.AppendLine($"public clreplaced {destinationClreplacedName}");
            clreplacedBuilder.AppendLine("{");
            clreplacedBuilder.AppendLine();

            foreach (var method in methods)
            {
                if (string.IsNullOrWhiteSpace(method.IntrinsicSignature.Name))
                    continue;

                string args = "";
                string inputArgs = "";
                if (method.CsharpSignature.Arguments.Any())
                {
                    foreach (var arg in method.CsharpSignature.Arguments)
                    {
                        args += $"{arg.Name}, ";
                        inputArgs += $"{arg.ArgumentType} {arg.Name}, ";
                    }

                    args = args.Remove(args.Length - 2, 2);
                    inputArgs = inputArgs.Remove(inputArgs.Length - 2, 2);
                }

                //string convertedReturn = signature.ReturnType;
                //switch (signature.ReturnType)
                //{
                //    case "int": convertedReturn = "bool"; break;
                //    case "__int64": convertedReturn = "long"; break;
                //}
                
                string subClreplacedName = 
                    rootClreplacedName == method.CsharpSignature.ParentClreplaced ? string.Empty : method.CsharpSignature.ParentClreplaced;

                StringBuilder commentBuilder = new StringBuilder();
                commentBuilder.AppendLine(pad + "/// <summary>");
                commentBuilder.AppendLine(pad + $"/// {method.CsharpSignature.Name}");
                commentBuilder.AppendLine(pad + "/// </summary>");

                var methodNameWithArgs = $"{method.IntrinsicSignature.Name} ({inputArgs})";

                if(conflictinSignatures.TryGetValue(methodNameWithArgs, out var counter))
                {
                    conflictinSignatures[methodNameWithArgs] = counter + 1;
                    methodNameWithArgs = $"{method.IntrinsicSignature.Name}__{counter} ({inputArgs})";
                }
                else
                {
                    conflictinSignatures.Add(methodNameWithArgs, 1);
                }

                string inlineSignature = "[MethodImpl(MethodImplOptions.AggressiveInlining)]";
                string methodSignature = 
                    $"public static " +
                    $"{(method.CsharpSignature.IsUnsafe ? "unsafe " : string.Empty)}" +
                    $"{method.CsharpSignature.ReturnType} {methodNameWithArgs}";

                string bracketOpen = "{";

                string methodImplementation = 
                    $"{(method.CsharpSignature.ReturnType == "void" ? string.Empty : "return")} " +
                    $"{rootClreplacedName}{(subClreplacedName != string.Empty ? "." + subClreplacedName : string.Empty)}.{method.CsharpSignature.Name}" +
                    $"({args});";


                string bracketClose = "}";

                clreplacedBuilder.AppendLine(commentBuilder.ToString());
                clreplacedBuilder.AppendLine(pad + inlineSignature);
                clreplacedBuilder.AppendLine(pad + methodSignature);
                clreplacedBuilder.AppendLine(pad + bracketOpen);
                clreplacedBuilder.AppendLine(pad + pad + methodImplementation);
                clreplacedBuilder.AppendLine(pad + bracketClose);

                ConsoleUtils.WriteLine(pad + inlineSignature);
                ConsoleUtils.WriteLine(pad + methodSignature);
                ConsoleUtils.WriteLine(ConsoleColor.White, pad + bracketOpen);
                ConsoleUtils.WriteLine(pad + methodImplementation);
                ConsoleUtils.WriteLine(ConsoleColor.White, pad + bracketClose);
            }

            clreplacedBuilder.AppendLine("}");

            return clreplacedBuilder.ToString();
        }

19 View Source File : OperationsProcessor.cs
License : MIT License
Project Creator : baking-bad

public async Task Subscribe(IClientProxy client, string connectionId, OperationsParameter parameter)
        {
            Task sending = Task.CompletedTask;
            try
            {
                await Sema.WaitAsync();
                Logger.LogDebug("New subscription...");

                #region check limits
                if (Limits.TryGetValue(connectionId, out var cnt) && cnt >= Config.MaxOperationSubscriptions)
                    throw new HubException($"Subscriptions limit exceeded");

                if (cnt > 0) // reuse already allocated string
                    connectionId = Limits.Keys.First(x => x == connectionId);
                #endregion

                #region add to subs
                foreach (var type in parameter.TypesList)
                {
                    if (!TypesSubs.TryGetValue(type, out var typeSub))
                    {
                        typeSub = new();
                        TypesSubs.Add(type, typeSub);
                    }
                    if (parameter.Address == null)
                    {
                        typeSub.All ??= new();
                        if (typeSub.All.Add(connectionId))
                            Limits[connectionId] = Limits.GetValueOrDefault(connectionId) + 1;
                    }   
                    else
                    {
                        typeSub.Addresses ??= new(4);
                        if (!typeSub.Addresses.TryGetValue(parameter.Address, out var addressSub))
                        {
                            addressSub = new(4);
                            typeSub.Addresses.Add(parameter.Address, addressSub);
                        }

                        if (addressSub.Add(connectionId))
                            Limits[connectionId] = Limits.GetValueOrDefault(connectionId) + 1;
                    }
                }
                #endregion

                #region add to group
                await Context.Groups.AddToGroupAsync(connectionId, OperationsGroup);
                #endregion

                sending = client.SendState(OperationsChannel, State.Current.Level);

                Logger.LogDebug("Client {0} subscribed with state {1}", connectionId, State.Current.Level);
            }
            catch (HubException)
            {
                throw;
            }
            catch (Exception ex)
            {
                Logger.LogError("Failed to add subscription: {0}", ex.Message);
            }
            finally
            {
                Sema.Release();
                try
                {
                    await sending;
                }
                catch (Exception ex)
                {
                    // should never get here
                    Logger.LogError("Sending failed: {0}", ex.Message);
                }
            }
        }

See More Examples