int.Parse(string)

Here are the examples of the csharp api int.Parse(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

8156 Examples 7

19 Source : StringHelper.cs
with MIT License
from 0x1000000

public static string AddNumberUntilUnique(string input, string delimiter, Predicate<string> test)
        {
            Regex regex = new Regex($"(.+?){delimiter}(\\d+)");
            while (!test(input))
            {
                int nextNo = 2; 
                var m = regex.Match(input);
                if (m.Success)
                {
                    input = m.Result("$1");
                    nextNo = int.Parse(m.Result("$2")) + 1;

                }

                input = input + delimiter + nextNo;
            }
            return input;
        }

19 Source : IntegrationTest.cs
with MIT License
from 0x1000000

[Test]
        public async Task Test_OldWay()
        {
            var sw = Stopwatch.StartNew();

            Task<int> get1 = Get1();
            Task<int> get2 = Get2();
            Task<string> get3Str = Get3Str();
            Task<int> get4 = Get4();

            await Task.WhenAll(get1, get2, get3Str, get4);

            var result = get1.Result + get2.Result + int.Parse(get3Str.Result) + get4.Result;


            sw.Stop();

            replacedert.AreEqual(9, result);
            replacedert.GreaterOrEqual(sw.ElapsedMilliseconds, TimeSlotMs);
            replacedert.Less(sw.ElapsedMilliseconds, TimeSlotMs + LagMs);
        }

19 Source : Program.cs
with MIT License
from 0xDivyanshu

static int Main(string[] args)
        {
            //xenon.exe -m <1,2,3> --<shellcode/dll> --location <http://1.1.1.1/name, C:\\A\\B\\name> --<enc> --key <preplacedword>
            //IEnumerable<string> arg = Arguments.SplitCommandLine(string.Join(" ", args));
            IEnumerable<string> arg = args;
            var arguments = new Arguments(arg);

            if (arguments.Exists("m"))
            {
                int m = int.Parse(arguments.Single("m"));
                if (m == 5)
                {
                    if (arguments.Exists("TempFile"))
                    {
                        string name = arguments.Single("TempFile");
                        powershell_clm(name);
                        Console.WriteLine("Powershell session exit!");
                        return 0;
                    }
                    else
                    {
                        help_xenon();
                        return -1;
                    }
                }
            }

            if ((arguments.Exists("m") && arguments.Exists("location") && (arguments.Exists("shellcode") || arguments.Exists("dll"))) == false || arguments.Count < 3)
            {
                help_xenon();
                return -1;
            }

            // Sleep AV detection

            DateTime t1 = DateTime.Now;
            Sleep(2000);
            if (DateTime.Now.Subtract(t1).TotalSeconds < 2)
            {
                Console.WriteLine("[!] AV Emulator detected! Behaving like a good boy :)");
                return 0;
            }

            //Options to transfer shellcode/DLL - Via SMB share and local disk (.dll for dll and .txt for shellcode)

            //1. Process injection via shellcode
            //2. Reflective Process injection via DLL (in memory)
            //3. Process Hollowing (shellcode)


            Console.WriteLine("[+] Parsing command line arguments");

            //Parsing Command line arguments
            int mode = int.Parse(arguments.Single("m"));
            string location = arguments.Single("location");
            int button = 0;

            if (arguments.Exists("shellcode"))
            {
                button = 1;
            }
            else
                button = 2;

            int decryption = 0;
            string preplaced = "";

            if (arguments.Exists("decrypt-xor"))
            {
                decryption = 1;
                preplaced = arguments.Single("preplaced");
                preplaced = CreateMD5(preplaced);
            }
            else if (arguments.Exists("decrypt-aes"))
            {
                decryption = 2;
                preplaced = arguments.Single("preplaced");
                preplaced = CreateMD5(preplaced);
            }

            if (arguments.Exists("bypreplaced"))
            {
                Flags.advanced_bypreplaced = 1;
            }

            // Dealing with command line arguments for main logic
            int response = 0;

            switch (mode)
            {
                case 1:
                    if (button == 1)
                        Console.WriteLine("Injecting into process via shellcode at " + location);
                    else
                        Console.WriteLine("Injecting into process via DLL at " + location);
                    response = process_injection(location, button, decryption, preplaced);

                    if (response == 0)
                        Console.WriteLine("[+] Process Injection done :)");
                    else
                        Console.WriteLine("[!] Error running the process injection module");
                    break;

                case 2:
                    Console.WriteLine("DLL Injection into process using DLL at " + location);
                    response = reflective_dll_injection(location);

                    if (response == 0)
                        Console.WriteLine("[+] DLL Injection done :)");
                    else
                        Console.WriteLine("[!] Error running the DLL injection module");
                    break;

                case 3:
                    Console.WriteLine("Using Process hollowing into process using DLL at " + location);
                    response = process_hollowing(location, decryption, preplaced);

                    if (response == 0)
                        Console.WriteLine("[+] Process hollowing done :)");
                    else
                        Console.WriteLine("[!] Error running the process hollowing module");
                    break;

                case 4:
                    Console.WriteLine("Getting a basic reverse shell for you using shellcode at " + location);
                    basic_rev(location, decryption, preplaced);
                    Console.WriteLine("Reverse Shell done :)");
                    break;

                case 6:
                    Console.WriteLine("DLL Hollowing in process! Using shellcode at " + location);
                    int res = dll_hollowing(location, decryption, preplaced);
                    if (res == 0)
                        Console.WriteLine("[+] DLL Hollowing done :)");
                    else
                        Console.WriteLine("[!] Error running the DLL hollowing module");
                    break;

                default:
                    Console.WriteLine("Mode not found");
                    break;
            }

            return 0;
        }

19 Source : TypeConverterHelper.cs
with MIT License
from 1iveowl

public static object Convert(string value, string destinationTypeFullName)
        {
            if (string.IsNullOrWhiteSpace(destinationTypeFullName))
            {
                throw new ArgumentNullException(destinationTypeFullName);
            }

            var scope = GetScope(destinationTypeFullName);

            if (string.Equals(scope, "System", StringComparison.Ordinal))
            {
                if (string.Equals(destinationTypeFullName, typeof(string).FullName, StringComparison.Ordinal))
                {
                    return value;
                }
                else if (string.Equals(destinationTypeFullName, typeof(bool).FullName, StringComparison.Ordinal))
                {
                    return bool.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(int).FullName, StringComparison.Ordinal))
                {
                    return int.Parse(value);
                }
                else if (string.Equals(destinationTypeFullName, typeof(double).FullName, StringComparison.Ordinal))
                {
                    return double.Parse(value);
                }
            }

            return null;
        }

19 Source : Resp3HelperTests.cs
with MIT License
from 2881099

[Fact]
		public void Command()
		{
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = rds.Command();
			var sb = string.Join("\r\n\r\n", (rt.Value).OrderBy(a1 => (a1 as List<object>)[0].ToString()).Select(a1 =>
			{
				var a = a1 as List<object>;
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());
				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += "string parm, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += "string parm, ";
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}
				
				return $@"
//{string.Join(", ", a[2] as List<object>)}
//{string.Join(", ", a[6] as List<object>)}
public void {UFString(a[0].ToString())}({parms}) {{ }}";
			}));
		}

19 Source : CommandFlagsTests.cs
with MIT License
from 2881099

