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 : XMLStuff.cs
with GNU General Public License v3.0
from Albo1125

public static List<TransportRegion> LoadTransportRegionsFromXMLFile(string file)
        {
            try
            {
                #region defaultdoreplacedent
                if (!File.Exists(file))
                {
                    Directory.CreateDirectory(Directory.GetParent(file).FullName);
                    new XDoreplacedent(
                    new XElement("ArrestManager",
                        new XComment(@"These Transport Regions are used to override the Transport World Districts if you call for transport in a certain Zone that you've set up below.
	Multiple regions can be set up for one zone - in that case, Arrest Manager will select a random transport region from the ones that you've specified for that zone.
	A list of zone names can be found in the Doreplacedentation and Licence folder.
		
	The same restrictions apply here as in the world districts file: Driver & Preplacedenger & Vehicle models must be valid. 
	A vehicle must have at least 4 free seats and must be a Police vehicle (with the exception of the RIOT van).
		
	LiveryNumber and ExtraNumbers are optional.
	For LiveryNumber&ExtraNumbers: Keep in mind the code starts counting at 0. If a LiveryNumber is 1 in OpenIV, it will be 0 in code so you must enter 0.
	If the LiveryNumber is 2 in OpenIV it will be 1 in code so you must enter 1 etc.
		
	ExtraNumbers must be separated by commas, e.g. 2, 3, 4, 5.


    The default XML file that comes with the Arrest Manager download(this one, if you haven't changed it) works ingame.

    There's no need to change anything if you don't want to.
    Naturally, you can add as many TransportRegions as you like(add them between the < ArrestManager > and </ ArrestManager > tags).The below regions are meant as examples of what you can do.

        Here you can change the ped that's driving the transport vehicle. You can find all valid values here: http://ragepluginhook.net/PedModels.aspx

    Police unit uniforms
    Male City Police: s_m_y_cop_01
    Female City Police: s_f_y_cop_01
    Female Sheriff: s_f_y_sheriff_01
    Male Sheriff: s_m_y_sheriff_01
    Male Highway: s_m_y_hwaycop_01
    Prison Guard: s_m_m_prisguard_01

    Police Vehicle Examples: POLICE, POLICE2, POLICE3, POLICE4, POLICET, SHERIFF, SHERIFF2"),

                        new XElement("TransportRegion",
                            new XAttribute("ZoneName", "East Vinewood"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICE4"), new XAttribute("LiveryNumber", "0"), new XAttribute("ExtraNumbers", "2,3,4"))
                            ),
                        new XElement("TransportRegion",
                            new XAttribute("ZoneName", "West Vinewood"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_COP_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_COP_01")),
                            new XElement("Vehicle", new XAttribute("Model", "POLICET"), new XAttribute("LiveryNumber", "0"))
                            ),
                        new XElement("TransportRegion",
                            new XAttribute("ZoneName", "Sandy Sreplaceds"),
                            new XElement("Driver", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Driver", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_M_Y_SHERIFF_01")),
                            new XElement("Preplacedenger", new XAttribute("Model", "S_F_Y_SHERIFF_01")),
                            new XElement("Vehicle", new XAttribute("Model", "SHERIFF"))
                            )
                            )).Save(file);



                }
                #endregion
                XDoreplacedent xdoc = XDoreplacedent.Load(file);
                char[] trim = new char[] { '\'', '\"', ' ' };

                List<TransportRegion> trnsregs = xdoc.Descendants("TransportRegion").Select(x => new TransportRegion()
                {
                    ZoneName = ((string)x.Attribute("ZoneName")).Trim(trim),
                    DriverModels = (x.Elements("Driver").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    PreplacedengerModels = (x.Elements("Preplacedenger").Select(y => new Model(((string)y.Attribute("Model")).Trim(trim))).ToArray()),
                    VehSettings = (x.Elements("Vehicle").Select(y => new VehicleSettings(new Model((((string)y.Attribute("Model"))).Trim(trim)),
                    (string)y.Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("LiveryNumber")) ? Int32.Parse(((string)y.Attribute("LiveryNumber")).Trim(trim)) : -1,
                    (string)y.Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)y.Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)y.Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { })).ToArray()),
                    //VehicleModel = new Model(((string)x.Element("Vehicle").Attribute("Model")).Trim(trim)),
                    //LiveryNumber = (string)x.Element("Vehicle").Attribute("LiveryNumber") != null && !string.IsNullOrWhiteSpace((string)x.Element("Vehicle").Attribute("LiveryNumber")) ?  Int32.Parse(((string)x.Element("Vehicle").Attribute("LiveryNumber")).Trim(trim)) : -1,
                    //ExtraNumbers = (string)x.Element("Vehicle").Attribute("ExtraNumbers") != null && !string.IsNullOrWhiteSpace((string)x.Element("Vehicle").Attribute("ExtraNumbers")) ? Array.ConvertAll(((string)x.Element("Vehicle").Attribute("ExtraNumbers")).Trim(trim).Replace(" ", "").ToLower().Split(','), int.Parse) : new int[] { },
                }).ToList<TransportRegion>();
                
                return trnsregs;
            }
            catch (System.Threading.ThreadAbortException) { }
            catch (Exception e)
            {
                Game.LogTrivial("Arrest Manager encountered an exception reading \'" + file + "\'. It was: " + e.ToString());
                Game.DisplayNotification("~r~Error reading Transport Regions.xml. Setting default values.");
            }
            return new List<TransportRegion>();
        }

19 Source : ChineseIdCardNumberAttribute.cs
with MIT License
from albyho

private static bool CheckIDCard18(string id)
        {
            if (!long.TryParse(id.Remove(17), out var n) || n < Math.Pow(10, 16) || !long.TryParse(id.Replace('x', '0').Replace('X', '0'), out _))
            {
                return false;//数字验证
            }

            if (AddressCode.IndexOf(id.Remove(2)) == -1)
            {
                return false;//省份验证

            }
            var birth = id.Substring(6, 8).Insert(6, "-").Insert(4, "-");
            if (!DateTime.TryParse(birth, out _))
            {
                return false;//生日验证
            }

            var varifyCodes = ("1,0,x,9,8,7,6,5,4,3,2").Split(',');
            var wi = ("7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2").Split(',');
            var ai = id.Remove(17).ToCharArray();
            var sum = 0;
            for (var i = 0; i < 17; i++)
            {
                sum += int.Parse(wi[i]) * int.Parse(ai[i].ToString());
            }

            Math.DivRem(sum, 11, out int y);
            if (varifyCodes[y] != id.Substring(17, 1).ToLower())
            {
                return false;//校验码验证
            }

            return true;//符合GB11643-1999标准
        }

19 Source : StatisticsCounter.cs
with GNU General Public License v3.0
from Albo1125

public static void AddCountToStatistic(string Statistic, string PluginName)
        {

            try
            {
                SimpleAES StringEncrypter = new SimpleAES();
                Directory.CreateDirectory(Directory.GetParent(StatisticsFilePath).FullName);
                if (!File.Exists(StatisticsFilePath))
                {

                    new XDoreplacedent(
                        new XElement("LSPDFRPlus")
                    )
                    .Save(StatisticsFilePath);

                }              
                
                string pswd = Environment.UserName;
                
                string EncryptedStatistic = XmlConvert.EncodeName(StringEncrypter.EncryptToString(Statistic + PluginName + pswd));

                string EncryptedPlugin = XmlConvert.EncodeName(StringEncrypter.EncryptToString(PluginName + pswd));
                
                XDoreplacedent xdoc = XDoreplacedent.Load(StatisticsFilePath);
                char[] trim = new char[] { '\'', '\"', ' ' };
                XElement LSPDFRPlusElement;
                if (xdoc.Element("LSPDFRPlus") == null)
                {
                    LSPDFRPlusElement = new XElement("LSPDFRPlus");
                    xdoc.Add(LSPDFRPlusElement);
                }

                LSPDFRPlusElement = xdoc.Element("LSPDFRPlus");
                XElement StatisticElement;
                if (LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).ToList().Count == 0)
                {
                    //Game.LogTrivial("Creating new statistic entry.");
                    StatisticElement = new XElement(EncryptedStatistic);
                    StatisticElement.Add(new XAttribute("Plugin", EncryptedPlugin));
                    LSPDFRPlusElement.Add(StatisticElement);
                }
                StatisticElement = LSPDFRPlusElement.Elements(EncryptedStatistic).Where(x => (string)x.Attribute("Plugin") == EncryptedPlugin).FirstOrDefault();
                int StatisticCount;
                if (StatisticElement.IsEmpty)
                {
                    StatisticCount = 0;
                }
                else
                {
                    string DecryptedStatistic = StringEncrypter.DecryptString(XmlConvert.DecodeName(StatisticElement.Value));
                    //Game.LogTrivial("Decryptedstatistic: " + DecryptedStatistic);
                    int index = DecryptedStatistic.IndexOf(EncryptedStatistic);
                    string cleanPath = (index < 0)
                        ? "0"
                        : DecryptedStatistic.Remove(index, EncryptedStatistic.Length);
                    //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 2"); }
                    
                    index = cleanPath.IndexOf(pswd);
                    cleanPath = (index < 0)
                        ? "0"
                        : cleanPath.Remove(index, pswd.Length);
                    //if (cleanPath == "0") { Game.LogTrivial("Cleanpath debug 1"); }
                    StatisticCount = int.Parse(cleanPath);


                }
                //Game.LogTrivial("Statisticscount: " + StatisticCount.ToString());
                StatisticCount++;
                string ValueToWrite = StatisticCount.ToString() + pswd;
                int indextoinsertat = LSPDFRPlusHandler.rnd.Next(ValueToWrite.Length);
                ValueToWrite = ValueToWrite.Substring(0, indextoinsertat) + EncryptedStatistic + ValueToWrite.Substring(indextoinsertat);
                //Game.LogTrivial("Valueotwrite: " + ValueToWrite);
                StatisticElement.Value = XmlConvert.EncodeName(StringEncrypter.EncryptToString(ValueToWrite));

                xdoc.Save(StatisticsFilePath);

            }
            catch (System.Threading.ThreadAbortException e) { }
            catch (Exception e)
            {
                Game.LogTrivial("LSPDFR+ encountered a statistics exception. It was: " + e.ToString());
                Game.DisplayNotification("~r~LSPDFR+: Statistics error.");
            }
        }

19 Source : TrafficPolicerHandler.cs
with GNU General Public License v3.0
from Albo1125

