string.StartsWith(string, bool, System.Globalization.CultureInfo)

Here are the examples of the csharp api string.StartsWith(string, bool, System.Globalization.CultureInfo) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

1288 Examples 7

19 View Source File : MicroSplatUtilities.cs
License : MIT License
Project Creator : alelievr

public static string MakeAbsolutePath(string path)
      {
         if (!path.StartsWith(Application.dataPath))
         {
            if (path.StartsWith("replacedets"))
            {
               path = path.Substring(6);
               path = Application.dataPath + path;
            }
         }
         return path;
      }

19 View Source File : DataColumnsToRowsConverter.cs
License : MIT License
Project Creator : aloneguid

private bool TryBuildListCell(ListField lf, Dictionary<string, LazyColumnEnumerator> pathToColumn, out object cell)
      {
         //As this is the list, all sub-columns of this list have to be cut into. This is essentially a more complicated version of
         //the TryBuildMapCell method

         var nestedPathTicks = pathToColumn
            .Where(ptc => ptc.Key.StartsWith(lf.Path))
            .Select(ptc => new { path = ptc.Key, collection = ptc.Value, moved = ptc.Value.MoveNext() })
            .ToList();

         if(nestedPathTicks.Any(t => !t.moved))
         {
            cell = new Row[0];
            return true;
         }

         var nestedPathToColumn = nestedPathTicks
            .ToDictionary(ptc => ptc.path, ptc => (LazyColumnEnumerator)ptc.collection.Current);

         IReadOnlyList<Row> rows = BuildRows(new[] { lf.Item }, nestedPathToColumn);

         cell = rows.Select(r => r[0]).ToArray();

         return true;
      }

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

private static bool IsAnnotation(Enreplacedy enreplacedy)
			{
				var notesFilter = HttpContext.Current.GetSiteSetting("KnowledgeManagement/NotesFilter") ?? string.Empty;

				return enreplacedy != null 
					&& enreplacedy.LogicalName == "annotation"
					&& enreplacedy.GetAttributeValue<string>("objecttypecode") == "knowledgearticle"
					&& enreplacedy.GetAttributeValue<string>("notetext").StartsWith(notesFilter);
			}

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

public override void FromString(string value) {
			if (Value != default)
				Dat.ReferenceDataOffsets.Remove(ToString());

			var value2 = TypeOfValue == FieldType.String || TypeOfValue == FieldType.ValueString ? value.Trim(' ') : Regex.Replace(value, @"\s", "");
			if (!value2.StartsWith('[') || !value2.EndsWith(']'))
				throw new InvalidCastException("\"" + value + "\" cannot be converted to an array");
			if (TypeOfValue == FieldType.Unknown || value2 == "[]")
				Value = Array.Empty<TypeOfValueInArray>();
			else if (TypeOfValue == FieldType.ForeignRow) {
				value2 = value2[1..^1]; // Trim '[' ']'
				if (!value2.StartsWith('<') || !value2.EndsWith('>'))
					throw new InvalidCastException("\"" + value + "\" cannot be converted to an array of ForeignKeyType(foreignrow)");
				var sarray = value2[1..^1].Split(">,<"); // Trim '<' '>'
				Value = new TypeOfValueInArray[sarray.Length];
				for (var n = 0; n < sarray.Length; ++n) {
					var d = new ForeignRowData(Dat);
					d.FromString("<" + sarray[n] + ">");
					Value[n] = (TypeOfValueInArray)(object)d;
				}
			} else {
				var sarray = value2[1..^1].Split(','); // Trim '[' ']'
				Value = new TypeOfValueInArray[sarray.Length];
				switch (TypeOfValue) {
					case FieldType.String:
					case FieldType.ValueString:
						for (var n = 0; n < sarray.Length; ++n)
							Value[n] = (TypeOfValueInArray)IFieldData.FromString(sarray[n], TypeOfValue, Dat);
						break;
					default:
						for (var n = 0; n < sarray.Length; ++n)
							Value[n] = (TypeOfValueInArray)IFieldData.FromString(sarray[n], TypeOfValue, Dat).Value;
						break;
				}
			}

			Length = CalculateLength();
			if (Offset == default) {
				Offset = Dat.CurrentOffset;
				Dat.CurrentOffset += Length;
				Dat.ReferenceDatas[Offset] = this;
			}
			Dat.ReferenceDataOffsets[value] = Offset;
		}

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

public static string GetServiceRequestTypeThumbnailImageUrl(OrganizationServiceContext context, Enreplacedy enreplacedy)
		{
			if (enreplacedy == null)
			{
				return string.Empty;
			}

			var url = enreplacedy.GetAttributeValue<string>("adx_thumbnailimageurl");

			if (string.IsNullOrWhiteSpace(url))
			{
				return string.Empty;
			}

			if (url.StartsWith("http", true, CultureInfo.InvariantCulture))
			{
				return url;
			}

			var portalContext = PortalCrmConfigurationManager.CreatePortalContext();

			return WebsitePathUtility.ToAbsolute(portalContext.Website, url);
		}

19 View Source File : CodeResolvingUtils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

[MethodImpl(MethodImplOptions.AggressiveInlining)]
		public static bool IsBqlConstant(this ITypeSymbol typeSymbol)
		{
			if (!typeSymbol.IsValidForColoring() || typeSymbol.Name.StartsWith(TypeNames.Constant))
				return false;

			return typeSymbol.InheritsOrImplementsOrEquals(TypeNames.Constant, includeInterfaces: false);
		}

19 View Source File : NewSecurityUi.xaml.cs
License : Apache License 2.0
Project Creator : AlexWan

private void SearchSecurity(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Back)
            {
                _startSearch = DateTime.Now;
                _searchString = "";
                LabelSearchString.Content = "";
                return;
            }

            if (!char.IsLetter(e.KeyChar) && !char.IsDigit(e.KeyChar))
            {
                return;
            }

            int freshnessTime = 3; // seconds

            if (_startSearch == null || DateTime.Now.Subtract(_startSearch).Seconds > freshnessTime)
            {
                _startSearch = DateTime.Now;
                _searchString = e.KeyChar.ToString();
                RefreshSearchLabel(freshnessTime);
            }
            else
            {
                _searchString += e.KeyChar.ToString();
                RefreshSearchLabel(freshnessTime);
            }

            char[] charsToTrim = { '*', ' ', '\'', '\"', '+', '=', '-', '!', '#', '%', '.', ',' };

            for (int c = 0; c < _grid.Columns.Count; c++)
            {
                for (int r = 0; r < _grid.Rows.Count; r++)
                {
                    if (_grid.Rows[r].Cells[c].Value.ToString().Trim(charsToTrim)
                        .StartsWith(_searchString, true, CultureInfo.InvariantCulture))
                    {
                        _grid.Rows[r].Cells[c].Selected = true;
                        return; // stop looping
                    }
                }
            }
        }