[Fact]
        public void Command()
        {
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = cli.Command();
			//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
			var flags = new List<string>();
			var flags7 = new List<string>();
			var diccmd = new Dictionary<string, (string[], string[])>();

			var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
			{
				var a = a1 as object[];
				var cmd = a[0].ToString();
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());

				var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
				var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
				flags.AddRange(aflags);
				flags7.AddRange(fopts);

				diccmd.Add(cmd.ToUpper(), (aflags, fopts));

				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += $"string arg{x}, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey)
						{
							if (firstKey != lastKey) parms += "string[] keys, ";
							else parms += "string key, ";
						}
						else
						{
							if (firstKey != lastKey) parms += $"string[] arg{x}, ";
							else parms += $"string arg{x}, ";
						}
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}

				return $@"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
			}));
			flags = flags.Distinct().ToList();
			flags7 = flags7.Distinct().ToList();


			var sboptions = new StringBuilder();
            foreach (var cmd in CommandSets._allCommands)
            {
                if (diccmd.TryGetValue(cmd, out var tryv))
                {
                    sboptions.Append($@"
[""{cmd}""] = new CommandSets(");

                    for (var x = 0; x < tryv.Item1.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
                    }

                    sboptions.Append(", ");
                    for (var x = 0; x < tryv.Item2.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
                    }

                    sboptions.Append(", LocalStatus.none),");
                }
                else
                {
                    sboptions.Append($@"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
                }
            }

            var optioncode = sboptions.ToString();
		}

19 Source : Program.cs
with MIT License
from 2881099

static void Main(string[] args) {

			fsql.CodeFirst.SyncStructure(typeof(Song), typeof(Song_tag), typeof(Tag));
			//sugar.CodeFirst.InitTables(typeof(Song), typeof(Song_tag), typeof(Tag));
			//sugar创建表失败:SqlSugar.SqlSugarException: Sequence contains no elements

			//测试前清空数据
			fsql.Delete<Song>().Where(a => a.Id > 0).ExecuteAffrows();
			sugar.Deleteable<Song>().Where(a => a.Id > 0).ExecuteCommand();
			fsql.Ado.ExecuteNonQuery("delete from efcore_song");


			var sql = fsql.Select<Song>().Where(a => a.Id == int.Parse("55")).ToSql();

			var sb = new StringBuilder();
			Console.WriteLine("插入性能:");
			//Insert(sb, 1000, 1);
			//Console.Write(sb.ToString());
			//sb.Clear();
			//Insert(sb, 1000, 10);
			//Console.Write(sb.ToString());
			//sb.Clear();

			Insert(sb, 1, 1000);
			Console.Write(sb.ToString());
			sb.Clear();
			Insert(sb, 1, 10000);
			Console.Write(sb.ToString());
			sb.Clear();
			Insert(sb, 1, 50000);
			Console.Write(sb.ToString());
			sb.Clear();
			Insert(sb, 1, 100000);
			Console.Write(sb.ToString());
			sb.Clear();

			Console.WriteLine("查询性能:");
			Select(sb, 1000, 1);
			Console.Write(sb.ToString());
			sb.Clear();
			Select(sb, 1000, 10);
			Console.Write(sb.ToString());
			sb.Clear();

			Select(sb, 1, 1000);
			Console.Write(sb.ToString());
			sb.Clear();
			Select(sb, 1, 10000);
			Console.Write(sb.ToString());
			sb.Clear();
			Select(sb, 1, 50000);
			Console.Write(sb.ToString());
			sb.Clear();
			Select(sb, 1, 100000);
			Console.Write(sb.ToString());
			sb.Clear();

			Console.WriteLine("更新:");
			Update(sb, 1000, 1);
			Console.Write(sb.ToString());
			sb.Clear();
			Update(sb, 1000, 10);
			Console.Write(sb.ToString());
			sb.Clear();

			Update(sb, 1, 1000);
			Console.Write(sb.ToString());
			sb.Clear();
			Update(sb, 1, 10000);
			Console.Write(sb.ToString());
			sb.Clear();
			Update(sb, 1, 50000);
			Console.Write(sb.ToString());
			sb.Clear();
			Update(sb, 1, 100000);
			Console.Write(sb.ToString());
			sb.Clear();

			Console.WriteLine("测试结束,按任意键退出...");
			Console.ReadKey();
		}

19 Source : ShareHandler.cs
with GNU General Public License v3.0
from 2dust

private static VmessItem ResolveSSLegacy(string result)
        {
            var match = UrlFinder.Match(result);
            if (!match.Success)
                return null;

            VmessItem server = new VmessItem();
            var base64 = match.Groups["base64"].Value.TrimEnd('/');
            var tag = match.Groups["tag"].Value;
            if (!Utils.IsNullOrEmpty(tag))
            {
                server.remarks = Utils.UrlDecode(tag);
            }
            Match details;
            try
            {
                details = DetailsParser.Match(Encoding.UTF8.GetString(Convert.FromBase64String(
                    base64.PadRight(base64.Length + (4 - base64.Length % 4) % 4, '='))));
            }
            catch (FormatException)
            {
                return null;
            }
            if (!details.Success)
                return null;
            server.security = details.Groups["method"].Value;
            server.id = details.Groups["preplacedword"].Value;
            server.address = details.Groups["hostname"].Value;
            server.port = int.Parse(details.Groups["port"].Value);
            return server;
        }

19 Source : Program.cs
with MIT License
from 3583Bytes

private static byte GetRow(string move)
	{
		if (move != null)
		{
			if (move.Length == 2)
			{
				return (byte)(8 - int.Parse(move.Substring(1, 1).ToLower()));
			}
		}

		return 255;
	}

19 Source : MoveContent.cs
with MIT License
from 3583Bytes

public static bool ParseAN(string move, ref byte sourceColumn, ref byte sourceRow, ref byte destinationColumn, ref byte destinationRow)
		{
			if (move.Length != 4) return false;
			sourceColumn = (byte)GetIntFromColumn(move[0]);
			sourceRow = (byte)(8 - int.Parse(""+move[1]));
			destinationColumn = (byte)GetIntFromColumn(move[2]);
			destinationRow = (byte)(8 - int.Parse(""+move[3]));
			return true;
		}

19 Source : BeatmapConverter.cs
with MIT License
from 39M

static void Convert()
    {
        Debug.Log(string.Format("Source path: {0}", beatmapPath));

        // 每个目录代表一首歌,里面按字典序放置至多三个谱面,依次为 Easy, Normal, Hard
        string[] sourceDirectories = Directory.GetDirectories(beatmapPath);
        foreach (string directoryPath in sourceDirectories)
        {
            Music music = new Music();

            // 遍历单个目录下的所有 osu 文件,对每个文件创建一个 Beatmap 对象,加到 Music 对象里面
            string[] sourceFiles = Directory.GetFiles(directoryPath, "*.osu");
            int count = 0;
            foreach (string filepath in sourceFiles)
            {
                string[] lines = File.ReadAllLines(filepath);

                Beatmap beatmap = new Beatmap();
                music.beatmapList.Add(beatmap);

                #region Set Difficulty
                beatmap.difficultyName = difficultyNames[Mathf.Min(count, difficultyNames.Length - 1)];
                beatmap.difficultyDisplayColor = new SimpleColor(difficultyColors[Mathf.Min(count, difficultyNames.Length - 1)]);
                count++;
                #endregion

                #region Processing file line by line
                bool startProcessNotes = false;
                foreach (string line in lines)
                {
                    if (line.StartsWith("[HitObjects]"))
                    {
                        startProcessNotes = true;
                        continue;
                    }

                    if (!startProcessNotes)
                    {
                        // 处理谱面信息

                        int lastIndex = line.LastIndexOf(':');
                        if (lastIndex < 0)
                        {
                            // 如果不是有效信息行则跳过
                            continue;
                        }

                        string value = line.Substring(lastIndex + 1).Trim();

                        if (line.StartsWith("replacedle"))
                        {
                            music.replacedle = value;
                        }
                        else if (line.StartsWith("Artist"))
                        {
                            music.artist = value;
                        }
                        else if (line.StartsWith("AudioFilename"))
                        {
                            value = value.Remove(value.LastIndexOf('.'));
                            music.audioFilename = value;
                            music.bannerFilename = value;
                            music.soundEffectFilename = value;
                        }
                        else if (line.StartsWith("PreviewTime"))
                        {
                            music.previewTime = float.Parse(value) / 1000;
                        }
                        else if (line.StartsWith("Creator"))
                        {
                            beatmap.creator = value;
                        }
                        else if (line.StartsWith("Version"))
                        {
                            beatmap.version = value;
                        }
                    }
                    else
                    {
                        // 开始处理 HitObject

                        string[] noteInfo = line.Split(',');
                        int type = int.Parse(noteInfo[3]);

                        if ((type & 0x01) != 0)
                        {
                            // Circle
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Circle 相关的处理
                            });
                        }
                        else if ((type & 0x02) != 0)
                        {
                            // Slider
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Slider 相关的处理
                            });
                        }
                        else if ((type & 0x08) != 0)
                        {
                            // Spinner
                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[2]) / 1000,
                                // 其他 Spinner 相关的处理
                            });

                            beatmap.noteList.Add(new Note
                            {
                                x = int.Parse(noteInfo[0]),
                                y = int.Parse(noteInfo[1]),
                                time = float.Parse(noteInfo[5]) / 1000,
                                // 其他 Spinner 相关的处理
                            });
                        }
                    }
                }
                #endregion
            }

            string targetPath = directoryPath + ".json";
            if (File.Exists(targetPath))
            {
                File.Delete(targetPath);
            }
            File.WriteAllText(targetPath, music.ToJson());

            Debug.Log(string.Format("Converted osu! beatmap\n[{0}]\nto json file\n[{1}]", directoryPath, targetPath));
        }

        Debug.Log(string.Format("All done, converted {0} files.", sourceDirectories.Length));
    }

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static void LoadErr(Dictionary<int, string> dict, string path)
		{
			if (!File.Exists(path))
			{
				MainWindow.Logger.Warn("Error Code File Missing: {0}", path);
				return;
			}

			string FileContents;

			try
			{
				FileContents = File.ReadAllText(path);
			}
			catch (Exception ex)
			{
                MainWindow.Logger.Error(ex.Message);
				return;
			}

			Regex LineParser = new Regex(@"""([0-9]+)"",""[^\n\r""]*"",""([^\n\r""]*)""");     //test here https://regex101.com/r/hO5zI1/4

			MatchCollection mc = LineParser.Matches(FileContents);

			foreach (Match m in mc)
			{
				try //shouldn't be needed as regex matched already
				{
					int number = int.Parse(m.Groups[1].Value);

					dict.Add(number, m.Groups[2].Value);
				}
				catch { }
			}
		}

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static string ErrorMatchEvaluator(Match m)
		{
			return GetErrorMessage(int.Parse(m.Groups[1].Value));
		}

19 Source : GrblSettingsWindow.xaml.cs
with MIT License
from 3RD-Dimension