private static void loadValuesFromIniFile()
        {
            try
            {
                drunkDriverChance = Int32.Parse(getDrunkDriverChance()) + 1;
                mobilePhoneChance = initialiseFile().ReadInt32("Ambient Event Chances", "MobilePhone", 100) + 1;
                speederChance = Int32.Parse(getSpeederChance()) + 1;
                drugDriverChance = initialiseFile().ReadInt32("Ambient Event Chances", "DrugDriver", 140) + 1;
                noLightAtDarkChance = initialiseFile().ReadInt32("Ambient Event Chances", "NoLightsAtDark", 110) + 1;
                noBrakeLightsChance = initialiseFile().ReadInt32("Ambient Event Chances", "NoBrakeLights", 150) + 1;
                BrokenDownVehicleChance = initialiseFile().ReadInt32("Ambient Event Chances", "BrokenDownVehicle", 220) + 1;
                BurnoutWhenStationaryChance = initialiseFile().ReadInt32("Ambient Event Chances", "BurnoutWhenStationary", 190) + 1;
                RevEngineWhenStationaryChance = initialiseFile().ReadInt32("Ambient Event Chances", "RevEngineWhenStationary", 190) + 1;
                NumberOfAmbientEventsBeforeTimer = initialiseFile().ReadInt32("Ambient Event Chances", "NumberOfAmbientEventsBeforeTimer");
                if (NumberOfAmbientEventsBeforeTimer < 1) { NumberOfAmbientEventsBeforeTimer = 1; }
                motorcyclistWithoutHelmetChance = Int32.Parse(getMotorcyclistWithoutHelmetChance()) + 1;
                unroadworthyVehicleChance = Int32.Parse(getUnroadworthyVehicleChance()) + 1;
                streetRaceChance = Int32.Parse(getStreetRaceChance()) + 1;
                getStolenVehicleChance();
                blipStatus = bool.Parse(getBlipStatus());
                showAmbientEventDescriptionMessage = bool.Parse(getShowAmbientEventDescriptionMessage());
                parkingTicketKey = (Keys)kc.ConvertFromString(getParkingTicketKey());
                trafficStopFollowKey = (Keys)kc.ConvertFromString(getTrafficStopFollowKey());

                parkModifierKey = (Keys)kc.ConvertFromString(getParkModifierKey());
                trafficStopFollowModifierKey = (Keys)kc.ConvertFromString(getTrafficStopFollowModifierKey());
                roadManagementMenuKey = (Keys)kc.ConvertFromString(getRoadManagementMenuKey());
                drugsTestKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "DrugalyzerKey", "O"));
                drugsTestModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "DrugalyzerModifierKey", "LControlKey"));
                trafficStopMimicKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "TrafficStopMimicKey"));
                trafficStopMimicModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "TrafficStopMimicModifierKey"));
                RoadManagementModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RoadManagementMenuModifierKey", "None"));
                RepairVehicleKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RepairBrokenDownVehicleKey", "T"));
                RoadSigns.placeSignShortcutKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "PlaceSignShortcutKey", "J"));
                RoadSigns.placeSignShortcutModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "PlaceSignShortcutModifierKey", "LControlKey"));
                RoadSigns.removeAllSignsKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RemoveAllSignsKey", "J"));
                RoadSigns.removeAllSignsModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "RemoveAllSignsModifierKey", "None"));

                SpeedChecker.ToggleSpeedCheckerKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "ToggleSpeedCheckerKey"));
                SpeedChecker.ToggleSpeedCheckerModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "ToggleSpeedCheckerModifierKey"));
                SpeedChecker.SpeedUnit = initialiseFile().ReadString("Speed Checker Settings", "SpeedUnit");
                if (SpeedChecker.SpeedUnit != "MPH" && SpeedChecker.SpeedUnit != "KMH")
                {
                    SpeedChecker.SpeedUnit = "MPH";
                }

                SpeedChecker.speedgunWeapon = initialiseFile().ReadString("Speed Checker Settings", "SpeedgunWeaponreplacedet", "WEAPON_MARKSMANPISTOL");

                SpeedChecker.PositionUpKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionUpKey", "NumPad9"));
                SpeedChecker.PositionRightKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionRightKey", "NumPad6"));
                SpeedChecker.PositionResetKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionResetKey", "NumPad5"));
                SpeedChecker.PositionLeftKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionLeftKey", "NumPad4"));
                SpeedChecker.PositionForwardKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionForwardKey", "NumPad8"));
                SpeedChecker.PositionDownKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionDownKey", "NumPad3"));
                SpeedChecker.PositionBackwardKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "PositionBackwardKey", "NumPad2"));
                SpeedChecker.SecondaryDisableKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "SecondaryDisableKey", "Back"));
                SpeedChecker.MaxSpeedUpKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "MaxSpeedUpKey", "PageUp"));
                SpeedChecker.MaxSpeedDownKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "MaxSpeedDownKey", "PageDown"));
                SpeedChecker.FlagChance = initialiseFile().ReadInt32("Speed Checker Settings", "BringUpFlagChance");
                if (SpeedChecker.FlagChance < 1) { SpeedChecker.FlagChance = 1; }
                else if (SpeedChecker.FlagChance > 100) { SpeedChecker.FlagChance = 100; }
                SpeedChecker.SpeedToColourAt = initialiseFile().ReadInt32("Speed Checker Settings", "SpeedToColourAt");
                SpeedChecker.PlayFlagBlip = initialiseFile().ReadBoolean("Speed Checker Settings", "PlayFlagBlip");

                SpeedChecker.StartStopAverageSpeedCheckKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "StartStopAverageSpeedCheckKey", "PageUp"));
                SpeedChecker.ResetAverageSpeedCheckKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Speed Checker Settings", "ResetAverageSpeedCheckKey", "PageDown"));
                DUIEnabled = initialiseFile().ReadBoolean("Callouts", "DriverUnderTheInfluenceEnabled");
                DUIFrequency = initialiseFile().ReadInt32("Callouts", "DriverUnderTheInfluenceFrequency");

                //MimickMeDistanceModifier = initialiseFile().ReadSingle("Features", "MimickMeDistanceModifier", 19f);
                TrafficStopreplacedist.VehicleDoorLockDistance = initialiseFile().ReadSingle("Features", "VehicleDoorLockDistance", 5.2f);
                TrafficStopreplacedist.VehicleDoorUnlockDistance = initialiseFile().ReadSingle("Features", "VehicleDoorUnlockDistance", 3.5f);
                AutoVehicleDoorLock = initialiseFile().ReadBoolean("Features", "AutoVehicleDoorLock", true);
                OtherUnitRespondingAudio = initialiseFile().ReadBoolean("Features", "OtherUnitRespondingAudio", true);

                CustomPulloverLocationKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "CustomPulloverLocationKey", "W"));
                CustomPulloverLocationModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Keybindings", "CustomPulloverLocationModifierKey", "LControlKey"));

                markMapKey = (Keys)kc.ConvertFromString(getMarkMapKey());
                courtKey = (Keys)kc.ConvertFromString(getCourtKey());
                dispatchCautionMessages = initialiseFile().ReadBoolean("Callouts", "DispatchCautionMessages", true);
                VehicleDetails.AutomaticDetailsChecksEnabledBaseSetting = initialiseFile().ReadBoolean("Features", "VehicleDetailsChecksEnabled");
                ownerWantedCalloutEnabled = bool.Parse(getOwnerWantedCallout());
                ownerWantedFrequency = ownerWantedFrequent();
                drugsRunnersEnabled = bool.Parse(getDrugsRunnersCallout());
                drugsRunnersFrequency = drugsRunnersFrequent();

                Impairment_Tests.Breathalyzer.BreathalyzerKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Breathalyzer Settings", "BreathalyzerKey"));
                Impairment_Tests.Breathalyzer.BreathalyzerModifierKey = (Keys)kc.ConvertFromString(initialiseFile().ReadString("Breathalyzer Settings", "BreathalyzerModifierKey"));
                Impairment_Tests.Breathalyzer.AlcoholLimit = initialiseFile().ReadSingle("Breathalyzer Settings", "AlcoholLimit");
                Impairment_Tests.Breathalyzer.AlcoholLimitUnit = initialiseFile().ReadString("Breathalyzer Settings", "AlcoholLimitUnit");

                FailToProvideChance = initialiseFile().ReadInt32("Breathalyzer Settings", "FailToProvideChance", 7);

                getNextEventTimer();

                DetermineUnitBeatStrings();

            }
            catch (Exception e)
            {
                drunkDriverChance = 190;
                mobilePhoneChance = 95;
                speederChance = 90;
                unroadworthyVehicleChance = 200;
                motorcyclistWithoutHelmetChance = 180;
                streetRaceChance = 250;
                stolenVehicleChance = 190;
                drugDriverChance = 140;
                noLightAtDarkChance = 120;
                blipStatus = true;
                showAmbientEventDescriptionMessage = false;
                parkingTicketKey = Keys.E;
                trafficStopFollowKey = Keys.T;

                roadManagementMenuKey = Keys.F6;
                parkModifierKey = Keys.LControlKey;
                drugsTestKey = Keys.O;
                drugsTestModifierKey = Keys.LControlKey;
                trafficStopFollowModifierKey = Keys.LControlKey;

                markMapKey = Keys.D9;
                courtKey = Keys.D0;
                RoadManagementModifierKey = Keys.None;
                nextEventTimer = 15000;

                dispatchCautionMessages = true;
                ownerWantedCalloutEnabled = true;
                ownerWantedFrequency = 3;
                trafficStopMimicKey = Keys.R;
                trafficStopMimicModifierKey = Keys.LControlKey;
                Game.LogTrivial(e.ToString());
                Game.LogTrivial("Loading default Traffic Policer INI file - Error detected in user's INI file.");
                Game.DisplayNotification("~r~~h~Error~s~ reading Traffic Policer ini file. Default values set; replace with default INI file!");
                Albo1125.Common.CommonLibrary.ExtensionMethods.DisplayPopupTextBoxWithConfirmation("Traffic Policer INI file", "Error reading Traffic Policer INI file. To fix this, replace your current INI file with the original one from the download. Loading default values...", true);

            }

        }

19 Source : MobileUserService.cs
with MIT License
from albyho

private string GenerateMobileValidationCode(int codeLength)
        {
            int[] randMembers = new int[codeLength];
            int[] validateNums = new int[codeLength];
            string validateNumberStr = String.Empty;
            //生成起始序列值
            int seekSeek = unchecked((int)DateTime.Now.Ticks);
            Random seekRand = new Random(seekSeek);
            int beginSeek = seekRand.Next(0, Int32.MaxValue - codeLength * 10000);
            int[] seeks = new int[codeLength];
            for (int i = 0; i < codeLength; i++)
            {
                beginSeek += 10000;
                seeks[i] = beginSeek;
            }
            //生成随机数字
            for (int i = 0; i < codeLength; i++)
            {
                var rand = new Random(seeks[i]);
                int pownum = 1 * (int)Math.Pow(10, codeLength);
                randMembers[i] = rand.Next(pownum, Int32.MaxValue);
            }
            //抽取随机数字
            for (int i = 0; i < codeLength; i++)
            {
                string numStr = randMembers[i].ToString(CultureInfo.InvariantCulture);
                int numLength = numStr.Length;
                Random rand = new Random();
                int numPosition = rand.Next(0, numLength - 1);
                validateNums[i] = Int32.Parse(numStr.Substring(numPosition, 1));
            }
            //生成验证码
            for (int i = 0; i < codeLength; i++)
            {
                validateNumberStr += validateNums[i].ToString();
            }
            return validateNumberStr;
        }

19 Source : GraphCLI.Parser.cs
with MIT License
from alelievr

static Vector2 TryParsePosition(string x, string y)
		{
			return new Vector2(Int32.Parse(x), Int32.Parse(y));
		}

19 Source : GraphCLI.Parser.cs
with MIT License
from alelievr

static BaseGraphCommand CreateGraphCommand(BaseGraphCommandTokenSequence seq, List< BaseGraphTokenMatch > tokens)
		{
			Type	nodeType;
			string	attributes = null;

			switch (seq.type)
			{
				case BaseGraphCommandType.Link:
					return new BaseGraphCommand(tokens[1].value, tokens[2].value);
				case BaseGraphCommandType.LinkAnchor:
					int fromAnchorField = int.Parse(tokens[3].value);
					int toAnchorField = int.Parse(tokens[6].value);
					return new BaseGraphCommand(tokens[1].value, fromAnchorField, tokens[4].value, toAnchorField);
				case BaseGraphCommandType.LinkAnchorName:
					return new BaseGraphCommand(tokens[1].value, tokens[3].value, tokens[4].value, tokens[6].value);
				case BaseGraphCommandType.NewNode:
					nodeType = TryParseNodeType(tokens[1].value);
					if (tokens.Count > 4)
						attributes = tokens[5].value;
					return new BaseGraphCommand(nodeType, tokens[2].value, attributes);
				case BaseGraphCommandType.NewNodePosition:
					nodeType = TryParseNodeType(tokens[1].value);
					if (tokens.Count > 9)
						attributes = tokens[10].value;
					Vector2 position = TryParsePosition(tokens[4].value, tokens[6].value);
					return new BaseGraphCommand(nodeType, tokens[2].value, position, attributes);
				case BaseGraphCommandType.GraphAttribute:
					object value = TryParseGraphAttr(tokens[2].value);
					
					if (value == null)
						return null;
					
					return new BaseGraphCommand(tokens[1].value, value);
				default:
					return null;
			}
		}

19 Source : ClientConfigView.cs
with MIT License
from alerdenisov

public void PortChange(string port)
        {
            OnPortChange(int.Parse(port));
        }