19 View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<BiffRecord> ConvertStringToFormulas(string str, int rwStart, int colStart, int dstRw, int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
        {
            List<BiffRecord> formulaList = new List<BiffRecord>();
            List<Cell> createdCells = new List<Cell>();

            int curRow = rwStart;
            int curCol = colStart;

            bool instaEval = false;
            if (str.StartsWith(MacroPatterns.InstaEvalMacroPrefix))
            {
                if (packingMethod != SheetPackingMethod.ArgumentSubroutines)
                {
                    throw new NotImplementedException("Must use ArgumentSubroutines Sheet Packing for InstaEval");
                }
                instaEval = true;
                str = str.Replace(MacroPatterns.InstaEvalMacroPrefix, "");
            }

            
            List<Formula> charFormulas = GetCharFormulasForString(str, curRow, curCol, packingMethod);
            formulaList.AddRange(charFormulas);
            curRow += charFormulas.Count;
            createdCells = charFormulas.Select(formula => new Cell(formula.rw, formula.col, ixfe)).ToList();
            
            List<BiffRecord> formulaInvocationRecords =
                BuildFORMULAFunctionCall(createdCells, curRow, curCol, dstRw, dstCol, packingMethod, instaEval);

            formulaList.AddRange(formulaInvocationRecords);

            return formulaList;
        }

19 View Source File : ValidationAppSI.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : Altinn

private (ValidationIssueSeverity severity, string message) GetSeverityFromMessage(string originalMessage)
        {
            if (originalMessage.StartsWith(_generalSettings.SoftValidationPrefix))
            {
                return (ValidationIssueSeverity.Warning,
                    originalMessage.Remove(0, _generalSettings.SoftValidationPrefix.Length));
            }

            if (_generalSettings.FixedValidationPrefix != null 
                && originalMessage.StartsWith(_generalSettings.FixedValidationPrefix))
            {
                return (ValidationIssueSeverity.Fixed,
                    originalMessage.Remove(0, _generalSettings.FixedValidationPrefix.Length));
            }

            return (ValidationIssueSeverity.Error, originalMessage);
        }

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

public static string PrependPath(string path, string currentPath)
        {
            ArgUtil.NotNullOrEmpty(path, nameof(path));
            if (string.IsNullOrEmpty(currentPath))
            {
                // Careful not to add a trailing separator if the PATH is empty.
                // On OSX/Linux, a trailing separator indicates that "current directory"
                // is added to the PATH, which is considered a security risk.
                return path;
            }

            // Not prepend path if it is already the first path in %PATH%
            if (currentPath.StartsWith(path + Path.PathSeparator, IOUtil.FilePathStringComparison))
            {
                return currentPath;
            }
            else
            {
                return path + Path.PathSeparator + currentPath;
            }
        }

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

public bool ContainsWildcardMatchedNamespaceRule(string typeNamespace)
        {
            return _namespaces.Where(ns => ns.Value.Permission == Permission.Allowed
                                           && !ns.Value.Types.Any()
                                           && ns.Key.EndsWith("*"))
                .Any(ns => typeNamespace.StartsWith(ns.Key.Replace(".*", "")
                    .Replace("*", "")));
        }

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

private void RegisterClientSideDependencies(Control control)
		{
			foreach (var script in ScriptIncludes)
			{
				if (string.IsNullOrWhiteSpace(script))
				{
					continue;
				}

				var scriptManager = ScriptManager.GetCurrent(control.Page);

				if (scriptManager == null)
				{
					continue;
				}

				var absolutePath = script.StartsWith("http", true, CultureInfo.InvariantCulture) ? script : VirtualPathUtility.ToAbsolute(script);

				scriptManager.Scripts.Add(new ScriptReference(absolutePath));
			}
		}

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

public string ResolvePathForStepHost(string path)
        {
            // make sure container exist.
            ArgUtil.NotNull(Container, nameof(Container));
            ArgUtil.NotNullOrEmpty(Container.ContainerId, nameof(Container.ContainerId));

            // remove double quotes around the path
            path = path.Trim('\"');

            // try to resolve path inside container if the request path is part of the mount volume
#if OS_WINDOWS
            if (Container.MountVolumes.Exists(x => !string.IsNullOrEmpty(x.SourceVolumePath) && path.StartsWith(x.SourceVolumePath, StringComparison.OrdinalIgnoreCase)))
#else
            if (Container.MountVolumes.Exists(x => !string.IsNullOrEmpty(x.SourceVolumePath) && path.StartsWith(x.SourceVolumePath)))
#endif
            {
                return Container.TranslateToContainerPath(path);
            }
            else
            {
                return path;
            }
        }

19 View Source File : TokenEnsurer.cs
License : MIT License
Project Creator : AiursoftWeb

public void Ensure(string pbToken, string action, string siteName, string folderNames)
        {
            var token = _pbTokenManager.ValidateAccessToken(pbToken);
            if (token.SiteName != siteName)
            {
                throw new AiurAPIModelException(ErrorType.Unauthorized, $"Your token was not authorized to {action.ToLower()} files to this site: '{siteName}'.");
            }
            if (!token.Permissions.ToLower().Contains(action.ToLower().Trim()))
            {
                throw new AiurAPIModelException(ErrorType.Unauthorized, $"Your token was not authorized to {action.ToLower()}. Your token is only permitted to '{token.Permissions}'");
            }
            if (!string.IsNullOrWhiteSpace(token.UnderPath) && folderNames != null && !folderNames.StartsWith(token.UnderPath))
            {
                throw new AiurAPIModelException(ErrorType.Unauthorized, $"Your token is only authorized to {action.ToLower()} files from path: '{token.UnderPath}', not '{folderNames}'.");
            }
        }

19 View Source File : MacroPatterns.cs
License : Apache License 2.0
Project Creator : aaaddress1

private static string ImportCellFormula(string cellFormula)
        {
            if (cellFormula.Length == 0) return cellFormula;

            string newCellFormula = cellFormula;

            //Unescape the "s if we are looking at a CellFormula that has been escaped
            if (newCellFormula.StartsWith('"'))
            {
                //Strip the outer quotes
                newCellFormula = new string(newCellFormula.Skip(1).Take(newCellFormula.Length - 2).ToArray());

                //Escape the inside content
                newCellFormula = ExcelHelperClreplaced.UnescapeFormulaString(newCellFormula);
            }

            //Replace any uses of SELECT and ACTIVE.CELL with variable usage to better enable the sheet being hidden
            //Mainly for use with importing EXCELntDonut macros
            newCellFormula = ReplaceSelectActiveCellFormula(newCellFormula);

            //FORMULA requires R1C1 strings
            newCellFormula = ConvertA1StringToR1C1String(newCellFormula);

            int charReplacements = 0;
            //Remap CHAR() to actual bytes
            for (int i = 1; i <= 255; i += 1)
            {
                int oldLength = newCellFormula.Length;
                newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})&", i), "" + (char) i);
                newCellFormula = newCellFormula.Replace(string.Format("CHAR({0})", i), "" + (char)i);

                //Update our poor heuristic for when we're getting a cell that is just CHAR()&CHAR()&CHAR()&CHAR()...
                if (oldLength != newCellFormula.Length)
                {
                    double lengthDelta = oldLength - newCellFormula.Length;
                    charReplacements += (int)Math.Floor(lengthDelta / 6.0);
                }
            }
            
            //Arbitrary metric to determine if we should convert this to a string cell vs. formula cell
            if (charReplacements > 3 && newCellFormula[0] == '=')
            {
                newCellFormula = new string(newCellFormula.Skip(1).ToArray());

                //Excel cells will also check to see if we are a variable replacedignment cell:
                //if we have valid variable letters before an =, it will process the replacedignment value
                bool looksLikeVariablereplacedignment = LooksLikeVariablereplacedignment(newCellFormula);

                //If we have a raw string content that starts with = or @, we can wrap this with ="" and it will work
                //If the string content is already 255 bytes though, this won't work (FORMULA will fail trying to write the 258 byte string)
                //If we're close to the limit then populate the cell with =CHAR(w/e)&Ref to cell with remainder of the content
                if (newCellFormula.StartsWith('=') || newCellFormula.StartsWith('@') || looksLikeVariablereplacedignment)
                {
                    //Need to make sure there's room for inserting 3 more characters =""
                    if (newCellFormula.Length >= 255 - 3)
                    {
                        //If this is a max length cell (common with 255 byte increments of shellcode)
                        //then mark the macro with a marker and we'll break it into two cells when we're building the sheet
                        return FormulaHelper.TOOLONGMARKER + newCellFormula;
                    }
                    else
                    {
                        newCellFormula = string.Format("=\"{0}\"", newCellFormula);
                    }
                    
                }
            }
            else
            {
                //TODO Use a proper logging package and log this as DEBUG info
                // Console.WriteLine(newCellFormula);
            }

            if (newCellFormula.Length > 255)
            {
                throw new ArgumentException(string.Format("Imported Cell Formula is too long - length must be 255 or less:\n{0}", newCellFormula));
            }


            return newCellFormula;
        }

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