public void LineReceived(string line)
        {
            // Recieve GRBL Controller Version number and display - $i
            // Recieved in format [VER: ... and [OPT:

            if (!line.StartsWith("$") && !line.StartsWith("[VER:") && !line.StartsWith("[OPT:"))
                return;

            if (line.StartsWith("$"))
            {
                try
                {
                    Match m = settingParser.Match(line);
                    int number = int.Parse(m.Groups[1].Value);
                    double value = double.Parse(m.Groups[2].Value, Util.Constants.DecimalParseFormat);

                    // Value = Setting Value, Number = Setting Code

                    if (!CurrentSettings.ContainsKey(number))
                    {
                        RowDefinition rowDef = new RowDefinition();
                        rowDef.Height = new GridLength(25);
                        gridMain.RowDefinitions.Add(rowDef);

                        TextBox valBox = new TextBox // Value of Setting Textbox
                        {
                            Text = value.ToString(Util.Constants.DecimalOutputFormat),
                            VerticalAlignment = VerticalAlignment.Center
                        };

                        // Define Mouseclick for textbox to open GRBLStepsCalcWindow for setting $100, $101, $102
                        if (number == 100) { valBox.Name = "Set100"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 101) { valBox.Name = "Set101"; valBox.MouseDoubleClick += openStepsCalc; }
                        else if (number == 102) { valBox.Name = "Set102"; valBox.MouseDoubleClick += openStepsCalc; }
                        Grid.SetRow(valBox, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(valBox, 1);
                        gridMain.Children.Add(valBox);

                        TextBlock num = new TextBlock
                        {
                            Text = $"${number}=",
                            HorizontalAlignment = HorizontalAlignment.Right,
                            VerticalAlignment = VerticalAlignment.Center
                        };
                        Grid.SetRow(num, gridMain.RowDefinitions.Count - 1);
                        Grid.SetColumn(num, 0);
                        gridMain.Children.Add(num);

                        if (Util.GrblCodeTranslator.Settings.ContainsKey(number))
                        {
                            Tuple<string, string, string> labels = Util.GrblCodeTranslator.Settings[number];

                            TextBlock name = new TextBlock
                            {
                                Text = labels.Item1,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(name, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(name, 0);
                            gridMain.Children.Add(name);

                            TextBlock unit = new TextBlock
                            {
                                Text = labels.Item2,
                                VerticalAlignment = VerticalAlignment.Center
                            };
                            Grid.SetRow(unit, gridMain.RowDefinitions.Count - 1);
                            Grid.SetColumn(unit, 2);
                            gridMain.Children.Add(unit);

                            valBox.ToolTip = $"{labels.Item1} ({labels.Item2}):\n{labels.Item3}";
                        }

                        CurrentSettings.Add(number, value);
                        SettingsBoxes.Add(number, valBox);
                    }
                    else
                    {
                        SettingsBoxes[number].Text = value.ToString(Util.Constants.DecimalOutputFormat);
                        CurrentSettings[number] = value;
                    }
                }
                catch { }
            }
            // If the line starts with [VER: then we know we are getting the version and options
            else if (line.StartsWith("[VER:") || line.StartsWith("[OPT:"))
            {
                // Frist need to remove front [ and rear ]
                string VerOptInput; // Input string
                string[] VerOptTrimmed;
                VerOptInput = line.Remove(0, 1); // Remove [ from the start
                VerOptInput = VerOptInput.Remove(VerOptInput.Length - 1);

                // Next, split the values in half at the : - we only want VER/OPT and then the values
                VerOptTrimmed = VerOptInput.Split(':');

                // Now we fill in the boxes depending on which one
                switch (VerOptTrimmed[0])
                {
                    case "VER":
                        controllerInfo += "Version: " + VerOptTrimmed[1];
                        break;

                    case "OPT":
                        // First we have to split commas
                        string[] optSplit;
                        optSplit = VerOptTrimmed[1].Split(','); // Splits Options into 3.  0=Options, 1=blockBufferSize, 2=rxBufferSize
                        var individualChar = optSplit[0].ToCharArray();// Now split optSplit[0] into each option character

                        controllerInfo += " | Options: " + VerOptTrimmed[1]; // Full Options Non-Decoded String

                        foreach (char c in individualChar)
                        {
                            // Lookup what each code is and display....  buildCodes Dictionary
                            if (Util.GrblCodeTranslator.BuildCodes.ContainsKey(c.ToString()))
                            {
                                // Now lets try and create and append to a string and then bind it to a ToolTip? or some other way
                                controllerInfo += Environment.NewLine + Util.GrblCodeTranslator.BuildCodes[c.ToString()];
                            }
                        }
                        controllerInfo += Environment.NewLine + "Block Buffer Size: " + optSplit[1];
                        controllerInfo += Environment.NewLine + "RX Buffer Size: " + optSplit[2];
                        GRBL_Controller_Info.Text = controllerInfo.ToString();
                        break;
                }
            }
        }

19 Source : Machine.cs
with MIT License
from 3RD-Dimension

private void ParseStatus(string line)
        {
            MatchCollection statusMatch = StatusEx.Matches(line);

            if (statusMatch.Count == 0)
            {
                NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line));
                return;
            }

            bool posUpdate = false;
            bool overrideUpdate = false;
            bool pinStateUpdate = false;
            bool resetPins = true;

            foreach (Match m in statusMatch)
            {
                if (m.Index == 1)
                {
                    Status = m.Groups[1].Value;
                    continue;
                }

                if (m.Groups[1].Value == "Ov")
                {
                    try
                    {
                        string[] parts = m.Groups[2].Value.Split(',');
                        FeedOverride = int.Parse(parts[0]);
                        RapidOverride = int.Parse(parts[1]);
                        SpindleOverride = int.Parse(parts[2]);
                        overrideUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "WCO")
                {
                    try
                    {
                        string OffsetString = m.Groups[2].Value;

                        if (Properties.Settings.Default.IgnoreAdditionalAxes)
                        {
                            string[] parts = OffsetString.Split(',');
                            if (parts.Length > 3)
                            {
                                Array.Resize(ref parts, 3);
                                OffsetString = string.Join(",", parts);
                            }
                        }

                        WorkOffset = Vector3.Parse(OffsetString);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (SyncBuffer && m.Groups[1].Value == "Bf")
                {
                    try
                    {
                        int availableBytes = int.Parse(m.Groups[2].Value.Split(',')[1]);
                        int used = Properties.Settings.Default.ControllerBufferSize - availableBytes;

                        if (used < 0)
                            used = 0;

                        BufferState = used;
                        RaiseEvent(Info, $"Buffer State Synced ({availableBytes} bytes free)");
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "Pn")
                {
                    resetPins = false;

                    string states = m.Groups[2].Value;

                    bool stateX = states.Contains("X");
                    if (stateX != PinStateLimitX)
                        pinStateUpdate = true;
                    PinStateLimitX = stateX;

                    bool stateY = states.Contains("Y");
                    if (stateY != PinStateLimitY)
                        pinStateUpdate = true;
                    PinStateLimitY = stateY;

                    bool stateZ = states.Contains("Z");
                    if (stateZ != PinStateLimitZ)
                        pinStateUpdate = true;
                    PinStateLimitZ = stateZ;

                    bool stateP = states.Contains("P");
                    if (stateP != PinStateProbe)
                        pinStateUpdate = true;
                    PinStateProbe = stateP;
                }

                else if (m.Groups[1].Value == "F")
                {
                    try
                    {
                        FeedRateRealtime = double.Parse(m.Groups[2].Value, Constants.DecimalParseFormat);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

                else if (m.Groups[1].Value == "FS")
                {
                    try
                    {
                        string[] parts = m.Groups[2].Value.Split(',');
                        FeedRateRealtime = double.Parse(parts[0], Constants.DecimalParseFormat);
                        SpindleSpeedRealtime = double.Parse(parts[1], Constants.DecimalParseFormat);
                        posUpdate = true;
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }
            }

            SyncBuffer = false; //only run this immediately after button press

            //run this later to catch work offset changes before parsing position
            Vector3 NewMachinePosition = MachinePosition;

            foreach (Match m in statusMatch)
            {
                if (m.Groups[1].Value == "MPos" || m.Groups[1].Value == "WPos")
                {
                    try
                    {
                        string PositionString = m.Groups[2].Value;

                        if (Properties.Settings.Default.IgnoreAdditionalAxes)
                        {
                            string[] parts = PositionString.Split(',');
                            if (parts.Length > 3)
                            {
                                Array.Resize(ref parts, 3);
                                PositionString = string.Join(",", parts);
                            }
                        }

                        NewMachinePosition = Vector3.Parse(PositionString);

                        if (m.Groups[1].Value == "WPos")
                            NewMachinePosition += WorkOffset;

                        if (NewMachinePosition != MachinePosition)
                        {
                            posUpdate = true;
                            MachinePosition = NewMachinePosition;
                        }
                    }
                    catch { NonFatalException.Invoke(string.Format("Received Bad Status: '{0}'", line)); }
                }

            }

            if (posUpdate && Connected && PositionUpdateReceived != null)
                PositionUpdateReceived.Invoke();

            if (overrideUpdate && Connected && OverrideChanged != null)
                OverrideChanged.Invoke();

            if (resetPins)  //no pin state received in status -> all zero
            {
                pinStateUpdate = PinStateLimitX | PinStateLimitY | PinStateLimitZ | PinStateProbe;  //was any pin set before

                PinStateLimitX = false;
                PinStateLimitY = false;
                PinStateLimitZ = false;
                PinStateProbe = false;
            }

            if (pinStateUpdate && Connected && PinStateChanged != null)
                PinStateChanged.Invoke();

            if (Connected && StatusReceived != null)
                StatusReceived.Invoke(line);
        }

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static string AlarmMatchEvaluator(Match m)
		{
			return GetErrorMessage(int.Parse(m.Groups[1].Value), true);
		}

19 Source : UserManager.cs
with MIT License
from 404Lcc

public void InitManager()
        {
            AudioManager.Instance.SetVolume(GameDataManager.Instance.userSetData.audio, Objects.AudioSource);
            string name = Enum.GetName(typeof(ResolutionType), GameDataManager.Instance.userSetData.resolutionType).Substring(10);
            int width = int.Parse(name.Substring(0, name.IndexOf('x')));
            int height = int.Parse(name.Substring(name.IndexOf('x') + 1));
            if (GameDataManager.Instance.userSetData.displayModeType == DisplayModeType.FullScreen)
            {
                LccUtil.SetResolution(true, width, height);
            }
            else if (GameDataManager.Instance.userSetData.displayModeType == DisplayModeType.Window)
            {
                LccUtil.SetResolution(false, width, height);
            }
            else if (GameDataManager.Instance.userSetData.displayModeType == DisplayModeType.BorderlessWindow)
            {
                LccUtil.SetResolution(false, width, height);
                StartCoroutine(DisplayMode.SetNoFrame(width, height));
            }
            QualitySettings.SetQualityLevel(6, true);
        }

19 Source : LogConfigUtil.cs
with MIT License
from 404Lcc

public static int GetFileLine(string data)
        {
            int start = data.LastIndexOf(':') + 1;
            int end = data.LastIndexOf(')');
            return int.Parse(data.Substring(start, end - start));
        }

19 Source : GrblCodeTranslator.cs
with MIT License
from 3RD-Dimension

private static void LoadSettings(Dictionary<int, Tuple<string, string, string>> dict, string path)
		{
			if (!File.Exists(path))
			{
                MainWindow.Logger.Warn("GRBL Settings File Missing: {0}", path);
				return;
			}

			string FileContents;

			try
			{
				FileContents = File.ReadAllText(path);
			}
			catch (Exception ex)
			{
                MainWindow.Logger.Error(ex.Message);
				return;
			}

			Regex LineParser = new Regex(@"""([0-9]+)"",""([^\n\r""]*)"",""([^\n\r""]*)"",""([^\n\r""]*)""");

			MatchCollection mc = LineParser.Matches(FileContents);

			foreach (Match m in mc)
			{
				try //shouldn't be needed as regex matched already
				{
					int number = int.Parse(m.Groups[1].Value);

					dict.Add(number, new Tuple<string, string, string>(m.Groups[2].Value, m.Groups[3].Value, m.Groups[4].Value));
				}
				catch { }
			}
		}

19 Source : Program.cs
with MIT License
from 42skillz

private static void Main(string[] args)
        {
            var train = args[0];
            var seats = int.Parse(args[1]);

            var manager = new WebTicketManager();

            var jsonResult = manager.Reserve(train, seats);

            Console.WriteLine(jsonResult.Result);

            Console.WriteLine("Type <enter> to exit.");
            Console.ReadLine();
        }

19 Source : Util.cs
with MIT License
from 499116344

public static byte[] IPStringToByteArray(string ip)
        {
            var array = new byte[4];
            var array2 = ip.Split('.');
            if (array2.Length == 4)
            {
                for (var i = 0; i < 4; i++)
                {
                    array[i] = (byte) int.Parse(array2[i]);
                }
            }

            return array;
        }

19 Source : EnvironmentReader.cs
with MIT License
from 5minlab

public bool Parse(string s, out int val) {
                if (s == null) {
                    val = 0;
                    return false;
                }

                try {
                    val = int.Parse(s);
                    return true;

                } catch (FormatException) {
                    val = 0;
                    return false;
                }
            }

19 Source : Shell.cs
with MIT License
from 5minlab

[Route("^/shell/commandHistory$")]
        public static void History(RequestContext context) {
            string index = context.Request.QueryString.Get("index");

            string previous = null;
            if (!string.IsNullOrEmpty(index))
                previous = PreviousCommand(System.Int32.Parse(index));

            context.Response.WriteString(previous);
        }

19 Source : LyricsFetcher.cs
with MIT License
from 71

private static void PopulateFromSrt(TextReader reader, List<Subreplacedle> subreplacedles)
        {
            // Parse using a simple state machine:
            //   0: Parsing number
            //   1: Parsing start / end time
            //   2: Parsing text
            byte state = 0;

            float startTime = 0f,
                  endTime = 0f;

            StringBuilder text = new StringBuilder();
            string line;

            while ((line = reader.ReadLine()) != null)
            {
                switch (state)
                {
                    case 0:
                        if (string.IsNullOrEmpty(line))
                            // No number found; continue in same state.
                            continue;

                        if (!int.TryParse(line, out int _))
                            goto Invalid;

                        // Number found; continue to next state.
                        state = 1;
                        break;

                    case 1:
                        Match m = Regex.Match(line, @"(\d+):(\d+):(\d+,\d+) *--> *(\d+):(\d+):(\d+,\d+)");

                        if (!m.Success)
                            goto Invalid;

                        startTime = int.Parse(m.Groups[1].Value) * 3600
                                  + int.Parse(m.Groups[2].Value) * 60
                                  + float.Parse(m.Groups[3].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);

                        endTime = int.Parse(m.Groups[4].Value) * 3600
                                + int.Parse(m.Groups[5].Value) * 60
                                + float.Parse(m.Groups[6].Value.Replace(',', '.'), NumberStyles.Float, CultureInfo.InvariantCulture);

                        // Subreplacedle start / end found; continue to next state.
                        state = 2;
                        break;

                    case 2:
                        if (string.IsNullOrEmpty(line))
                        {
                            // End of text; continue to next state.
                            subreplacedles.Add(new Subreplacedle(text.ToString(), startTime, endTime));

                            text.Length = 0;
                            state = 0;
                        }
                        else
                        {
                            // Continuation of text; continue in same state.
                            text.AppendLine(line);
                        }

                        break;

                    default:
                        // Shouldn't happen.
                        throw new Exception();
                }
            }

            Invalid:

            Debug.Log("[Beat Singer] Invalid subtiles file found, cancelling load...");
            subreplacedles.Clear();
        }

19 Source : String.Extension.cs
with MIT License
from 7Bytes-Studio

public static string Slice(this string str,string sliceOp)
        {
            sliceOp = sliceOp.Trim();
            if (!sliceOp.Contains(":")) throw new System.Exception("操作必需符合 lop:rop");

            if (sliceOp == ":") // ":"
            {
                return str;
            }
            else if (sliceOp[0] == ':') //":xxx"
            {
                var s = sliceOp.Split(':');
                int rop = int.Parse(s[1]);
                char[] charArr = new char[rop];

                for (int i = 0; i < charArr.Length; i++)
                {
                    charArr[i] = str[i];
                }

                return new string(charArr);
            }
            else if (sliceOp[sliceOp.Length - 1] == ':') //"xxx:"
            {
                var s = sliceOp.Split(':');
                int lop = int.Parse(s[0]);
                lop = 0>lop?str.Length+lop:lop;
                char[] charArr = new char[str.Length-lop];

                for (int i = 0; i < charArr.Length; i++)
                {
                    charArr[i] = str[lop+i];
                }

                return new string(charArr);
            }
            else//"xxx:xxx"
            {
                var s = sliceOp.Split(':');
                int lop = int.Parse(s[0]);
                int rop = int.Parse(s[1]);
                char[] charArr = new char[rop - lop];

                for (int i = 0; i < charArr.Length; i++)
                {
                    charArr[i] = str[lop+i];
                }

                return new string(charArr);
            }
        }

19 Source : String.Extension.cs
with MIT License
from 7Bytes-Studio

public static string Replace(this string str,string replaceOp)
        {
            if (!replaceOp.Contains(":") || !replaceOp.Contains("|")) throw new System.Exception("操作必需符合 lop:rop|your replace string");

            string sliceOp = replaceOp.Split('|')[0].Trim();
            string replaceStr = replaceOp.Slice(string.Format("{0}:", sliceOp.Length+1));

            var strArr = str.ToCharArray();

            if (sliceOp == ":") // ":"
            {
                return replaceStr;
            }
            else if (sliceOp[0] == ':') //":xxx"
            {
                var s = sliceOp.Split(':');
                int lop = 0;
                int rop = int.Parse(s[1]);
                int replaceStrIndex = 0;
                for (int i = lop; i < rop; i++)
                {
                    if (replaceStrIndex < replaceStr.Length)
                    {
                        strArr[i] = replaceStr[replaceStrIndex++];
                    }
                }

                return new string(strArr);
            }
            else if (sliceOp[sliceOp.Length - 1] == ':') //"xxx:"
            {
                var s = sliceOp.Split(':');
                int lop = int.Parse(s[0]);
                lop = 0 > lop ? strArr.Length + lop : lop;
                int rop = strArr.Length;
                int replaceStrIndex = 0;
                for (int i = lop; i < rop; i++)
                {
                    if (replaceStrIndex < replaceStr.Length)
                    {
                        strArr[i] = replaceStr[replaceStrIndex++];
                    }
                }

                return new string(strArr);
            }
            else//"xxx:xxx"
            {
                var s = sliceOp.Split(':');
                int lop = int.Parse(s[0]);
                int rop = int.Parse(s[1]);
                int replaceStrIndex = 0;
                for (int i = lop; i < rop; i++)
                {
                    if (replaceStrIndex < replaceStr.Length)
                    {
                        strArr[i] = replaceStr[replaceStrIndex++];
                    }           
                }

                return new string(strArr);
            }
        }

19 Source : NhentaiHelper.cs
with GNU General Public License v3.0
from 9vult

public static int GetPageCount(string hUrl)
        {
            HtmlDoreplacedent doreplacedent;
            if (hUrl.EndsWith("/"))
                doreplacedent = new HtmlWeb().Load(hUrl.Substring(0, hUrl.Length - 2));
            else
                doreplacedent = new HtmlWeb().Load(hUrl.Substring(0, hUrl.Length - 1));

            int startIndex = doreplacedent.DoreplacedentNode.InnerHtml.IndexOf("\"num_pages\":") + 12;
            int length = 7;

            string crop = doreplacedent.DoreplacedentNode.InnerHtml.Substring(startIndex, length);

            string pages = Regex.Replace(crop, "[^0-9.]", "");
            return int.Parse(pages);
        }

19 Source : ToolsMain.cs
with Apache License 2.0
from 91270

static void Main(string[] args)
        {
            do
            {
                try
                {
                    Console.Clear();
                    Console.ForegroundColor = ConsoleColor.DarkYellow;
                    Console.WriteLine("=============================================================================");
                    Console.WriteLine("*            1      -      生成模型");
                    Console.WriteLine("=============================================================================");
                    Console.Write("请选择要执行的程序 : ");
                    Console.ResetColor();

                    switch (Int32.Parse(Console.ReadLine()))
                    {
                        case 1:

                            #region  生成模型
                            Task001.Execute();
                            #endregion

                            Console.ReadKey();

                            break;
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    Console.ReadKey();
                }
            } while (true);
        }

19 Source : ExternalCommunicator.cs
with Apache License 2.0
from A7ocin

private void ReadArgs()
    {
        string[] args = System.Environment.GetCommandLineArgs();
        string inputPort = "";
        for (int i = 0; i < args.Length; i++)
        {
            if (args[i] == "--port")
            {
                inputPort = args[i + 1];
            }
        }

        comPort = int.Parse(inputPort);
    }

19 Source : Program.cs
with Apache License 2.0
from AantCoder

static void Main(string[] args)
        {
            var workPort = args == null || args.Length < 2 ? 0 : int.Parse(args[1]);
            var workPath = @"C:\World" + (workPort == 0 ? "" : "\\" + workPort.ToString());

            var SaveFileName = Path.Combine(workPath, "World.dat");
            var SaveFileNameOld = Path.Combine(workPath, "WorldOld.dat");
    
            if (!File.Exists(SaveFileName)) 
            {
                return;
            }

            File.Copy(SaveFileName, SaveFileNameOld, true);

            BaseContainer Data;
            using (var fs = File.OpenRead(SaveFileName))
            {
                var bf = new BinaryFormatter();
                Data = (BaseContainer)bf.Deserialize(fs);
            }

            //тут будет код конвертации, если понадобиться


            using (var fs = File.OpenWrite(SaveFileName))
            {
                var bf = new BinaryFormatter();
                bf.Serialize(fs, Data);
            }
        }

19 Source : OCIncident.cs
with Apache License 2.0
from AantCoder

public static string GetCostOnGameByCommand(string command, bool onliCheck, out string error)
        {
            Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 1 command:" + command);
            //разбираем аргументы в кавычках '. Удвоенная кавычка указывает на её символ.
            string cmd;
            List<string> args;
            ChatUtils.ParceCommand(command, out cmd, out args);

            if (args.Count < 3)
            {
                error = "OC_Incidents_OCIncident_WrongArg".Translate().ToString();
                Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand error:" + error);
                return null;
            }

            // /call raid '111' 1 10 air tribe

            //проверка, что денег хватает
            int cost = OCIncident.CalculateRaidCost(args[0].ToLower(), Int64.Parse(args[2])
                , args.Count > 3 ? Int32.Parse(args[3]) : 1
                , args.Count > 4 ? args[4].ToLower() : null
                , args.Count > 5 ? args[5].ToLower() : null);
            int gold = -1;

            Map map = null;
            if (cost > 0)
            {
                gold = GameUtils.FindThings(ThingDefOf.Gold, 0, false);
            }

            if (cost < 0 || gold < 0 || gold < cost)
            {
                error = cost < 0 || gold < 0
                    ? "OC_Incidents_OCIncident_WealthErr".Translate().ToString() + $" cost={cost} gold={gold}"
                    : "OC_Incidents_OCIncident_GoldErr".Translate(gold, cost, cost - gold).ToString();
                Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand error:" + error);
                return null;
            }

            if (onliCheck)
            {
                error = null;
                return "OC_Incidents_OCIncident_NotEnoughGold".Translate(cost);
            }

            Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 2");

            //отнимаем нужное кол-во денег(золото или серебро... или что-нибудь ещё)
            GameUtils.FindThings(ThingDefOf.Gold, cost, false);

            Loger.Log("IncidentLod OCIncident.GetCostOnGameByCommand 3");
            //принудительное сохранение
            if (!SessionClientController.Data.BackgroundSaveGameOff)
                SessionClientController.SaveGameNow(true);
            Loger.Log("IncidentLod ChatController.AfterStartIncident 4");

            error = null;
            return "OC_Incidents_OCIncident_GoldPay".Translate(cost);
        }

19 Source : PanelProfilePlayer.cs
with Apache License 2.0
from AantCoder

public void Save()
        {
            if (!Validate())
            {
                Load();
                return;
            }
            var delaySaveGame = int.Parse(Input_DelaySaveGame);

            var spi = new SetPlayerInfo(SessionClient.Get);
            spi.GenerateRequestAndDoJob(new ModelPlayerInfo()
            {
                DelaySaveGame = delaySaveGame,
                EnablePVP = Input_EnablePVP,
                DiscordUserName = Input_DiscordUserName,
                EMail = Input_EMail,
                AboutMyTextBox = Input_AboutMyTextBox.Text,
            });

            Load();
        }

19 Source : Repository.cs
with Apache License 2.0
from AantCoder

public static bool CheckIsBanIP(string IP)
        {
            if ((DateTime.UtcNow - BlockipUpdate).TotalSeconds > 30)
            {
                var fileName = Loger.PathLog + "blockip.txt";

                BlockipUpdate = DateTime.UtcNow;
                if (!File.Exists(fileName)) Blockip = new HashSet<string>();
                else
                    try
                    {
                        var listBlock = File.ReadAllLines(fileName, Encoding.UTF8);
                        if (listBlock.Any(b => b.Contains("/")))
                        {
                            listBlock = listBlock
                                .SelectMany(b =>
                                {
                                    var bb = b.Trim();
                                    var comment = "";
                                    var ic = bb.IndexOf(" ");
                                    if (ic > 0)
                                    {
                                        comment = bb.Substring(ic);
                                        bb = bb.Substring(0, ic);
                                    }
                                    if (bb.Any(c => !char.IsDigit(c) && c != '.' && c != '/')) return new List<string>();
                                    var ls = bb.LastIndexOf("/");
                                    if (ls < 0) return new List<string>() { bb + comment };
                                    var lp = bb.LastIndexOf(".");
                                    if (lp <= 0) return new List<string>();
                                    var ib = int.Parse(bb.Substring(lp + 1, ls - (lp + 1)));
                                    var ie = int.Parse(bb.Substring(ls + 1));
                                    var res = new List<string>();
                                    var s = bb.Substring(0, lp + 1);
                                    for (int i = ib; i <= ie; i++)
                                        res.Add(s + i.ToString() + comment);
                                    return res;
                                })
                                .ToArray();
                            File.WriteAllLines(fileName, listBlock, Encoding.Default);
                        }
                        Blockip = new HashSet<string>(listBlock
                            .Select(b => b.Contains(" ") ? b.Substring(0, b.IndexOf(" ")) : b));
                    }
                    catch (Exception exp)
                    {
                        Loger.Log("CheckIsBanIP error " + exp.Message);
                        Blockip = new HashSet<string>();
                        return false;
                    }

            }

            return Blockip.Contains(IP.Trim());
        }

19 Source : DellFanCmd.cs
with GNU General Public License v3.0
from AaronKelley

public static int ProcessCommand(string[] args)
        {
            int returnCode = 0;

            try
            {
                if (args.Length != 1)
                {
                    Usage();
                }
                else
                {
                    // Behavior variables.
                    bool disableEcFanControl = false;
                    bool enableEcFanControl = false;
                    bool setFansToMax = false;
                    bool useAlternateCommand = false;
                    bool setFanLevel = false;
                    bool getFanRpm = false;
                    bool runTest = false;
                    BzhFanIndex fanSelection = BzhFanIndex.Fan1;
                    BzhFanLevel fanLevel = BzhFanLevel.Level0;

                    // Figure out what was requested.
                    if (args[0] == "ec-disable")
                    {
                        disableEcFanControl = true;
                        setFansToMax = true;
                    }
                    else if (args[0] == "ec-disable-nofanchg")
                    {
                        disableEcFanControl = true;
                    }
                    else if (args[0] == "ec-enable")
                    {
                        enableEcFanControl = true;
                    }
                    else if (args[0] == "ec-disable-alt")
                    {
                        disableEcFanControl = true;
                        setFansToMax = true;
                        useAlternateCommand = true;
                    }
                    else if (args[0] == "ec-disable-alt-nofanchg")
                    {
                        disableEcFanControl = true;
                        useAlternateCommand = true;
                    }
                    else if (args[0] == "ec-enable-alt")
                    {
                        enableEcFanControl = true;
                        useAlternateCommand = true;
                    }
                    else if (args[0] == "fan1-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan1;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan1-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan1;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan1-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan1;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan2-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan2;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan2-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan2;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan2-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan2;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan3-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan3;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan3-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan3;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan3-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan3;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan4-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan4;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan4-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan4;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan4-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan4;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan5-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan5;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan5-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan5;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan5-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan5;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan6-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan6;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan6-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan6;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan6-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan6;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "fan7-level0")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan7;
                        fanLevel = BzhFanLevel.Level0;
                    }
                    else if (args[0] == "fan7-level1")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan7;
                        fanLevel = BzhFanLevel.Level1;
                    }
                    else if (args[0] == "fan7-level2")
                    {
                        setFanLevel = true;
                        fanSelection = BzhFanIndex.Fan7;
                        fanLevel = BzhFanLevel.Level2;
                    }
                    else if (args[0] == "rpm-fan1")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan1;
                    }
                    else if (args[0] == "rpm-fan2")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan2;
                    }
                    else if (args[0] == "rpm-fan3")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan3;
                    }
                    else if (args[0] == "rpm-fan4")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan4;
                    }
                    else if (args[0] == "rpm-fan5")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan5;
                    }
                    else if (args[0] == "rpm-fan6")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan6;
                    }
                    else if (args[0] == "rpm-fan7")
                    {
                        getFanRpm = true;
                        fanSelection = BzhFanIndex.Fan7;
                    }
                    else if (args[0] == "test")
                    {
                        runTest = true;
                    }
                    else if (args[0] == "test-alt")
                    {
                        runTest = true;
                        useAlternateCommand = true;
                    }
                    else
                    {
                        Usage();
                        return -3;
                    }

                    // Execute request.

                    // Load driver first.
                    if (LoadDriver())
                    {
                        if (disableEcFanControl)
                        {
                            // Disable EC fan control.
                            Console.WriteLine("Attempting to disable EC control of the fan...");

                            bool success = DellSmbiosBzh.DisableAutomaticFanControl(useAlternateCommand);

                            if (!success)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" ...Success.");

                            if (setFansToMax)
                            {
                                // Crank the fans up, for safety.
                                Console.WriteLine("Setting fan 1 speed to maximum...");
                                success = DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level2);
                                if (!success)
                                {
                                    Console.Error.WriteLine("Failed.");
                                }

                                Console.WriteLine("Setting fan 2 speed to maximum...");
                                success = DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level2);
                                if (!success)
                                {
                                    Console.Error.WriteLine("Failed.  (Maybe your system just has one fan?)");
                                }
                            }
                            else
                            {
                                Console.WriteLine("WARNING: CPU and GPU are not designed to run under load without active cooling.");
                                Console.WriteLine("Make sure that you have alternate fan speed control measures in place.");
                            }
                        }
                        else if (enableEcFanControl)
                        {
                            // Enable EC fan control.
                            Console.WriteLine("Attempting to enable EC control of the fan...");

                            bool success = DellSmbiosBzh.EnableAutomaticFanControl(useAlternateCommand);

                            if (!success)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" ...Success.");
                        }
                        else if (setFanLevel)
                        {
                            // Set the fan to a specific level.
                            Console.WriteLine("Attempting to set the fan level...");
                            bool success = DellSmbiosBzh.SetFanLevel(fanSelection, fanLevel);

                            if (!success)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" ...Success.");
                        }
                        else if (getFanRpm)
                        {
                            // Query the fan RPM.
                            Console.WriteLine("Attempting to query the fan RPM...");
                            uint? result = DellSmbiosBzh.GetFanRpm(fanSelection);

                            if (result == null)
                            {
                                Console.Error.WriteLine("Failed.");
                                UnloadDriver();
                                return -1;
                            }

                            Console.WriteLine(" Result: {0}", result);
                            if (result < int.MaxValue)
                            {
                                returnCode = int.Parse(result.ToString());
                            }
                            else
                            {
                                Console.WriteLine(" (Likely error)");
                                returnCode = -1;
                            }
                        }
                        else if (runTest)
                        {
                            // Test all of the fan levels and report RPMs.

                            uint? rpmIdleFan1;
                            uint? rpmLevel0Fan1;
                            uint? rpmLevel1Fan1;
                            uint? rpmLevel2Fan1;

                            uint? rpmIdleFan2 = null;
                            uint? rpmLevel0Fan2 = null;
                            uint? rpmLevel1Fan2 = null;
                            uint? rpmLevel2Fan2 = null;

                            int sleepInterval = 7500;
                            bool fan2Present = true;

                            // Disable EC fan control.
                            Console.WriteLine("Disabling EC fan control...");
                            DellSmbiosBzh.DisableAutomaticFanControl(useAlternateCommand);

                            // Query current idle fan levels.
                            rpmIdleFan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);
                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level0);

                            rpmIdleFan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);
                            bool success = DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level0);

                            if (!success)
                            {
                                // No fan 2?
                                fan2Present = false;
                                Console.WriteLine("Looks like fan 2 is not present, system only has one fan?");
                            }

                            // Measure fan 1.
                            Console.WriteLine("Measuring: Fan 1, level 0...");
                            Thread.Sleep(sleepInterval);
                            rpmLevel0Fan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);

                            Console.WriteLine("Measuring: Fan 1, level 1..."); 
                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level1);
                            Thread.Sleep(sleepInterval);
                            rpmLevel1Fan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);

                            Console.WriteLine("Measuring: Fan 1, level 2..."); 
                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level2);
                            Thread.Sleep(sleepInterval);
                            rpmLevel2Fan1 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);

                            DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan1, BzhFanLevel.Level0);

                            if (fan2Present)
                            {
                                // Measure fan 2.
                                Console.WriteLine("Measuring: Fan 2, level 0...");
                                rpmLevel0Fan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);

                                Console.WriteLine("Measuring: Fan 2, level 1..."); 
                                DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level1);
                                Thread.Sleep(sleepInterval);
                                rpmLevel1Fan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);

                                Console.WriteLine("Measuring: Fan 2, level 2..."); 
                                DellSmbiosBzh.SetFanLevel(BzhFanIndex.Fan2, BzhFanLevel.Level2);
                                Thread.Sleep(sleepInterval);
                                rpmLevel2Fan2 = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan2);
                            }

                            // Enable EC fan control.
                            Console.WriteLine("Enabling EC fan control...");
                            DellSmbiosBzh.EnableAutomaticFanControl(useAlternateCommand);

                            Console.WriteLine("Test procedure is finished.");
                            Console.WriteLine();
                            Console.WriteLine();

                            // Output results.
                            Console.WriteLine("Fan 1 initial speed: {0}", rpmIdleFan1);
                            if (fan2Present)
                            {
                                Console.WriteLine("Fan 2 initial speed: {0}", rpmIdleFan2);
                            }
                            Console.WriteLine();

                            Console.WriteLine("Fan 1 level 0 speed: {0}", rpmLevel0Fan1);
                            Console.WriteLine("Fan 1 level 1 speed: {0}", rpmLevel1Fan1);
                            Console.WriteLine("Fan 1 level 2 speed: {0}", rpmLevel2Fan1);
                            Console.WriteLine();

                            if (fan2Present)
                            {
                                Console.WriteLine("Fan 2 level 0 speed: {0}", rpmLevel0Fan2);
                                Console.WriteLine("Fan 2 level 1 speed: {0}", rpmLevel1Fan2);
                                Console.WriteLine("Fan 2 level 2 speed: {0}", rpmLevel2Fan2);
                                Console.WriteLine();
                            }
                        }

                        // Unload driver.
                        UnloadDriver();
                    }
                }
            }
            catch (DllNotFoundException)
            {
                Console.Error.WriteLine("Unable to load DellSmbiosBzh.dll");
                Console.Error.WriteLine("Make sure that the file is present.  If it is, install the required Visual C++ redistributable:");
                Console.Error.WriteLine("https://aka.ms/vs/16/release/vc_redist.x64.exe");
                returnCode = -1;
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("Error: {0}", exception.Message);
                Console.Error.WriteLine(exception.StackTrace);
                returnCode = -1;
                UnloadDriver();
            }

            return returnCode;
        }

