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

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

1978 Examples 7

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

public override string GetUID(string key) {
            if (key.IsNullOrEmpty())
                return "";
            lock (GlobalLock) {
                if (LoadRaw<Global>(GlobalPath).UIDs.TryGetValue(key, out string? uid))
                    return uid;
                return "";
            }
        }

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

public override void RevokeKey(string key) {
            lock (GlobalLock) {
                Global global = LoadRaw<Global>(GlobalPath);
                if (!global.UIDs.TryGetValue(key, out string? uid))
                    return;

                global.UIDs.Remove(key);
                SaveRaw(GlobalPath, global);

                Delete<PrivateUserInfo>(uid);
            }
        }

19 View Source File : Configuration.ValueConfig.cs
License : GNU Affero General Public License v3.0
Project Creator : 0ceal0t

public ElementColor Get(string name, ElementColor defaultColor) => Color.TryGetValue(name, out var val) ?
            UIColor.GetColor(val, defaultColor) : defaultColor;

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

public static string ChangePath(string path, char separator) {
            // Can't trust File.Exists if MONO_IOMAP_ALL is set.
            if (!MONO_IOMAP_ALL) {
                string pathMaybe = path;
                // Check if target exists in the first place.
                if (Directory.Exists(path) || File.Exists(path))
                    return pathMaybe;

                // Try a simpler fix first: Maybe the casing is already correct...
                pathMaybe = path.Replace('/', separator).Replace('\\', separator);
                if (Directory.Exists(pathMaybe) || File.Exists(pathMaybe))
                    return pathMaybe;

                // Fall back to the slow rebuild.
            }

            // Check if the path has been rebuilt before.
            Dictionary<string, string> cachedPaths;
            if (!_CachedChanges.TryGetValue(separator, out cachedPaths))
                _CachedChanges[separator] = cachedPaths = new Dictionary<string, string>();
            string cachedPath;
            if (cachedPaths.TryGetValue(path, out cachedPath))
                return cachedPath;

            // Split and rebuild path.

            string[] pathSplit = path.Split(DirectorySeparatorChars);

            StringBuilder builder = new StringBuilder();

            bool unixRooted = false;

            if (Path.IsPathRooted(path)) {
                // The first element in a rooted path will always be correct.
                // On Windows, this will be the drive letter.
                // On Unix and Unix-like systems, this will be empty.
                if (unixRooted = (builder.Length == 0))
                    // Path is rooted, but the path separator is the root.
                    builder.Append(separator);
                else
                    builder.Append(pathSplit[0]);
            }

            for (int i = 1; i < pathSplit.Length; i++) {
                string next;
                if (i < pathSplit.Length - 1)
                    next = GetDirectory(builder.ToString(), pathSplit[i]);
                else
                    next = GetTarget(builder.ToString(), pathSplit[i]);
                next = next ?? pathSplit[i];

                if (i != 1 || !unixRooted)
                    builder.Append(separator);

                builder.Append(next);
            }

            return cachedPaths[path] = builder.ToString();
        }

19 View Source File : TestFileSystem.cs
License : MIT License
Project Creator : 0x1000000

public string ReadAllText(string path)
        {
            if (this._files.TryGetValue(path, out var list))
            {
                return list;
            }
            throw new Exception("File does not exists: " + path);
        }

19 View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever

private static bool IsMatch(Dictionary<string, string> hashes, List<Dictionary<string, string>> expectedHashes)
        {
            foreach (var eh in expectedHashes)
            foreach (var h in hashes)
                if (eh.TryGetValue(h.Key, out var expectedHash) && expectedHash == h.Value)
                    return true;
            return false;
        }

19 View Source File : Server.cs
License : MIT License
Project Creator : 5minlab

static void FindFileType(RequestContext context, bool download, out string path, out string type) {
            path = Path.Combine(fileRoot, context.match.Groups[1].Value);

            string ext = Path.GetExtension(path).ToLower().TrimStart(new char[] { '.' });
            if (download || !fileTypes.TryGetValue(ext, out type))
                type = "application/octet-stream";
        }

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

private List<ConfigModel> GetAppConfigValue(Dictionary<string,string> configDic, Type type, string parentName = "")
        {
            var configs = new List<ConfigModel>();
            PropertyInfo[] props = type.GetProperties();
            foreach (PropertyInfo prop in props)
            {

                string name = prop.Name;
                string key = string.IsNullOrEmpty(parentName) ? $"{name}" : $"{parentName}:{name}";

                if (prop.PropertyType.IsValueType || prop.PropertyType.Name.StartsWith("String"))
                {
                    string value = "";
                    try
                    {
                        configDic.TryGetValue(key, out  value);
                    }
                    catch (Exception)
                    {

                    }

                    if (string.IsNullOrEmpty(value))
                    {
                        if (prop.PropertyType == typeof(int) || prop.PropertyType == typeof(int?) ||
                            prop.PropertyType == typeof(bool) || prop.PropertyType == typeof(bool?) ||
                            prop.PropertyType == typeof(float) || prop.PropertyType == typeof(float?) ||
                            prop.PropertyType == typeof(double)|| prop.PropertyType == typeof(double?) 
                            )
                        {
                            var defaultValue = Activator.CreateInstance(prop.PropertyType);
                            value = defaultValue.ToString();
                        }
                        else if (prop.PropertyType == typeof(DateTime?) || prop.PropertyType == typeof(DateTime))
                        {
                            value = DateTime.Now.ToString();
                        }
                        else if (prop.PropertyType == typeof(Guid?) || prop.PropertyType == typeof(Guid))
                        {
                            value = Guid.Empty.ToString();
                        }
                    }

                    var attribute = prop.GetCustomAttribute(typeof(DisplayNameAttribute)) as DisplayNameAttribute;
                    configs.Add(new ConfigModel
                    {
                        Key = key,
                        Name = attribute?.DisplayName ?? name,
                        Value = value,
                        Type = prop.PropertyType
                    });
                }
                else
                {
                    configs.AddRange(GetAppConfigValue(configDic, prop.PropertyType, key));
                }

            }

            return configs;
        }

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