private void AddPluginClick(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog()
            {
                RestoreDirectory = true,
                Filter = "Plugin files (*.wlx;*.wlx64)|*.wlx;*.wlx64|All files (*.*)|*.*"
            };
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                var fileName = dialog.FileName;
                if (fileName.StartsWith(replacedemblyUtils.replacedemblyDirectory, StringComparison.InvariantCultureIgnoreCase))
                {
                    fileName = fileName.Substring(replacedemblyUtils.replacedemblyDirectory.Length).TrimStart('\\');
                }
                if (IsGridViewContainFile(fileName))
                {
                    MessageBox.Show("The file already exists in the list.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                var index = gridViewPlugin.Rows.Add();
                var row = gridViewPlugin.Rows[index];
                row.Cells[0].Value = fileName;
                row.Cells[1].Value = string.Join(";", Plugin.GetSupportedExtensions(fileName));
                gridViewPlugin.FirstDisplayedScrollingRowIndex = gridViewPlugin.RowCount - 1;
                gridViewPlugin.Rows[index].Selected = true;
            }
        }

19 View Source File : Parser.cs
License : MIT License
Project Creator : adamant

private static string? GetConfig(IEnumerable<string> lines, string config)
        {
            var start = Program.DirectiveMarker + config;
            var line = lines.SingleOrDefault(l => l.StartsWith(start, StringComparison.InvariantCulture));
            line = line?.Substring(start.Length);
            line = line?.TrimEnd(';'); // TODO error if no semicolon
            line = line?.Trim();
            return line;
        }

19 View Source File : MQSigner.cs
License : MIT License
Project Creator : aliyunmq

protected static string CanonoicalizeHeaders(IDictionary<string, string> headers)
        {
            var headersToCanonicalize = new SortedDictionary<string, string>(StringComparer.OrdinalIgnoreCase);
            if (headers != null && headers.Count > 0)
            {
                foreach (var header in headers.Where(header =>
                    header.Key.ToLowerInvariant().StartsWith(Constants.X_MQ_HEADER_PREFIX)))
                {
                    headersToCanonicalize.Add(header.Key.ToLowerInvariant(), header.Value);
                }
            }
            return CanonicalizeHeaders(headersToCanonicalize);
        }

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

private void BtnEnable_Click(object sender, EventArgs e)
        {
            DialogResult result =
                MessageBox.Show("Changing these settings may require a re-download of manga files.\n\n" +
                                "Also, enabling this section may take several moments, depending on your Internet speed.\n\n" +
                                "Continue?", "Confirmation", MessageBoxButtons.YesNo);
            if (result == DialogResult.Yes)
            {
                btnEnable.Enabled = false;

                if (replacedle is Manga m && m is MangaDex)
                {
                    cmboLang.Items.Clear();

                    foreach (string lc in m.GetLangs())
                    {
                        cmboLang.Items.Add(lc);
                    }
                    foreach (string localeOption in cmboLang.Items)
                    {
                        if (localeOption.StartsWith(m.GetUserLang()))
                        {
                            cmboLang.SelectedItem = localeOption;
                            break;
                        }
                    }

                    cmboGroup.Enabled = true;
                    cmboLang.Enabled = true;
                }
                if (replacedle is Manga)
                    btnChapSelect.Enabled = true; // should allow chapter download for any manga
            }
        }

19 View Source File : SVTXPainterWindow.cs
License : MIT License
Project Creator : alpacasking

private void OnGUI()
        {
            //Header
            GUILayout.BeginHorizontal();
            GUILayout.Box("Simple Vertex Painter", replacedleStyle, GUILayout.Height(60), GUILayout.ExpandWidth(true));
            GUILayout.EndHorizontal();

            //Body
            GUILayout.BeginVertical(GUI.skin.box);

            if (m_target != null)
            {
                if (!m_target.isActiveAndEnabled)
                {
                    EditorGUILayout.LabelField("(Enable " + m_target.name + " to show Simple Vertex Painter)");
                }
                else
                {
                    //bool lastAP = allowPainting;
                    allowPainting = GUILayout.Toggle(allowPainting, "Paint Mode");

                    if (allowPainting)
                    {
                        //Selection.activeGameObject = null;
                        Tools.current = Tool.None;
                    }


                    GUILayout.BeginHorizontal();
                    GUILayout.Label("Paint Type:", GUILayout.Width(90));
                    string[] channelName = { "All", "R", "G", "B", "A" };
                    int[] channelIds = { 0, 1, 2, 3, 4 };
                    curColorChannel = EditorGUILayout.IntPopup(curColorChannel, channelName, channelIds, GUILayout.Width(50));
                    GUILayout.EndHorizontal();
                    GUILayout.BeginHorizontal();
                    if (curColorChannel == (int)PaintType.All)
                    {
                        brushColor = EditorGUILayout.ColorField("Brush Color:", brushColor);
                    }
                    else
                    {
                        brushIntensity = EditorGUILayout.Slider("Intensity:", brushIntensity, 0, 1);
                    }
                    if (GUILayout.Button("Fill"))
                    {
                        FillVertexColor();
                    }
                    GUILayout.EndHorizontal();
                    brushSize = EditorGUILayout.Slider("Brush Size:", brushSize, MinBrushSize, MaxBrushSize);
                    brushOpacity = EditorGUILayout.Slider("Brush Opacity:", brushOpacity, 0, 1);
                    brushFalloff = EditorGUILayout.Slider("Brush Falloff:", brushFalloff, MinBrushSize, brushSize);

                    if (GUILayout.Button("Export .replacedet file") && curMesh != null)
                    {
                        string path = EditorUtility.SaveFilePanel("Export .replacedet file", "replacedets", SVTXPainterUtils.SanitizeForFileName(curMesh.name), "replacedet");
                        if (path.Length > 0)
                        {
                            var dataPath = Application.dataPath;
                            if (!path.StartsWith(dataPath))
                            {
                                Debug.LogError("Invalid path: Path must be under " + dataPath);
                            }
                            else
                            {
                                path = path.Replace(dataPath, "replacedets");
                                replacedetDatabase.Createreplacedet(Instantiate(curMesh), path);
                                Debug.Log("replacedet exported: " + path);
                            }
                        }
                    }




                    //Footer
                    GUILayout.Label("Key Z:Turn on or off\nRight mouse button:Paint\nRight mouse button+Shift:Opacity\nRight mouse button+Ctrl:Size\nRight mouse button+Shift+Ctrl:Falloff\n", EditorStyles.helpBox);
                    Repaint();
                }
            }
            else if (m_active != null)
            {
                if (GUILayout.Button("Add SVTX Object to " + m_active.name))
                {
                    m_active.AddComponent<SVTXObject>();
                    OnSelectionChange();
                }
            }
            else
            {
                EditorGUILayout.LabelField("Please select a mesh or skinnedmesh.");
            }
            GUILayout.EndVertical();
        }

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

protected virtual void RegisterClientSideDependencies(Control control)
		{
			foreach (var script in ScriptIncludes)
			{
				if (string.IsNullOrWhiteSpace(script)) continue;

				var scriptManager = ScriptManager.GetCurrent(control.Page);

				if (scriptManager == null) continue;

				var absolutePath = script.StartsWith("http", true, CultureInfo.InvariantCulture) ? script : VirtualPathUtility.ToAbsolute(script);

				scriptManager.Scripts.Add(new ScriptReference(absolutePath));
			}
		}

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

private void UpdateDeviceCredentials(ClientCredentials deviceCredentials)
		{
			var deviceId = deviceCredentials.UserName.UserName ?? string.Empty;

			txtDeviceId.Text = deviceId.StartsWith(DeviceIdManager.DevicePrefix) & deviceId.Length > DeviceIdManager.MaxDeviceNameLength ? deviceId.Substring(DeviceIdManager.DevicePrefix.Length) : deviceId;

			txtDevicePreplacedword.Text = deviceCredentials.UserName.Preplacedword ?? string.Empty;
		}

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

private void Setup(dynamic contents)
        {
            m.LoadSettings();
            // Group Names
            cmboGroup.Items.Add("{Any}");
            cmboGroup.SelectedIndex = 0;
            foreach (var chapterID in contents.chapter)
            {
                foreach (var chapter in chapterID)
                {
                    string group = chapter.group_name;
                    if (!IsGroupInList(group))
                    {
                        cmboGroup.Items.Add(group);
                        if (group.Equals(m.settings.group))
                            cmboGroup.SelectedIndex = cmboGroup.Items.Count - 1;
                    }
                }
            }

            foreach (string localeOption in cmboLang.Items)
            {
                if (localeOption.StartsWith(m.settings.lang))
                {
                    cmboLang.SelectedItem = localeOption;
                    break;
                }
            }

            if (m.settings.name == "" || m.settings.name == null)
            {
                txtName.Text = m.name;
            } else
            {
                txtName.Text = m.settings.name;
            }
        }

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

public static string GetPushpinImageUrl(OrganizationServiceContext context, Enreplacedy enreplacedy)
		{
			var serviceRequestType = enreplacedy.GetAttributeValue<EnreplacedyReference>("adx_servicerequesttype");

			if (serviceRequestType == null)
			{
				return string.Empty;
			}

			var type = context.CreateQuery("adx_servicerequesttype").FirstOrDefault(s => s.GetAttributeValue<Guid>("adx_servicerequesttypeid") == serviceRequestType.Id);

			if (type == null)
			{
				return string.Empty;
			}

			var url = type.GetAttributeValue<string>("adx_mapiconimageurl");

			if (string.IsNullOrWhiteSpace(url))
			{
				return string.Empty;
			}

			if (url.StartsWith("http", true, CultureInfo.InvariantCulture))
			{
				return url;
			}

			var portalContext = PortalCrmConfigurationManager.CreatePortalContext();

			return WebsitePathUtility.ToAbsolute(portalContext.Website, url);
		}

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

private bool IsUriInBypreplacedList(Uri input)
        {
            foreach (var noProxy in _noProxyList)
            {
                var matchHost = false;
                var matchPort = false;

                if (string.IsNullOrEmpty(noProxy.Port))
                {
                    matchPort = true;
                }
                else
                {
                    matchPort = string.Equals(noProxy.Port, input.Port.ToString());
                }

                if (noProxy.Host.StartsWith('.'))
                {
                    matchHost = input.Host.EndsWith(noProxy.Host, StringComparison.OrdinalIgnoreCase);
                }
                else
                {
                    matchHost = string.Equals(input.Host, noProxy.Host, StringComparison.OrdinalIgnoreCase) || input.Host.EndsWith($".{noProxy.Host}", StringComparison.OrdinalIgnoreCase);
                }

                if (matchHost && matchPort)
                {
                    return true;
                }
            }

            return false;
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static void breakStone_Postfix(GameLocation __instance, ref bool __result, int indexOfStone, int x, int y, Farmer who, Random r)
        {
            SMonitor.Log($"Checking for custom ore in stone {indexOfStone}");

            CustomOreNode node = customOreNodesList.Find(n => n.parentSheetIndex == indexOfStone);

            if (node == null)
                return;

            SMonitor.Log($"Got custom ore in stone {indexOfStone}");


            OreLevelRange gotRange = null;
            foreach (OreLevelRange range in node.oreLevelRanges)
            {
                if (IsInRange(range, __instance, false))
                {
                    gotRange = range;
                    break;
                }
            }
            if (gotRange == null)
            {
                SMonitor.Log($"No range for {indexOfStone}!", LogLevel.Warn);

                return;
            }

            int addedOres = who.professions.Contains(18) ? 1 : 0;
            SMonitor.Log($"custom node has {node.dropItems.Count} potential items.");
            foreach (DropItem item in node.dropItems)
            {
                if (Game1.random.NextDouble() < item.dropChance * gotRange.dropChanceMult/100) 
                {
                    SMonitor.Log($"dropping item {item.itemIdOrName}");

                    if(!int.TryParse(item.itemIdOrName, out int itemId))
                    {
                        foreach(KeyValuePair<int,string> kvp in Game1.objectInformation)
                        {
                            if (kvp.Value.StartsWith(item.itemIdOrName + "/"))
                            {
                                itemId = kvp.Key;
                                break;
                            }
                        }
                    }

                    Game1.createMultipleObjectDebris(itemId, x, y, addedOres + (int)Math.Round(r.Next(item.minAmount, (Math.Max(item.minAmount + 1, item.maxAmount + 1)) + ((r.NextDouble() < who.LuckLevel / 100f) ? item.luckyAmount : 0) + ((r.NextDouble() < who.MiningLevel / 100f) ? item.minerAmount : 0)) * gotRange.dropMult), who.UniqueMultiplayerID, __instance);
                }
            }
            int experience = (int)Math.Round(node.exp * gotRange.expMult);
            who.gainExperience(3, experience);
            __result = experience > 0;
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private void Input_ButtonPressed(object sender, StardewModdingAPI.Events.ButtonPressedEventArgs e)
        {
            if (!Config.Enabled || !Context.IsWorldReady)
                return;

            Dictionary<string, string> npcDic;
            List<string> npcKeys;

            // check for click on dialogue

            if (Game1.activeClickableMenu != null && Game1.player?.currentLocation?.lastQuestionKey?.StartsWith("DialogueTrees_") == true)
            {
                IClickableMenu menu = Game1.activeClickableMenu;
                if (menu == null || menu.GetType() != typeof(DialogueBox))
                    return;

                DialogueBox db = menu as DialogueBox;
                int resp = db.selectedResponse;
                List<Response> resps = db.responses;

                if (resp < 0 || resps == null || resp >= resps.Count || resps[resp] == null)
                    return;

                string[] parts = resps[resp].responseKey.Split('#');
                string npcName = parts[1];
                string topicID = parts[2];
                string responseID = parts[3];
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npcName}", ContentSource.GameContent);
                npcKeys = npcDic.Keys.ToList();

                if (Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_Player_Question")
                {
                    Monitor.Log($"asking {npcName} about {loadedTopicNames[topicID]}");
                    var possibleResponses = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_response_" + topicID + "_"));
                    NPC n = Game1.getCharacterFromName(npcName);
                    Game1.drawDialogue(n, npcDic[possibleResponses[myRand.Next(possibleResponses.Count)]]);

                    string nextTopicID = GetNextTopicID(topicID, "any");

                    if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID) && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + nextTopicID + "_")))
                    {
                        if (responseData != null)
                        {
                            responseData.lastTopic = loadedDialogues[topicID];
                            responseData.nextTopic = loadedDialogues[nextTopicID];
                            responseData.npc = n;
                            responseData.topicResponses[topicID] = responseID;
                        }
                        else
                            responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                    }
                }
                else if(Game1.player.currentLocation.lastQuestionKey == "DialogueTrees_NPC_Question")
                {
                    Monitor.Log($"{npcName} is asking player about {loadedTopicNames[topicID]}, player response: {loadedResponseStrings[responseID]}");

                    var possibleReactions = npcKeys.FindAll(k => k.StartsWith("DialogueTrees_reaction_" + topicID + "_" + responseID + "_"));

                    if (!possibleReactions.Any())
                    {
                        Monitor.Log($"{npcName} has no reaction to {loadedTopicNames[topicID]} response {loadedResponseStrings[responseID]}! Check the [DT] content pack.", LogLevel.Warn);
                    }
                    else
                    {
                        NPC n = Game1.getCharacterFromName(npcName);
                        Game1.drawDialogue(n, npcDic[possibleReactions[myRand.Next(possibleReactions.Count)]]);
                        if (npcDic.ContainsKey("DialogueTrees_friendship_" + topicID + "_" + responseID) && int.TryParse(npcDic["DialogueTrees_friendship_" + topicID + "_" + responseID], out int amount))
                        {
                            Monitor.Log($"changing friendship with {n.Name} by {amount}");
                            Game1.player.changeFriendship(amount, n);
                        }

                        string nextTopicID = GetNextTopicID(topicID, responseID);

                        if (nextTopicID != null && loadedDialogues.ContainsKey(nextTopicID))
                        {
                            Monitor.Log($"Preparing followup dialogue {nextTopicID}");
                            if (responseData != null)
                            {
                                Monitor.Log($"Adding to existing responseData");

                                responseData.lastTopic = loadedDialogues[topicID];
                                responseData.nextTopic = loadedDialogues[nextTopicID];
                                responseData.npc = n;
                                responseData.topicResponses[topicID] = responseID;
                            }
                            else
                                responseData = new DialogueTreeResponse(loadedDialogues[topicID], loadedDialogues[nextTopicID], n, responseID);
                        }
                        else
                        {
                            if(responseData != null)
                                Monitor.Log("No next topic, erasing response data");
                            responseData = null;
                        }
                    }
                }
                
                Game1.player.currentLocation.lastQuestionKey = "";
                return;
            }

            // check for click on NPC

            if (Game1.activeClickableMenu != null || !Context.CanPlayerMove || (Config.ModButton != SButton.None && !Helper.Input.IsDown(Config.ModButton)) || (e.Button != Config.AskButton && e.Button != Config.AnswerButton))
                return;

            Monitor.Log($"Pressed modkey + {e.Button}");

            Rectangle tileRect = new Rectangle((int)Game1.currentCursorTile.X * 64, (int)Game1.currentCursorTile.Y * 64, 64, 64);

            NPC npc = null;

            foreach (NPC i in Game1.currentLocation.characters)
            {
                if (i != null && !i.IsMonster && (!Game1.player.isRidingHorse() || !(i is Horse)) && i.GetBoundingBox().Intersects(tileRect) && !i.IsInvisible && !i.checkAction(Game1.player, Game1.currentLocation))
                {
                    npc = i;
                    break;
                }
            }

            if (npc == null)
                return;
            try
            {
                npcDic = Helper.Content.Load<Dictionary<string, string>>($"Characters/Dialogue/{npc.Name}", ContentSource.GameContent);

            }
            catch
            {
                Monitor.Log($"No dialogue file for {npc.Name}", LogLevel.Warn);

                return;
            }
            npcKeys = npcDic.Keys.ToList();

            if (e.Button == Config.AskButton)
            {

                Monitor.Log($"Asking question of {npc.Name}");

                var shuffled = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && d.playerCanAsk && npcKeys.Exists(k => k.StartsWith("DialogueTrees_response_" + d.topicID+"_")));

                if(!shuffled.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} has a response to! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }
                Monitor.Log($"{shuffled.Count} questions that {npc.Name} has a response to.");

                ShuffleList(shuffled);
                var questions = shuffled.Take(Config.MaxPlayerQuestions);
                List<Response> responses = new List<Response>();
                foreach(var q in questions)
                {
                    Monitor.Log(q.topicID);
                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{q.topicID}", string.Format(loadedQuestionStrings[q.questionIDs[myRand.Next(q.questionIDs.Count)]], loadedTopicNames[q.topicID])));
                }

                Game1.player.currentLocation.createQuestionDialogue(string.Format(Helper.Translation.Get("ask-npc"), npc.Name), responses.ToArray(), "DialogueTrees_Player_Question");
            }
            else if (e.Button == Config.AnswerButton)
            {
                Monitor.Log($"Answering {npc.Name}'s question");

                var possibleQuestions = loadedDialogues.Values.ToList().FindAll(d => d.isStarter && npcKeys.Exists(k => k.StartsWith("DialogueTrees_reaction_" + d.topicID+"_")));

                if (!possibleQuestions.Any())
                {
                    Monitor.Log($"No questions that {npc.Name} can ask (no reactions)! Check the [DT] content pack.", LogLevel.Warn);
                    return;
                }

                DialogueTree p = possibleQuestions[myRand.Next(possibleQuestions.Count)];

                Monitor.Log($"Asking about {loadedTopicNames[p.topicID]}");

                List<Response> responses = new List<Response>();
                foreach(var r in p.responseIDs)
                {
                    Monitor.Log(r);

                    responses.Add(new Response($"DialogueTrees_Response#{npc.Name}#{p.topicID}#{r}", string.Format(loadedResponseStrings[r], loadedTopicNames[p.topicID])));
                }
                string qid = p.questionIDs[myRand.Next(p.questionIDs.Count)];

                List<string> possibleQuestionStrings = npcDic.Keys.ToList().FindAll(k => k.StartsWith("DialogueTrees_question_" + qid + "_"));
                string questionString = possibleQuestionStrings.Any() ? npcDic[possibleQuestionStrings[myRand.Next(possibleQuestionStrings.Count)]] : loadedQuestionStrings[qid];

                Game1.player.currentLocation.createQuestionDialogue(string.Format(questionString, loadedTopicNames[p.topicID]), responses.ToArray(), "DialogueTrees_NPC_Question");
                Game1.objectDialoguePortraitPerson = npc;
            }
        }

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