19 Source : CallIncidentCmd.cs
with Apache License 2.0
from AantCoder

public ModelStatus Execute(ref PlayerServer player, Chat chat, List<string> argsM)
        {
            Loger.Log("IncidentLod CallIncidentCmd Execute 1");
            var ownLogin = player.Public.Login;
            
            //базовая проверка аргументов
            if (argsM.Count < 2)
                return _chatManager.PostCommandPrivatPostActivChat(ChatCmdResult.IncorrectSubCmd, ownLogin, chat,
                    "OC_Incidents_CallIncidents_Err1");

            //собираем данные
            var type = CallIncident.ParseIncidentTypes(argsM[0]); 

            PlayerServer targetPlayer = Repository.GetPlayerByLogin(argsM[1]);
            if (targetPlayer == null)
            {
                return _chatManager.PostCommandPrivatPostActivChat(ChatCmdResult.UserNotFound, ownLogin, chat, "User " + argsM[1] + " not found");
            }

            long serverId = 0;
            if (argsM.Count > 2)
            {
                serverId = Int64.Parse(argsM[2]);
            }

            int mult = 1;
            if (argsM.Count > 3)
            {
                mult = Int32.Parse(argsM[3]);
            }

            //  walk, random, air
            IncidentArrivalModes? arrivalMode = null;
            if (argsM.Count > 4)
            {
                arrivalMode = CallIncident.ParseArrivalMode(argsM[4]);
            }

            string faction = null;
            if (argsM.Count > 5)
            {
                faction = CallIncident.ParseFaction(argsM[5]);
            }

            Loger.Log("IncidentLod CallIncidentCmd Execute 2");
            var error = CallIncident.CreateIncident(player, targetPlayer, serverId, type, mult, arrivalMode, faction);
            if (error != null)
            {
                Loger.Log("IncidentLod CallIncidentCmd Execute error: " + error);
                return _chatManager.PostCommandPrivatPostActivChat(ChatCmdResult.IncorrectSubCmd, ownLogin, chat, error);
            }

            //var msg = argsM[0] + " lvl " + mult + " for user " + targetPlayer.Public.Login + " from " + ownLogin;
            //_chatManager.AddSystemPostToPublicChat(msg);

            Loger.Log("IncidentLod CallIncidentCmd Execute 3");

            return new ModelStatus() { Status = 0 };
        }