static public LoadedreplacedetBundle GetLoadedreplacedetBundle(string replacedetBundleName, out string error)
		{
			if (m_DownloadingErrors.TryGetValue(replacedetBundleName, out error))
			{
				if (!error.StartsWith("-"))
				{
					m_DownloadingErrors[replacedetBundleName] = "-" + error;
#if UNITY_EDITOR
					if (replacedetBundleName == Utility.GetPlatformName().ToLower() + "index")
					{
						if (EditorPrefs.GetBool(Application.dataPath+"LocalreplacedetBundleServerEnabled") == false || SimpleWebServer.serverStarted == false)//when the user restarts Unity this might be true even if the server has not actually been started
						{
							if (SimulatereplacedetBundleInEditor)
							{
								//we already outputted a message in Dynamicreplacedetloader
							}
							else
							{
								Debug.LogWarning("replacedetBundleManager could not download the replacedetBundleIndex from the Remote Server URL you have set in DynamicreplacedetLoader. Have you set the URL correctly and uploaded your replacedetBundles?");
								error = "replacedetBundleManager could not download the replacedetBundleIndex from the Remote Server URL you have set in DynamicreplacedetLoader. Have you set the URL correctly and uploaded your replacedetBundles?";
							}
						}
						else
						{

							//Otherwise the replacedetBundles themselves will not have been built.
							Debug.LogWarning("Switched to Simulation mode because no replacedetBundles were found. Have you build them? (Go to 'replacedets/replacedetBundles/Build replacedetBundles').");
							error = "Switched to Simulation mode because no replacedetBundles were found.Have you build them? (Go to 'replacedets/replacedetBundles/Build replacedetBundles').";
							//this needs to hide the loading infobox- or something needs too..
						}
						SimulateOverride = true;
					}
					else
#endif
						Debug.LogWarning("Could not return " + replacedetBundleName + " because of error:" + error);
				}
				return null;
			}

			LoadedreplacedetBundle bundle = null;
			m_LoadedreplacedetBundles.TryGetValue(replacedetBundleName, out bundle);
			if (bundle == null)
				return null;

			// No dependencies are recorded, only the bundle itself is required.
			string[] dependencies = null;
			if (!m_Dependencies.TryGetValue(replacedetBundleName, out dependencies))
				return bundle;

			// Otherwise Make sure all dependencies are loaded
			foreach (var dependency in dependencies)
			{
				if (m_DownloadingErrors.TryGetValue(dependency, out error))
					return null;
				// Wait all the dependent replacedetBundles being loaded.
				LoadedreplacedetBundle dependentBundle = null;
				m_LoadedreplacedetBundles.TryGetValue(dependency, out dependentBundle);
				if (dependentBundle == null)
					return null;
			}
			return bundle;
		}

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

static public float GetBundleDownloadProgress(string replacedetBundleName, bool andDependencies)
		{
			float overallProgress = 0;
			string error;
			if (m_DownloadingErrors.TryGetValue(replacedetBundleName, out error))
			{
				Debug.LogWarning(error);
				return 0;
			}

			if (m_LoadedreplacedetBundles.ContainsKey(replacedetBundleName))
			{
				overallProgress = 1f;
			}
			else
			{
				//find out its progress
				foreach (replacedetBundleLoadOperation operation in m_InProgressOperations)
				{
					if (operation.GetType() == typeof(replacedetBundleDownloadOperation) || operation.GetType().IsSubclreplacedOf(typeof(replacedetBundleDownloadOperation)))
					{
						replacedetBundleDownloadOperation typedOperation = (replacedetBundleDownloadOperation)operation;
						if (typedOperation.replacedetBundleName == replacedetBundleName)
							overallProgress = typedOperation.downloadProgress == 1f ? 0.99f : typedOperation.downloadProgress;
					}
				}
			}
			//deal with dependencies if necessary
			if (andDependencies)
			{
				string[] dependencies = null;
				m_Dependencies.TryGetValue(replacedetBundleName, out dependencies);
				if (dependencies != null)
				{
					if (dependencies.Length > 0)
					{
						foreach (string dependency in dependencies)
						{
							if (m_LoadedreplacedetBundles.ContainsKey(dependency))
							{
								overallProgress += 1;
							}
							else //It must be in progress
							{
								foreach (replacedetBundleLoadOperation operation in m_InProgressOperations)
								{
									if (operation.GetType() == typeof(replacedetBundleDownloadOperation) || operation.GetType().IsSubclreplacedOf(typeof(replacedetBundleDownloadOperation)))
									{
										replacedetBundleDownloadOperation typedOperation = (replacedetBundleDownloadOperation)operation;
										if (typedOperation.replacedetBundleName == dependency)
											overallProgress += typedOperation.downloadProgress == 1f ? 0.99f : typedOperation.downloadProgress;
									}
								}
							}
						}
						//divide by num dependencies +1
						overallProgress = overallProgress / (dependencies.Length + 1);
					}
				}
			}
			return overallProgress;
		}

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