19 Source : CheckWantsView.cs
with GNU Affero General Public License v3.0
from alexander-pick

private void checkListRun(string listID, float maxAllowedPrice, float shippingAdd, float percentBelow, bool checkTrend)
    {
      XmlDoreplacedent doc;
      try
      {
        doc = MKMInteract.RequestHelper.GetWantsListByID(listID);
      }
      catch (Exception eError)
      {
        MKMHelpers.LogError("checking wantlist ID " + listID, eError.Message, true);
        return;
      }

      MainView.Instance.LogMainWindow("Starting to check your wantlist ID:" + listID + " ...");
      var node = doc.GetElementsByTagName("item");
      foreach (XmlNode article in node)
      {
        // articles in a wantlist can be either product or metaproducts (the same card from multiple sets)
        // each metaproduct needs to be expanded into a list of products that are "realized" by it
        System.Collections.Generic.List<XmlNode> products = new System.Collections.Generic.List<XmlNode>();
        if (article["type"].InnerText == "product")
          products.Add(article["product"]);
        else // it is a metaproduct
        {
          try
          {
            XmlDoreplacedent metaDoc = MKMInteract.RequestHelper.GetMetaproduct(article["metaproduct"]["idMetaproduct"].InnerText);
            XmlNodeList mProducts = metaDoc.GetElementsByTagName("product");
            foreach (XmlNode prod in mProducts)
              products.Add(prod);
          }
          catch (Exception eError)
          {
            MKMHelpers.LogError("checking wantlist metaproduct ID " + article["metaproduct"]["idMetaproduct"], eError.Message, false);
            continue;
          }
        }
        foreach (XmlNode product in products)
        {
          // As of 25.6.2019, the countArticles and countFoils fields are not described in MKM doreplacedentation, but they seem to be there.
          // I think this is indeed a new thing that appeared since MKM started to force promo-sets as foils only
          // We can use this to prune lot of useless calls that will end up in empty responses from searching for non foils in promo (foil only) sets
          int total = int.Parse(product["countArticles"].InnerText);
          int foils = int.Parse(product["countFoils"].InnerText);
          string artFoil = article["isFoil"] == null ? "" : article["isFoil"].InnerText;
          if ((artFoil == "true" && foils == 0) || // there are only non-foils of this article and we want foils
              (artFoil == "false" && foils == total)) // there are only foils and we want non-foil
            continue;
          MainView.Instance.LogMainWindow("checking:" + product["enName"].InnerText + " from " + product["expansionName"].InnerText + "...");

          // a wantlist item can have more idLanguage entries, one for each wanted language
          System.Collections.Generic.List<string> selectedLanguages = new System.Collections.Generic.List<string>();
          foreach (XmlNode langNodes in product.ChildNodes)
          {
            if (langNodes.Name == "idLanguage")
              selectedLanguages.Add(langNodes.InnerText);
          }
          string artSigned = article["isSigned"] == null ? "" : article["isSigned"].InnerText;
          string artAltered = article["isAltered"] == null ? "" : article["isAltered"].InnerText;
          checkArticle(product["idProduct"].InnerText, selectedLanguages, article["minCondition"].InnerText,
              artFoil, artSigned, artAltered,
              // isPlayset seems to no longer be part of the API, instead there is a count of how many times is the card wanted, let's use it
              int.Parse(article["count"].InnerText) == 4 ? "true" : "false",
              "", maxAllowedPrice, shippingAdd, percentBelow, checkTrend);
        }
      }
      MainView.Instance.LogMainWindow("Check finished.");
    }

19 Source : MKMInteract.cs
with GNU Affero General Public License v3.0
from alexander-pick

public static XmlDoreplacedent MakeRequest(string url, string method, string body = null)
      {
        // throw the exception ourselves to prevent sending requests to MKM that would end with this error 
        // because MKM tends to revoke the user's app token if it gets too many requests above the limit
        // the 429 code is the same MKM uses for this error
        if (denyAdditionalRequests)
        {
          // MKM resets the counter at 0:00 CET. CET is two hours ahead of UCT, so if it is after 22:00 of the same day
          // the denial was triggered, that means the 0:00 CET has preplaceded and we can reset the deny
          if (DateTime.UtcNow.Date == denyTime.Date && DateTime.UtcNow.Hour < 22)
            throw new HttpListenerException(429, "Too many requests. Wait for 0:00 CET for request counter to reset.");
          else
            denyAdditionalRequests = false;
        }
        // enforce the maxRequestsPerMinute limit - technically it's just an approximation as the requests
        // can arrive to MKM with some delay, but it should be close enough
        var now = DateTime.Now;
        while (requestTimes.Count > 0 && (now - requestTimes.Peek()).TotalSeconds > 60)
        {
          requestTimes.Dequeue();// keep only times of requests in the past 60 seconds
        }
        if (requestTimes.Count >= maxRequestsPerMinute)
        {
          // wait until 60.01 seconds preplaceded since the oldest request
          // we know (now - peek) is <= 60, otherwise it would get dequeued above,
          // so we are preplaceding a positive number to sleep
          System.Threading.Thread.Sleep(
              60010 - (int)(now - requestTimes.Peek()).TotalMilliseconds);
          requestTimes.Dequeue();
        }

        requestTimes.Enqueue(DateTime.Now);
        XmlDoreplacedent doc = new XmlDoreplacedent();
        for (int numAttempts = 0; numAttempts < MainView.Instance.Config.MaxTimeoutRepeat; numAttempts++)
        {
          try
          {
            var request = WebRequest.CreateHttp(url);
            request.Method = method;

            request.Headers.Add(HttpRequestHeader.Authorization, header.GetAuthorizationHeader(method, url));
            request.Method = method;

            if (body != null)
            {
              request.ServicePoint.Expect100Continue = false;
              request.ContentLength = System.Text.Encoding.UTF8.GetByteCount(body);
              request.ContentType = "text/xml";

              var writer = new StreamWriter(request.GetRequestStream());

              writer.Write(body);
              writer.Close();
            }

            var response = request.GetResponse() as HttpWebResponse;

            // just for checking EoF, it is not accessible directly from the Stream object
            // Empty streams can be returned for example for article fetches that result in 0 matches (happens regularly when e.g. seeking nonfoils in foil-only promo sets). 
            // Preplaceding empty stream to doc.Load causes exception and also sometimes seems to screw up the XML parser 
            // even when the exception is handled and it then causes problems for subsequent calls => first check if the stream is empty
            StreamReader s = new StreamReader(response.GetResponseStream());
            if (!s.EndOfStream)
              doc.Load(s);
            s.Close();
            int requestCount = int.Parse(response.Headers.Get("X-Request-Limit-Count"));
            int requestLimit = int.Parse(response.Headers.Get("X-Request-Limit-Max"));
            if (requestCount >= requestLimit)
            {
              denyAdditionalRequests = true;
              denyTime = DateTime.UtcNow;
            }
            MainView.Instance.Invoke(new MainView.UpdateRequestCountCallback(MainView.Instance.UpdateRequestCount), requestCount, requestLimit);
            break;
          }
          catch (WebException webEx)
          {
            // timeout can be either on our side (Timeout) or on server
            bool isTimeout = webEx.Status == WebExceptionStatus.Timeout;
            if (webEx.Status == WebExceptionStatus.ProtocolError)
            {
              if (webEx.Response is HttpWebResponse response)
              {
                isTimeout = response.StatusCode == HttpStatusCode.GatewayTimeout
                    || response.StatusCode == HttpStatusCode.ServiceUnavailable;
              }
            }
            // handle only timeouts, client handles other exceptions
            if (isTimeout && numAttempts + 1 < MainView.Instance.Config.MaxTimeoutRepeat)
              System.Threading.Thread.Sleep(1500); // wait and try again
            else
              throw webEx;
          }
        }
        return doc;
      }

19 Source : Program.Commands.cs
with MIT License
from alexanderdna

private static void cmd_print(string[] arr)
        {
            int from, count;
            if (arr.Length == 1)
            {
                count = 10;
                from = Math.Max(0, _app.ChainManager.Height - count + 1);
                Console.WriteLine(_app.ChainManager.ToDisplayString(from, count));
            }
            else if (arr.Length == 2)
            {
                if (int.TryParse(arr[1], out count))
                {
                    from = Math.Max(0, _app.ChainManager.Height - count + 1);
                    Console.WriteLine(_app.ChainManager.ToDisplayString(from, count));
                }
                else
                {
                    string blockHash = arr[1];
                    var block = _app.ChainManager.GetBlock(blockHash);
                    if (block != null)
                    {
                        Console.WriteLine(JsonConvert.SerializeObject(block, Formatting.Indented));
                    }
                    else
                    {
                        Console.WriteLine("Block not found.");
                    }
                }
            }
            else if (arr.Length == 3)
            {
                from = int.Parse(arr[1]);
                count = int.Parse(arr[2]);
                Console.WriteLine(_app.ChainManager.ToDisplayString(from, count));
            }
            else
            {
                return;
            }
        }

19 Source : App.cs
with MIT License
from alexanderdna

public ConnectPeersResult ConnectToPeers()
        {
            var peersFile = PathsProvider.Peers;
            if (File.Exists(peersFile) is false)
            {
                Logger.Log(LogLevel.Warning, "Cannot find peers file.");
                return ConnectPeersResult.NoPeersFile;
            }

            List<(IPAddress, int)> addresses = new();
            try
            {
                var lines = File.ReadAllLines(peersFile);
                for (int i = 0, c = lines.Length; i < c; ++i)
                {
                    if (lines[i] == "") continue;

                    int posOfColon = lines[i].LastIndexOf(':');
                    if (posOfColon < 0)
                    {
                        Logger.Log(LogLevel.Warning, "Peers file seems to have invalid addresses.");
                        continue;
                    }

                    var host = IPAddress.Parse(lines[i].Substring(0, posOfColon));
                    var port = int.Parse(lines[i].Substring(posOfColon + 1));
                    if (port <= 0 || port > 65535)
                    {
                        Logger.Log(LogLevel.Warning, "Peers file seems to have invalid addresses.");
                        continue;
                    }

                    addresses.Add((host, port));
                }
            }
            catch (Exception ex)
            {
                Logger.Log(LogLevel.Error, "Cannot connect to peers: " + ex.Message);
                return ConnectPeersResult.Failure;
            }

            return Daemon.AcceptPeerList(addresses) ? ConnectPeersResult.Success : ConnectPeersResult.Failure;
        }

19 Source : ExperimentInstanceController.cs
with MIT License
from AlexanderFroemmgen

public override void OnActionExecuting(ActionExecutingContext context)
        {
            var simId = int.Parse((string)context.RouteData.Values["simid"]);
            var instanceId = int.Parse((string)context.RouteData.Values["instanceid"]);

            var instance = _context.ExperimentInstances
                .Include(si => si.Experiment)
                .SingleOrDefault(i => (i.Id == instanceId) && (i.ExperimentId == simId));

            if (instance == null)
            {
                context.Result = NotFound();
                return;
            }

            _currentExperimentInstance = instance;

            base.OnActionExecuting(context);
        }

19 Source : SmartSystemMenuSettings.cs
with MIT License
from AlexanderPro