19 Source : SimpleAnimationNodeEditor.cs
with MIT License
from aarthificial

[MenuItem("replacedets/Create/Reanimator/Simple Animation (From Textures)", false, 400)]
        private static void CreateFromTextures()
        {
            var trailingNumbersRegex = new Regex(@"(\d+$)");

            var sprites = new List<Sprite>();
            var textures = Selection.GetFiltered<Texture2D>(SelectionMode.replacedets);
            foreach (var texture in textures)
            {
                string path = replacedetDatabase.GetreplacedetPath(texture);
                sprites.AddRange(replacedetDatabase.LoadAllreplacedetsAtPath(path).OfType<Sprite>());
            }

            var cels = sprites
                .OrderBy(
                    sprite =>
                    {
                        var match = trailingNumbersRegex.Match(sprite.name);
                        return match.Success ? int.Parse(match.Groups[0].Captures[0].ToString()) : 0;
                    }
                )
                .Select(sprite => new SimpleCel(sprite))
                .ToArray();

            var replacedet = SimpleAnimationNode.Create<SimpleAnimationNode>(
                cels: cels
            );
            string baseName = trailingNumbersRegex.Replace(textures[0].name, "");
            replacedet.name = baseName + "_animation";

            string replacedetPath = Path.GetDirectoryName(replacedetDatabase.GetreplacedetPath(textures[0]));
            replacedetDatabase.Createreplacedet(replacedet, Path.Combine(replacedetPath ?? Application.dataPath, replacedet.name + ".replacedet"));
            replacedetDatabase.Savereplacedets();
        }