public static void DebugLogHumanAvatar(GameObject root, HumanDescription description)
		{
			Debug.Log("***", root);
			Dictionary<String, String> bones = new Dictionary<String, String>();
			foreach (var sb in description.skeleton)
			{
				Debug.Log(sb.name);
				bones[sb.name] = sb.name;
			}
			Debug.Log("----");
			foreach (var hb in description.human)
			{
				string boneName;
				if (bones.TryGetValue(hb.boneName, out boneName))
				{
					Debug.Log(hb.humanName + " -> " + boneName);
				}
				else
				{
					Debug.LogWarning(hb.humanName + " !-> " + hb.boneName);
				}
			}
			Debug.Log("++++");
		}

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

[CommandHandler("config", AccessLevel.Player, CommandHandlerFlag.RequiresWorld, 1, "Manually sets a character option on the server.\nUse /config list to see a list of settings.", "<setting> <on/off>")]
        public static void HandleConfig(Session session, params string[] parameters)
        {
            if (!PropertyManager.GetBool("player_config_command").Item)
            {
                session.Network.EnqueueSend(new GameMessageSystemChat("The command \"config\" is not currently enabled on this server.", ChatMessageType.Broadcast));
                return;
            }

            // /config list - show character options
            if (parameters[0].Equals("list", StringComparison.OrdinalIgnoreCase))
            {
                foreach (var line in configList)
                    session.Network.EnqueueSend(new GameMessageSystemChat(line, ChatMessageType.Broadcast));

                return;
            }

            // translate GDLE CharacterOptions for existing plugins
            if (!translateOptions.TryGetValue(parameters[0], out var param) || !Enum.TryParse(param, out CharacterOption characterOption))
            {
                session.Network.EnqueueSend(new GameMessageSystemChat($"Unknown character option: {parameters[0]}", ChatMessageType.Broadcast));
                return;
            }

            var option = session.Player.GetCharacterOption(characterOption);

            // modes of operation:
            // on / off / toggle

            // - if none specified, default to toggle
            var mode = "toggle";

            if (parameters.Length > 1)
            {
                if (parameters[1].Equals("on", StringComparison.OrdinalIgnoreCase))
                    mode = "on";
                else if (parameters[1].Equals("off", StringComparison.OrdinalIgnoreCase))
                    mode = "off";
            }

            // set character option
            if (mode.Equals("on"))
                option = true;
            else if (mode.Equals("off"))
                option = false;
            else
                option = !option;

            session.Player.SetCharacterOption(characterOption, option);

            session.Network.EnqueueSend(new GameMessageSystemChat($"Character option {parameters[0]} is now {(option ? "on" : "off")}.", ChatMessageType.Broadcast));

            // update client
            session.Network.EnqueueSend(new GameEventPlayerDescription(session));
        }

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

public static string GetEnvironmentVariable(this Process process, IHostContext hostContext, string variable)
        {
            var trace = hostContext.GetTrace(nameof(LinuxProcessExtensions));
            Dictionary<string, string> env = new Dictionary<string, string>();

            if (Directory.Exists("/proc"))
            {
                string envFile = $"/proc/{process.Id}/environ";
                trace.Info($"Read env from {envFile}");
                string envContent = File.ReadAllText(envFile);
                if (!string.IsNullOrEmpty(envContent))
                {
                    // on linux, environment variables are seprated by '\0'
                    var envList = envContent.Split('\0', StringSplitOptions.RemoveEmptyEntries);
                    foreach (var envStr in envList)
                    {
                        // split on the first '='
                        var keyValuePair = envStr.Split('=', 2);
                        if (keyValuePair.Length == 2)
                        {
                            env[keyValuePair[0]] = keyValuePair[1];
                            trace.Verbose($"PID:{process.Id} ({keyValuePair[0]}={keyValuePair[1]})");
                        }
                    }
                }
            }
            else
            {
                // On OSX, there is no /proc folder for us to read environment for given process,
                // So we have call `ps e -p <pid> -o command` to print out env to STDOUT,
                // However, the output env are not format in a parseable way, it's just a string that concatenate all envs with space,
                // It doesn't escape '=' or ' ', so we can't parse the output into a dictionary of all envs.
                // So we only look for the env you request, in the format of variable=value. (it won't work if you variable contains = or space)
                trace.Info($"Read env from output of `ps e -p {process.Id} -o command`");
                List<string> psOut = new List<string>();
                object outputLock = new object();
                using (var p = hostContext.CreateService<IProcessInvoker>())
                {
                    p.OutputDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stdout)
                    {
                        if (!string.IsNullOrEmpty(stdout.Data))
                        {
                            lock (outputLock)
                            {
                                psOut.Add(stdout.Data);
                            }
                        }
                    };

                    p.ErrorDataReceived += delegate (object sender, ProcessDataReceivedEventArgs stderr)
                    {
                        if (!string.IsNullOrEmpty(stderr.Data))
                        {
                            lock (outputLock)
                            {
                                trace.Error(stderr.Data);
                            }
                        }
                    };

                    int exitCode = p.ExecuteAsync(workingDirectory: hostContext.GetDirectory(WellKnownDirectory.Root),
                                                  fileName: "ps",
                                                  arguments: $"e -p {process.Id} -o command",
                                                  environment: null,
                                                  cancellationToken: CancellationToken.None).GetAwaiter().GetResult();
                    if (exitCode == 0)
                    {
                        trace.Info($"Successfully dump environment variables for {process.Id}");
                        if (psOut.Count > 0)
                        {
                            string psOutputString = string.Join(" ", psOut);
                            trace.Verbose($"ps output: '{psOutputString}'");

                            int varStartIndex = psOutputString.IndexOf(variable, StringComparison.Ordinal);
                            if (varStartIndex >= 0)
                            {
                                string rightPart = psOutputString.Substring(varStartIndex + variable.Length + 1);
                                if (rightPart.IndexOf(' ') > 0)
                                {
                                    string value = rightPart.Substring(0, rightPart.IndexOf(' '));
                                    env[variable] = value;
                                }
                                else
                                {
                                    env[variable] = rightPart;
                                }

                                trace.Verbose($"PID:{process.Id} ({variable}={env[variable]})");
                            }
                        }
                    }
                }
            }

            if (env.TryGetValue(variable, out string envVariable))
            {
                return envVariable;
            }
            else
            {
                return null;
            }
        }

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