private List<string> GetRunnerDiagnosticLogFiles(string diagnosticFolder, DateTime jobStartTimeUtc)
        {
            // Get the newest runner log file that created just before the start of the job
            var runnerLogFiles = new List<string>();
            var directoryInfo = new DirectoryInfo(diagnosticFolder);

            // The runner log that record the start point of the job should created before the job start time.
            // The runner log may get paged if it reach size limit.
            // We will only need upload 1 runner log file in 99%.
            // There might be 1% we need to upload 2 runner log files.
            String recentLog = null;
            DateTime recentTimeUtc = DateTime.MinValue;

            foreach (FileInfo file in directoryInfo.GetFiles().Where(f => f.Name.StartsWith(Constants.Path.RunnerDiagnosticLogPrefix)))
            {
                // The format of the logs is:
                // Runner_20171003-143110-utc.log
                if (DateTime.TryParseExact(
                    s: file.Name.Substring(startIndex: Constants.Path.RunnerDiagnosticLogPrefix.Length, length: DateTimeFormat.Length),
                    format: DateTimeFormat,
                    provider: CultureInfo.InvariantCulture,
                    style: DateTimeStyles.None,
                    result: out DateTime fileCreateTime))
                {
                    // always add log file created after the job start.
                    if (fileCreateTime >= jobStartTimeUtc)
                    {
                        runnerLogFiles.Add(file.FullName);
                    }
                    else if (fileCreateTime > recentTimeUtc)
                    {
                        recentLog = file.FullName;
                        recentTimeUtc = fileCreateTime;
                    }
                }
            }

            if (!String.IsNullOrEmpty(recentLog))
            {
                runnerLogFiles.Add(recentLog);
            }

            return runnerLogFiles;
        }

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