public static SmartSystemMenuSettings Read(string fileName, string languageFileName)
        {
            var settings = new SmartSystemMenuSettings();
            var doreplacedent = XDoreplacedent.Load(fileName);
            var languageDoreplacedent = XDoreplacedent.Load(languageFileName);

            settings.ProcessExclusions = doreplacedent
                .XPathSelectElements("/smartSystemMenu/processExclusions/processName")
                .Where(x => !string.IsNullOrWhiteSpace(x.Value))
                .Select(x => x.Value.ToLower())
                .ToList();

            settings.MenuItems.WindowSizeItems = doreplacedent
                .XPathSelectElements("/smartSystemMenu/menuItems/windowSizeItems/item")
                .Select(x => new WindowSizeMenuItem
                {
                    replacedle = x.Attribute("replacedle") != null ? x.Attribute("replacedle").Value : "",
                    Left = !string.IsNullOrEmpty(x.Attribute("left").Value) ? int.Parse(x.Attribute("left").Value) : (int?)null,
                    Top = !string.IsNullOrEmpty(x.Attribute("top").Value) ? int.Parse(x.Attribute("top").Value) : (int?)null,
                    Width = int.Parse(x.Attribute("width").Value),
                    Height = int.Parse(x.Attribute("height").Value),
                    Key1 = x.Attribute("key1") != null && !string.IsNullOrEmpty(x.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key1").Value) : VirtualKeyModifier.None,
                    Key2 = x.Attribute("key2") != null && !string.IsNullOrEmpty(x.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key2").Value) : VirtualKeyModifier.None,
                    Key3 = x.Attribute("key3") != null && !string.IsNullOrEmpty(x.Attribute("key3").Value) ? (VirtualKey)int.Parse(x.Attribute("key3").Value) : VirtualKey.None
                })
                .ToList();

            settings.MenuItems.StartProgramItems = doreplacedent
                .XPathSelectElements("/smartSystemMenu/menuItems/startProgramItems/item")
                .Select(x => new StartProgramMenuItem
                {
                    replacedle = x.Attribute("replacedle") != null ? x.Attribute("replacedle").Value : "",
                    FileName = x.Attribute("fileName") != null ? x.Attribute("fileName").Value : "",
                    Arguments = x.Attribute("arguments") != null ? x.Attribute("arguments").Value : "",
                })
                .ToList();

            settings.MenuItems.Items = doreplacedent
                .XPathSelectElements("/smartSystemMenu/menuItems/items/item")
                .Select(x => {
                    var menuItem = new MenuItem
                    {
                        Name = x.Attribute("name") != null ? x.Attribute("name").Value : "",
                        Show = x.Attribute("show") != null ? x.Attribute("show").Value.ToLower() != "false" : true,
                        Type = x.Attribute("type") != null && !string.IsNullOrEmpty(x.Attribute("type").Value) ? (MenuItemType)Enum.Parse(typeof(MenuItemType), x.Attribute("type").Value, true) : MenuItemType.Item,
                        Key1 = x.Attribute("key1") != null && !string.IsNullOrEmpty(x.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key1").Value) : VirtualKeyModifier.None,
                        Key2 = x.Attribute("key2") != null && !string.IsNullOrEmpty(x.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(x.Attribute("key2").Value) : VirtualKeyModifier.None,
                        Key3 = x.Attribute("key3") != null && !string.IsNullOrEmpty(x.Attribute("key3").Value) ? (VirtualKey)int.Parse(x.Attribute("key3").Value) : VirtualKey.None
                    };
                    menuItem.Items = menuItem.Type == MenuItemType.Group ?
                    x.XPathSelectElements("./items/item")
                    .Select(y => new MenuItem
                    {
                        Name = y.Attribute("name") != null ? y.Attribute("name").Value : "",
                        Show = y.Attribute("show") != null ? y.Attribute("show").Value.ToLower() != "false" : true,
                        Type = y.Attribute("type") != null && !string.IsNullOrEmpty(y.Attribute("type").Value) ? (MenuItemType)Enum.Parse(typeof(MenuItemType), y.Attribute("type").Value, true) : MenuItemType.Item,
                        Key1 = y.Attribute("key1") != null && !string.IsNullOrEmpty(y.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(y.Attribute("key1").Value) : VirtualKeyModifier.None,
                        Key2 = y.Attribute("key2") != null && !string.IsNullOrEmpty(y.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(y.Attribute("key2").Value) : VirtualKeyModifier.None,
                        Key3 = y.Attribute("key3") != null && !string.IsNullOrEmpty(y.Attribute("key3").Value) ? (VirtualKey)int.Parse(y.Attribute("key3").Value) : VirtualKey.None
                    }).ToList() : new List<MenuItem>();
                    return menuItem;
                })
                .ToList();

            var closerElement = doreplacedent.XPathSelectElement("/smartSystemMenu/closer");
            settings.Closer.Type = closerElement.Attribute("type") != null && !string.IsNullOrEmpty(closerElement.Attribute("type").Value) ? (WindowCloserType)int.Parse(closerElement.Attribute("type").Value) : WindowCloserType.CloseForegroundWindow;
            settings.Closer.Key1 = closerElement.Attribute("key1") != null && !string.IsNullOrEmpty(closerElement.Attribute("key1").Value) ? (VirtualKeyModifier)int.Parse(closerElement.Attribute("key1").Value) : VirtualKeyModifier.None;
            settings.Closer.Key2 = closerElement.Attribute("key2") != null && !string.IsNullOrEmpty(closerElement.Attribute("key2").Value) ? (VirtualKeyModifier)int.Parse(closerElement.Attribute("key2").Value) : VirtualKeyModifier.None;
            settings.Closer.MouseButton = closerElement.Attribute("mouseButton") != null && !string.IsNullOrEmpty(closerElement.Attribute("mouseButton").Value) ? (MouseButton)int.Parse(closerElement.Attribute("mouseButton").Value) : MouseButton.None;

            var sizerElement = doreplacedent.XPathSelectElement("/smartSystemMenu/sizer");
            settings.Sizer = sizerElement.Attribute("type") != null && !string.IsNullOrEmpty(sizerElement.Attribute("type").Value) ? (WindowSizerType)int.Parse(sizerElement.Attribute("type").Value) : WindowSizerType.WindowWithMargins;

            var systemTrayIconElement = doreplacedent.XPathSelectElement("/smartSystemMenu/systemTrayIcon");
            if (systemTrayIconElement != null && systemTrayIconElement.Attribute("show") != null && systemTrayIconElement.Attribute("show").Value != null && systemTrayIconElement.Attribute("show").Value.ToLower() == "false")
            {
                settings.ShowSystemTrayIcon = false;
            }

            var languageElement = doreplacedent.XPathSelectElement("/smartSystemMenu/language");
            var languageName = "";
            var languageNameList = new[] { "en", "ru", "zh_cn", "zh_tw", "ja", "ko", "de", "sr", "pt" };
            if (languageElement != null && languageElement.Attribute("name") != null && languageElement.Attribute("name").Value != null)
            {
                languageName = languageElement.Attribute("name").Value.ToLower().Trim();
                settings.LanguageName = languageName;
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "zh-CN"))
            {
                languageName = "zh_cn";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "zh-TW"))
            {
                languageName = "zh_tw";
            }

            if (languageName == "" && Thread.CurrentThread.CurrentCulture.Name == "ja-JP")
            {
                languageName = "ja";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "ko-KR" || Thread.CurrentThread.CurrentCulture.Name == "ko-KP"))
            {
                languageName = "ko";
            }

            if (languageName == "" && Thread.CurrentThread.CurrentCulture.Name == "ru-RU")
            {
                languageName = "ru";
            }

            if (languageName == "" && Thread.CurrentThread.CurrentCulture.Name == "de-DE")
            {
                languageName = "de";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "pt-BR" || Thread.CurrentThread.CurrentCulture.Name == "pt-PT"))
            {
                languageName = "pt";
            }

            if (languageName == "" && (Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-BA" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-ME" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-RS" ||
                Thread.CurrentThread.CurrentCulture.Name == "sr-Cyrl-CS"))
            {
                languageName = "sr";
            }

            if (languageName == "" || !languageNameList.Contains(languageName))
            {
                languageName = "en";
            }

            var languageItemPath = "/language/items/" + languageName + "/item";
            settings.LanguageSettings.Items = languageDoreplacedent
                .XPathSelectElements(languageItemPath)
                .Select(x => new LanguageItem
                {
                    Name = x.Attribute("name") != null ? x.Attribute("name").Value : "",
                    Value = x.Attribute("value") != null ? x.Attribute("value").Value : "",
                })
                .ToList();

            return settings;
        }

19 Source : ProgramSettings.cs
with MIT License
from AlexanderPro

public static ProgramSettings Read(string fileName)
        {
            var doreplacedent = XDoreplacedent.Load(fileName);
            var settings = new ProgramSettings();
            settings.ListerFormKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key1").Value);
            settings.ListerFormKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key2").Value);
            settings.ListerFormKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerFormHotKeys").Attribute("key3").Value);
            settings.SearchDialogKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key1").Value);
            settings.SearchDialogKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key2").Value);
            settings.SearchDialogKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/SearchDialogHotKeys").Attribute("key3").Value);
            settings.PrintDialogKey1 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key1").Value);
            settings.PrintDialogKey2 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key2").Value);
            settings.PrintDialogKey3 = int.Parse(doreplacedent.XPathSelectElement("//Settings/PrintDialogHotKeys").Attribute("key3").Value);
            settings.ListerFormMaximized = bool.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("maximized").Value);
            settings.ListerFormWidth = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("width").Value);
            settings.ListerFormHeight = int.Parse(doreplacedent.XPathSelectElement("//Settings/ListerForm").Attribute("height").Value);
            settings.PluginHighVersion = int.Parse(doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("highVersion").Value);
            settings.PluginLowVersion = int.Parse(doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("lowVersion").Value);
            settings.PluginIniFile = doreplacedent.XPathSelectElement("//Settings/PluginDefaultSettings").Attribute("iniFile").Value;
            settings.PluginIniFile = new FileInfo(settings.PluginIniFile).FullName;
            settings.Plugins = doreplacedent.XPathSelectElements("//Settings/Plugins/Plugin").Select(el => new PluginInfo(el.Attribute("path").Value,
                                                                                                                     string.IsNullOrWhiteSpace(el.Attribute("extensions").Value) ? new List<string>() :
                                                                                                                                                                              el.Attribute("extensions").Value.Split(';').ToList())).ToList();
            return settings;
        }

19 Source : ListNode.cs
with MIT License
from AlexChesser

public static ListNode Create(string commaSepartatedValues)
    {
        if (commaSepartatedValues.Length == 0)
        {
            return null;
        }
        int[] values = commaSepartatedValues
            .Split(",")
            .Select(c => int.Parse(c))
            .ToArray();
        ListNode head = new ListNode(values[0]);
        ListNode tmp = head;
        for (int i = 1; i < values.Length; i++)
        {
            tmp.next = new ListNode(values[i]);
            tmp = tmp.next;
        }
        return head;
    }

19 Source : Day01Tests.cs
with MIT License
from AlexChesser

[Test]
        [TestCase("1,3,5,6", 5, 2)]
        [TestCase("1,3,5,6", 2, 1)]
        [TestCase("1,3,5,6", 7, 4)]
        [TestCase("1,3,5,6", 0, 0)]
        [TestCase("1", 0, 0)]
        public void _35_SearchInsertPosition(string arr, int target, int expected)
        {
            var s = new _35_SearchInsertPosition.Solution();
            int[] haystack = arr.Split(",")
                .Select(i => int.Parse(i))
                .ToArray();
            int result = s.SearchInsert(haystack, target);
            replacedert.AreEqual(result, expected, $"target {target} expected {expected}");
        }

19 Source : Day01Tests.cs
with MIT License
from AlexChesser

[Test]
        [TestCase("-1,0,3,5,9,12", 9, 4)]
        [TestCase("-1,0,3,5,9,12", 2, -1)]
        public void _704_BinarySearch(string arr, int target, int expected)
        {
            var s = new _704_BinarySearch.Solution();
            int[] haystack = arr.Split(",")
                .Select(i => int.Parse(i))
                .ToArray();
            int result = s.Search(haystack, target);
            replacedert.AreEqual(result, expected, $"target {target} expected {expected}");
        }

19 Source : Day02Tests.cs
with MIT License
from AlexChesser

[Test]
        [TestCase("-4,-1,0,3,10", "0,1,9,16,100")]
        [TestCase("-7,-3,2,3,11", "4,9,9,49,121")]
        public void _977_SquaresofaSortedArray(string arr, string expected)
        {
            var s = new _977_SquaresofaSortedArray.Solution();
            int[] haystack = arr.Split(",")
                .Select(i => int.Parse(i))
                .ToArray();
            int[] result = s.SortedSquares(haystack);
            replacedert.AreEqual(expected, string.Join(",", result), $"records did not match");
        }