public bool MoveNext()
        {
            while (originalWords != null && currentIndex < (originalWords.Length - 1))
            {
                currentIndex++;

                // Continue if a number is found...
                if (rgx.IsMatch(Currentreplacedtring)) {
                    continue;
                }

                if (autoReplacementList.ContainsKey(Currentreplacedtring)) {
                    string replacement;
                    if (autoReplacementList.TryGetValue(Currentreplacedtring, out replacement)) {
                        // FIXME this reaplces the first, not the current.
                        ReplaceCurrent(replacement);
                        continue;
                    }
                }

                if (!hunspell.Spell(originalWords[currentIndex].Trim())) {
                    return false;
                }
            }

            // Reset here so any futures checks in this actually check the whole string.
            Reset();
            return true;
        }

19 View Source File : FileHandle.cs
License : MIT License
Project Creator : action-bi-toolkit

private static string ResolveDosFilePath(string name)
        {
            if (string.IsNullOrEmpty(name)) return null;

            var volumeNumberLocation = 0;
            for (var j = 0; j < 2 && volumeNumberLocation != -1; j++)
            {
                volumeNumberLocation = name.IndexOf('\\', volumeNumberLocation + 1);
            }

            if (volumeNumberLocation == -1)
            {
                volumeNumberLocation = name.Length;
            }

            var volumeNumber = name.Substring(0, volumeNumberLocation);
            if (DeviceMap.TryGetValue(volumeNumber, out var drive))
            {
                return Regex.Replace(name, Regex.Escape(volumeNumber), drive,
                    RegexOptions.IgnoreCase);
            }

            return null;
        }

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

private string GetEnvArg(string name)
        {
            string val;
            if (_envArgs.TryGetValue(name, out val) && !string.IsNullOrEmpty(val))
            {
                _trace.Info($"Env arg '{name}': '{val}'");
                return val;
            }

            return null;
        }

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

protected void AddPrependPathToEnvironment()
        {
            // Validate args.
            Trace.Entering();
            ArgUtil.NotNull(ExecutionContext.Global.PrependPath, nameof(ExecutionContext.Global.PrependPath));
            if (ExecutionContext.Global.PrependPath.Count == 0)
            {
                return;
            }

            // Prepend path.
            string prepend = string.Join(Path.PathSeparator.ToString(), ExecutionContext.Global.PrependPath.Reverse<string>());
            var containerStepHost = StepHost as ContainerStepHost;
            if (containerStepHost != null)
            {
                containerStepHost.PrependPath = prepend;
            }
            else
            {
                string taskEnvPATH;
                Environment.TryGetValue(Constants.PathVariable, out taskEnvPATH);
                string originalPath = RuntimeVariables.Get(Constants.PathVariable) ?? // Prefer a job variable.
                    taskEnvPATH ?? // Then a task-environment variable.
                    System.Environment.GetEnvironmentVariable(Constants.PathVariable) ?? // Then an environment variable.
                    string.Empty;
                string newPath = PathUtil.PrependPath(prepend, originalPath);
                AddEnvironmentVariable(Constants.PathVariable, newPath);
            }
        }

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

private string GetRepositoryPath(string filePath, int recursion = 0)
        {
            // Prevent the cache from growing too much
            if (_directoryMap.Count > 100)
            {
                _directoryMap.Clear();
            }

            // Empty directory means we hit the root of the drive
            var directoryPath = Path.GetDirectoryName(filePath);
            if (string.IsNullOrEmpty(directoryPath) || recursion > _failsafe)
            {
                return null;
            }

            // Check the cache
            if (_directoryMap.TryGetValue(directoryPath, out string repositoryPath))
            {
                return repositoryPath;
            }

            try
            {
                // Check if .git/config exists
                var gitConfigPath = Path.Combine(directoryPath, ".git", "config");
                if (File.Exists(gitConfigPath))
                {
                    // Check if the config contains the workflow repository url
                    var serverUrl = _executionContext.GetGitHubContext("server_url");
                    serverUrl = !string.IsNullOrEmpty(serverUrl) ? serverUrl : "https://github.com";
                    var host = new Uri(serverUrl, UriKind.Absolute).Host;
                    var nameWithOwner = _executionContext.GetGitHubContext("repository");
                    var patterns = new[] {
                        $"url = {serverUrl}/{nameWithOwner}",
                        $"url = [email protected]{host}:{nameWithOwner}.git",
                    };
                    var content = File.ReadAllText(gitConfigPath);
                    foreach (var line in content.Split("\n").Select(x => x.Trim()))
                    {
                        foreach (var pattern in patterns)
                        {
                            if (String.Equals(line, pattern, StringComparison.OrdinalIgnoreCase))
                            {
                                repositoryPath = directoryPath;
                                break;
                            }
                        }
                    }
                }
                else
                {
                    // Recursive call
                    repositoryPath = GetRepositoryPath(directoryPath, recursion + 1);
                }
            }
            catch (Exception ex)
            {
                _executionContext.Debug($"Error when attempting to determine whether the path '{filePath}' is under the workflow repository: {ex.Message}");
            }

            _directoryMap[directoryPath] = repositoryPath;
            return repositoryPath;
        }

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