public Task<ByteString> GetStateAsync(Address contractAddress, string key, long blockHeight, Hash blockHash)
        {
            var address = contractAddress.ToBase58();
            if(!key.StartsWith(address))
                throw new InvalidOperationException("a contract cannot access other contracts data");
            
            return _blockchainStateManager.GetStateAsync(key, blockHeight,
                blockHash);
        }

19 View Source File : WavUtility.cs
License : GNU General Public License v3.0
Project Creator : a2659802

public static AudioClip ToAudioClip(string filePath)
		{
			if (!filePath.StartsWith(Application.persistentDataPath) && !filePath.StartsWith(Application.dataPath))
			{
				Debug.LogWarning("This only supports files that are stored using Unity's Application data path. \nTo load bundled resources use 'Resources.Load(\"filename\") typeof(AudioClip)' method. \nhttps://docs.unity3d.com/ScriptReference/Resources.Load.html");
				return null;
			}
			byte[] fileBytes = File.ReadAllBytes(filePath);
			return ToAudioClip(fileBytes, 0);
		}

19 View Source File : IFileStore.cs
License : MIT License
Project Creator : aishang2015

public static string Combine(this IFileStore fileStore, params string[] paths)
        {
            if (paths.Length == 0)
                return null;

            var normalizedParts = paths
                    .Select(x => fileStore.NormalizePath(x))
                    .Where(x => !string.IsNullOrEmpty(x))
                    .ToArray();

            var combined = string.Join("/", normalizedParts);

            if (paths[0]?.StartsWith('/') == true)
                combined = "/" + combined;

            return combined;
        }

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

public static String TrimDoubleQuotes(String value)
        {
            var trimmed = string.Empty;
            if (!string.IsNullOrEmpty(value) &&
                value.Length > 8 &&
                value.StartsWith('"') &&
                value.EndsWith('"'))
            {
                trimmed = value.Substring(1, value.Length - 2);
            }

            return trimmed;
        }

19 View Source File : XmlNodeConverter.cs
License : MIT License
Project Creator : akaskela

private void ReadElement(JsonReader reader, IXmlDoreplacedent doreplacedent, IXmlNode currentNode, string propertyName, XmlNamespaceManager manager)
        {
            if (string.IsNullOrEmpty(propertyName))
            {
                throw JsonSerializationException.Create(reader, "XmlNodeConverter cannot convert JSON with an empty property name to XML.");
            }

            Dictionary<string, string> attributeNameValues = ReadAttributeElements(reader, manager);

            string elementPrefix = MiscellaneousUtils.GetPrefix(propertyName);

            if (propertyName.StartsWith('@'))
            {
                string attributeName = propertyName.Substring(1);
                string attributePrefix = MiscellaneousUtils.GetPrefix(attributeName);

                AddAttribute(reader, doreplacedent, currentNode, attributeName, manager, attributePrefix);
                return;
            }

            if (propertyName.StartsWith('$'))
            {
                switch (propertyName)
                {
                    case JsonTypeReflector.ArrayValuesPropertyName:
                        propertyName = propertyName.Substring(1);
                        elementPrefix = manager.LookupPrefix(JsonNamespaceUri);
                        CreateElement(reader, doreplacedent, currentNode, propertyName, manager, elementPrefix, attributeNameValues);
                        return;
                    case JsonTypeReflector.IdPropertyName:
                    case JsonTypeReflector.RefPropertyName:
                    case JsonTypeReflector.TypePropertyName:
                    case JsonTypeReflector.ValuePropertyName:
                        string attributeName = propertyName.Substring(1);
                        string attributePrefix = manager.LookupPrefix(JsonNamespaceUri);
                        AddAttribute(reader, doreplacedent, currentNode, attributeName, manager, attributePrefix);
                        return;
                }
            }

            CreateElement(reader, doreplacedent, currentNode, propertyName, manager, elementPrefix, attributeNameValues);
        }

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

private void Browser_DoreplacedentCompleted(object sender, WebBrowserDoreplacedentCompletedEventArgs e)
        {
            if (gfxBrowser.Url == null) return;
            
            switch (cmboSource.SelectedItem.ToString().ToLower())
            {
                case "mangadex":
                    if (gfxBrowser.Url.ToString().StartsWith(MangaDexHelper.MANGADEX_URL + "/replacedle/"))
                        btnAdd.Enabled = true;
                    else
                        btnAdd.Enabled = false;
                    break;
                case "kissmanga":
                    if(gfxBrowser.Url.ToString().StartsWith(KissMangaHelper.KISS_URL + "/manga/"))
                        btnAdd.Enabled = true;
                    else
                        btnAdd.Enabled = false;
                    break;
                case "nhentai":
                    if (gfxBrowser.Url.ToString().StartsWith("https://nhentai.net/g/"))
                        btnAdd.Enabled = true;
                    else
                        btnAdd.Enabled = false;
                    break;
                default:
                    break;
            }
        }