19 Source : Parser.cs
with MIT License
from abdullin

static Process Parse(int pid, string source) {
            var items = source.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            var arrival = int.Parse(items[0]);

            var list = new Queue<Burst>();


            for (var i = 2; i < items.Length; i++) {
                var type = i % 2 == 0 ? Resource.CPU : Resource.IO;
                var duration = int.Parse(items[i]);
                list.Enqueue(new Burst(type, duration));
            }

            return new Process(pid, list, arrival);
        }

19 Source : MatchmakingManager.cs
with MIT License
from absurd-joy

private void ProcessRemoteMove(string moveString)
		{
			Debug.Log("Processing remote move string: " + moveString);
			string[] tokens = moveString.Split(':');

			GamePiece.Piece piece = (GamePiece.Piece)Enum.Parse(typeof(GamePiece.Piece), tokens[0]);
			int x = Int32.Parse(tokens[1]);
			int y = Int32.Parse(tokens[2]);

			// swap the coordinates since each player replacedumes they are player 0
			x = GameBoard.LENGTH_X-1 - x;
			y = GameBoard.LENGTH_Y-1 - y;

			m_gameController.MakeRemoteMove(piece, x, y);
		}

19 Source : _Host.cshtml.cs
with Apache License 2.0
from acblog

private Task GeneratePagereplacedle(string[] path, List<string> result)
        {
            int pageNumber = int.Parse(path[0]);
            result.Add($"Page {pageNumber + 1}");
            return Task.CompletedTask;
        }