internal static string GetScriptArgumentsFormat(string scriptType)
        {
            if (_defaultArguments.TryGetValue(scriptType, out var argFormat))
            {
                return argFormat;
            }
            return "";
        }

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

internal static string GetScriptFileExtension(string scriptType)
        {
            if (_extensions.TryGetValue(scriptType, out var extension))
            {
                return extension;
            }
            return "";
        }

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

private String GetValueOrDefault(String key)
        {
            String value;
            if (!TryGetValue(key, out value))
            {
                value = null;
            }

            return value;
        }

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

private static string FixWords(string original)
        {
            if (original.StartsWith("`") || original.StartsWith("‘"))
            {
                original = original.Remove(0, 1);
            }
            return Words.Replace
            (original,
                m => WordFixes.TryGetValue(m.Groups[1].Value, out var value) ?
                    value :
                    m.Groups[1].Value);
        }

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

public static Territory GetTerritory(string localizedName)
        {
            var acceptableDistance = localizedName.Length > 10 ? 2 : 1;


            if (TerritoryNames == null || TerritoryNames.Count == 0)
            {
                return null;
            }

            if (TerritoryNames.TryGetValue(localizedName, out var territoryId))
            {
                return new Territory { TerritoryId= territoryId, Name = localizedName};
            }

            if (localizedName.Contains("m"))
            {
                var rrName = localizedName.Replace("m", "rr");
                if (TerritoryNames.TryGetValue(rrName, out var rrId))
                {
                    return new Territory { TerritoryId = rrId, Name = rrName };
                }
            }

            var smallestDistance = int.MaxValue;
            var currentName = localizedName;
            foreach (var itemName in TerritoryNames.Keys)
            {
                var distance = DamerauLevenshteinDistance(localizedName, itemName, 5);
                if (smallestDistance <= distance) continue;
                smallestDistance = distance;
                currentName = itemName;
            }

            if (smallestDistance <= acceptableDistance)
            {
                return new Territory { TerritoryId = TerritoryNames[currentName], Name = currentName };
            }

            return null;

        }

19 View Source File : WorldControllerEditor.cs
License : MIT License
Project Creator : adamgoodrich

private void DrawHelpLabel(string replacedle)
        {
            if (m_globalHelp)
            {
                string description;
                if (m_tooltips.TryGetValue(replacedle, out description))
                {
                    //EditorGUILayout.LabelField(string.Format("<color=lightblue><b>{0}</b>\n{1}</color>", replacedle, description), m_wrapHelpStyle);
                    EditorGUI.indentLevel++;
                    if (EditorGUIUtility.isProSkin)
                    {
                        EditorGUILayout.LabelField(string.Format("<color=#98918F>{0}</color>", description), m_wrapHelpStyle);
                    }
                    else
                    {
                        EditorGUILayout.LabelField(string.Format("<color=#6F6C6F>{0}</color>", description), m_wrapHelpStyle);
                    }
                    EditorGUI.indentLevel--;
                }
            }
        }

19 View Source File : WorldControllerEditor.cs
License : MIT License
Project Creator : adamgoodrich

GUIContent GetLabel(string name)
        {
            string tooltip = "";
            if (m_showTooltips)
            {
                if (m_tooltips.TryGetValue(name, out tooltip))
                {
                    return new GUIContent(name, tooltip);
                }
                else
                {
                    return new GUIContent(name);
                }
            }
            else
            {
                return new GUIContent(name);
            }
        }

19 View Source File : MainViewModel.cs
License : GNU General Public License v3.0
Project Creator : AdamMYoung

private void LoadGroup()
        {
#if (DEBUG)
            Group = FileManager.LoadGroups().First();
        #endif

#if (!DEBUG)
            var args = Environment.GetCommandLineArgs();
            var dictionary = new Dictionary<string, string>();

            for (var index = 1; index < args.Length; index += 2) dictionary.Add(args[index], args[index + 1]);

            if (dictionary.TryGetValue("/GroupId", out var value))
                Group = FileManager.LoadGroups().FirstOrDefault(x => x.Uid == value);
#endif
        }

19 View Source File : WorldControllerEditor.cs
License : MIT License
Project Creator : adamgoodrich

private void DrawHelpSectionLabel(string replacedle)
        {
            if (m_globalHelp)
            {
                string description;
                if (m_tooltips.TryGetValue(replacedle, out description))
                {
                    GUILayout.BeginVertical(m_boxStyle);
                    if (EditorGUIUtility.isProSkin)
                    {
                        EditorGUILayout.LabelField(string.Format("<color=#CBC5C1><b>{0}</b>\n\n{1}\n</color>", replacedle, description), m_wrapHelpStyle);
                    }
                    else
                    {
                        EditorGUILayout.LabelField(string.Format("<color=#3F3D40><b>{0}</b>\n\n{1}\n</color>", replacedle, description), m_wrapHelpStyle);
                    }
                    GUILayout.EndVertical();
                }
            }
        }

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

private static void SetResponseParameters(HttpResponse response, string virtualPath, string resourceName)
		{
			var extensionWithDot = Path.GetExtension(virtualPath);
			var extension = extensionWithDot != null ? extensionWithDot.TrimStart('.') : string.Empty;

			string contentType;

			if (!string.IsNullOrWhiteSpace(extension) && _mimeMap.TryGetValue(extension, out contentType))
			{
				response.ContentType = contentType;
			}
		}

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