19 View Source File : WavUtility.cs
License : MIT License
Project Creator : alessandroTironi

public static AudioClip ToAudioClip (string filePath)
	{
		if (!filePath.StartsWith (Application.persistentDataPath) && !filePath.StartsWith (Application.dataPath)) {
			Debug.LogWarning ("This only supports files that are stored using Unity's Application data path. \nTo load bundled resources use 'Resources.Load(\"filename\") typeof(AudioClip)' method. \nhttps://docs.unity3d.com/ScriptReference/Resources.Load.html");
			return null;
		}
		byte[] fileBytes = File.ReadAllBytes (filePath);
		return ToAudioClip (fileBytes, 0);
	}

19 View Source File : DiagnosticUtils.cs
License : GNU General Public License v3.0
Project Creator : Acumatica

public static bool IsAreplacedinatorDiagnostic(this Diagnostic diagnostic)
		{
			diagnostic.ThrowOnNull(nameof(diagnostic));
			return diagnostic.Id.StartsWith(SharedConstants.AreplacedinatorDiagnosticPrefix);
		}

19 View Source File : AbstractHarddrive.cs
License : MIT License
Project Creator : AlexGyver

public static AbstractHarddrive CreateInstance(ISmart smart, 
      int driveIndex, ISettings settings) 
    {
      IntPtr deviceHandle = smart.OpenDrive(driveIndex);

      string name = null;
      string firmwareRevision = null;
      DriveAttributeValue[] values = { };

      if (deviceHandle != smart.InvalidHandle) {
        bool nameValid = smart.ReadNameAndFirmwareRevision(deviceHandle,
        driveIndex, out name, out firmwareRevision);
        bool smartEnabled = smart.EnableSmart(deviceHandle, driveIndex);

        if (smartEnabled)
          values = smart.ReadSmartData(deviceHandle, driveIndex);

        smart.CloseHandle(deviceHandle);

        if (!nameValid) {
          name = null;
          firmwareRevision = null;
        }
      } else {
        string[] logicalDrives = smart.GetLogicalDrives(driveIndex);
        if (logicalDrives == null || logicalDrives.Length == 0)
          return null;

        bool hasNonZeroSizeDrive = false;
        foreach (string logicalDrive in logicalDrives) {
          try {
            DriveInfo di = new DriveInfo(logicalDrive);
            if (di.TotalSize > 0) {
              hasNonZeroSizeDrive = true;
              break;
            }
          } catch (ArgumentException) { 
          } catch (IOException) { 
          } catch (UnauthorizedAccessException) {
          }
        }

        if (!hasNonZeroSizeDrive)
          return null;
      }

      if (string.IsNullOrEmpty(name))
        name = "Generic Hard Disk";

      if (string.IsNullOrEmpty(firmwareRevision))
        firmwareRevision = "Unknown";

      foreach (Type type in hddTypes) {
        // get the array of name prefixes for the current type
        NamePrefixAttribute[] namePrefixes = type.GetCustomAttributes(
          typeof(NamePrefixAttribute), true) as NamePrefixAttribute[];

        // get the array of the required SMART attributes for the current type
        RequireSmartAttribute[] requiredAttributes = type.GetCustomAttributes(
          typeof(RequireSmartAttribute), true) as RequireSmartAttribute[];

        // check if all required attributes are present
        bool allRequiredAttributesFound = true;
        foreach (var requireAttribute in requiredAttributes) {
          bool adttributeFound = false;
          foreach (DriveAttributeValue value in values) {
            if (value.Identifier == requireAttribute.AttributeId) {
              adttributeFound = true;
              break;
            }
          }
          if (!adttributeFound) {
            allRequiredAttributesFound = false;
            break;
          }
        }

        // if an attribute is missing, then try the next type
        if (!allRequiredAttributesFound)
          continue;        

        // check if there is a matching name prefix for this type
        foreach (NamePrefixAttribute prefix in namePrefixes) {
          if (name.StartsWith(prefix.Prefix, StringComparison.InvariantCulture)) 
            return Activator.CreateInstance(type, smart, name, firmwareRevision,
              driveIndex, settings) as AbstractHarddrive;
        }
      }

      // no matching type has been found
      return null;
    }

19 View Source File : FormulaHelper.cs
License : Apache License 2.0
Project Creator : aaaddress1

public static List<BiffRecord> ConvertChunkedStringToFormulas(List<string> chunkedString, int rwStart, int colStart, int dstRw,
            int dstCol, int ixfe = 15, SheetPackingMethod packingMethod = SheetPackingMethod.ObfuscatedCharFunc)
        {
            bool instaEval = false;
            if (chunkedString[0].StartsWith(MacroPatterns.InstaEvalMacroPrefix))
            {
                if (packingMethod != SheetPackingMethod.ArgumentSubroutines)
                {
                    throw new NotImplementedException("Must use ArgumentSubroutines Sheet Packing for InstaEval");
                }
                instaEval = true;
                chunkedString[0] = chunkedString[0].Replace(MacroPatterns.InstaEvalMacroPrefix, "");
            }
            
            List<BiffRecord> formulaList = new List<BiffRecord>();
            
            List<Cell> concatCells = new List<Cell>();

            int curRow = rwStart;
            int curCol = colStart;

            foreach (string str in chunkedString)
            {
                List<Cell> createdCells = new List<Cell>();

                //TODO [Stealth] Perform additional operations to obfuscate static =CHAR(#) signature
                foreach (char c in str)
                {
                    Stack<AbstractPtg> ptgStack = GetPtgStackForChar(c, packingMethod);

                    ushort charValue = Convert.ToUInt16(c);
                    if (charValue > 0xFF)
                    {
                        ptgStack = new Stack<AbstractPtg>();
                        ptgStack.Push(new PtgStr("" + c, true));
                    }
                    Cell curCell = new Cell(curRow, curCol, ixfe);
                    createdCells.Add(curCell);
                    Formula charFrm = new Formula(curCell, FormulaValue.GetEmptyStringFormulaValue(), true, new CellParsedFormula(ptgStack));
                    byte[] formulaBytes = charFrm.GetBytes();
                    formulaList.Add(charFrm);
                    curRow += 1;
                }

                Formula concatFormula = BuildConcatCellsFormula(createdCells, curRow, curCol);
                concatCells.Add(new Cell(curRow, curCol, ixfe));
                formulaList.Add(concatFormula);
                curRow += 1;
            }

            Formula concatConcatFormula = BuildConcatCellsFormula(concatCells, curRow, curCol);
            formulaList.Add(concatConcatFormula);
            curRow += 1;

            PtgRef srcCell = new PtgRef(curRow - 1, curCol, false, false, AbstractPtg.PtgDataType.VALUE);
            
            Random r = new Random();
            int randomBitStuffing = r.Next(1, 32) * 0x100;

            PtgRef destCell = new PtgRef(dstRw, dstCol + randomBitStuffing, false, false);

            Formula formula = GetFormulaInvocation(srcCell, destCell, curRow, curCol, packingMethod, instaEval);
            formulaList.Add(formula);

            return formulaList;
        }

19 View Source File : ArgumentParseHelper.cs
License : Apache License 2.0
Project Creator : alexyakunin

public static double ParseRelativeValue(string value, double defaultValue, bool negativeSubtractsFromDefault = false)
        {
            value = value?.Trim();
            if (string.IsNullOrEmpty(value))
                return defaultValue;

            var offset = 0.0;
            var unit = 1.0;
            if (value.EndsWith('%')) {
                value = value.Substring(0, value.Length - 1).Trim();
                unit = defaultValue / 100;
            }
            else if (value.EndsWith("pct")) {
                value = value.Substring(0, value.Length - 3).Trim();
                unit = defaultValue / 100;
            }
            else if (value.EndsWith("pts")) {
                value = value.Substring(0, value.Length - 3).Trim();
                unit = defaultValue / 1000;
            }
            if (value.StartsWith('-') && negativeSubtractsFromDefault) {
                offset = defaultValue;
            }
            return offset + double.Parse(value) * unit;
        }

19 View Source File : Parser.cs
License : MIT License
Project Creator : adamant