19 Source : Day02Tests.cs
with MIT License
from AlexChesser

[Test]
        [TestCase("1,2,3,4,5,6,7", 3, "5,6,7,1,2,3,4")]
        [TestCase("-1,-100,3,99", 2, "3,99,-1,-100")]
        public void _189_RotateArray(string arr, int k, string expected)
        {
            var s = new _189_RotateArray.Solution();
            int[] haystack = arr.Split(",")
                .Select(i => int.Parse(i))
                .ToArray();
            s.Rotate(haystack, k);
            replacedert.AreEqual(expected, string.Join(",", haystack), $"shifting {arr} {k} times gives {expected} got { string.Join(",", haystack)}");
        }

19 Source : Day03Tests.cs
with MIT License
from AlexChesser

[Test]
        [TestCase("0,1,0,3,12", "1,3,12,0,0")]
        [TestCase("0", "0")]
        public void _283_MoveZeroes(string arr, string expected)
        {
            var s = new _283_MoveZeroes.Solution();
            int[] haystack = arr.Split(",")
                .Select(i => int.Parse(i))
                .ToArray();
            s.MoveZeroes(haystack);
            replacedert.AreEqual(expected, string.Join(",", haystack));
        }

19 Source : Day03Tests.cs
with MIT License
from AlexChesser

[Test]
        [TestCase("2,7,11,15", 9, "1,2")]
        [TestCase("2,3,4", 6, "1,3")]
        [TestCase("-1,0", -1, "1,2")]
        public void _167_TwoSum_Sorted(string arr, int target, string expected)
        {
            var s = new _167_TwoSum_Sorted.Solution();
            int[] haystack = arr.Split(",")
                .Select(i => int.Parse(i))
                .ToArray();
            int[] result = s.TwoSum(haystack, target);
            replacedert.AreEqual(expected, string.Join(",", result));
        }

19 Source : CnpjValidation.cs
with MIT License
from alexandrebeato

public static bool Validar(string cnpj)
        {
            if (string.IsNullOrEmpty(cnpj))
                return false;

            if (cnpj.Length != 14)
                return false;

            var igual = true;
            for (var i = 1; i < 14 && igual; i++)
                if (cnpj[i] != cnpj[0])
                    igual = false;

            if (igual || cnpj == "12345678901234")
                return false;

            int[] multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
            int[] multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
            cnpj = cnpj.Trim();
            cnpj = cnpj.Replace(".", "").Replace("-", "").Replace("/", "");
            if (cnpj.Length != 14)
                return false;
            var tempCnpj = cnpj.Substring(0, 12);
            var soma = 0;
            for (int i = 0; i < 12; i++)
                soma += int.Parse(tempCnpj[i].ToString()) * multiplicador1[i];
            var resto = (soma % 11);
            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;
            var digito = resto.ToString();
            tempCnpj = tempCnpj + digito;
            soma = 0;
            for (int i = 0; i < 13; i++)
                soma += int.Parse(tempCnpj[i].ToString()) * multiplicador2[i];
            resto = (soma % 11);
            if (resto < 2)
                resto = 0;
            else
                resto = 11 - resto;
            digito = digito + resto.ToString();
            return cnpj.EndsWith(digito);
        }

19 Source : CpfValidation.cs
with MIT License
from alexandrebeato

public static bool Validar(string cpf)
        {
            if (string.IsNullOrEmpty(cpf))
                return false;

            if (cpf.Length != 11)
                return false;

            var igual = true;
            for (var i = 1; i < 11 && igual; i++)
                if (cpf[i] != cpf[0])
                    igual = false;

            if (igual || cpf == "12345678909")
                return false;

            var numeros = new int[11];

            for (var i = 0; i < 11; i++)
                numeros[i] = int.Parse(cpf[i].ToString());

            var soma = 0;
            for (var i = 0; i < 9; i++)
                soma += (10 - i) * numeros[i];

            var resultado = soma % 11;

            if (resultado == 1 || resultado == 0)
            {
                if (numeros[9] != 0)
                    return false;
            }
            else if (numeros[9] != 11 - resultado)
                return false;

            soma = 0;
            for (var i = 0; i < 10; i++)
                soma += (11 - i) * numeros[i];

            resultado = soma % 11;

            if (resultado == 1 || resultado == 0)
            {
                if (numeros[10] != 0)
                    return false;
            }
            else if (numeros[10] != 11 - resultado)
                return false;

            return true;
        }

19 Source : Solution.cs
with MIT License
from AlexChesser

public int MyAtoi(string s) {
        if(s.Length == 0){
            return 0;
        }
        char check;
        bool IsNegative = false;
        List<char> digits = new List<char>();;
        for(int i = 0; i < s.Length; i++){
            check = s[i];
            if(digits.Count == 0){
                if(char.IsWhiteSpace(check)){
                    continue;
                }
                if(i == s.Length - 1 && (!char.IsNumber(check) || check == ZERO) ){
                    return 0;   
                }
                if(check == ZERO && !char.IsNumber(s[i+1])){
                    return 0;
                }
                if(check == ZERO){
                    continue;
                }
                if(check == '-'){
                    if(!char.IsNumber(s[i+1])){
                        return 0;
                    }
                    IsNegative = true;
                    continue;
                }
                if(check == '+' ){
                    if(!char.IsNumber(s[i+1])){
                        return 0;
                    }
                    continue;
                }
                if(check < ZERO || check > NINE){
                    return 0;
                }
            }
            if(char.IsNumber(check)){
                digits.Add(check);
                if(digits.Count > 10){
                    return IsNegative ? int.MinValue : int.MaxValue; 
                }
                continue;
            }
            break;
        }
        if(digits.Count == 0){
            return 0;
        }
        if(digits.Count <= 10){
            try{
                return int.Parse(string.Join(null, digits)) * (IsNegative ? -1 : 1);
            } catch {

            }
        }
        return IsNegative ? int.MinValue : int.MaxValue;
    }

19 Source : SigRecord.cs
with Apache License 2.0
from alexreinert

internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
		{
			if (stringRepresentation.Length < 9)
				throw new FormatException();

			TypeCovered = RecordTypeHelper.ParseShortString(stringRepresentation[0]);
			Algorithm = (DnsSecAlgorithm) Byte.Parse(stringRepresentation[1]);
			Labels = Byte.Parse(stringRepresentation[2]);
			OriginalTimeToLive = Int32.Parse(stringRepresentation[3]);
			SignatureExpiration = DateTime.ParseExact(stringRepresentation[4], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
			SignatureInception = DateTime.ParseExact(stringRepresentation[5], "yyyyMMddHHmmss", CultureInfo.InvariantCulture);
			KeyTag = UInt16.Parse(stringRepresentation[6]);
			SignersName = ParseDomainName(origin, stringRepresentation[7]);
			Signature = String.Join(String.Empty, stringRepresentation.Skip(8)).FromBase64String();
		}

19 Source : DnsRecordBase.cs
with Apache License 2.0
from alexreinert

internal void ParseUnknownRecordData(string[] stringRepresentation)
		{
			if (stringRepresentation.Length < 2)
				throw new FormatException();

			if (stringRepresentation[0] != @"\#")
				throw new FormatException();

			int length = Int32.Parse(stringRepresentation[1]);

			byte[] byteData = String.Join("", stringRepresentation.Skip(2)).FromBase16String();

			if (length != byteData.Length)
				throw new FormatException();

			ParseRecordData(byteData, 0, length);
		}

19 Source : SoaRecord.cs
with Apache License 2.0
from alexreinert

internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
		{
			MasterName = ParseDomainName(origin, stringRepresentation[0]);
			ResponsibleName = ParseDomainName(origin, stringRepresentation[1]);

			SerialNumber = UInt32.Parse(stringRepresentation[2]);
			RefreshInterval = Int32.Parse(stringRepresentation[3]);
			RetryInterval = Int32.Parse(stringRepresentation[4]);
			ExpireInterval = Int32.Parse(stringRepresentation[5]);
			NegativeCachingTTL = Int32.Parse(stringRepresentation[6]);
		}

19 Source : Zone.cs
with Apache License 2.0
from alexreinert

private static List<DnsRecordBase> ParseRecords(StreamReader reader, DomainName origin, int ttl, DnsRecordBase lastRecord)
		{
			List<DnsRecordBase> records = new List<DnsRecordBase>();

			while (!reader.EndOfStream)
			{
				string line = ReadRecordLine(reader);

				if (!String.IsNullOrEmpty(line))
				{
					string[] parts = _lineSplitterRegex.Matches(line).Cast<Match>().Select(x => x.Groups.Cast<Group>().Last(g => g.Success).Value.FromMasterfileLabelRepresentation()).ToArray();

					if (parts[0].Equals("$origin", StringComparison.InvariantCultureIgnoreCase))
					{
						origin = DomainName.ParseFromMasterfile(parts[1]);
					}
					if (parts[0].Equals("$ttl", StringComparison.InvariantCultureIgnoreCase))
					{
						ttl = Int32.Parse(parts[1]);
					}
					if (parts[0].Equals("$include", StringComparison.InvariantCultureIgnoreCase))
					{
						FileStream fileStream = reader.BaseStream as FileStream;

						if (fileStream == null)
							throw new NotSupportedException("Includes only supported when loading files");

						// ReSharper disable once replacedignNullToNotNullAttribute
						string path = Path.Combine(new FileInfo(fileStream.Name).DirectoryName, parts[1]);

						DomainName includeOrigin = (parts.Length > 2) ? DomainName.ParseFromMasterfile(parts[2]) : origin;

						using (StreamReader includeReader = new StreamReader(path))
						{
							records.AddRange(ParseRecords(includeReader, includeOrigin, ttl, lastRecord));
						}
					}
					else
					{
						string domainString;
						RecordType recordType;
						RecordClreplaced recordClreplaced;
						int recordTtl;
						string[] rrData;

						if (Int32.TryParse(parts[0], out recordTtl))
						{
							// no domain, starts with ttl
							if (RecordClreplacedHelper.TryParseShortString(parts[1], out recordClreplaced, false))
							{
								// second is record clreplaced
								domainString = null;
								recordType = RecordTypeHelper.ParseShortString(parts[2]);
								rrData = parts.Skip(3).ToArray();
							}
							else
							{
								// no record clreplaced
								domainString = null;
								recordClreplaced = RecordClreplaced.Invalid;
								recordType = RecordTypeHelper.ParseShortString(parts[1]);
								rrData = parts.Skip(2).ToArray();
							}
						}
						else if (RecordClreplacedHelper.TryParseShortString(parts[0], out recordClreplaced, false))
						{
							// no domain, starts with record clreplaced
							if (Int32.TryParse(parts[1], out recordTtl))
							{
								// second is ttl
								domainString = null;
								recordType = RecordTypeHelper.ParseShortString(parts[2]);
								rrData = parts.Skip(3).ToArray();
							}
							else
							{
								// no ttl
								recordTtl = 0;
								domainString = null;
								recordType = RecordTypeHelper.ParseShortString(parts[1]);
								rrData = parts.Skip(2).ToArray();
							}
						}
						else if (RecordTypeHelper.TryParseShortString(parts[0], out recordType))
						{
							// no domain, start with record type
							recordTtl = 0;
							recordClreplaced = RecordClreplaced.Invalid;
							domainString = null;
							rrData = parts.Skip(2).ToArray();
						}
						else
						{
							domainString = parts[0];

							if (Int32.TryParse(parts[1], out recordTtl))
							{
								// domain, second is ttl
								if (RecordClreplacedHelper.TryParseShortString(parts[2], out recordClreplaced, false))
								{
									// third is record clreplaced
									recordType = RecordTypeHelper.ParseShortString(parts[3]);
									rrData = parts.Skip(4).ToArray();
								}
								else
								{
									// no record clreplaced
									recordClreplaced = RecordClreplaced.Invalid;
									recordType = RecordTypeHelper.ParseShortString(parts[2]);
									rrData = parts.Skip(3).ToArray();
								}
							}
							else if (RecordClreplacedHelper.TryParseShortString(parts[1], out recordClreplaced, false))
							{
								// domain, second is record clreplaced
								if (Int32.TryParse(parts[2], out recordTtl))
								{
									// third is ttl
									recordType = RecordTypeHelper.ParseShortString(parts[3]);
									rrData = parts.Skip(4).ToArray();
								}
								else
								{
									// no ttl
									recordTtl = 0;
									recordType = RecordTypeHelper.ParseShortString(parts[2]);
									rrData = parts.Skip(3).ToArray();
								}
							}
							else
							{
								// domain with record type
								recordType = RecordTypeHelper.ParseShortString(parts[1]);
								recordTtl = 0;
								recordClreplaced = RecordClreplaced.Invalid;
								rrData = parts.Skip(2).ToArray();
							}
						}

						DomainName domain;
						if (String.IsNullOrEmpty(domainString))
						{
							domain = lastRecord.Name;
						}
						else if (domainString == "@")
						{
							domain = origin;
						}
						else if (domainString.EndsWith("."))
						{
							domain = DomainName.ParseFromMasterfile(domainString);
						}
						else
						{
							domain = DomainName.ParseFromMasterfile(domainString) + origin;
						}

						if (recordClreplaced == RecordClreplaced.Invalid)
						{
							recordClreplaced = lastRecord.RecordClreplaced;
						}

						if (recordType == RecordType.Invalid)
						{
							recordType = lastRecord.RecordType;
						}

						if (recordTtl == 0)
						{
							recordTtl = ttl;
						}
						else
						{
							ttl = recordTtl;
						}

						lastRecord = DnsRecordBase.Create(recordType);
						lastRecord.RecordType = recordType;
						lastRecord.Name = domain;
						lastRecord.RecordClreplaced = recordClreplaced;
						lastRecord.TimeToLive = recordTtl;

						if ((rrData.Length > 0) && (rrData[0] == @"\#"))
						{
							lastRecord.ParseUnknownRecordData(rrData);
						}
						else
						{
							lastRecord.ParseRecordData(origin, rrData);
						}

						records.Add(lastRecord);
					}
				}
			}

			return records;
		}

19 Source : RrSigRecord.cs
with Apache License 2.0
from alexreinert

internal override void ParseRecordData(DomainName origin, string[] stringRepresentation)
		{
			if (stringRepresentation.Length < 9)
				throw new FormatException();

			TypeCovered = RecordTypeHelper.ParseShortString(stringRepresentation[0]);
			Algorithm = (DnsSecAlgorithm) Byte.Parse(stringRepresentation[1]);
			Labels = Byte.Parse(stringRepresentation[2]);
			OriginalTimeToLive = Int32.Parse(stringRepresentation[3]);
			SignatureExpiration = DateTime.ParseExact(stringRepresentation[4], "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.replacedumeUniversal);
			SignatureInception = DateTime.ParseExact(stringRepresentation[5], "yyyyMMddHHmmss", CultureInfo.InvariantCulture, DateTimeStyles.replacedumeUniversal);
			KeyTag = UInt16.Parse(stringRepresentation[6]);
			SignersName = ParseDomainName(origin, stringRepresentation[7]);
			Signature = String.Join(String.Empty, stringRepresentation.Skip(8)).FromBase64String();
		}

19 Source : SenderIDRecord.cs
with Apache License 2.0
from alexreinert

private static bool TryParsePrefix(string prefix, out int version, out int minor, out List<SenderIDScope> scopes)
		{
			Match match = _prefixRegex.Match(prefix);
			if (!match.Success)
			{
				version = 0;
				minor = 0;
				scopes = null;

				return false;
			}

			version = Int32.Parse(match.Groups["version"].Value);
			minor = Int32.Parse("0" + match.Groups["minor"].Value);
			scopes = match.Groups["scopes"].Value.Split(',').Select(t => EnumHelper<SenderIDScope>.Parse(t, true, SenderIDScope.Unknown)).ToList();

			return true;
		}

19 Source : ValidatorBase.cs
with Apache License 2.0
from alexreinert

private async Task<string> ExpandMacroAsync(Match pattern, IPAddress ip, DomainName domain, string sender, CancellationToken token)
		{
			switch (pattern.Value)
			{
				case "%%":
					return "%";
				case "%_":
					return "_";
				case "%-":
					return "-";

				default:
					string letter;
					switch (pattern.Groups["letter"].Value)
					{
						case "s":
							letter = sender;
							break;
						case "l":
							// no boundary check needed, sender is validated on start of CheckHost
							letter = sender.Split('@')[0];
							break;
						case "o":
							// no boundary check needed, sender is validated on start of CheckHost
							letter = sender.Split('@')[1];
							break;
						case "d":
							letter = domain.ToString();
							break;
						case "i":
							letter = String.Join(".", ip.GetAddressBytes().Select(b => b.ToString()));
							break;
						case "p":
							letter = "unknown";

							DnsResolveResult<PtrRecord> dnsResult = await ResolveDnsAsync<PtrRecord>(ip.GetReverseLookupDomain(), RecordType.Ptr, token);
							if ((dnsResult == null) || ((dnsResult.ReturnCode != ReturnCode.NoError) && (dnsResult.ReturnCode != ReturnCode.NxDomain)))
							{
								break;
							}

							int ptrCheckedCount = 0;
							foreach (PtrRecord ptrRecord in dnsResult.Records)
							{
								if (++ptrCheckedCount == 10)
									break;

								bool? isPtrMatch = await IsIpMatchAsync(ptrRecord.PointerDomainName, ip, 0, 0, token);
								if (isPtrMatch.HasValue && isPtrMatch.Value)
								{
									if (letter == "unknown" || ptrRecord.PointerDomainName.IsSubDomainOf(domain))
									{
										// use value, if first record or subdomain
										// but evaluate the other records
										letter = ptrRecord.PointerDomainName.ToString();
									}
									else if (ptrRecord.PointerDomainName.Equals(domain))
									{
										// ptr equal domain --> best match, use it
										letter = ptrRecord.PointerDomainName.ToString();
										break;
									}
								}
							}
							break;
						case "v":
							letter = (ip.AddressFamily == AddressFamily.InterNetworkV6) ? "ip6" : "in-addr";
							break;
						case "h":
							letter = HeloDomain?.ToString() ?? "unknown";
							break;
						case "c":
							IPAddress address =
								LocalIP
								?? NetworkInterface.GetAllNetworkInterfaces()
									.Where(n => (n.OperationalStatus == OperationalStatus.Up) && (n.NetworkInterfaceType != NetworkInterfaceType.Loopback))
									.SelectMany(n => n.GetIPProperties().UnicastAddresses)
									.Select(u => u.Address)
									.FirstOrDefault(a => a.AddressFamily == ip.AddressFamily)
								?? ((ip.AddressFamily == AddressFamily.InterNetwork) ? IPAddress.Loopback : IPAddress.IPv6Loopback);
							letter = address.ToString();
							break;
						case "r":
							letter = LocalDomain?.ToString() ?? System.Net.Dns.GetHostName();
							break;
						case "t":
							letter = ((int) (new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc) - DateTime.Now).TotalSeconds).ToString();
							break;
						default:
							return null;
					}

					// only letter
					if (pattern.Value.Length == 4)
						return letter;

					char[] delimiters = pattern.Groups["delimiter"].Value.ToCharArray();
					if (delimiters.Length == 0)
						delimiters = new[] { '.' };

					string[] parts = letter.Split(delimiters);

					if (pattern.Groups["reverse"].Value == "r")
						parts = parts.Reverse().ToArray();

					int count = Int32.MaxValue;
					if (!String.IsNullOrEmpty(pattern.Groups["count"].Value))
					{
						count = Int32.Parse(pattern.Groups["count"].Value);
					}

					if (count < 1)
						return null;

					count = Math.Min(count, parts.Length);

					return String.Join(".", parts, (parts.Length - count), count);
			}
		}

19 Source : FunctionExtensions.cs
with MIT License
from alfa-laboratory

public static object parseInt(string str)
        {
            try
            {
                return int.Parse(str);
            }catch(FormatException ex)
            {
                Log.Logger().LogWarning($"Parsing string to int return an error {ex.Message}.");
                return str;
            }
        }

19 Source : GenerationFunctions.cs
with MIT License
from alfa-laboratory

public static string randomInt(string len = "15")
        {
            return new FakerGenerator().Numbers(int.Parse(len));
        }

19 Source : GenerationFunctions.cs
with MIT License
from alfa-laboratory

public static string randomChars(string len = "15")
        {
            return new FakerGenerator().Chars(int.Parse(len));
        }

19 Source : GenerationFunctions.cs
with MIT License
from alfa-laboratory

public static string randomString(string len = "15")
        {
            return new FakerGenerator().String(int.Parse(len));
        }

19 Source : Variable.Steps.cs
with MIT License
from alfa-laboratory

[StepDefinition(@"я сохраняю число ""(.+)"" в переменную ""(.*)""")]
        public void StoreAsVariableNumber(string number, string varName)
        {
            if (decimal.TryParse(number, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.CurrentCulture, out var dec))
            {
                variableController.SetVariable(varName, typeof(decimal), dec);
                return;
            }

            if (decimal.TryParse(number, System.Globalization.NumberStyles.Float, new System.Globalization.NumberFormatInfo() { PercentDecimalSeparator = ".", CurrencyDecimalSeparator = ".", NumberDecimalSeparator = "." }, out dec))
            {
                variableController.SetVariable(varName, typeof(decimal), dec);
                return;
            }

            variableController.SetVariable(varName, typeof(int), int.Parse(number));
        }

19 Source : TgParser.cs
with MIT License
from ali4heydari

private List<Message> GetMessages()
        {
            var doreplacedent = new HtmlDoreplacedent();
            doreplacedent.Load(InputHtmlPath, encoding: Encoding.UTF8);

            var messageNodes = doreplacedent.QuerySelectorAll(MESSAGES_QUERY_SELECTOR);

            Stack<Message> messagesStack = new Stack<Message>();


            try
            {
                foreach (var messageNode in messageNodes)
                {
                    int messageId = int.Parse(
                        messageNode
                            .Attributes["id"]
                            .Value.Substring(7));

                    // text can be null
                    string text = messageNode
                        .QuerySelector(MESSAGE_TEXT_QUERY_SELECTOR)
                        ?.InnerText.Trim();

                    string date = messageNode
                        .QuerySelector(MESSAGE_DATE_QUERY_SELECTOR)
                        .Attributes["replacedle"].Value;

                    string author = messageNode
                        .QuerySelector(MESSAGE_FROM_NAME_QUERY_SELECTOR)
                        ?.InnerText.Trim();

                    int? replyMessageId = null;
                    if (messageNode.QuerySelector(MESSAGE_REPLY_QUERY_SELECTOR) != null)
                    {
                        replyMessageId = int.Parse(messageNode
                                                       .QuerySelector(MESSAGE_REPLY_QUERY_SELECTOR)
                                                       ?.Attributes["href"].Value.Substring(14) ??
                                                   throw new Exception());
                    }

                    messagesStack.Push(author != null
                        ? new Message(text, author, date, replyMessageId, messageId)
                        : new Message(text, messagesStack.Peek().Author, date, replyMessageId, messageId));
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine($"Exception thrown: \nMessage -> {e.Message}\nStackTrace -> {e.StackTrace}");
                Console.ForegroundColor = ConsoleColor.White;
            }

            return messagesStack.ToList();
        }

19 Source : InstructorsController.cs
with MIT License
from alimon808

[HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("FirstMidName,HireDate,LastName,Officereplacedignment")] Instructor instructor, string[] selectedCourses)
        {
            if (selectedCourses != null)
            {
                instructor.Coursereplacedignments = new List<Coursereplacedignment>();
                foreach (var course in selectedCourses)
                {
                    var courseToAdd = new Coursereplacedignment { InstructorID = instructor.ID, CourseID = int.Parse(course) };
                    instructor.Coursereplacedignments.Add(courseToAdd);
                }
            }

            if (ModelState.IsValid)
            {
                await _instructorRepo.AddAsync(instructor);
                await _instructorRepo.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            PopulatereplacedignedCourseData(instructor);
            return View(instructor);
        }

19 Source : SmallFunctions.cs
with MIT License
from Alkl58

public static void GetSourceFrameCount(string source)
        {
            // Skip Framecount Calculation if it already "exists" (Resume Mode)
            if (File.Exists(Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log")) == false)
            {
                // This function calculates the total number of frames
                Process process = new Process
                {
                    StartInfo = new ProcessStartInfo()
                    {
                        UseShellExecute = false,
                        CreateNoWindow = true,
                        WindowStyle = ProcessWindowStyle.Hidden,
                        FileName = "cmd.exe",
                        WorkingDirectory = Global.FFmpeg_Path,
                        Arguments = "/C ffmpeg.exe -i " + '\u0022' + source + '\u0022' + " -hide_banner -loglevel 32 -map 0:v:0 -f null -",
                        RedirectStandardError = true,
                        RedirectStandardOutput = true
                    }
                };
                process.Start();
                string stream = process.StandardError.ReadToEnd();
                process.WaitForExit();
                string tempStream = stream.Substring(stream.LastIndexOf("frame="));
                string data = GetBetween(tempStream, "frame=", "fps=");
                MainWindow.TotalFrames = int.Parse(data);
                Helpers.WriteToFileThreadSafe(data, Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log"));
            }
            else
            {
                // Reads the first line of the framecount file
                MainWindow.TotalFrames = int.Parse(File.ReadLines(Path.Combine(Global.temp_path, Global.temp_path_folder, "framecount.log")).First());
            }
        }

19 Source : Settings.xaml.cs
with MIT License
from Alkl58

private void LoadSettingsTab()
        {
            if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "settings.xml")))
            {
                string language = "English";
                try
                {
                    XmlDoreplacedent doc = new XmlDoreplacedent();
                    doc.Load(Path.Combine(Directory.GetCurrentDirectory(), "settings.xml"));
                    XmlNodeList node = doc.GetElementsByTagName("Settings");
                    foreach (XmlNode n in node[0].ChildNodes)
                    {
                        switch (n.Name)
                        {
                            case "DeleteTempFiles":
                                ToggleSwitchDeleteTempFiles.IsOn = n.InnerText == "True";
                                break;
                            case "PlaySound":
                                ToggleSwitchUISounds.IsOn = n.InnerText == "True";
                                break;
                            case "Logging":
                                ToggleSwitchLogging.IsOn = n.InnerText == "True";
                                break;
                            case "ShowDialog":
                                ToggleSwitchShowWindow.IsOn = n.InnerText == "True";
                                break;
                            case "Shutdown":
                                ToggleSwitchShutdownAfterEncode.IsOn = n.InnerText == "True";
                                break;
                            case "TempPathActive":
                                ToggleSwitchTempFolder.IsOn = n.InnerText == "True";
                                break;
                            case "TempPath":
                                TextBoxCustomTempPath.Text = n.InnerText;
                                break;
                            case "Terminal":
                                ToggleSwitchHideTerminal.IsOn = n.InnerText == "True";
                                break;
                            case "ThemeAccent":
                                ComboBoxAccentTheme.SelectedIndex = int.Parse(n.InnerText);
                                break;
                            case "ThemeBase":
                                ComboBoxBaseTheme.SelectedIndex = int.Parse(n.InnerText);
                                break;
                            case "BatchContainer":
                                ComboBoxContainerBatchEncoding.SelectedIndex = int.Parse(n.InnerText);
                                break;
                            case "SkipSubreplacedles":
                                ToggleSkipSubreplacedleExtraction.IsOn = n.InnerText == "True";
                                break;
                            case "Language":
                                language = n.InnerText;
                                break;
                            case "OverrideWorkerCount":
                                ToggleOverrideWorkerCount.IsOn = n.InnerText == "True";
                                break;
                            default: break;
                        }
                    }
                }
                catch { }

                ThemeManager.Current.ChangeTheme(this, ComboBoxBaseTheme.Text + "." + ComboBoxAccentTheme.Text);

                switch (language)
                {
                    case "Deutsch":
                        ComboBoxUILanguage.SelectedIndex = 1;
                        break;
                    case "Français":
                        ComboBoxUILanguage.SelectedIndex = 2;
                        break;
                    default:
                        ComboBoxUILanguage.SelectedIndex = 0;
                        break;
                }
            }
        }

19 Source : Helpers.cs
with MIT License
from Alkl58

public static int GetCoreCount()
        {
            // Gets Core Count
            int coreCount = 0;
            foreach (System.Management.ManagementBaseObject item in new System.Management.ManagementObjectSearcher("Select * from Win32_Processor").Get())
            {
                coreCount += int.Parse(item["NumberOfCores"].ToString());
            }
            return coreCount;
        }

19 Source : IterativePermutation.cs
with MIT License
from AllAlgorithms

public static void Main()
    {
        Console.WriteLine("Enter a number: ");
        var num = int.Parse(Console.ReadLine());
 
        var numberOfPerm = 1;
        var elements = Enumerable.Range(1, num).ToArray();
        var workArr = Enumerable.Range(0, elements.Length + 1).ToArray();
 
        PrintPerm(elements);
        var index = 1;
        while (index < elements.Length)
        {
            workArr[index]--;
            var j = 0;
            if (index % 2 == 1)
            {
                j = workArr[index];
            }
 
            SwapInts(ref elements[j], ref elements[index]);
            index = 1;
            while (workArr[index] == 0)
            {
                workArr[index] = index;
                index++;
            }
 
            numberOfPerm++;
            PrintPerm(elements);
        }
 
        Console.WriteLine("Total permutations: {0}", numberOfPerm);
    }

19 Source : mergesort.cs
with MIT License
from AllAlgorithms

static void Main(string[] args)
        {
            Console.WriteLine("Enter the Size of Array");
            int size = int.Parse(Console.ReadLine());  //Read array size.
            Console.WriteLine("Enter the Array elements");

            string[] usrInput = Console.ReadLine().Split(' '); //Read user input.

            int[] inputArray = new int[size];

            for (int i = 0; i < size; i++)
            {
                inputArray[i] = int.Parse(usrInput[i]); //replacedign user input to array.
            }

            MergeSort(inputArray, 0, size - 1);

            Console.WriteLine("The sorted array after applying Merge Sort ");

            for (int k = 0; k < inputArray.Length; k++)
            {
                Console.Write(inputArray[k] + " "); //Print the sorted array to console.
            }
            Console.ReadLine();
        }

19 Source : FilterIntegers.cs
with MIT License
from AllAlgorithms

public static int[] FilterIntsFromString(string input)
    {
        List<int> integerList = new List<int>();
        var match = Regex.Match(input, @"\d+");
        while(match != null && !String.IsNullOrEmpty(match.Value))
        {
            int newInt = int.Parse(match.Value);
            if(match.Index > 0 && input[match.Index-1] == '-')
            {
                newInt *= -1;
            }
            integerList.Add(newInt);
            match = match.NextMatch();
        }
        return integerList.ToArray();
    }

19 Source : PdfImageConverter.cs
with MIT License
from allantargino

public void GenerateImage(Stream pdfInput, ref Stream[] imageListOutput)
        {
            if (!pdfInput.CanSeek) throw new Exception("PdfInput Stream can not be seek!");

            var rand = new Random(DateTime.Now.Second);

            int value = rand.Next();
            string tempPrefix = $"dou_pdf_temp_{value}";
            string pdfDirectory = $@"{_tempFolder}\{tempPrefix}";
            string pdfFileName = $"{tempPrefix}.pdf";

            var pdfFile = ToFile(pdfInput, pdfFileName);

            var images = ConvertAsync(pdfFile.FullName, _ratio).GetAwaiter().GetResult();

            Console.Write($"Images generated: {images.Length}");

            if (images == null)
            {
                Console.WriteLine("Error generating the images!");
                return;
            }

            imageListOutput = new Stream[images.Length];

            for (var i = 0; i < images.Length; i++)
            {                 
                var bytes = File.ReadAllBytes(images[i]);
                MemoryStream jpgMemory = new MemoryStream(bytes);

                //As the images are not in the proper order it is necessary to retrieve the page index.
                var parts = images[i].Replace(".jpg", "").Split('_');
                int pageIdx = int.Parse(parts[parts.Length - 1]);

                imageListOutput[pageIdx - 1] = jpgMemory;
                File.Delete(images[i]);
            }

            try
            {
                Directory.Delete($@"{pdfDirectory}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Erro deleting directory {pdfDirectory} - {ex.Message}");
                throw new Exception(ex.Message, ex);
            }
        }

19 Source : Program.cs
with MIT License
from allantargino

static void Main(string[] args)
        {
            Initialize(args);

            while (true)
            {
                ProcessJob();

                _semapreplaced.Wait();
                if ((DateTime.Now - _lastExecution).Seconds <= int.Parse("1"))
                    break;
                else
                {
                    Thread.Sleep(2000);
                    _semapreplaced.Release();
                }
            }
        }

19 Source : StanfordNLPClassifier.cs
with MIT License
from allisterb

public override StageResult Train(Dictionary<string, object> options = null)
        {
            ClreplacedifierPropsFile = CreatePropsFile(ClreplacedifierProperties);
            if (!ClreplacedifierPropsFile.Exists)
            {
                Error("Could not find clreplacedifier props file {0}.", ClreplacedifierPropsFile.FullName);
            }
            else
            {
                Debug("Using clreplacedifier props file {0}.", ClreplacedifierPropsFile.FullName);
            }

            javaCommand = new JavaCommand(JavaHome, ClreplacedPath, "edu.stanford.nlp.clreplacedify.ColumnDataClreplacedifier", "-mx16000m", 
                "-trainFile", TrainingFile.FullName, "-testFile", TestFile.FullName, "-prop", ClreplacedifierPropsFile.FullName);
            PrintCommand(javaCommand);
            Task c = javaCommand.Run();
            if (!CheckCommandStartedAndReport(javaCommand))
            {
                return StageResult.FAILED;
            }
 
            ClreplacedifierOutput = new List<string>();

            foreach (string s in javaCommand.GetOutputAndErrorLines())
            {
                if (!BuiltClreplacedifier && s.StartsWith("Built this clreplacedifier"))
                {
                    BuiltClreplacedifier = true;
                    
                    Match m = builtClreplacedifierRegex.Match(s);
                    if (m.Success)
                    {
                        ClreplacedifierType = m.Groups[1].Value;
                        NumberofFeatures = Int32.Parse(m.Groups[2].Value);
                        NumberofClreplacedes = Int32.Parse(m.Groups[3].Value);
                        NumberofParameters = Int32.Parse(m.Groups[4].Value);
                        Info("Built clreplacedifier {0} with {1} features, {2} clreplacedes and {3} parameters.", ClreplacedifierType, NumberofFeatures, NumberofClreplacedes, NumberofParameters);
                    }
                }
                else if (ClreplacedifierType.IsEmpty() && s.StartsWith("QNMinimizer called on double function"))
                {
                    ClreplacedifierType = "BinaryLogisticClreplacedifier";
                    Match m = binaryClreplacediferQNN.Match(s);
                    if (m.Success)
                    {
                        NumberofFeatures = Int32.Parse(m.Groups[1].Value);
                        Info("Built clreplacedifier {0} with {1} features.", ClreplacedifierType, NumberofFeatures);
                    }
                    else
                    {
                        Error("Could not parse BinaryLogisticClreplacedifier output: {0}.", s);
                    }
                }

            
                else if (!ReadTrainingDataset && s.StartsWith("Reading dataset from {0} ... done".F(TrainingFile.FullName)))
                {
                    ReadTrainingDataset = true;
                    Match m = readDataSetRegex.Match(s);
                    if (m.Success)
                    {
                        TrainingDataSereplacedems = Int32.Parse(m.Groups[3].Value);
                        Info("{0} items in training dataset read in {1} s.", TrainingDataSereplacedems, m.Groups[2].Value);
                    }
                    else
                    {
                        Error("Could not parse clreplacedifier output line: {0}.", s);
                        return StageResult.FAILED;
                    }
                }

                else if (!ReadTestDataset && s.StartsWith("Reading dataset from {0} ... done".F(TestFile.FullName)))
                {
                    ReadTestDataset = true;
                    Match m = readDataSetRegex.Match(s);
                    if (m.Success)
                    {
                        TestDataSereplacedems = Int32.Parse(m.Groups[3].Value);
                        Info("{0} items in test dataset read in {1} s.", TestDataSereplacedems, m.Groups[2].Value);
                    }
                    else
                    {
                        Error("Could not parse clreplacedifier output line: {0}.", s);
                        return StageResult.FAILED;
                    }
                }

                else if (!KFoldCrossValidation && s.StartsWith("### Fold"))
                {
                    KFoldCrossValidation = true;
                    Match m = kFold.Match(s);
                    if (m.Success)
                    {
                        if (!KFoldIndex.HasValue)
                        {
                            MicroAveragedF1Folds = new float[10];
                            MacroAveragedF1Folds = new float[10];
                        }
                        KFoldIndex = Int32.Parse(m.Groups[1].Value);
                    }
                }

                else if (KFoldCrossValidation && s.StartsWith("### Fold"))
                {
                    Match m = kFold.Match(s);
                    if (m.Success)
                    {
                        KFoldIndex = Int32.Parse(m.Groups[1].Value);
                    }
                    else
                    {
                        Error("Could not parse k-fold output line: {0}.", s);
                        return StageResult.FAILED;
                    }
                }

                else if (!KFoldCrossValidation && !MicroAveragedF1.HasValue && s.StartsWith("Accuracy/micro-averaged F1"))
                {
                    Match m = f1MicroRegex.Match(s);
                    if (m.Success)
                    {
                        MicroAveragedF1 = Single.Parse(m.Groups[1].Value);
                        Info("Micro-averaged F1 = {0}.", MicroAveragedF1);
                    }
                    else
                    {
                        Error("Could not parse micro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && ReadTestDataset && !MicroAveragedF1.HasValue && s.StartsWith("Accuracy/micro-averaged F1"))
                {
                    Match m = f1MicroRegex.Match(s);
                    if (m.Success)
                    {
                        MicroAveragedF1 = Single.Parse(m.Groups[1].Value);
                        Info("Micro-averaged F1 = {0}.", MicroAveragedF1);
                    }
                    else
                    {
                        Error("Could not parse micro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && s.StartsWith("Accuracy/micro-averaged F1"))
                {
                    Match m = f1MicroRegex.Match(s);
                    if (m.Success)
                    {
                        MicroAveragedF1Folds[KFoldIndex.Value] = Single.Parse(m.Groups[1].Value);
                        Info("Fold {0} Micro-averaged F1 = {1}.", KFoldIndex.Value, MicroAveragedF1Folds[KFoldIndex.Value]);
                    }
                    else
                    {
                        Error("Could not parse micro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (!KFoldCrossValidation && !MacroAveragedF1.HasValue && s.StartsWith("Macro-averaged F1"))
                {
                    Match m = f1MacroRegex.Match(s);
                    if (m.Success)
                    {
                        MacroAveragedF1 = Single.Parse(m.Groups[1].Value);
                        Info("Macro-averaged F1 = {0}.", MacroAveragedF1);
                    }
                    else
                    {
                        Error("Could not parse macro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && ReadTestDataset && !MacroAveragedF1.HasValue && s.StartsWith("Macro-averaged F1"))
                {
                    Match m = f1MacroRegex.Match(s);
                    if (m.Success)
                    {
                        MacroAveragedF1Folds[KFoldIndex.Value] = Single.Parse(m.Groups[1].Value);
                        Info("Macro-averaged F1 = {0}.\n", MacroAveragedF1Folds[KFoldIndex.Value]);
                    }
                    else
                    {
                        Error("Could not parse macro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (KFoldCrossValidation && s.StartsWith("Macro-averaged F1"))
                {
                    Match m = f1MacroRegex.Match(s);
                    if (m.Success)
                    {
                        MacroAveragedF1Folds[KFoldIndex.Value] = Single.Parse(m.Groups[1].Value);
                        Info("Fold {0} Macro-averaged F1 = {1}.\n", KFoldIndex.Value, MacroAveragedF1Folds[KFoldIndex.Value]);
                    }
                    else
                    {
                        Error("Could not parse macro-averaged F1 statistic {0}.", s);
                    }
                }

                else if (Features == null && s.StartsWith("Built this clreplacedifier: 1"))
                {
                    Features = new Dictionary<string, float>();
                    string f = s.Remove(0,"Built this clreplacedifier: ".Length);
                    foreach (string l in f.Split("/".ToCharArray(), StringSplitOptions.RemoveEmptyEntries))
                    {
                        string[] ls = l.Split('=');
                        Features.Add(ls[0].Trim(), Single.Parse(ls[1].Trim()));
                    }
                    Info("Using {0} features.", Features.Count);
          
                }
                else if (s.StartsWith("Cls"))
                {
                    Match m = clreplacedStatisticRegex.Match(s);
                    if (m.Success)
                    {
                        ClreplacedStatistic cs = new ClreplacedStatistic()
                        {
                            Name = m.Groups[1].Value,
                            TruePositives = Int32.Parse(m.Groups[2].Value),
                            FalsePositives = Int32.Parse(m.Groups[3].Value),
                            TrueNegatives = Int32.Parse(m.Groups[4].Value),
                            Accuracy = Single.Parse(m.Groups[5].Value),
                            Precision = Single.Parse(m.Groups[6].Value),
                            Recall = Single.Parse(m.Groups[7].Value),
                            F1 = Single.Parse(m.Groups[8].Value)
                        };
                        _ClreplacedStatistics.Add(cs);
                        Info(s);
                    }
                    else
                    {
                        L.Error("Could not parse clreplaced statistic: {0}.", s);
                    }
                }

                else if (resultRegex.IsMatch(s))
                {
                    Match m = resultRegex.Match(s);
                    ClreplacedifierResult cr = new ClreplacedifierResult()
                    {
                        GoldAnswer = m.Groups[1].Value,
                        ClreplacedifierAnswer = m.Groups[2].Value,
                        P_GoldAnswer = Single.Parse(m.Groups[3].Value),
                        P_ClAnswer = Single.Parse(m.Groups[4].Value)

                    };
                    _Results.Add(cr);
                }
                ClreplacedifierOutput.Add(s);
                Debug(s);
            }

            c.Wait();
            if (!CheckCommandSuccessAndReport(javaCommand))
            {
                return StageResult.FAILED;
            }
            
            if (!KFoldCrossValidation)
            {
                Info("Got {0} clreplaced statistics.", _ClreplacedStatistics.Count);
                Info("Got {0} results.", _Results.Count);
            }
            return StageResult.SUCCESS;
        }

19 Source : Program.cs
with GNU Lesser General Public License v3.0
from Alois-xx

private bool Parse()
        {
            Queue<string> args = new Queue<string>(Args);
            if( args.Count == 0)
            {
                Help("Error: You need to specify a dump file or live process to replacedyze.");
                return false;
            }

            bool lret = true;
            try
            {
                while (args.Count > 0)
                {
                    string param = args.Dequeue();
                    switch (param.ToLower())
                    {
                        case "-f":
                            SetDefaultActionIfNotSet();
                            TargetInformation.DumpFileName1 = NotAnArg(args.Dequeue());
                            break;
                        case "-f2":
                            TargetInformation.DumpFileName2 = NotAnArg(args.Dequeue());
                            break;
                        case "-pid":
                            SetDefaultActionIfNotSet();
                            TargetInformation.Pid1 = int.Parse(NotAnArg(args.Dequeue()));
                            break;
                        case "-child":
                            IsChild = true;
                            break;
                        case "-pid2":
                            TargetInformation.Pid2 = int.Parse(NotAnArg(args.Dequeue()));
                            break;
                        case "-silent":
                            IsSilent = true;
                            break;
                        case "-unit":
                            string next = args.Dequeue();
                            if ( Enum.TryParse(NotAnArg(next), true, out DisplayUnit tmpUnit) )
                            {
                                DisplayUnit = tmpUnit;
                            }
                            else
                            {
                                Console.WriteLine($"Warning: DisplayUnit {next} is not a valid value. Using default: {DisplayUnit}");
                            }
                            break;
                        case "-vmmap":
                            GetVMMapData = true;
                            break;
                        case "-procdump":
                            Action = Actions.ProcDump;
                            // give remaining args to procdump and to not try to parse them by ourself
                            ProcDumpArgs = args.ToArray();
                            args.Clear();
                            break;
                        case "-verifydump":
                            VerifyDump = true;
                            break;
                        case "-renameproc":
                            ProcessRenameFile = NotAnArg(args.Dequeue());
                            break;
                        case "-debug":
                            IsDebug = true;
                            break;
                        case "-noexcelsep":
                            DisableExcelCSVSep = true;
                            break;
                        case "-sep":
                            string sep = NotAnArg(args.Dequeue());
                            sep = sep.Trim(new char[] { '"', '\'' });
                            sep = sep == "\\t" ? "\t" : sep;
                            if( sep.Length != 1)
                            {
                                Console.WriteLine($"Warning CSV separator character \"{sep}\" was not recognized. Using default \t");
                            }
                            else
                            {
                                OutputStringWriter.SeparatorChar = sep[0];
                            }
                            break;
                        case "-dts":
                            Action = Actions.DumpTypesBySize;
                            if ( args.Count > 0 && NotAnArg(args.Peek(),false) != null)
                            {
                                ParseTopNQuery(args.Dequeue(), out int n, out int MinCount);
                                TopN = n > 0 ? n : TopN;
                            }
                            break;
                        case "-dtn":
                            Action = Actions.DumpTypesByCount;
                            if (args.Count > 0 && NotAnArg(args.Peek(),false) != null)
                            {
                                ParseTopNQuery(args.Dequeue(), out int n, out MinCount);
                                TopN =  n > 0 ? n : TopN;
                            }
                            break;
                        case "-live":
                            LiveOnly = true;
                            break;
                        case "-dacdir":
                            DacDir = NotAnArg(args.Dequeue());
                            // quoted mscordacwks file paths are not correctly treated so far. 
                            Environment.SetEnvironmentVariable("_NT_SYMBOL_PATH", DacDir.Trim(new char[] { '"' }));
                            break;
                        case "-process":
                            ProcessNameFilter = NotAnArg(args.Dequeue());
                            break;
                        case "-dstrings":
                            Action = Actions.DumpStrings;
                            if (args.Count > 0 && NotAnArg(args.Peek(), false) != null)
                            {
                                TopN = int.Parse(args.Dequeue());
                            }
                            break;
                        case "-showaddress":
                            ShowAddress = true;
                            break;
                        case "-o":
                            OutFile = NotAnArg(args.Dequeue());
                            TopN = 20 * 1000; // if output is dumped to file pipe all types to output
                                              // if later -dts/-dstrings/-dtn is specified one can still override this behavior.
                            break;
                        case "-overwrite":
                            OverWriteOutFile = true;
                            break;
                        case "-timefmt":
                            TimeFormat = NotAnArg(args.Dequeue());
                            break;
                        case "-time":
                            TargetInformation.ExternalTime = NotAnArg(args.Dequeue());
                            break;
                        case "-context":
                            Context = NotAnArg(args.Dequeue());
                            break;
                        default:
                            throw new ArgNotExpectedException(param);
                    }
                    
                }
            }
            catch(ArgNotExpectedException ex)
            {
                Help("Unexpected command line argument: {0}", ex.Message);
                lret = false;
            }

            return lret;
        }

19 Source : AddPlayerViewModel.cs
with MIT License
from almirvuk

void SavePlayer() {

            var team = _context.Teams.Where(t => t.TeamId == _teamId).FirstOrDefault();

            Player player = new Player() {

                JerseyNumber = Int32.Parse(JerseyNumber),
                Name = Name,
                Position = Position,
                TeamId = _teamId
            };

            _context.Players.Add(player);
            _context.SaveChanges();

            Application.Current.MainPage.Navigation.PopAsync();
        }

See More Examples