private static Func<Guid, Guid, string> Memoize(Func<Guid, Guid, string> getResult)
		{
			var cache = new Dictionary<string, string>();

			return (a, b) =>
			{
				var key = "{0}:{1}".FormatWith(a, b);
				string result;

				if (cache.TryGetValue(key, out result))
				{
					return result;
				}

				result = getResult(a, b);

				cache[key] = result;

				return result;
			};
		}

19 View Source File : StringExtensions.cs
License : MIT License
Project Creator : adrianoc

internal static string[] CloneMethodReferenceOverriding(this string methodRef, IVisitorContext context, Dictionary<string, string> overridenProperties, bool hasParameters, out string resolvedVariable)
        {
            var exps = new List<string>();
            var cloned = new StringBuilder($"new MethodReference({methodRef}.Name, {methodRef}.ReturnType) {{ ");
            foreach (var propName in methodReferencePropertiesToClone)
            {
                if (!overridenProperties.TryGetValue(propName, out var propValue))
                {
                    propValue = $"{methodRef}.{propName}";
                }

                cloned.AppendFormat($" {propName} = {propValue},");
            }

            cloned.Append("}");
            
            if (hasParameters)
            {
                resolvedVariable = context.Naming.SyntheticVariable("m", ElementKind.Method);
                
                exps.Add($"var {resolvedVariable} = {cloned};");
                exps.Add($"foreach(var p in {methodRef}.Parameters)");
                exps.Add("{");
                exps.Add($"\t{resolvedVariable}.Parameters.Add(new ParameterDefinition(p.Name, p.Attributes, p.ParameterType));");
                exps.Add("}");
            }
            else
            {
                resolvedVariable = cloned.ToString();
            }
            
            return exps.ToArray();
        }

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

private string NewName(string name)
        {
            string newName;
            if(!nameMap.TryGetValue(name, out newName))
            {
                nameMap[name] = newName = ToString(next);
				next = next * 0x15660D + 0x3D6EF85F;
            }
            return newName;
        }

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

public bool GetBool(string key)
        {
            bool result;
            if (booleans.TryGetValue(key, out result))
            {
                return result;
            }
            string val;
            if (allValues.TryGetValue(key, out val))
            {
                if (bool.TryParse(val, out result))
                {
                    booleans.Add(key, result);
                }
            }
            return result;
        }

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

public string GetString(string key)
        {
            string result = string.Empty;
            if (strings.TryGetValue(key, out result))
            {
                return result;
            }
            if (allValues.TryGetValue(key, out result))
            {
                strings.Add(key, result);
            }
            else
            {
                result = string.Empty;
            }
            return result;
        }

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

public float GetFloat(string key)
        {
            float result;
            if (floats.TryGetValue(key, out result))
            {
                return result;
            }
            string val;
            if (allValues.TryGetValue(key, out val))
            {
                if (float.TryParse(val, out result))
                {
                    floats.Add(key, result);
                }
            }
            return result;
        }

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 : Localization.cs
License : GNU General Public License v3.0
Project Creator : aelariane

public string Get(string key)
    {
        string text;
        return (!this.mDictionary.TryGetValue(key, out text)) ? key : text;
    }

19 View Source File : Util.cs
License : MIT License
Project Creator : Aeroblast

public static string GetMimeType(string filename)
    {
        string a;
        bool r = mimeMap.TryGetValue(Path.GetExtension(filename).ToLower(), out a);
        if (r) return a;
        else return null;

    }

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

private string Convert(MemberExpression expression)
        {
            if (expression.Expression is ParameterExpression)
            {
                string field;
                if (!_columnMap.TryGetValue(expression.Member.Name, out field))
                {
                    throw new ArgumentException(@"�ֶβ����������ݿ���", expression.Member.Name);
                }
                return $"[{field}]";
            }
            var par1 = expression.Expression as MemberExpression;
            if (par1?.Expression is ParameterExpression)
            {
                if (par1.Type == typeof(string))
                {
                    switch (expression.Member.Name)
                    {
                        case "Length":
                            return $"LEN([{par1.Member.Name}])";
                    }
                }
                if (par1.Type == typeof(DateTime))
                {
                    switch (expression.Member.Name)
                    {
                        case "Now":
                            return $"@{_condition.AddParameter(DateTime.Now)}";
                        case "Today":
                            return $"@{_condition.AddParameter(DateTime.Today)}";
                    }
                }
                throw new ArgumentException("��֧�ֵ���չ����");
            }
            var vl = GetValue(expression);
            if (vl.GetType().IsValueType)
            {
                return $"@{_condition.AddParameter(vl)}";
            }
            if (vl is string)
            {
                return $"@{_condition.AddParameter(vl)}";
            }
            var ilist = vl as IList<int>;
            if (ilist != null)
            {
                return string.Join(",", ilist);
            }
            var slist = vl as IList<string>;
            if (slist != null)
            {
                return "'" + string.Join("','", slist) + "'";
            }
            var dlist = vl as IList<DateTime>;
            if (dlist != null)
            {
                return "'" + string.Join("','", dlist) + "'";
            }
            return $"@{_condition.AddParameter(vl)}";
        }

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