private static IEnumerable<GrammarRule> GetRules(List<string> lines)
        {
            var ruleLines = lines.Select(l => l.Trim())
                                 .Where(l => !l.StartsWith(Program.DirectiveMarker, StringComparison.InvariantCulture)
                                            && !l.StartsWith("//", StringComparison.InvariantCulture)
                                            && !string.IsNullOrWhiteSpace(l))
                                 .Select(l => l.TrimEnd(';')) // TODO error if no semicolon
                                 .ToList()!;
            foreach (var ruleLine in ruleLines)
            {
                var equalSplit = ruleLine.Split('=');
                if (equalSplit.Length > 2)
                    throw new FormatException($"Too many equal signs on line: '{ruleLine}'");
                var declaration = equalSplit[0];
                var (nonterminal, parents) = ParseDeclaration(declaration);
                var definition = equalSplit.Length == 2 ? equalSplit[1].Trim() : null;
                var properties = ParseDefinition(definition).ToList();
                if (properties.Select(p => p.Name).Distinct().Count() != properties.Count)
                    throw new FormatException($"Rule for {nonterminal} contains duplicate property definitions");

                yield return new GrammarRule(nonterminal, parents, properties);
            }
        }

19 View Source File : StanfordNLPClassifier.cs
License : MIT License
Project Creator : 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 View Source File : ConfigHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static int AddBatchServers(ref Config config, string clipboardData, string subid = "")
        {
            if (Utils.IsNullOrEmpty(clipboardData))
            {
                return -1;
            }
            //if (clipboardData.IndexOf("vmess") >= 0 && clipboardData.IndexOf("vmess") == clipboardData.LastIndexOf("vmess"))
            //{
            //    clipboardData = clipboardData.Replace("\r\n", "").Replace("\n", "");
            //}
            int countServers = 0;

            //string[] arrData = clipboardData.Split(new string[] { "\r\n" }, StringSplitOptions.None);
            string[] arrData = clipboardData.Split(Environment.NewLine.ToCharArray());
            foreach (string str in arrData)
            {
                //maybe sub
                if (str.StartsWith(Global.httpsProtocol) || str.StartsWith(Global.httpProtocol))
                {
                    if (AddSubItem(ref config, str) == 0)
                    {
                        countServers++;
                    }
                    continue;
                }
                VmessItem vmessItem = ShareHandler.ImportFromClipboardConfig(str, out string msg);
                if (vmessItem == null)
                {
                    continue;
                }
                vmessItem.subid = subid;
                if (vmessItem.configType == (int)EConfigType.Vmess)
                {
                    if (AddServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.Shadowsocks)
                {
                    if (AddShadowsocksServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.Socks)
                {
                    if (AddSocksServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.Trojan)
                {
                    if (AddTrojanServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
                else if (vmessItem.configType == (int)EConfigType.VLESS)
                {
                    if (AddVlessServer(ref config, vmessItem, -1, false) == 0)
                    {
                        countServers++;
                    }
                }
            }
            ToJsonFile(config);
            return countServers;
        }

19 View Source File : ConnectionString.cs
License : Apache License 2.0
Project Creator : aloneguid

private void Parse(string connectionString)
      {
         int idx = connectionString.IndexOf(PrefixSeparator);

         if(idx == -1)
         {
            Prefix = connectionString;
            return;
         }

         Prefix = connectionString.Substring(0, idx);
         connectionString = connectionString.Substring(idx + PrefixSeparator.Length);

         // prefix extracted, now get the parts of the string

         //check if this is a native connection string
         if(connectionString.StartsWith(KnownParameter.Native + "="))
         {
            _nativeConnectionString = connectionString.Substring(KnownParameter.Native.Length + 1);
            _parts[KnownParameter.Native] = _nativeConnectionString;
         }
         else
         {
            string[] parts = connectionString.Split(PartsSeparators, StringSplitOptions.RemoveEmptyEntries);
            foreach(string part in parts)
            {
               string[] kv = part.Split(PartSeparator, 2);

               string key = kv[0];
               string value = kv.Length == 1 ? string.Empty : kv[1];
               _parts[key] = value.UrlDecode();
            }
         }
      }

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

protected virtual void RegisterClientSideDependencies(Control control)
		{
			foreach (var script in ScriptIncludes)
			{
				if (string.IsNullOrWhiteSpace(script))
				{
					continue;
				}

				var scriptManager = ScriptManager.GetCurrent(control.Page);

				if (scriptManager == null)
				{
					continue;
				}

				var absolutePath = script.StartsWith("http", true, CultureInfo.InvariantCulture) ? script : VirtualPathUtility.ToAbsolute(script);

				scriptManager.Scripts.Add(new ScriptReference(absolutePath));
			}
		}

19 View Source File : LanguageParser.cs
License : MIT License
Project Creator : ABTSoftware

private void AppendCapturedStylesForRegexCapture(Capture regexCapture,
                                                         int currentIndex,
                                                         string styleName,
                                                         ICollection<Scope> capturedStyles)
        {
            if (styleName.StartsWith(ScopeName.LanguagePrefix))
            {
                string nestedGrammarId = styleName.Substring(1);
                AppendCapturedStylesForNestedLanguage(regexCapture, regexCapture.Index - currentIndex, nestedGrammarId, capturedStyles);
            }
            else
                capturedStyles.Add(new Scope(styleName, regexCapture.Index - currentIndex, regexCapture.Length));
        }

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

public void ReadTeapot(out string[] features, out uint token) {
            features = Dummy<string>.EmptyArray;
            token = 0;
            using StreamReader reader = new(TCPReaderStream, Encoding.UTF8, false, 1024, true);
            for (string line; !string.IsNullOrWhiteSpace(line = reader?.ReadLine() ?? "");) {
                if (line.StartsWith(CelesteNetUtils.HTTPTeapotConFeatures)) {
                    features = line.Substring(CelesteNetUtils.HTTPTeapotConFeatures.Length).Trim().Split(CelesteNetUtils.ConnectionFeatureSeparators);
                }
                if (line.StartsWith(CelesteNetUtils.HTTPTeapotConToken)) {
                    token = uint.Parse(line.Substring(CelesteNetUtils.HTTPTeapotConToken.Length).Trim());
                }
            }
        }

19 View Source File : ShareHandler.cs
License : GNU General Public License v3.0
Project Creator : 2dust

public static VmessItem ImportFromClipboardConfig(string clipboardData, out string msg)
        {
            msg = string.Empty;
            VmessItem vmessItem = new VmessItem();

            try
            {
                //载入配置文件 
                string result = clipboardData.TrimEx();// Utils.GetClipboardData();
                if (Utils.IsNullOrEmpty(result))
                {
                    msg = UIRes.I18N("FailedReadConfiguration");
                    return null;
                }

                if (result.StartsWith(Global.vmessProtocol))
                {
                    int indexSplit = result.IndexOf("?");
                    if (indexSplit > 0)
                    {
                        vmessItem = ResolveStdVmess(result) ?? ResolveVmess4Kitsunebi(result);
                    }
                    else
                    {
                        vmessItem.configType = (int)EConfigType.Vmess;
                        result = result.Substring(Global.vmessProtocol.Length);
                        result = Utils.Base64Decode(result);

                        //转成Json
                        VmessQRCode vmessQRCode = Utils.FromJson<VmessQRCode>(result);
                        if (vmessQRCode == null)
                        {
                            msg = UIRes.I18N("FailedConversionConfiguration");
                            return null;
                        }

                        vmessItem.network = Global.DefaultNetwork;
                        vmessItem.headerType = Global.None;

                        vmessItem.configVersion = Utils.ToInt(vmessQRCode.v);
                        vmessItem.remarks = Utils.ToString(vmessQRCode.ps);
                        vmessItem.address = Utils.ToString(vmessQRCode.add);
                        vmessItem.port = Utils.ToInt(vmessQRCode.port);
                        vmessItem.id = Utils.ToString(vmessQRCode.id);
                        vmessItem.alterId = Utils.ToInt(vmessQRCode.aid);
                        vmessItem.security = Utils.ToString(vmessQRCode.scy);

                        if (!Utils.IsNullOrEmpty(vmessQRCode.scy))
                        {
                            vmessItem.security = vmessQRCode.scy;
                        }
                        else
                        {
                            vmessItem.security = Global.DefaultSecurity;
                        }
                        if (!Utils.IsNullOrEmpty(vmessQRCode.net))
                        {
                            vmessItem.network = vmessQRCode.net;
                        }
                        if (!Utils.IsNullOrEmpty(vmessQRCode.type))
                        {
                            vmessItem.headerType = vmessQRCode.type;
                        }

                        vmessItem.requestHost = Utils.ToString(vmessQRCode.host);
                        vmessItem.path = Utils.ToString(vmessQRCode.path);
                        vmessItem.streamSecurity = Utils.ToString(vmessQRCode.tls);
                        vmessItem.sni = Utils.ToString(vmessQRCode.sni);
                    }

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else if (result.StartsWith(Global.ssProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem = ResolveSSLegacy(result);
                    if (vmessItem == null)
                    {
                        vmessItem = ResolveSip002(result);
                    }
                    if (vmessItem == null)
                    {
                        return null;
                    }
                    if (vmessItem.address.Length == 0 || vmessItem.port == 0 || vmessItem.security.Length == 0 || vmessItem.id.Length == 0)
                    {
                        return null;
                    }

                    vmessItem.configType = (int)EConfigType.Shadowsocks;
                }
                else if (result.StartsWith(Global.socksProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Socks;
                    result = result.Substring(Global.socksProtocol.Length);
                    //remark
                    int indexRemark = result.IndexOf("#");
                    if (indexRemark > 0)
                    {
                        try
                        {
                            vmessItem.remarks = Utils.UrlDecode(result.Substring(indexRemark + 1, result.Length - indexRemark - 1));
                        }
                        catch { }
                        result = result.Substring(0, indexRemark);
                    }
                    //part decode
                    int indexS = result.IndexOf("@");
                    if (indexS > 0)
                    {
                    }
                    else
                    {
                        result = Utils.Base64Decode(result);
                    }

                    string[] arr1 = result.Split('@');
                    if (arr1.Length != 2)
                    {
                        return null;
                    }
                    string[] arr21 = arr1[0].Split(':');
                    //string[] arr22 = arr1[1].Split(':');
                    int indexPort = arr1[1].LastIndexOf(":");
                    if (arr21.Length != 2 || indexPort < 0)
                    {
                        return null;
                    }
                    vmessItem.address = arr1[1].Substring(0, indexPort);
                    vmessItem.port = Utils.ToInt(arr1[1].Substring(indexPort + 1, arr1[1].Length - (indexPort + 1)));
                    vmessItem.security = arr21[0];
                    vmessItem.id = arr21[1];
                }
                else if (result.StartsWith(Global.trojanProtocol))
                {
                    msg = UIRes.I18N("ConfigurationFormatIncorrect");

                    vmessItem.configType = (int)EConfigType.Trojan;

                    Uri uri = new Uri(result);
                    vmessItem.address = uri.IdnHost;
                    vmessItem.port = uri.Port;
                    vmessItem.id = uri.UserInfo;

                    var qurery = HttpUtility.ParseQueryString(uri.Query);
                    vmessItem.sni = qurery["sni"] ?? "";

                    var remarks = uri.Fragment.Replace("#", "");
                    if (Utils.IsNullOrEmpty(remarks))
                    {
                        vmessItem.remarks = "NONE";
                    }
                    else
                    {
                        vmessItem.remarks = Utils.UrlDecode(remarks);
                    }
                }
                else if (result.StartsWith(Global.vlessProtocol))
                {
                    vmessItem = ResolveStdVLESS(result);

                    ConfigHandler.UpgradeServerVersion(ref vmessItem);
                }
                else
                {
                    msg = UIRes.I18N("NonvmessOrssProtocol");
                    return null;
                }
            }
            catch
            {
                msg = UIRes.I18N("Incorrectconfiguration");
                return null;
            }

            return vmessItem;
        }

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

private void BtnHentaiSettings_Click(object sender, EventArgs e)
        {
            foreach (Manga m in mangas)
            {
                if (File.Exists(m.mangaDirectory.FullName + "\\replacedle"))
                {
                    string replacedle = File.ReadAllText(m.mangaDirectory.FullName + "\\replacedle");
                    if (replacedle.StartsWith(lstHentai.SelectedItem.ToString().Split('»')[0].Trim()))
                    {
                        new FrmHentaiSettings(m).ShowDialog();
                        break;
                    }
                }
            }
            RefreshContents();
        }

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

private List<string> GetWorkerDiagnosticLogFiles(string diagnosticFolder, DateTime jobStartTimeUtc)
        {
            // Get all worker log files with a timestamp equal or greater than the start of the job
            var workerLogFiles = new List<string>();
            var directoryInfo = new DirectoryInfo(diagnosticFolder);

            // Sometimes the timing is off between the job start time and the time the worker log file is created.
            // This adds a small buffer that provides some leeway in case the worker log file was created slightly
            // before the time we log as job start time.
            int bufferInSeconds = -30;
            DateTime searchTimeUtc = jobStartTimeUtc.AddSeconds(bufferInSeconds);

            foreach (FileInfo file in directoryInfo.GetFiles().Where(f => f.Name.StartsWith(Constants.Path.WorkerDiagnosticLogPrefix)))
            {
                // The format of the logs is:
                // Worker_20171003-143110-utc.log
                DateTime fileCreateTime = DateTime.ParseExact(
                    s: file.Name.Substring(startIndex: Constants.Path.WorkerDiagnosticLogPrefix.Length, length: DateTimeFormat.Length),
                    format: DateTimeFormat,
                    provider: CultureInfo.InvariantCulture);

                if (fileCreateTime >= searchTimeUtc)
                {
                    workerLogFiles.Add(file.FullName);
                }
            }

            return workerLogFiles;
        }

19 View Source File : ModEntry.cs
License : GNU General Public License v3.0
Project Creator : aedenthorn

private static bool ResourceClump_performToolAction_prefix(ref ResourceClump __instance, Tool t, Vector2 tileLocation, GameLocation location, ref bool __result)
        {
            int indexOfClump = __instance.parentSheetIndex;
            if (indexOfClump >= 0)
            {
                return true;
            }
            CustomResourceClump clump = customClumps.FirstOrDefault(c => c.index == indexOfClump);
            if (clump == null)
                return true;

            if (t == null)
            {
                return false;
            }
            SMonitor.Log($"hitting custom clump {indexOfClump} with {t.GetType()} (should be {ToolTypes[clump.toolType]})");

            if (!CheckToolType(clump, t))
            {
                return false;
            } 
            SMonitor.Log($"tooltype is correct");
            if (t.upgradeLevel < clump.toolMinLevel)
            {
                foreach (string sound in clump.failSounds)
                    location.playSound(sound, NetAudio.SoundContext.Default);
                
                Game1.drawObjectDialogue(string.Format(SHelper.Translation.Get("failed"), t.DisplayName));

                Game1.player.jitterStrength = 1f;
                return false;
            }

            float power = Math.Max(1f, (float)(t.upgradeLevel + 1) * 0.75f);
            __instance.health.Value -= power;
            Game1.createRadialDebris(Game1.currentLocation, clump.debrisType, (int)tileLocation.X + Game1.random.Next(__instance.width / 2 + 1), (int)tileLocation.Y + Game1.random.Next(__instance.height / 2 + 1), Game1.random.Next(4, 9), false, -1, false, -1);

            if (__instance.health > 0f)
            {
                foreach (string sound in clump.hitSounds)
                    location.playSound(sound, NetAudio.SoundContext.Default);
                if (clump.shake != 0)
                {
                    SHelper.Reflection.GetField<float>(__instance, "shakeTimer").SetValue(clump.shake);
                    __instance.NeedsUpdate = true;
                }
                return false;
            }

            __result = true;

            foreach (string sound in clump.breakSounds)
                location.playSound(sound, NetAudio.SoundContext.Default);

            Farmer who = t.getLastFarmerToUse();

            int addedItems = who.professions.Contains(18) ? 1 : 0;
            int experience = 0;
            SMonitor.Log($"custom clump has {clump.dropItems.Count} potential items.");
            foreach (DropItem item in clump.dropItems)
            {
                if (Game1.random.NextDouble() < item.dropChance/100) 
                {
                    SMonitor.Log($"dropping item {item.itemIdOrName}");

                    if(!int.TryParse(item.itemIdOrName, out int itemId))
                    {
                        foreach(KeyValuePair<int,string> kvp in Game1.objectInformation)
                        {
                            if (kvp.Value.StartsWith(item.itemIdOrName + "/"))
                            {
                                itemId = kvp.Key;
                                break;
                            }
                        }
                    }
                    int amount = addedItems + Game1.random.Next(item.minAmount, Math.Max(item.minAmount + 1, item.maxAmount + 1)) + ((Game1.random.NextDouble() < (double)((float)who.LuckLevel / 100f)) ? item.luckyAmount : 0);
                    Game1.createMultipleObjectDebris(itemId, (int)tileLocation.X, (int)tileLocation.Y, amount, who.uniqueMultiplayerID, location);
                }
            }
            if (expTypes.ContainsKey(clump.expType))
            {
                experience = clump.exp;
                who.gainExperience(expTypes[clump.expType], experience);
            }
            else
            {
                SMonitor.Log($"Invalid experience type {clump.expType}", LogLevel.Warn);
            }
            return false;
        }

See More Examples