19 Source : GenericInterface.cs
with MIT License
from Accelerider

private static DelegateType GetDelegateType<TDelegate>()
            {
                var actionMatch = ActionDelegateRegex.Match(typeof(TDelegate).FullName ?? throw new InvalidOperationException());
                if (actionMatch.Success)
                {
                    return actionMatch.Groups.Count > 1 ? DelegateType.ActionWithParams : DelegateType.Action;
                }

                var funcMatch = FuncDelegateRegex.Match(typeof(TDelegate).FullName ?? throw new InvalidOperationException());
                if (funcMatch.Success)
                {
                    return int.Parse(actionMatch.Groups[1].Value) > 1 ? DelegateType.FuncWithParams : DelegateType.Func;
                }

                return DelegateType.NotSupported;
            }

19 Source : VRSL_LightGroupZone.cs
with MIT License
from AcChosen

void SynAnimVars()
    {
        //if(colorAnimSync >= 1)
            colorAnim = int.Parse(animSync.Substring(0,3));
        //if(intensityAnimSync >= 1)
            intensityAnim = int.Parse(animSync.Substring(4,2));
        //if(panTiltAnimSync >= 1)
            panTiltAnim = int.Parse(animSync.Substring(6,3));
        //if(gOBOAnimSync >= 1)
            gOBOAnim = int.Parse(animSync.Substring(9,3));
        foreach(VRStageLighting_Animated stagelight in stageLightsList)
        {
            stagelight._UpdateAnimations();
        }
        foreach(VRStageLighting_Animated_Static stagelight in staticStageLightsList)
        {
            stagelight._UpdateAnimations();
        }
    }

19 Source : Increment.cs
with GNU Lesser General Public License v3.0
from acnicholas

private static void SetParameterToValue(Parameter p, string s)
        {
            switch (p.StorageType) {
                case StorageType.Integer:
                    p.Set(int.Parse(s));
                    break;
                case StorageType.String:
                    if (!string.IsNullOrEmpty(s)) {
                        p.Set(s);
                    }
                    break;
                case StorageType.None:
                    break;
                case StorageType.Double:
                    break;
                case StorageType.ElementId:
                    break;
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }

19 Source : ThrottlingReportHandler.cs
with MIT License
from actions

protected async override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            // Call the inner handler.
            var response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false);

            // Inspect whether response has throttling information
            IEnumerable<string> vssRequestDelayed = null;
            IEnumerable<string> vssRequestQuotaReset = null;

            if (response.Headers.TryGetValues(HttpHeaders.VssRateLimitDelay, out vssRequestDelayed) &&
                response.Headers.TryGetValues(HttpHeaders.VssRateLimitReset, out vssRequestQuotaReset) &&
                !string.IsNullOrEmpty(vssRequestDelayed.FirstOrDefault()) &&
                !string.IsNullOrEmpty(vssRequestQuotaReset.FirstOrDefault()))
            {
                TimeSpan delay = TimeSpan.FromSeconds(double.Parse(vssRequestDelayed.First()));
                int expirationEpoch = int.Parse(vssRequestQuotaReset.First());
                DateTime expiration = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc).AddSeconds(expirationEpoch);

                _throttlingReporter.ReportThrottling(delay, expiration);
            }

            return response;
        }

19 Source : DateIncrement.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static string GetDateIDGivenIncrements(string dateIdA, string dateIdB)
        {
            var year = 0m;
            var month = 0m;
            var day = 0m;


            var yearA = int.Parse(dateIdA.ToString().Substring(0, 2));
            var monthA = int.Parse(dateIdA.ToString().Substring(2, 2));
            var dayA = int.Parse(dateIdA.ToString().Substring(4, 2));


            var yearB = int.Parse(dateIdB.ToString().Substring(0, 2));
            var monthB = int.Parse(dateIdB.ToString().Substring(2, 2));
            var dayB = int.Parse(dateIdB.ToString().Substring(4, 2));


            year = yearB - yearA > 24 ? yearB - yearA - 24 : yearB - yearA;
            month = monthB - monthA > 60 ? monthB - monthA - 60 : monthB - monthA;
            day = dayB - dayA > 60 ? dayB - dayA : dayB - dayA;

            return (DoubleCharacterOut(year.ToString()) + DoubleCharacterOut(month.ToString()) + DoubleCharacterOut(day.ToString()));
        }

19 Source : TimeIncrement.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static string GetTimeIDGivenIncrementsOnInputTimeId(string timeId, TimeIncrement increment)
        {
            var hour = int.Parse(timeId.ToString().Substring(0, 2));
            var minute = int.Parse(timeId.ToString().Substring(2, 2));
            var second = int.Parse(timeId.ToString().Substring(4, 2));
            var milliSecond = int.Parse(timeId.ToString().Substring(6, 4));
            if (increment.type == TimeIncrementTypes.Hour)
            {
                hour = hour + increment.increments > 24 ? hour + increment.increments - 24 : hour + increment.increments;
            }
            if (increment.type == TimeIncrementTypes.Minute)
            {
                minute = minute + increment.increments > 60 ? minute + increment.increments - 60 : minute + increment.increments;
            }
            if (increment.type == TimeIncrementTypes.Second)
            {
                second = second + increment.increments > 60 ? second + increment.increments - 60 : second + increment.increments;
            }
            if (increment.type == TimeIncrementTypes.MilliSecond)
            {
                milliSecond = milliSecond + increment.increments > 1000 ? milliSecond + increment.increments - 1000 : milliSecond + increment.increments;
            }

            return (DoubleCharacterOut(hour.ToString()) + DoubleCharacterOut(minute.ToString()) + DoubleCharacterOut(second.ToString()));
        }

19 Source : TimeIncrement.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static string GetTimeIDGivenIncrements(string timeIdA, string timeIdB)
        {
            var hour = 0m;
            var minute = 0m;
            var second = 0m;
            var miliSecond = 0m;

            var hourA = int.Parse(timeIdA.ToString().Substring(0, 2));
            var minuteA = int.Parse(timeIdA.ToString().Substring(2, 2));
            var secondA = int.Parse(timeIdA.ToString().Substring(4, 2));
            var miliSecondA = int.Parse(timeIdA.ToString().Substring(6, 2));

            var hourB = int.Parse(timeIdB.ToString().Substring(0, 2));
            var minuteB = int.Parse(timeIdB.ToString().Substring(2, 2));
            var secondB = int.Parse(timeIdB.ToString().Substring(4, 2));
            var miliSecondB = int.Parse(timeIdB.ToString().Substring(6, 2));

            hour = hourB - hourA > 24 ? hourB - hourA - 24 : hourB - hourA;
            minute = minuteB - minuteA > 60 ? minuteB - minuteA - 60 : minuteB - minuteA;
            second = secondB - secondA > 60 ? secondB - secondA : secondB - secondA;
            miliSecond = miliSecondB = miliSecondA > 1000 ? miliSecondB = miliSecondA : miliSecondB = miliSecondA;

            return (DoubleCharacterOut(hour.ToString()) + DoubleCharacterOut(minute.ToString()) + DoubleCharacterOut(second.ToString()) + DoubleCharacterOut(miliSecond.ToString()));
        }

19 Source : ModelStatesSuggestionReader.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