protected virtual bool CheckFieldMaps()
        {
            var row = Sheet.GetRow(0);
            ColumnFields = new Dictionary<int, string>();
            var emptyCnt = 0;
            MaxColumn = 0;
            for (var column = 0; column < short.MaxValue; column++)
            {
                var cell = row.GetCell(column);
                if (cell == null)
                {
                    if (++emptyCnt > 3) break;
                    continue;
                }

                if (cell.CellType != CellType.String) cell.SetCellType(CellType.String);
                var field = cell.StringCellValue;
                if (string.IsNullOrWhiteSpace(field))
                {
                    if (++emptyCnt > 3) break;
                    continue;
                }
                //if (emptyCnt > 0)
                //{
                //    WriteCellState(row, column, "�ֶ�����Ϊ�հ�,����ֱ����ֹ", true);
                //    return false;
                //}

                if (!FieldMap.TryGetValue(field.Trim(), out var innerFile)) continue;
                emptyCnt = 0;
                MaxColumn = column;
                ColumnFields.Add(cell.ColumnIndex, innerFile);
            }

            MaxColumn += 1;
            {
                var cell = row.SafeGetCell(MaxColumn);
                cell.SetCellValue("У��״̬");
                cell = row.SafeGetCell(MaxColumn + 1);
                cell.SetCellValue("У����Ϣ");
            }
            return true;
        }

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

protected virtual bool CheckFieldMaps()
        {
            var row = Sheet.GetRow(0);
            ColumnFields = new Dictionary<int, string>();
            var emptyCnt = 0;
            MaxColumn = 0;
            for (var column = 0; column < short.MaxValue; column++)
            {
                var cell = row.GetCell(column);
                if (cell == null)
                {
                    if (++emptyCnt > 3)
                    {
                        break;
                    }
                    continue;
                }
                if (cell.CellType != CellType.String)
                {
                    cell.SetCellType(CellType.String);
                }
                var field = cell.StringCellValue;
                if (string.IsNullOrWhiteSpace(field))
                {
                    if (++emptyCnt > 3)
                    {
                        break;
                    }
                    continue;
                }
                //if (emptyCnt > 0)
                //{
                //    WriteCellState(row, column, "�ֶ�����Ϊ�հ�,����ֱ����ֹ", true);
                //    return false;
                //}

                if (!FieldMap.TryGetValue(field.Trim(), out var innerFile))
                {
                    continue;
                    //WriteCellState(row, column, $"�ֶ�����{field}ӳ���ϵ����ȷ,����ֱ����ֹ", true);
                    //return false;
                }
                emptyCnt = 0;
                MaxColumn = column;
                ColumnFields.Add(cell.ColumnIndex, innerFile);
            }
            MaxColumn += 1;
            {
                var cell = row.SafeGetCell(MaxColumn);
                cell.SetCellValue("У��״̬");
                cell = row.SafeGetCell(MaxColumn + 1);
                cell.SetCellValue("У����Ϣ");
            }
            return true;
        }

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

private string Convert(MemberExpression expression)
        {
            if (expression.Expression is ParameterExpression)
            {
                if (_columnMap.TryGetValue(expression.Member.Name,out var field))
                    return $"`{field}`";
                throw new ArgumentException(@"�ֶβ����������ݿ���", expression.Member.Name);
            }
            var par1 = expression.Expression as MemberExpression;
            if (!(par1?.Expression is ParameterExpression))
                return CheckDynamicValue(GetValue(expression));

            if (par1.Type == typeof(string))
            {
                switch (expression.Member.Name)
                {
                    case "Length":
                        return $"LENGTH(`{par1.Member.Name}`)";
                }
            }
            else if (par1.Type == typeof(DateTime))
            {
                switch (expression.Member.Name)
                {
                    case "Now":
                        return $"?{_condition.AddParameter(DateTime.Now)}";
                    case "Today":
                        return $"?{_condition.AddParameter(DateTime.Today)}";
                }
            }
            throw new ArgumentException($"��֧������:{expression.Member.DeclaringType.FullName}.{expression.Member.Name}");
        }

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

private string GetValue(string name)
        {
            return !_arguments.TryGetValue(name, out var val) ? null : val?.Trim();
        }

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

private string Convert(MemberExpression expression)
        {
            if (expression.Expression is ParameterExpression)
            {
                string field;
                if (!_columnMap.TryGetValue(expression.Member.Name, out field))
                {
                    throw new ArgumentException(@"�ֶβ����������ݿ���", expression.Member.Name);
                }
                return $"[{field}]";
            }
            var par1 = expression.Expression as MemberExpression;
            if (par1?.Expression is ParameterExpression)
            {
                if (par1.Type == typeof(string))
                {
                    switch (expression.Member.Name)
                    {
                        case "Length":
                            return $"LEN([{par1.Member.Name}])";
                    }
                }
                if (par1.Type == typeof(DateTime))
                {
                    switch (expression.Member.Name)
                    {
                        case "Now":
                            return $"@{_condition.AddParameter(DateTime.Now)}";
                        case "Today":
                            return $"@{_condition.AddParameter(DateTime.Today)}";
                    }
                }
                throw new ArgumentException($"��֧������:{expression.Member.DeclaringType.FullName}.{expression.Member.Name}");
            }
            var vl = GetValue(expression);
            if (vl.GetType().IsValueType)
            {
                return $"@{_condition.AddParameter(vl)}";
            }
            switch (vl)
            {
                case Array array:
                    return array.LinkToString("'", "','", "'");
                case string _:
                    return $"@{_condition.AddParameter(vl)}";
                case IEnumerable<string> slist:
                    return slist.LinkToString("'", "','", "'");
                case IEnumerable<DateTime> dlist:
                    return dlist.LinkToString("'", "','", "'");
                case ICollection list:
                    return list.LinkToString("'", "','", "'");
            }

            return $"@{_condition.AddParameter(vl)}";
        }

19 View Source File : GrantTypes.cs
License : Apache License 2.0
Project Creator : Aguafrommars

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

19 View Source File : AssetReferenceTreeModel.cs
License : MIT License
Project Creator : akof1314

public override void SetDataPaths(string refPathStr, string pathStr, string commonPathStr)
        {
            base.SetDataPaths(refPathStr, pathStr, commonPathStr);
            replacedetPaths = refPathStr;

            var resFileList = GetResFileList();
            var guidList = GetGuidFromFileList(resFileList);
            var fileList = GetRefFileList();
            var searchRetList = GetSearchResultList(fileList.Count, guidList.Count);

            ThreadDoFilesTextSearchReplace(fileList, guidList, String.Empty, searchRetList);
            var rootInfo = DirToreplacedetInfoTree(refPaths);
            var refInfos = FileListToreplacedetInfos(fileList);

            // 隶属信息
            var spritePackingDict = new Dictionary<string, string>();

            // 根据搜索结果来挂载额外信息
            for (int i = 0; i < fileList.Count; i++)
            {
                for (int j = 0; j < guidList.Count; j++)
                {
                    if (searchRetList[i][j])
                    {
                        replacedetInfo info = GenreplacedetInfo(resFileList[j]);
                        info.isExtra = true;
                        refInfos[i].AddChild(info);

                        // 隶属
                        string val;
                        if (!spritePackingDict.TryGetValue(info.fileRelativePath, out val))
                        {
                            var replacedetImporter = replacedetImporter.GetAtPath(info.fileRelativePath);
                            TextureImporter textureImporter = replacedetImporter as TextureImporter;
                            if (textureImporter)
                            {
                                val = textureImporter.spritePackingTag;
                            }
                        }

                        info.bindObj = val;
                    }
                }
            }
            MergereplacedetInfo(rootInfo, refInfos);

            if (rootInfo.hasChildren)
            {
                data = rootInfo;
            }
            EditorUtility.ClearProgressBar();
        }

19 View Source File : TechLogItem.cs
License : MIT License
Project Creator : akpaevj

private long? GetLongOrNull(string propertyName)
        {
            if (AllProperties.TryGetValue(propertyName, out var value))
                return long.Parse(value);
            else
                return null;
        }

19 View Source File : TechLogItem.cs
License : MIT License
Project Creator : akpaevj

private int? GetIntOrNull(string propertyName)
        {
            if (AllProperties.TryGetValue(propertyName, out var value))
                return int.Parse(value);
            else
                return null;
        }

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

public virtual void Import(string inputPath, string[] changedFilesFull, string outputBins, string outputCode, Func<string, string> namer)
         {
            Dictionary<string, string> correspondenceList = GetCorrespondenceList(inputPath, outputBins, namer);
            List<string> allFilesInDest = GetAllFilesInDest(outputBins);

            Dbg.Write($"importing files from {inputPath} into {outputBins}, generating code into {outputCode}");

            List<string> orphans = new List<string>();
            foreach (string file in GetFilesInDestWithNoCorrespondent(correspondenceList, allFilesInDest))
            {
               Dbg.Write("found orphan "+file);
               orphans.Add(file);
            }
        
            Dictionary<string, string> correspondents = new Dictionary<string, string>();
            foreach (string changedFile in changedFilesFull)
            {
               if (correspondenceList.TryGetValue(changedFile, out string finalFilePath))
               {
                  Dbg.Write("found corresponding pair "+changedFile+"  -  "+finalFilePath);
                  correspondents[changedFile] = finalFilePath;
               }
               else
               {
                  Dbg.Write("FOUND MODIFIED FILE WITH NO CORRESPONDENT!!! "+changedFile);
               }
            }

            Dbg.Write("running high-level importing");
            ImportHighLevel(correspondents, orphans);
         }

19 View Source File : Common.cs
License : MIT License
Project Creator : AlbertMN

static Stream LoadStream(Dictionary<string, string> resourceNames, string name)
    {
        string value;
        if (resourceNames.TryGetValue(name, out value))
            return LoadStream(value);

        return null;
    }

19 View Source File : ConvertProcess.cs
License : MIT License
Project Creator : Aleksbgbg

private protected override void OnStart()
        {
            ParameterMonitoring progressMonitoring = ProcessMonitor.ParameterMonitorings["Progress"];

            ProcessMonitor.Finished += ProcessMonitorFinished;
            progressMonitoring.ValueUpdated += ProgressUpdated;

            void ProcessMonitorFinished(object sender, EventArgs e)
            {
                ProcessMonitor.Finished -= ProcessMonitorFinished;
                progressMonitoring.ValueUpdated -= ProgressUpdated;
            }

            void ProgressUpdated(object sender, ParameterUpdatedEventArgs e)
            {
                Dictionary<string, string> keyValuePairs = (Dictionary<string, string>)e.NewValue;

                if (keyValuePairs.TryGetValue("size", out string size))
                {
                    Match sizeMatch = Regex.Match(size, @"(?<Size>\d+)(?<Units>.+)");
                    _convertProgress.ConvertedBytes = DigitalStorageManager.GetBytes(double.Parse(sizeMatch.Groups["Size"].Value), sizeMatch.Groups["Units"].Value);
                }

                if (keyValuePairs.TryGetValue("bitrate", out string bitrate))
                {
                    Match bitrateMatch = Regex.Match(bitrate, @"(?<Size>\d+(?:\.\d+)?)(?<Units>.+)its\/s");
                    _convertProgress.Bitrate = DigitalStorageManager.GetBytes(double.Parse(bitrateMatch.Groups["Size"].Value), bitrateMatch.Groups["Units"].Value);
                }
            }
        }

See More Examples