private void CreateCodeList(List<int> codeList)
        {
            for (int i = 1; i <= stateRange; i++)
            {
                for (int j = 1; j <= stateRange; j++)
                {
                    codeList.Add(int.Parse(i.ToString() + j.ToString()));
                }
            }
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

static void Main(string[] args)
        {
            bool DonotLoadGrid = true;
            var grid = new List<IList<double>>();
            if (!DonotLoadGrid)
            {
                Console.WriteLine("Loading Stream: " + DateTime.Now.ToString());
                var sr = new StreamReader(@"C:\data\table.csv");

                while (!sr.EndOfStream)
                {
                    var line = sr.ReadLine();
                    var fieldValues = line.Split(',');
                    var fields = new List<double>();
                    var rdm = new Random(100000);
                    foreach (var field in fieldValues)
                    {
                        var res = 0d;
                        var add = double.TryParse(field, out res) == true ? res : rdm.NextDouble();
                        fields.Add(add);
                    }
                    grid.Add(fields);
                }
                Console.WriteLine("Grid loaded successfully!! " + DateTime.Now.ToString());
            }
            var keepProcessing = true;
            while (keepProcessing)
            {
                Console.WriteLine(DateTime.Now.ToString());
                Console.WriteLine("Enter Expression:");
                var expression = Console.ReadLine();
                if (expression.ToLower() == "exit")
                {
                    keepProcessing = false;
                }
                else
                {
                    try
                    {
                        if(expression.Equals("zspread"))
                        {
                            var result = ConnectedInstruction.GetZSpread(grid,3,503);
                        }
                        if (expression.Substring(0, 19).ToLower().Equals("logisticregression "))
                        {
                            keepProcessing = true;
                            var paths = expression.Split(' '); 
                            #region Python
                                var script =@"
import pandas as pd
from sklearn.linear_model import LogisticRegression
from sklearn.cross_validation import train_test_split
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score

creditData = pd.read_csv("+paths[1]+@")

print(creditData.head())
print(creditData.describe())
print(creditData.corr())

features = creditData[['income', 'age', 'loan']]
target = creditData.default

feature_train, feature_test, target_train, target_test = train_test_split(features, target, test_size = 0.3)

model = LogisticRegression()
model.fit = model.fit(feature_train, target_train)
predictions = model.fit.predict(feature_test)

print(confusion_matrix(target_test, predictions))
print(accuracy_score(target_test, predictions))
";
                            var sw = new StreamWriter(@"c:\data\logistic.py");
                            sw.Write(script);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\logistic.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..."+ DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if(expression.Substring(0,12) == "videoreplacedyse")
                        {
                            #region python
                            var python = @"
from keras.preprocessing.image import img_to_array
import imutils
import cv2
from keras.models import load_model
import numpy as np
import geocoder
#import mysql.connector as con

#mydb = con.connect(
#  host=""localhost"",
#  user=""yourusername"",
#  preplacedwd=""yourpreplacedword"",
# database=""mydatabase""
#)
#mycursor = mydb.cursor()

g = geocoder.ip('me')

# parameters for loading data and images
detection_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\haarcascade_files\\haarcascade_frontalface_default.xml'
emotion_model_path = 'C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Sentiment replacedysis\\Emotion-recognition-master\\models\\_mini_XCEPTION.102-0.66.hdf5'

# hyper-parameters for bounding boxes shape
# loading models
face_detection = cv2.CascadeClreplacedifier(detection_model_path)
emotion_clreplacedifier = load_model(emotion_model_path, compile = False)
EMOTIONS = [""angry"", ""disgust"", ""scared"", ""happy"", ""sad"", ""surprised"",
""neutral""]


# feelings_faces = []
# for index, emotion in enumerate(EMOTIONS):
# feelings_faces.append(cv2.imread('emojis/' + emotion + '.png', -1))

# starting video streaming
cv2.namedWindow('your_face')
camera = cv2.VideoCapture(0)
f = open(""C:\\Users\\rajiyer\\Doreplacedents\\Test Data\\Probability.txt"", ""a+"")

while True:
frame = camera.read()[1]
#reading the frame
frame = imutils.resize(frame, width = 300)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = face_detection.detectMultiScale(gray, scaleFactor = 1.1, minNeighbors = 5, minSize = (30, 30), flags = cv2.CASCADE_SCALE_IMAGE)


canvas = np.zeros((250, 300, 3), dtype = ""uint8"")
frameClone = frame.copy()
if len(faces) > 0:
faces = sorted(faces, reverse = True,
key = lambda x: (x[2] - x[0]) * (x[3] - x[1]))[0]
(fX, fY, fW, fH) = faces
# Extract the ROI of the face from the grayscale image, resize it to a fixed 28x28 pixels, and then prepare
# the ROI for clreplacedification via the CNN
roi = gray[fY: fY + fH, fX: fX + fW]
roi = cv2.resize(roi, (64, 64))
roi = roi.astype(""float"") / 255.0
roi = img_to_array(roi)
roi = np.expand_dims(roi, axis = 0)



preds = emotion_clreplacedifier.predict(roi)[0]
emotion_probability = np.max(preds)
label = EMOTIONS[preds.argmax()]
else: continue



for (i, (emotion, prob)) in enumerate(zip(EMOTIONS, preds)):
# construct the label text
text = ""{}: {:.2f}%"".format(emotion, prob * 100)
#sql = ""INSERT INTO predData (Metadata, Probability) VALUES (%s, %s)""
#val = (""Meta"", prob * 100)
f.write(text)
#str1 = ''.join(str(e) for e in g.latlng)
#f.write(str1)
#mycursor.execute(sql, val)
#mydb.commit()
# draw the label + probability bar on the canvas
# emoji_face = feelings_faces[np.argmax(preds)]

                
w = int(prob * 300)
cv2.rectangle(canvas, (7, (i * 35) + 5),
(w, (i * 35) + 35), (0, 0, 255), -1)
cv2.putText(canvas, text, (10, (i * 35) + 23),
cv2.FONT_HERSHEY_SIMPLEX, 0.45,
(255, 255, 255), 2)
cv2.putText(frameClone, label, (fX, fY - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 255), 2)
cv2.rectangle(frameClone, (fX, fY), (fX + fW, fY + fH),
(0, 0, 255), 2)


#    for c in range(0, 3):
#        frame[200:320, 10:130, c] = emoji_face[:, :, c] * \
#        (emoji_face[:, :, 3] / 255.0) + frame[200:320,
#        10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0)


cv2.imshow('your_face', frameClone)
cv2.imshow(""Probabilities"", canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break

camera.release()
cv2.destroyAllWindows()
";
                            var sw = new StreamWriter(@"c:\data\face.py");
                            sw.Write(python);
                            sw.Close();
                            #endregion
                            ProcessStartInfo start = new ProcessStartInfo();
                            Console.WriteLine("Starting Python Engine...");
                            start.FileName = @"C:\Users\rajiyer\PycharmProjects\TestPlot\venv\Scripts\python.exe";
                            start.Arguments = string.Format("{0} {1}", @"c:\data\face.py", args);
                            start.UseShellExecute = false;
                            start.RedirectStandardOutput = true;
                            Console.WriteLine("Starting Process..." + DateTime.Now.ToString());
                            using (Process process = Process.Start(start))
                            {
                                using (StreamReader reader = process.StandardOutput)
                                {
                                    string result = reader.ReadToEnd();
                                    Console.Write(result);
                                }
                            }
                            Console.WriteLine("Process Succeeded..." + DateTime.Now.ToString());
                        }
                        if (expression.Substring(0,12).ToLower().Equals("kaplanmeier "))
                        {
                            keepProcessing = true;
                            var columnsOfconcern = expression.Split(' ');
                            Console.WriteLine("Preparing...");
                            var observations = new List<PairedObservation>();
                            var ca = GetColumn(grid,int.Parse(columnsOfconcern[1]));
                            var cb = GetColumn(grid, int.Parse(columnsOfconcern[2]));
                            var cc = GetColumn(grid, int.Parse(columnsOfconcern[3]));
                            for(int i=0;i<ca.Count;i++)
                            {
                                observations.Add(new PairedObservation((decimal)ca[i], (decimal)cb[i], (decimal)cc[i]));
                            }
                            var kp = new KaplanMeier(observations);
                        }
                        if (expression.Equals("write"))
                        {
                            keepProcessing = true;
                            ConnectedInstruction.WritetoCsvu(grid, @"c:\data\temp.csv");
                        }
                        if (expression.Substring(0, 9) == "getvalue(")
                        {
                            keepProcessing = true;
                            Regex r = new Regex(@"\(([^()]+)\)*");
                            var res = r.Match(expression);
                            var val = res.Value.Split(',');
                            try
                            {
                                var gridVal = grid[int.Parse(val[0].Replace("(", "").Replace(")", ""))]
                                    [int.Parse(val[1].Replace("(", "").Replace(")", ""))];
                                Console.WriteLine(gridVal.ToString() + "\n");
                            }
                            catch (ArgumentOutOfRangeException)
                            {
                                Console.WriteLine("Hmmm,... apologies, can't seem to find that within range...");
                            }
                        }
                        else
                        {
                            keepProcessing = true;
                            Console.WriteLine("Process Begin:" + DateTime.Now.ToString());
                            var result = ConnectedInstruction.ParseExpressionAndRunAgainstInMemmoryModel(grid, expression);
                            Console.WriteLine("Process Ended:" + DateTime.Now.ToString());
                        }
                    }
                    catch (ArgumentOutOfRangeException)
                    {

                    }
                }
            }
        }

19 Source : DateIncrement.cs
with BSD 3-Clause "New" or "Revised" License
from ActuarialIntelligence

public static string GetDateIDGivenIncrementsOnInputDateId(string dateId, DateIncrement increment)
        {
            var year = int.Parse(dateId.ToString().Substring(0, 4));
            var month = int.Parse(dateId.ToString().Substring(4, 2));
            var day = int.Parse(dateId.ToString().Substring(6, 2));

            if (increment.type == DateIncrementTypes.Year)
            {
                year = year + increment.increments > 99 ? year + increment.increments - 99 : year + increment.increments;
            }
            if (increment.type == DateIncrementTypes.Month)
            {
                if (month + increment.increments > 12)
                {
                    year = year + 1;
                }
                month = month + increment.increments > 12 ? month + increment.increments - 12 : month + increment.increments;

            }
            if (increment.type == DateIncrementTypes.Day)
            {
                day = day + increment.increments > 30 ? day + increment.increments - 30 : day + increment.increments;
            }


            return (DoubleCharacterOut(year.ToString()) + DoubleCharacterOut(month.ToString()) + DoubleCharacterOut(day.ToString()));
        }

19 Source : RpcServer.cs
with MIT License
from ad313

public static void Start()
        {
            var factory = new ConnectionFactory()
            {
                // 这是我这边的配置,自己改成自己用就好
                HostName = "192.168.1.120",
                UserName = "admin",
                Preplacedword = "123456",
                Port = 30483,
                VirtualHost = "/"
            };

            var connection = factory.CreateConnection();
            var channel = connection.CreateModel();
            
                channel.QueueDeclare(queue: "rpc_queue", durable: false, exclusive: false, autoDelete: false, arguments: null);
                channel.BasicQos(0, 1, false);
                var consumer = new EventingBasicConsumer(channel);
                channel.BasicConsume(queue: "rpc_queue", autoAck: false, consumer: consumer);
                Console.WriteLine(" [x] Awaiting RPC requests");

                consumer.Received += (model, ea) =>
                {
                    string response = null;

                    var body = ea.Body.ToArray();
                    var props = ea.BasicProperties;
                    var replyProps = channel.CreateBasicProperties();
                    replyProps.CorrelationId = props.CorrelationId;

                    try
                    {
                        var message = Encoding.UTF8.GetString(body);
                        int n = int.Parse(message);
                        Console.WriteLine(" [.] fib({0})", message);
                        response = fib(n).ToString();
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(" [.] " + e.Message);
                        response = "";
                    }
                    finally
                    {
                        var responseBytes = Encoding.UTF8.GetBytes(response);
                        channel.BasicPublish(exchange: "", routingKey: props.ReplyTo, basicProperties: replyProps, body: responseBytes);
                        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
                    }
                };

                Console.WriteLine(" Press [enter] to exit.");
                //Console.ReadLine();
            
        }

See More Examples