System.Text.RegularExpressions.Regex.Match(string, int, int)

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

1717 Examples 7

19 View Source File : MessageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void LoadAttachments()
        {
            bool hasMultipleImages = this.Message.Attachments.OfType<ImageAttachment>().Count() > 1;

            // Load GroupMe Image and Video Attachments
            foreach (var attachment in this.Message.Attachments)
            {
                if (attachment is ImageAttachment imageAttach)
                {
                    var displayMode = GroupMeImageAttachmentControlViewModel.GroupMeImageDisplayMode.Large;
                    if (hasMultipleImages && this.ShowPreviewsOnlyForMultiImages)
                    {
                        displayMode = GroupMeImageAttachmentControlViewModel.GroupMeImageDisplayMode.Preview;
                    }

                    var imageVm = new GroupMeImageAttachmentControlViewModel(imageAttach, this.Message.ImageDownloader, displayMode);
                    this.AttachedItems.Add(imageVm);

                    // Starting in 9/2019, GroupMe supports multiple images-per-message.
                }
                else if (attachment is LinkedImageAttachment linkedImage)
                {
                    var imageLinkVm = new ImageLinkAttachmentControlViewModel(linkedImage.Url, this.Message.ImageDownloader, this.Message.Text);
                    this.AttachedItems.Add(imageLinkVm);

                    // Linked Images can't have captions, so hide the entire body
                    this.HiddenText = this.Message.Text;

                    // Don't allow any other attachment types to be included if a linked_image is.
                    return;
                }
                else if (attachment is VideoAttachment videoAttach)
                {
                    var videoLinkedVm = new VideoAttachmentControlViewModel(videoAttach, this.Message.ImageDownloader);
                    this.AttachedItems.Add(videoLinkedVm);

                    // Videos can have captions, so only exclude the v.groupme url from the body
                    this.HiddenText = videoAttach.Url;

                    // Don't allow any other attachment types to be included if a video is.
                    return;
                }
                else if (attachment is FileAttachment fileAttach)
                {
                    var container = (IMessageContainer)this.Message.Group ?? (IMessageContainer)this.Message.Chat;
                    var doreplacedentVm = new FileAttachmentControlViewModel(fileAttach, container);
                    this.AttachedItems.Add(doreplacedentVm);

                    // Videos can have captions, so only exclude the share url from the body
                    if (this.Message.Text.Contains(" - Shared a doreplacedent"))
                    {
                        this.HiddenText = this.Message.Text.Substring(this.Message.Text.LastIndexOf(" - Shared a doreplacedent"));
                    }
                    else
                    {
                        this.HiddenText = this.Message.Text.Substring(this.Message.Text.LastIndexOf("Shared a doreplacedent"));
                    }

                    // Don't allow any other attachment types to be included if a video is.
                    return;
                }
            }

            // Load Link-Based Attachments (Tweets, Web Images, Websites, etc.)
            var text = this.Message.Text ?? string.Empty;
            if (text.Contains(" "))
            {
                // only look to see if the first chunk is a URL
                text = text.Substring(0, text.IndexOf(" "));
            }

            const string TwitterPrefixHttps = "https://twitter.com/";
            const string TwitterPrefixHttp = "http://twitter.com/";

            const string GroupMeImageRegexHttps = @"https:\/\/i.groupme.com\/[0-99999]*x[0-99999]*\..*";

            string[] imageExtensions = { "png", "jpg", "jpeg", "gif", "bmp" };

            const string WebPrefixHttps = "https://";
            const string WebPrefixHttp = "http://";

            LinkAttachmentBaseViewModel vm;

            var linkExtension = text.Split('.').LastOrDefault();

            if (text.StartsWith(TwitterPrefixHttps) || text.StartsWith(TwitterPrefixHttp))
            {
                vm = new TwitterAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (imageExtensions.Contains(linkExtension))
            {
                vm = new ImageLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (Regex.IsMatch(text, GroupMeImageRegexHttps))
            {
                var groupMeIUrl = Regex.Match(text, GroupMeImageRegexHttps).Value;
                vm = new ImageLinkAttachmentControlViewModel(groupMeIUrl, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (text.StartsWith(WebPrefixHttps) || text.StartsWith(WebPrefixHttp))
            {
                vm = new GenericLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else
            {
                return;
            }

            if (vm.Uri != null)
            {
                this.HiddenText = vm.Url;
            }
        }

19 View Source File : VariableController.cs
License : MIT License
Project Creator : alfa-laboratory

public object GetVariableValue(string key)
        {
            try
            {
                var name = key;
                var keyPath = string.Empty;
                var index = -1;
                string path = null;
                if (key.IndexOf('.') > 0)
                {
                    name = key.Substring(0, key.IndexOf('.'));
                    path = key.Substring(key.IndexOf('.') + 1);
                }

                if (name.IndexOf('[') > 0 && name.IndexOf(']') > name.IndexOf('['))
                {
                    if (!int.TryParse(key.Substring(name.IndexOf('[') + 1, Math.Max(0, name.IndexOf(']') - name.IndexOf('[') - 1)), out index))
                    {
                        index = -1;
                    }

                    name = key.Split('[').First();

                    keyPath = Regex.Match(key ?? string.Empty, StringPattern.BRACES, RegexOptions.None).Groups[1].Value;
                }

                var var = Variables.SingleOrDefault(_ => _.Key == name).Value;
                if (var == null)
                {
                    return null;
                }

                var varValue = var.Value;
                var varType = var.Type;

                if (varValue == null)
                {
                    return varType.GetDefault();
                }

                if (varType.HasElementType && index >= 0)
                {
                    var objArray = ((Array)varValue).Cast<object>().ToArray();
                    varValue = objArray[index];
                    varType = varType.GetElementType();
                }

                if (typeof(BsonDoreplacedent).IsreplacedignableFrom(varType))
                {
                    var json = JObject.Parse(((BsonDoreplacedent)varValue).ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.CanonicalExtendedJson }));
                    return json.SelectToken(path?.Remove(0, 2) ?? "/*") ?? varValue;
                }

                if (typeof(JObject).IsreplacedignableFrom(varType))
                {
                    var jsonObject = JObject.Parse(varValue.ToString());
                    return jsonObject.SelectToken(path?.Remove(0, 2) ?? "/*") ?? null;
                }

                if (typeof(JToken).IsreplacedignableFrom(varType))
                {
                    var jsonToken = JToken.Parse(varValue.ToString());
                    return jsonToken.SelectToken(path?.Remove(0, 2) ?? "/*") ?? null;
                }

                if (typeof(XNode).IsreplacedignableFrom(varType))
                {
                    return ((XNode)varValue).XPathSelectElement(path ?? "/*");
                }

                if (typeof(XmlNode).IsreplacedignableFrom(varType))
                {
                    return ((XmlNode)varValue).SelectSingleNode(path ?? "/*");
                }
                
                if (typeof(Dictionary<string, object>).IsreplacedignableFrom(varType))
                {
                    var objDict = ((Dictionary<string, object>)varValue);
                    return !string.IsNullOrWhiteSpace(keyPath) ? objDict[keyPath] : objDict;
                }

                if (typeof(ICollection).IsreplacedignableFrom(varType))
                {
                    var objList = ((IEnumerable)varValue).Cast<object>().ToList();
                    return index >= 0 ? objList[index] : objList;
                }
                
                try
                {
                    if (typeof(DataRow).IsreplacedignableFrom(varType))
                    {
                        if (keyPath == string.Empty)
                        {
                            return ((DataRow)varValue);
                        }
                        return int.TryParse(keyPath, out var id) ? ((DataRow)varValue).ItemArray[id]?.ToString() : ((DataRow)varValue)[keyPath].ToString();
                    }

                    if (!typeof(DataTable).IsreplacedignableFrom(varType))
                    {
                        return varValue;
                    }

                    if(!key.Contains("[") || !key.Contains("["))
                    {
                        return varValue;
                    }

                    if (!int.TryParse(key.Substring(key.IndexOf('[') + 1, key.IndexOf(']') - key.IndexOf('[') - 1), out index))
                    {
                        index = -1;
                    }

                    var row = ((DataTable)varValue).Rows[index];

                    var offset = key.IndexOf(']') + 1;

                    if (key.IndexOf('[', offset) < 0)
                    {
                        return row;
                    }

                    return int.TryParse(key.Substring(key.IndexOf('[', offset) + 1, key.IndexOf(']', offset) - key.IndexOf('[', offset) - 1), out index) ? row[index] : row[key.Substring(key.IndexOf('[', offset) + 1, key.IndexOf(']', offset) - key.IndexOf('[', offset) - 1)];
                }
                catch (IndexOutOfRangeException)
                {
                    Log.Logger().LogWarning($"Check the correctness of the key: \"{key}\"");
                    return null;
                }

            }catch (NullReferenceException)
            {
                Log.Logger().LogWarning($"Set NULL value in \"GetVariableValue\"/\"GetVariableValueText\"");
                return null;
            }
        }

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

protected override void OnInitialized()
        {
            Localizer.OnResourceReady = () => InvokeAsync(StateHasChanged);
            if (Value != null)
            {
                var timeSpan = TimeSpan.FromSeconds(Convert.ToInt32(Value));
                _token = new Token
                {
                    ValueString = timeSpan.ToString(DISPLAY_FORMAT)
                };
            }
            else
            {
                _token = new Token();
            }

            _token.PropertyChanged += (s, e) =>
            {
                if (_updatingValue)
                {
                    return;
                }

                var match = _regex.Match(_token.ValueString);
                if (!match.Success)
                {
                    return;
                }

                var groups = match.Groups;
                if (groups["DaysTime"].Success || groups["Time"].Success)
                {
                    var newTimeSpan = TimeSpan.Parse(_token.ValueString);
                    SetValue(newTimeSpan);
                }
                else if (groups["MinutesSecondes"].Success)
                {
                    var newTimeSpan = TimeSpan.Parse($"00:{_token.ValueString}");
                    SetValue(newTimeSpan);
                }
                else if (groups["Days"].Success)
                {
                    var newTimeSpan = TimeSpan.FromDays(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (groups["Hours"].Success)
                {
                    var newTimeSpan = TimeSpan.FromHours(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (groups["Minutes"].Success)
                {
                    var newTimeSpan = TimeSpan.FromMinutes(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else if (_token.ValueString.EndsWith("s"))
                {
                    var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString[0..^1]));
                    SetValue(newTimeSpan);
                }
                else
                {
                    var newTimeSpan = TimeSpan.FromSeconds(int.Parse(_token.ValueString));
                    SetValue(newTimeSpan);
                }
            };
            base.OnInitialized();
        }

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

protected IEnumerable< PortData > GetMaterialPortDatas(Material material)
		{
			if (material == null)
				yield break;

			var currentDimension = settings.GetResolvedTextureDimension(graph);

			var s = material.shader;
			for (int i = 0; i < material.shader.GetPropertyCount(); i++)
			{
				var flags = s.GetPropertyFlags(i);
				var name = s.GetPropertyName(i);
				var displayName = s.GetPropertyDescription(i);
				var type = s.GetPropertyType(i);
				var tooltip = s.GetPropertyAttributes(i).Where(s => s.Contains("Tooltip")).FirstOrDefault();

				// Inspector only properties aren't available as ports.
				if (displayName.ToLower().Contains("[inspector]"))
					continue;

				if (tooltip != null)
				{
					// Parse tooltip:
					var m = tooltipRegex.Match(tooltip);
					tooltip = m.Groups[1].Value;
				}

				if ((flags & ShaderPropertyFlags.HideInInspector) != 0
					|| (flags & ShaderPropertyFlags.NonModifiableTextureData) != 0
					|| (flags & ShaderPropertyFlags.PerRendererData) != 0)
					continue;
				
				if (!PropertySupportsDimension(s.GetPropertyName(i), currentDimension))
					continue;

				// We don't display textures specific to certain dimensions if the node isn't in this dimension.
				if (type == ShaderPropertyType.Texture)
				{
					bool is2D = displayName.EndsWith(MixtureUtils.texture2DPrefix);
					bool is3D = displayName.EndsWith(MixtureUtils.texture3DPrefix);
					bool isCube = displayName.EndsWith(MixtureUtils.textureCubePrefix);

					if (is2D || is3D || isCube)
					{
						if (currentDimension == TextureDimension.Tex2D && !is2D)
							continue;
						if (currentDimension == TextureDimension.Tex3D && !is3D)
							continue;
						if (currentDimension == TextureDimension.Cube && !isCube)
							continue;
						displayName = Regex.Replace(displayName, @"_2D|_3D|_Cube", "", RegexOptions.IgnoreCase);
					}
				}

				yield return new PortData{
					identifier = name,
					displayName = displayName,
					displayType = GetPropertyType(s, i),
					tooltip = tooltip,
				};
			}
		}

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

private async void OnLoaded(object sender, RoutedEventArgs e) {
            if (SteamMode)
                replacedle += " (SteamMode)";
            if (BundleMode)
                replacedle += " (SteamMode)";
            // Version Check
            try {
                var http = new HttpClient {
                    Timeout = TimeSpan.FromSeconds(2)
                };
                http.DefaultRequestHeaders.Add("User-Agent", "VisualGGPK2");
                var json = await http.GetStringAsync("https://api.github.com/repos/aianlinb/LibGGPK2/releases");
                var match = Regex.Match(json, "(?<=\"tag_name\":\"v).*?(?=\")");
                var currentVersion = replacedembly.GetEntryreplacedembly().GetName().Version;
                var versionText = $"{currentVersion.Major}.{currentVersion.Minor}.{currentVersion.Build}";
                if (match.Success && match.Value != versionText && MessageBox.Show(this, $"Found a new update on GitHub!\n\nCurrent Version: {versionText}\nLatest Version: {match.Value}\n\nDownload now?", "VisualGGPK2", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes) {
                    Process.Start(new ProcessStartInfo("https://github.com/aianlinb/LibGGPK2/releases") { UseShellExecute = true });
                    Close();
                    return;
                }
                http.Dispose();
            } catch { }

            // GGPK Selection
            if (FilePath == null) {
                var ofd = new OpenFileDialog {
                    DefaultExt = "ggpk",
                    FileName = SteamMode ? "_.index.bin" : "Content.ggpk",
                    Filter = SteamMode ? "Index Bundle File|*.index.bin" : "GGPK File|*.ggpk"
                };

                var setting = Properties.Settings.Default;
                if (setting.GGPKPath == "") {
                    setting.Upgrade();
                    setting.Save();
                }
                if (setting.GGPKPath == "") {
                    string path;
                    path = Registry.CurrentUser.OpenSubKey(@"Software\GrindingGearGames\Path of Exile")?.GetValue("InstallLocation") as string;
                    if (path != null && File.Exists(path + @"\Content.ggpk")) // Get POE path
                        ofd.InitialDirectory = path.TrimEnd('\\');
                } else
                    ofd.InitialDirectory = setting.GGPKPath;

                if (ofd.ShowDialog() == true) {
                    setting.GGPKPath = Directory.GetParent(FilePath = ofd.FileName).FullName;
                    setting.Save();
                } else {
                    Close();
                    return;
                }
            }

            // Initial GGPK
            await Task.Run(() => ggpkContainer = new GGPKContainer(FilePath, BundleMode, SteamMode));
            
            // Initial ContextMenu
            var mi = new MenuItem { Header = "Export" };
            mi.Click += OnExportClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Replace" };
            mi.Click += OnReplaceClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Recovery" };
            mi.Click += OnRecoveryClicked;
            TreeMenu.Items.Add(mi);
            mi = new MenuItem { Header = "Convert dds to png" };
            mi.Click += OnSavePngClicked;
            TreeMenu.Items.Add(mi);

            var imageMenu = new ContextMenu();
            mi = new MenuItem { Header = "Save as png" };
            mi.Click += OnSavePngClicked;
            imageMenu.Items.Add(mi);
            ImageView.ContextMenu = imageMenu;

            var root = CreateNode(ggpkContainer.rootDirectory);
            Tree.Items.Add(root); // Initial TreeView
            root.IsExpanded = true;

            FilterButton.IsEnabled = true;
            if (!SteamMode)
                AllowGameOpen.IsEnabled = true;

            // Mark the free spaces in data section of dat files
            DatReferenceDataTable.CellStyle = new Style(typeof(DataGridCell));
            DatReferenceDataTable.CellStyle.Setters.Add(new EventSetter(LoadedEvent, new RoutedEventHandler(OnCellLoaded)));

            // Make changes to DatContainer after editing DatTable
            DatTable.CellEditEnding += OnDatTableCellEdit;
            // Make changes to DatContainer after editing DatReferenceDataTable
            DatReferenceDataTable.CellEditEnding += OnDatReferenceDataTableCellEdit;

            TextView.AppendText("\r\n\r\nDone!\r\n");
        }

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

[Test]
        public void NoDllImport()
        {   
            var result = RunCecilifier("public clreplaced C { public extern int M(); int Call() => M(); }");
            var cecilifiedCode = result.GeneratedCode.ReadToEnd();

            var match = Regex.Match(cecilifiedCode, "var (?<methodVar>.+) = new MethodDefinition\\(\"M\"");
            replacedert.That(match.Success, Is.True);
            
            var methodVarName = match.Groups["methodVar"].Captures[0].Value;
            
            replacedert.That(methodVarName, Is.Not.Empty);
            replacedert.That(cecilifiedCode, Does.Not.Contains("new PInvokeInfo("));
            replacedert.That(cecilifiedCode, Does.Not.Contains($"{methodVarName}.Body")); 
        }

19 View Source File : TemplatePass.cs
License : MIT License
Project Creator : alexismorin

void FetchPreplacedName( int offsetIdx, string body )
		{
			Match match = Regex.Match( body, TemplateHelperFunctions.PreplacedNamePattern );
			if( match != null && match.Groups.Count > 1 )
			{
				m_preplacedNameContainer.Id = match.Groups[ 0 ].Value;
				m_preplacedNameContainer.Data = match.Groups[ 1 ].Value;
				m_preplacedNameContainer.Index = offsetIdx + match.Index;
			}
		}

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

private static void BuildHouseIdToGuid()
        {
            using (var ctx = new WorldDbContext())
            {
                var query = from weenie in ctx.Weenie
                            join inst in ctx.LandblockInstance on weenie.ClreplacedId equals inst.WeenieClreplacedId
                            where weenie.Type == (int)WeenieType.House
                            select new
                            {
                                Weenie = weenie,
                                Instance = inst
                            };

                var results = query.ToList();

                HouseIdToGuid = new Dictionary<uint, List<uint>>();

                foreach (var result in results)
                {
                    var clreplacedname = result.Weenie.ClreplacedName;
                    var guid = result.Instance.Guid;

                    if (!uint.TryParse(Regex.Match(clreplacedname, @"\d+").Value, out var houseId))
                    {
                        log.Error($"[HOUSE] HouseManager.BuildHouseIdToGuid(): couldn't parse {clreplacedname}");
                        continue;
                    }

                    if (!HouseIdToGuid.TryGetValue(houseId, out var houseGuids))
                    {
                        houseGuids = new List<uint>();
                        HouseIdToGuid.Add(houseId, houseGuids);
                    }
                    houseGuids.Add(guid);
                }
                //log.Info($"BuildHouseIdToGuid: {HouseIdToGuid.Count}");
            }
        }

19 View Source File : ContentNegotiationActionConstraint.cs
License : Apache License 2.0
Project Creator : alexz76

public bool Accept(ActionConstraintContext context)
        {
            var request = context.RouteContext.HttpContext.Request;
            request.Headers.TryGetValue("Content-Type", out var contentType);

            // TODO : Create a Content-Negotiation type discovery service and move it there
            var regex = new Regex(@";domain=(?<type>\w[.\w+]*)+");
            var results = regex.Match(contentType);

            if (results.Success)
            {
                var resourceType = results.Groups["type"].Value;
                return context.CurrentCandidate.Action.Parameters.Any(p => p.ParameterType.Name.Equals(resourceType, StringComparison.InvariantCultureIgnoreCase));
            }

            return false;
        }

private (string DacName, string FieldName) ParseMethodName(string methodName, EventType eventType)
		{
			var match = Regex.Match(methodName, @"([\w-[_]]+)_(\w+_){0,1}" + eventType,
				RegexOptions.CultureInvariant | RegexOptions.Singleline);

			if (match.Success)
			{
				string dacName = match.Groups[1].Value;
				string fieldName = match.Groups[2].Success ? match.Groups[2].Value.TrimEnd('_') : null;

				if (!String.IsNullOrEmpty(fieldName))
					fieldName = Char.ToLowerInvariant(fieldName[0]) + fieldName.Substring(1, fieldName.Length - 1);

				return (dacName, fieldName);
			}

			return (null, null);
		}

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

private async Task<IEnumerable<QueryResult>> QueryVideosPrivate(QueryResult query)
        {
            // Types of query:
            // == Video ==
            // 1. Video replacedle               Ed Sheeran - Perfect (Official Music Video)
            // 2. Full video URL            https://www.youtube.com/watch?v=2Vv-BfVoq4g
            // 3. Video ID                  2Vv-BfVoq4g
            //
            // == Playlist ==
            // 4. Full playlist video URL   https://www.youtube.com/watch?v=2Vv-BfVoq4g&list=PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG
            // 5. Full playlist URL         https://www.youtube.com/playlist?list=PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG
            // 6. Playlist ID               PLx0sYbCqOb8TBPRdmBHs5Iftvv9TPboYG

            // Query type 4
            {
                Match queryMatch = Regex.Match(query.Query, @"watch\?v=[^&]+.+list=(?<PlaylistId>[^&\n]+)");

                if (queryMatch.Success)
                {
                    return (await GetPlaylistVideos(queryMatch.Groups["PlaylistId"].Value)).Select(video => new QueryResult(query, video));
                }
            }

            SearchResource.ListRequest searchRequest = _youTubeApiService.Search.List("snippet");
            searchRequest.Q = query.Query;
            searchRequest.MaxResults = 1;

            SearchListResponse searchResponse = await searchRequest.ExecuteAsync();

            SearchResult result = searchResponse.Items.SingleOrDefault();

            if (result != null)
            {
                if (result.Id.Kind.Contains("video")) // Query types 1, 2, 3
                {
                    return new QueryResult(query, await GetVideo(result.Id.VideoId)).ToEnumerable();
                }

                if (result.Id.Kind.Contains("playlist")) // Query types 5, 6
                {
                    return (await GetPlaylistVideos(result.Id.PlaylistId)).Select(video => new QueryResult(query, video));
                }
            }

            // Invalid query (for the time being)
            return Enumerable.Empty<QueryResult>();
        }

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

public async Task<Dictionary<BaseGGUUID, BaseGGUUID>> GetVariantMapping(string path, OutfitsGenerator outfitsLogic)
        {
            var variantMapping = new Dictionary<BaseGGUUID, BaseGGUUID>();

            var models = outfitsLogic.GenerateModelList(f =>
                IoC.Archiver.LoadFile(path, f));
            foreach (var model in models)
            {
                var core = await IoC.Archiver.LoadFileAsync(path, model.Source);
                if (core == null) 
                    continue;

                if (!core.GetTypesById<HumanoidBodyVariant>().TryGetValue(model.Id, out var variant))
                    continue;

                var name = VariantNameMatcher.Match(variant.Name);
                if (name.Success)
                {
                    variantMapping.Add(model.Id, name.Groups["id"].Value);
                }
            }

            return variantMapping;
        }

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

private static UrlMappingResult<Enreplacedy> LookupPageByUrlPath(OrganizationServiceContext context, Enreplacedy website, string urlPath, Func<Enreplacedy, bool> predicate)
		{
			website.replacedertEnreplacedyName("adx_website");

			if (website.Id == Guid.Empty)
			{
				throw new ArgumentException(string.Format("Unable to retrieve the Id of the website. {0}", string.Empty), "website");
			}

			var urlWithoutWebsitePath = WebsitePathUtility.ToRelative(website, urlPath);

			if (!context.IsAttached(website))
			{
				context.ReAttach(website);
			}

			var pages = website.GetRelatedEnreplacedies(context, "adx_website_webpage").Where(predicate).ToArray();

			// Use _pagePathRegex to extract the right-most path segment (child path), and the remaining left
			// part of the path (parent path), while enforcing that web page paths must end in a '/'.
			var pathMatch = _pagePathRegex.Match(urlWithoutWebsitePath);

			if (!pathMatch.Success)
			{
				// If we don't have a valid path match, still see if there is a page with the entire literal
				// path as its partial URL. (The previous iteration of this method has this behaviour, so we
				// maintain it here.)
				return GetResultFromQuery(pages.Where(p => IsPartialUrlMatch(p, urlWithoutWebsitePath)));
			}

			var fullPath = pathMatch.Groups["full"].Value;
			var parentPath = pathMatch.Groups["parent"].Value;
			var childPath = pathMatch.Groups["child"].Value;

			// Check if we can find a page with the exact fullPath match. This may be a web page with a
			// partial URL that matches the entire path, but in the more common case, it will match the
			// root URL path "/".
			var fullPathMatchPageResult = GetResultFromQuery(pages.Where(p => IsPartialUrlMatch(p, fullPath)));

			if (fullPathMatchPageResult.Node != null)
			{
				return fullPathMatchPageResult;
			}

			// If we don't have non-empty parentPath and childPath, lookup fails.
			if (string.IsNullOrEmpty(parentPath) || string.IsNullOrEmpty(childPath))
			{
				return UrlMappingResult<Enreplacedy>.MatchResult(null);
			}

			// Look up the parent page, using the parent path. This will generally recurse until parentPath
			// is the root path "/", at which point fullPath will match the Home page and the recursion will
			// unwind.
			var parentPageFilterResult = LookupPageByUrlPath(context, website, parentPath, predicate);

			// If we can't find a parent page, lookup fails.
			if (parentPageFilterResult.Node == null)
			{
				return parentPageFilterResult;
			}

			// Look for a partial URL match for childPath, among the children of the returned parent page.
			var query = context.GetChildPages(parentPageFilterResult.Node).Where(p => predicate(p) && IsPartialUrlMatch(p, childPath));
			return GetResultFromQuery(query);
		}

19 View Source File : LocationProviderFactory.cs
License : MIT License
Project Creator : alen-smajic

[System.Diagnostics.Conditional("NOT_UNITY_EDITOR")]
		void InjectDeviceLocationProvider()
		{
			int AndroidApiVersion = 0;
			var regex = new Regex(@"(?<=API-)-?\d+");
			Match match = regex.Match(SystemInfo.operatingSystem); // eg 'Android OS 8.1.0 / API-27 (OPM2.171019.029/4657601)'
			if (match.Success) { int.TryParse(match.Groups[0].Value, out AndroidApiVersion); }
			Debug.LogFormat("{0} => API version: {1}", SystemInfo.operatingSystem, AndroidApiVersion);

			// only inject native provider if platform requirement is met
			// and script itself as well as parent game object are active
			if (Application.platform == RuntimePlatform.Android
				&& null != _deviceLocationProviderAndroid
				&& _deviceLocationProviderAndroid.enabled
				&& _deviceLocationProviderAndroid.transform.gameObject.activeInHierarchy
				// API version 24 => Android 7 (Nougat): we are using GnssStatus 'https://developer.android.com/reference/android/location/GnssStatus.html'
				// in the native plugin.
				// GnssStatus is not available with versions lower than 24
				&& AndroidApiVersion >= 24
			)
			{
				Debug.LogFormat("LocationProviderFactory: Injected native Android DEVICE Location Provider - {0}", _deviceLocationProviderAndroid.GetType());
				DefaultLocationProvider = _deviceLocationProviderAndroid;
			}
			else
			{
				Debug.LogFormat("LocationProviderFactory: Injected DEVICE Location Provider - {0}", _deviceLocationProviderUnity.GetType());
				DefaultLocationProvider = _deviceLocationProviderUnity;
			}
		}

19 View Source File : SimpleAnimationNodeEditor.cs
License : MIT License
Project Creator : aarthificial

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

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

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

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

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

19 View Source File : MessageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private void HandleLinkBasedAttachments()
        {
            // Load Link-Based Attachments (Tweets, Web Images, Websites, etc.)
            var text = this.Message.Text ?? string.Empty;
            if (text.IndexOf(" ") > 0)
            {
                // Use IndexOf instead of Contains to prevent issues with strange unicode characters.
                // only look to see if the first chunk is a URL
                text = text.Substring(0, text.IndexOf(" "));
            }

            const string TwitterPrefixHttps = "https://twitter.com/";
            const string TwitterPrefixHttp = "http://twitter.com/";

            const string GroupMeImageRegexHttps = @"https:\/\/i.groupme.com\/[0-99999]*x[0-99999]*\..*";

            string[] imageExtensions = { "png", "jpg", "jpeg", "gif", "bmp" };

            const string WebPrefixHttps = "https://";
            const string WebPrefixHttp = "http://";

            IHidesTextAttachment vm;

            var linkExtension = text.Split('.').LastOrDefault();

            if (text.StartsWith(TwitterPrefixHttps) || text.StartsWith(TwitterPrefixHttp))
            {
                vm = new TwitterAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (imageExtensions.Contains(linkExtension) && Uri.TryCreate(text, UriKind.Absolute, out var _))
            {
                vm = new ImageLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (Regex.IsMatch(text, GroupMeImageRegexHttps))
            {
                var groupMeIUrl = Regex.Match(text, GroupMeImageRegexHttps).Value;
                vm = new ImageLinkAttachmentControlViewModel(groupMeIUrl, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else if (text.StartsWith(WebPrefixHttps) || text.StartsWith(WebPrefixHttp))
            {
                vm = new GenericLinkAttachmentControlViewModel(text, this.Message.ImageDownloader);
                this.AttachedItems.Add(vm);
            }
            else
            {
                return;
            }

            if (!string.IsNullOrEmpty(vm.HiddenText))
            {
                this.HiddenText = vm.HiddenText + this.HiddenText;
            }
        }

19 View Source File : ComponentsBuilder.cs
License : MIT License
Project Creator : AgileoAutomation

private SoftwareComponent BuildComponent(Model model, ComponentSpecification spec)
        {
            List<replacedemblyPointer> componentPointers = new List<replacedemblyPointer>();
            List<SoftwareComponent> subcomponents = new List<SoftwareComponent>();

            foreach (ComponentSpecification subSpec in spec.Subcomponents)
            {
                SoftwareComponent subcomponent = BuildComponent(model, subSpec);
                if (subcomponent != null)
                    subcomponents.Add(subcomponent);
            }

            foreach (string replacedemblyname in spec.replacedemblies)
            {
                if (replacedemblyname.Contains("*"))
                {
                    Regex regex = new Regex(replacedemblyname);

                    foreach (replacedemblyPointer pointer in model.Allreplacedemblies().Where(x => regex.Match(x.GetName().Name).Success))
                    {
                        if (pointer.Component() == null)
                        {
                            componentPointers.Add(pointer);
                            pointer.AddProperty("Component", spec.Name);
                        }
                    }
                }
                else
                {
                    replacedemblyPointer pointer = model.FindPointerByName(replacedemblyname);
                    if (pointer != null && pointer.Component() == null)
                    {
                        componentPointers.Add(pointer);
                        pointer.AddProperty("Component", spec.Name);
                    }
                }
            }

            try
            {
                SoftwareComponent component = new SoftwareComponent(spec.Name, componentPointers, spec.Color, subcomponents);

                return component;
            }
            catch (ArgumentException e)
            {
                return null;
            }
        }

19 View Source File : TemplateSubShader.cs
License : MIT License
Project Creator : alexismorin

void FetchLOD( int offsetIdx, string body )
		{
			Match match = Regex.Match( body, TemplateHelperFunctions.SubShaderLODPattern );
			if( match != null && match.Groups.Count > 1 )
			{
				m_LODContainer.Id = match.Groups[ 0 ].Value;
				m_LODContainer.Data = match.Groups[ 1 ].Value;
				m_LODContainer.Index = offsetIdx + match.Index;
			}
		}

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

private Page[] SortPages(Page[] items)
        {
            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].num.ToString(), float_pattern).Value;
#pragma warning disable IDE0018 // Inline variable declaration
                double value;
#pragma warning restore IDE0018 // Inline variable declaration
                if (!double.TryParse(match, out value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

19 View Source File : TextWaitConditions.cs
License : MIT License
Project Creator : alfa-laboratory

public bool ToNotMatch(string regexPattern)
        {
            var regex = new Regex(regexPattern);
            return WaitFor(() => !regex.Match(_webelement.Text).Success);
        }

19 View Source File : TrjMediaProvider.cs
License : MIT License
Project Creator : aguang-xyz

public async Task<StreamInfo> GetStreamInfoAsync(Video video)
        {
            var html = await GetApi().GetPageAsync(video.ExternalId[1..]);
            var json = Regex.Match(html, @"player_aaaa\=\{[^}]+\}").Groups[0].Value[12..];
            var encodedUrl = JsonSerializer.Deserialize<Dictionary<string, object>>(json)!["url"].ToString();
            var src = HttpUtility.UrlDecode(Encoding.UTF8.GetString(Convert.FromBase64String(encodedUrl!)!));

            return new StreamInfo
            {
                Src = _proxyService.GetProxyUrl(src),
                Mime = "video/x-mpegurl",
                replacedle = video.replacedle
            };
        }

19 View Source File : CommandsNextUtilities.cs
License : MIT License
Project Creator : Aiko-IT-Systems

public static int GetMentionPrefixLength(this DiscordMessage msg, DiscordUser user)
        {
            var content = msg.Content;
            if (!content.StartsWith("<@"))
                return -1;

            var cni = content.IndexOf('>');
            if (cni == -1 || content.Length <= cni + 2)
                return -1;

            var cnp = content.Substring(0, cni + 2);
            var m = UserRegex.Match(cnp);
            if (!m.Success)
                return -1;

            var userId = ulong.Parse(m.Groups[1].Value, CultureInfo.InvariantCulture);
            return user.Id != userId ? -1 : m.Value.Length;
        }

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

public static Chapter[] SortChapters(List<Chapter> aList)
        {
            Chapter[] items = aList.ToArray();
            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].GetNum(), float_pattern).Value;
                if (!double.TryParse(match, out double value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

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

private UpdateManager CreateUpdater()
        {
            if (String.IsNullOrEmpty(IoC.Config.UpdatesRepo))
                throw new UpdateException("Update repo is null or empty");
            var repo = UpdateRepoMatcher.Match(IoC.Config.UpdatesRepo.Trim());
            if (!repo.Success)
                throw new UpdateException($"Update repo is not in the correct format: {IoC.Config.UpdatesRepo}");

            var meta = GetMetaData();

            var updater = new UpdateManager(
                meta,
                new GithubPackageResolver(repo.Groups["user"].Value, repo.Groups["repo"].Value, "*.zip"),
                new ReleaseExtractor());

            var updateDir = Path.GetFullPath(UpdateDir);


            //sketchy stuff
            SetPrivateField(updater, "_storageDirPath", updateDir);

            var updaterPath = GetPrivateField<string>(updater, "_updaterFilePath");
            updaterPath = Path.Combine(updateDir, Path.GetFileName(updaterPath));
            SetPrivateField(updater, "_updaterFilePath", updaterPath);

            var lockPath = GetPrivateField<string>(updater, "_lockFilePath");
            lockPath = Path.Combine(updateDir, Path.GetFileName(lockPath));
            SetPrivateField(updater, "_lockFilePath", lockPath);

            return updater;
        }

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

private static bool CheckSuppressionCommentOnNode(Diagnostic diagnostic, string diagnosticShortName, SyntaxNode node, CancellationToken cancellation)
		{
			cancellation.ThrowIfCancellationRequested();
			var successfulMatch = node?.GetLeadingTrivia()
									   .Where(x => x.IsKind(SyntaxKind.SingleLineCommentTrivia))
									   .Select(trivia => _suppressPattern.Match(trivia.ToString()))
									   .FirstOrDefault(match => match.Success &&
																diagnostic.Id == match.Groups[1].Value &&
																diagnosticShortName == match.Groups[2].Value);

			return successfulMatch != null;
		}

19 View Source File : SkillParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<SkillMetadata> Parse()
    {
        List<SkillMetadata> skillList = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            // Parsing Skills
            if (entry.Name.StartsWith("skill"))
            {
                XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
                XmlNode ui = doreplacedent.SelectSingleNode("/ms2/basic/ui");
                XmlNode kinds = doreplacedent.SelectSingleNode("/ms2/basic/kinds");
                XmlNode stateAttr = doreplacedent.SelectSingleNode("/ms2/basic/stateAttr");
                XmlNodeList levels = doreplacedent.SelectNodes("/ms2/level");

                int skillId = int.Parse(Path.GetFileNameWithoutExtension(entry.Name));
                string skillState = kinds.Attributes["state"]?.Value ?? "";
                byte skillAttackType = byte.Parse(ui.Attributes["attackType"]?.Value ?? "0");
                byte skillType = byte.Parse(kinds.Attributes["type"].Value);
                byte skillSubType = byte.Parse(kinds.Attributes["subType"]?.Value ?? "0");
                byte skillElement = byte.Parse(kinds.Attributes["element"].Value);
                byte skillSuperArmor = byte.Parse(stateAttr.Attributes["superArmor"].Value);
                bool skillRecovery = int.Parse(kinds.Attributes["spRecoverySkill"]?.Value ?? "0") == 1;

                List<SkillLevel> skillLevels = new();
                foreach (XmlNode level in levels)
                {
                    // Getting all skills level
                    string feature = level.Attributes["feature"]?.Value ?? "";
                    int levelValue = int.Parse(level.Attributes["value"].Value ?? "0");
                    // We prevent duplicates levels from older balances.
                    if (skillLevels.Exists(level => level.Level == levelValue))
                    {
                        continue;
                    }
                    int spirit = int.Parse(level.SelectSingleNode("consume/stat").Attributes["sp"]?.Value ?? "0");
                    int stamina = int.Parse(level.SelectSingleNode("consume/stat").Attributes["ep"]?.Value ?? "0");
                    float damageRate = float.Parse(level.SelectSingleNode("motion/attack/damageProperty")?.Attributes["rate"].Value ?? "0");
                    string sequenceName = level.SelectSingleNode("motion/motionProperty")?.Attributes["sequenceName"].Value ?? "";
                    string motionEffect = level.SelectSingleNode("motion/motionProperty")?.Attributes["motionEffect"].Value ?? "";

                    SkillUpgrade skillUpgrade = new();
                    if (level.SelectSingleNode("motion/upgrade")?.Attributes != null)
                    {
                        int upgradeLevel = int.Parse(level.SelectSingleNode("motion/upgrade").Attributes["level"].Value ?? "0");
                        int[] upgradeSkills = level.SelectSingleNode("motion/upgrade").Attributes["skillIDs"].Value.Split(",").Select(int.Parse).ToArray();
                        short[] upgradeSkillsLevel = level.SelectSingleNode("motion/upgrade").Attributes["skillLevels"].Value.Split(",").Select(short.Parse).ToArray();

                        skillUpgrade = new(upgradeLevel, upgradeSkills, upgradeSkillsLevel);
                    }

                    // Getting all Attack attr in each level.
                    List<SkillAttack> skillAttacks = new();
                    List<SkillCondition> skillConditions = new();

                    XmlNodeList conditionSkills = level.SelectNodes("motion/attack/conditionSkill") ?? level.SelectNodes("conditionSkill");
                    foreach (XmlNode conditionSkill in conditionSkills)
                    {
                        int conditionSkillId = int.Parse(conditionSkill.Attributes["skillID"]?.Value ?? "0");
                        short conditionSkillLevel = short.Parse(conditionSkill.Attributes["level"]?.Value ?? "0");
                        bool splash = conditionSkill.Attributes["splash"]?.Value == "1";
                        byte target = byte.Parse(conditionSkill.Attributes["skillTarget"].Value ?? "0");
                        byte owner = byte.Parse(conditionSkill.Attributes["skillOwner"]?.Value ?? "0");
                        SkillCondition skillCondition = new(conditionSkillId, conditionSkillLevel, splash, target, owner);

                        skillConditions.Add(skillCondition);
                    }

                    XmlNodeList attackListAttr = level.SelectNodes("motion/attack");
                    foreach (XmlNode attackAttr in attackListAttr)
                    {
                        // Many skills has a condition to proc another skill.
                        // We capture that as a list, since each Attack attr has one at least.
                        byte attackPoint = byte.Parse(Regex.Match(attackAttr.Attributes["point"]?.Value, @"\d").Value);
                        short targetCount = short.Parse(attackAttr.Attributes["targetCount"].Value);
                        long magicPathId = long.Parse(attackAttr.Attributes["magicPathID"]?.Value ?? "0");
                        long cubeMagicPathId = long.Parse(attackAttr.Attributes["cubeMagicPathID"]?.Value ?? "0");
                        SkillAttack skillAttack = new(attackPoint, targetCount, magicPathId, cubeMagicPathId);

                        skillAttacks.Add(skillAttack);
                    }

                    SkillMotion skillMotion = new(sequenceName, motionEffect);
                    SkillLevel skillLevel = new(levelValue, spirit, stamina, damageRate, feature, skillMotion, skillAttacks, skillConditions, skillUpgrade);
                    skillLevels.Add(skillLevel);
                }
                skillList.Add(new(skillId, skillLevels, skillState, skillAttackType, skillType, skillSubType, skillElement, skillSuperArmor, skillRecovery));
                continue;
            }

            // Parsing SubSkills
            if (entry.Name.StartsWith("table/job"))
            {
                XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
                XmlNodeList jobs = doreplacedent.SelectNodes("/ms2/job");
                foreach (XmlNode job in jobs)
                {
                    // Grabs all the skills and them the jobCode.
                    XmlNodeList skills = job.SelectNodes("skills/skill");
                    int jobCode = int.Parse(job.Attributes["code"].Value);
                    foreach (XmlNode skill in skills)
                    {
                        int id = int.Parse(skill.Attributes["main"].Value);
                        short maxLevel = short.Parse(skill.Attributes["maxLevel"]?.Value ?? "1");
                        skillList.Find(x => x.SkillId == id).Job = jobCode;
                        skillList.Find(x => x.SkillId == id).MaxLevel = maxLevel;

                        // If it has subSkill, add as well.
                        if (skill.Attributes["sub"] == null)
                        {
                            continue;
                        }

                        int[] sub = skill.Attributes["sub"].Value.Split(",").Select(int.Parse).ToArray();
                        skillList.Find(x => x.SkillId == id).SubSkills = sub;
                        for (int n = 0; n < sub.Length; n++)
                        {
                            if (skillList.Select(x => x.SkillId).Contains(sub[n]))
                            {
                                skillList.Find(x => x.SkillId == sub[n]).Job = jobCode;
                            }
                        }
                    }
                    XmlNodeList learnSkills = job.SelectNodes("learn/skill");
                    foreach (XmlNode learnSkill in learnSkills)
                    {
                        int id = int.Parse(learnSkill.Attributes["id"].Value);
                        skillList.Find(x => x.SkillId == id).CurrentLevel = 1;
                    }
                }
            }
        }

        // Parsing Additional Data
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("additionaleffect"))
            {
                continue;
            }

            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList levels = doreplacedent.SelectNodes("/ms2/level");
            int skillId = int.Parse(Path.GetFileNameWithoutExtension(entry.Name));

            List<SkillLevel> skillLevels = new();
            if (skillList.Select(x => x.SkillId).Contains(skillId))
            {
                foreach (XmlNode level in levels)
                {
                    int currentLevel = int.Parse(level.SelectSingleNode("BasicProperty").Attributes["level"]?.Value ?? "0");
                    skillLevels = skillList.Find(x => x.SkillId == skillId).SkillLevels;

                    if (skillLevels.Select(x => x.Level).Contains(currentLevel))
                    {
                        skillLevels.Find(x => x.Level == currentLevel).SkillAdditionalData = ParseSkillData(level);
                    }
                }
                continue;
            }

            // Adding missing skills from additionaleffect.
            // Since they are many skills that are called by another skill and not from player directly.
            foreach (XmlNode level in levels)
            {
                int currentLevel = int.Parse(level.SelectSingleNode("BasicProperty").Attributes["level"]?.Value ?? "0");
                skillLevels.Add(new(currentLevel, ParseSkillData(level)));
            }
            skillList.Add(new(skillId, skillLevels));

        }
        return skillList;
    }

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

public static bool GetMidiProgram(this Perform perform, out SevenBitNumber id, out string name)
    {
        id = SevenBitNumber.MinValue;
        if (perform.RowId == 0)
        {
            name = "None";
            return true;
        }

        Match match = MidiProgramRegex.Match(perform.Name);
        if (match.Success)
        {
            if (SevenBitNumber.TryParse(match.Groups[1].Value, out var GameId))
            {
                id = new SevenBitNumber((byte)(GameId - 1));
                name = match.Groups[2].Value;
                if (!string.IsNullOrWhiteSpace(name))
                    return true;
            }
        }

        name = "";
        return false;
    }

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

public override SiteMapNode FindSiteMapNode(string rawUrl)
		{
			TraceInfo("FindSiteMapNode({0})", rawUrl);

			var portal = PortalContext;
			var context = portal.ServiceContext;
			var website = portal.Website;

			var applicationPath = ApplicationPath.Parse(rawUrl);
			var path = new UrlBuilder(applicationPath.PartialPath).Path;

			// match on a regular webpage path followed by a thread Id segment

			const string pattern = @"(.+)/(\{?[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\}?)";
			var match = Regex.Match(path, pattern, RegexOptions.IgnoreCase);
			var isThreadUrl = match.Success && match.Groups.Count == 3;

			var forumPath = isThreadUrl
				? match.Groups[1].Value
				: path;

			var forum = FindForum(context, website, forumPath);

			if (forum == null)
			{
				return  null;
			}

			Enreplacedy foundThread = null;

			if (isThreadUrl)
			{
				var threadId = new Guid(match.Groups[2].Value);

				var forumThreads = context.CreateQuery("adx_communityforumthread")
					.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_forumid") == forum.ToEnreplacedyReference())
					.Where(e => e.GetAttributeValue<Guid>("adx_communityforumthreadid") == threadId);

				foundThread = forumThreads.FirstOrDefault();
			}

			if (foundThread == null)
			{
				return GetAccessibleNodeOrAccessDeniedNode(context, forum);
			}

			return GetAccessibleNodeOrAccessDeniedNode(context, foundThread);
		}

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

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

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

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

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

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

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

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

private Chapter[] SortChapters(Chapter[] items)
        {
            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].num.ToString(), float_pattern).Value;
#pragma warning disable IDE0018 // Inline variable declaration
                double value;
#pragma warning restore IDE0018 // Inline variable declaration
                if (!double.TryParse(match, out value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

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

protected bool MaterialPropertiesGUI(Material material, bool fromInspector, bool autoLabelWidth = true)
		{
			if (material == null || material.shader == null)
				return false;

			if (autoLabelWidth)
			{
				EditorGUIUtility.wideMode = false;
				EditorGUIUtility.labelWidth = nodeTarget.nodeWidth / 3.0f;
			}

			MaterialProperty[] properties = MaterialEditor.GetMaterialProperties(new []{material});
			var portViews = GetPortViewsFromFieldName(nameof(ShaderNode.materialInputs));

			MaterialEditor  editor;
			if (!materialEditors.TryGetValue(material, out editor))
			{
				foreach (var replacedembly in AppDomain.CurrentDomain.Getreplacedemblies())
				{
					var editorType = replacedembly.GetType("UnityEditor.MaterialEditor");
					if (editorType != null)
					{
						editor = materialEditors[material] = Editor.CreateEditor(material, editorType) as MaterialEditor;
						MixturePropertyDrawer.RegisterEditor(editor, this, owner.graph);
						break ;
					}
				}

			}

			bool propertiesChanged = CheckPropertyChanged(material, properties);

			foreach (var property in properties)
			{
				if ((property.flags & (MaterialProperty.PropFlags.HideInInspector | MaterialProperty.PropFlags.PerRendererData)) != 0)
					continue;

				int idx = material.shader.FindPropertyIndex(property.name);
				var propertyAttributes = material.shader.GetPropertyAttributes(idx);
				if (!fromInspector && propertyAttributes.Contains("ShowInInspector"))
					continue;

				// Retrieve the port view from the property name
				var portView = portViews?.FirstOrDefault(p => p.portData.identifier == property.name);
				if (portView != null && portView.connected)
					continue;
				
				// We only display textures that are excluded from the filteredOutProperties (i.e they are not exposed as ports)
				if (property.type == MaterialProperty.PropType.Texture && nodeTarget is ShaderNode sn)
				{
					if (!sn.GetFilterOutProperties().Contains(property.name))
						continue;
				}

				// TODO: cache to improve the performance of the UI
				var visibleIfAtribute = propertyAttributes.FirstOrDefault(s => s.Contains("VisibleIf"));
				if (!string.IsNullOrEmpty(visibleIfAtribute))
				{
					var match = visibleIfRegex.Match(visibleIfAtribute);
					if (match.Success)
					{
						string propertyName = match.Groups[1].Value;
						string[] accpectedValues = match.Groups[2].Value.Split(',');

						if (material.HasProperty(propertyName))
						{
							float f = material.GetFloat(propertyName);

							bool show = false;
							foreach (var value in accpectedValues)
							{
								float f2 = float.Parse(value);

								if (f == f2)
									show = true;
							}

							if (!show)
								continue;
						}
						else
							continue;
					}
				}

				// Hide all the properties that are not supported in the current dimension
				var currentDimension = nodeTarget.settings.GetResolvedTextureDimension(owner.graph);
				string displayName = property.displayName;

				bool is2D = displayName.Contains(MixtureUtils.texture2DPrefix);
				bool is3D = displayName.Contains(MixtureUtils.texture3DPrefix);
				bool isCube = displayName.Contains(MixtureUtils.textureCubePrefix);

				if (is2D || is3D || isCube)
				{
					if (currentDimension == TextureDimension.Tex2D && !is2D)
						continue;
					if (currentDimension == TextureDimension.Tex3D && !is3D)
						continue;
					if (currentDimension == TextureDimension.Cube && !isCube)
						continue;
					displayName = Regex.Replace(displayName, @"_2D|_3D|_Cube", "", RegexOptions.IgnoreCase);
				}

				// In ShaderGraph we can put [Inspector] in the name of the property to show it only in the inspector and not in the node
				if (property.displayName.ToLower().Contains("[inspector]"))
				{
					if (fromInspector)
						displayName = Regex.Replace(property.displayName, @"\[inspector\]\s*", "", RegexOptions.IgnoreCase);
					else
						continue;
				}

				float h = editor.GetPropertyHeight(property, displayName);

				// We always display textures on a single line without scale or offset because they are not supported
				if (property.type == MaterialProperty.PropType.Texture)
					h = EditorGUIUtility.singleLineHeight;

				Rect r = EditorGUILayout.GetControlRect(true, h);
				if (property.name.Contains("Vector2"))
					property.vectorValue = (Vector4)EditorGUI.Vector2Field(r, displayName, (Vector2)property.vectorValue);
				else if (property.name.Contains("Vector3"))
					property.vectorValue = (Vector4)EditorGUI.Vector3Field(r, displayName, (Vector3)property.vectorValue);
				else if (property.type == MaterialProperty.PropType.Range)
				{
					if (material.shader.GetPropertyAttributes(idx).Any(a => a.Contains("IntRange")))
						property.floatValue = EditorGUI.IntSlider(r, displayName, (int)property.floatValue, (int)property.rangeLimits.x, (int)property.rangeLimits.y);
					else
						property.floatValue = EditorGUI.Slider(r, displayName, property.floatValue, property.rangeLimits.x, property.rangeLimits.y);
				}
				else if (property.type == MaterialProperty.PropType.Texture)
					property.textureValue = (Texture)EditorGUI.ObjectField(r, displayName, property.textureValue, typeof(Texture), false);
				else
					editor.ShaderProperty(r, property, displayName);
			}

			return propertiesChanged;
		}

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

[Test] 
        public void TestEntryPoint()
        {   
            var result = RunCecilifier("using System.Runtime.InteropServices; public clreplaced C { [DllImport(\"Foo\", EntryPoint=\"NativeMethod\")] public static extern int M(); int Call() => M(); }");
            var cecilifiedCode = result.GeneratedCode.ReadToEnd();
            
            var match = Regex.Match(cecilifiedCode, "new PInvokeInfo\\(.+, \"NativeMethod\",.+\\);");
            replacedert.That(match.Success, Is.True, $"EntryPoint not propagated to PInvokeInfo constructor.{Environment.NewLine}{cecilifiedCode}");
        }

19 View Source File : PatreonCrawledUrlProcessor.cs
License : MIT License
Project Creator : AlexCSDev

public async Task<bool> ProcessCrawledUrl(ICrawledUrl udpCrawledUrl, string downloadDirectory)
        {
            PatreonCrawledUrl crawledUrl = (PatreonCrawledUrl)udpCrawledUrl;

            bool skipChecks = false; //skip sanitization, duplicate and other checks, do not preplaced filename to download path
            if (crawledUrl.Url.IndexOf("dropbox.com/", StringComparison.Ordinal) != -1)
            {
                if (!crawledUrl.Url.EndsWith("?dl=1"))
                {
                    if (crawledUrl.Url.EndsWith("?dl=0"))
                        crawledUrl.Url = crawledUrl.Url.Replace("?dl=0", "?dl=1");
                    else
                        crawledUrl.Url = $"{crawledUrl.Url}?dl=1";
                }

                _logger.Debug($"[{crawledUrl.PostId}] This is a dropbox entry: {crawledUrl.Url}");
            }
            else if (crawledUrl.Url.StartsWith("https://mega.nz/"))
            {
                _logger.Debug($"[{crawledUrl.PostId}] mega found: {crawledUrl.Url}");
                skipChecks = true; //mega plugin expects to see only path to the folder where everything will be saved
            }
            else if (_googleDriveRegex.Match(crawledUrl.Url).Success)
            {
                _logger.Debug($"[{crawledUrl.PostId}] google drive found: {crawledUrl.Url}");
                skipChecks = true; //no need for checks if we use google drive plugin
            }
            else if (crawledUrl.Url.IndexOf("youtube.com/watch?v=", StringComparison.Ordinal) != -1 ||
                     crawledUrl.Url.IndexOf("youtu.be/", StringComparison.Ordinal) != -1)
            {
                //TODO: YOUTUBE SUPPORT?
                _logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] YOUTUBE link found: {crawledUrl.Url}");
            }
            else if (crawledUrl.Url.IndexOf("imgur.com/", StringComparison.Ordinal) != -1)
            {
                //TODO: IMGUR SUPPORT
                _logger.Fatal($"[{crawledUrl.PostId}] [NOT SUPPORTED] IMGUR link found: {crawledUrl.Url}");
            }

            string filename = crawledUrl.Filename;

            if (!skipChecks)
            {
                if (!_patreonDownloaderSettings.UseSubDirectories)
                    filename = $"{crawledUrl.PostId}_";
                else
                    filename = "";

                switch (crawledUrl.UrlType)
                {
                    case PatreonCrawledUrlType.PostFile:
                        filename += "post";
                        break;
                    case PatreonCrawledUrlType.PostAttachment:
                        filename += "attachment";
                        break;
                    case PatreonCrawledUrlType.PostMedia:
                        filename += "media";
                        break;
                    case PatreonCrawledUrlType.AvatarFile:
                        filename += "avatar";
                        break;
                    case PatreonCrawledUrlType.CoverFile:
                        filename += "cover";
                        break;
                    case PatreonCrawledUrlType.ExternalUrl:
                        filename += "external";
                        break;
                    default:
                        throw new ArgumentException($"Invalid url type: {crawledUrl.UrlType}");
                }

                if (crawledUrl.Filename == null)
                {
                    _logger.Debug($"No filename for {crawledUrl.Url}, trying to retrieve...");
                    string remoteFilename =
                        await _remoteFilenameRetriever.RetrieveRemoteFileName(crawledUrl.Url);

                    if (remoteFilename == null)
                    {
                        throw new DownloadException(
                            $"[{crawledUrl.PostId}] Unable to retrieve name for external entry of type {crawledUrl.UrlType}: {crawledUrl.Url}");
                    }

                    filename += $"_{remoteFilename}";
                }
                else
                {
                    filename += $"_{crawledUrl.Filename}";
                }

                _logger.Debug($"Filename for {crawledUrl.Url} is {filename}");

                _logger.Debug($"Sanitizing filename: {filename}");
                filename = PathSanitizer.SanitizePath(filename);
                _logger.Debug($"Sanitized filename: {filename}");

                if (filename.Length > _patreonDownloaderSettings.MaxFilenameLength)
                {
                    _logger.Debug($"Filename is too long, will be truncated: {filename}");
                    string extension = Path.GetExtension(filename);
                    if (extension.Length > 4)
                    {
                        _logger.Warn($"File extension for file {filename} is longer 4 characters and won't be appended to truncated filename!");
                        extension = "";
                    }
                    filename = filename.Substring(0, _patreonDownloaderSettings.MaxFilenameLength) + extension;
                    _logger.Debug($"Truncated filename: {filename}");
                }

                string key = $"{crawledUrl.PostId}_{filename.ToLowerInvariant()}";
                if (!_fileCountDict.ContainsKey(key))
                    _fileCountDict.Add(key, 0);

                _fileCountDict[key]++;

                if (_fileCountDict[key] > 1)
                {
                    _logger.Warn($"Found more than a single file with the name {filename} in the same folder in post {crawledUrl.PostId}, sequential number will be appended to its name.");

                    string appendStr = _fileCountDict[key].ToString();

                    if (crawledUrl.UrlType != PatreonCrawledUrlType.ExternalUrl)
                    {
                        MatchCollection matches = _fileIdRegex.Matches(crawledUrl.Url);

                        if (matches.Count == 0)
                            throw new DownloadException($"[{crawledUrl.PostId}] Unable to retrieve file id for {crawledUrl.Url}, contact developer!");
                        if (matches.Count > 1)
                            throw new DownloadException($"[{crawledUrl.PostId}] More than 1 media found in URL {crawledUrl.Url}");

                        appendStr = matches[0].Groups[5].Value;
                    }

                    filename = $"{Path.GetFileNameWithoutExtension(filename)}_{appendStr}{Path.GetExtension(filename)}";
                }
            }

            if (_patreonDownloaderSettings.UseSubDirectories && 
                crawledUrl.UrlType != PatreonCrawledUrlType.AvatarFile &&
                crawledUrl.UrlType != PatreonCrawledUrlType.CoverFile)
                downloadDirectory = Path.Combine(downloadDirectory, PostSubdirectoryHelper.CreateNameFromPattern(crawledUrl, _patreonDownloaderSettings.SubDirectoryPattern));

            crawledUrl.DownloadPath = !skipChecks ? Path.Combine(downloadDirectory, filename) : downloadDirectory + Path.DirectorySeparatorChar;

            return true;
        }

19 View Source File : DbList.cs
License : MIT License
Project Creator : 2881099

[JSFunction]
        public void UpdateRow(string jsonStr)
        {
            Data.Clear();

            var enreplacedy = JsonConvert.DeserializeObject<DataBaseConfig>(jsonStr);


            if (string.IsNullOrEmpty(enreplacedy.ConnectionStrings))
            {
                #region 配置数据库连接串
                switch (enreplacedy.DataType)
                {
                    case FreeSql.DataType.MySql:
                        enreplacedy.ConnectionStrings = $"Data Source={enreplacedy.ServerIP};Port={enreplacedy.Port};User ID={enreplacedy.UserName};Preplacedword={enreplacedy.UserPreplaced};Initial Catalog={(string.IsNullOrEmpty(enreplacedy.DataBaseName) ? "mysql" : enreplacedy.DataBaseName)};Charset=utf8;SslMode=none;Max pool size=5";
                        break;
                    case FreeSql.DataType.SqlServer:
                        enreplacedy.ConnectionStrings = $"Data Source={enreplacedy.ServerIP},{enreplacedy.Port};Initial Catalog={enreplacedy.DataBaseName};User ID={enreplacedy.UserName};Preplacedword={enreplacedy.UserPreplaced};Pooling=true;Max Pool Size=5";
                        break;
                    case FreeSql.DataType.PostgreSQL:
                        enreplacedy.ConnectionStrings = $"Host={enreplacedy.ServerIP};Port={enreplacedy.Port};Username={enreplacedy.UserName};Preplacedword={enreplacedy.UserPreplaced};Database={(string.IsNullOrEmpty(enreplacedy.DataBaseName) ? "postgres" : enreplacedy.DataBaseName)};Pooling=true;Maximum Pool Size=5";
                        break;
                    case FreeSql.DataType.Oracle:
                        enreplacedy.ConnectionStrings = $"user id={enreplacedy.UserName};preplacedword={enreplacedy.UserPreplaced};data source=//{enreplacedy.ServerIP}:{enreplacedy.Port}/{enreplacedy.DataBaseName};Pooling=true;Max Pool Size=5";
                        break;
                }
                #endregion
            }
            else if (string.IsNullOrEmpty(enreplacedy.DataBaseName))
            {
                switch(enreplacedy.DataType)
                {
                    case FreeSql.DataType.Oracle:
                        enreplacedy.DataBaseName = Regex.Match(enreplacedy.ConnectionStrings, @"user id=([^;]+)", RegexOptions.IgnoreCase).Groups[1].Value;
                        break;
                    case FreeSql.DataType.MySql:
                        using (var conn = new MySql.Data.MySqlClient.MySqlConnection(enreplacedy.ConnectionStrings))
                        {
                            conn.Open();
                            enreplacedy.DataBaseName = conn.Database;
                            conn.Close();
                        }
                        break;
                    case FreeSql.DataType.SqlServer:
                        using (var conn = new System.Data.SqlClient.SqlConnection(enreplacedy.ConnectionStrings))
                        {
                            conn.Open();
                            enreplacedy.DataBaseName = conn.Database;
                            conn.Close();
                        }
                        break;
                    case FreeSql.DataType.PostgreSQL:
                        using (var conn = new Npgsql.NpgsqlConnection(enreplacedy.ConnectionStrings))
                        {
                            conn.Open();
                            enreplacedy.DataBaseName = conn.Database;
                            conn.Close();
                        }
                        break;
                }
            }

            Curd.DataBase.InsertOrUpdate(enreplacedy);
            var _list = Curd.DataBase.Select.ToList();
            Data.AddRange(_list);
            Data.SaveChanges();





            //InvokeJS("page.$confirm('添加完成, 是否继续?', '提示', {confirmButtonText: '确定',cancelButtonText: '取消',type: 'warning'})");
        }

19 View Source File : MessageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private (string replyId, bool isGroupMeNative) CheckReplyStatus()
        {
            var repliedMessageId = string.Empty;
            var isGroupMeNativeReply = false;

            if (MessageUtils.IsReplyGen1(this.Message))
            {
                // Method 1, where /rmid:<message-id> is appended to the end of the message body
                var token = Regex.Match(this.Message.Text, MessageUtils.RepliedMessageRegex).Value;
                this.HiddenText = token + this.HiddenText;
                repliedMessageId = token.Replace("\n/rmid:", string.Empty);
            }
            else if (MessageUtils.IsReplyGen2(this.Message))
            {
                // Method 2, where gmdc-r<message-id> is included as the prefix of the message GUID
                var parts = this.Message.SourceGuid.Split('-');
                repliedMessageId = parts[1].Substring(1);
            }
            else if (this.Message.Attachments.OfType<ReplyAttachment>().Count() > 0)
            {
                // GroupMe native reply, added in 10/2020.
                var replyAttach = this.Message.Attachments.OfType<ReplyAttachment>().First();
                repliedMessageId = replyAttach.RepliedMessageId;
                isGroupMeNativeReply = true;
            }

            return (replyId: repliedMessageId, isGroupMeNative: isGroupMeNativeReply);
        }

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

public static void Layer_Draw_Postfix(Layer __instance)
        {
            if (!config.EnableMod || Regex.IsMatch(__instance.Id, "[0-9]$"))
                return;

            foreach (Layer layer in Game1.currentLocation.Map.Layers)
            {
                Match match = Regex.Match(layer.Id, $"^{__instance.Id}([0-9]+)$");
                if (match.Success)
                {
                    thisLayerDepth = int.Parse(match.Groups[1].Value);
                    layer.Draw(Game1.mapDisplayDevice, Game1.viewport, Location.Origin, false, 4);
                    thisLayerDepth = 0;
                }
            }
        }

19 View Source File : MessageControlViewModel.cs
License : GNU General Public License v3.0
Project Creator : alexdillon

private List<Inline> ProcessHyperlinks(Run run)
        {
            var result = new List<Inline>();
            var text = run.Text;

            while (true)
            {
                if (!Regex.IsMatch(text, RegexUtils.UrlRegex))
                {
                    // no URLs contained
                    result.Add(new Run(text));
                    break;
                }
                else
                {
                    // url is contained in the input string
                    var match = Regex.Match(text, Utilities.RegexUtils.UrlRegex);

                    if (match.Index > 0)
                    {
                        // convert the leading text to a Run
                        result.Add(new Run(text.Substring(0, match.Index)));
                    }

                    try
                    {
                        var navigableUrl = match.Value;

                        if (navigableUrl.EndsWith("))"))
                        {
                            // URLs almost never end in )). This is typically a case where an entire URL containing a ) is wrapped in parenthesis.
                            // Trim the closing parenthesis.
                            navigableUrl = navigableUrl.Substring(0, navigableUrl.Length - 1);

                            result.Add(this.MakeHyperLink(navigableUrl));
                            result.Add(new Run(")"));
                        }
                        else if (navigableUrl.EndsWith(")") && !navigableUrl.Contains("("))
                        {
                            // It's extremely uncommon for a URL to contain a ) without a matching (.
                            // This is most likely caused by the entire URL being contained in parenthesis, and should be stripped.
                            navigableUrl = navigableUrl.Substring(0, navigableUrl.Length - 1);

                            result.Add(this.MakeHyperLink(navigableUrl));
                            result.Add(new Run(")"));
                        }
                        else
                        {
                            // Normal URL with no strange parenthesis to handle
                            result.Add(this.MakeHyperLink(navigableUrl));
                        }
                    }
                    catch (Exception)
                    {
                        // Some super strange URLs preplaced the regex, but fail
                        // to decode correctly. Ignore if this happens.
                        result.Add(new Run(match.Value));
                    }

                    // Keep looping over the rest of the string.
                    text = text.Substring(match.Index + match.Length);
                }
            }

            return result;
        }

19 View Source File : LinkElementGenerator.cs
License : MIT License
Project Creator : Abdesol

Match GetMatch(int startOffset, out int matchOffset)
		{
			int endOffset = CurrentContext.VisualLine.LastDoreplacedentLine.EndOffset;
			StringSegment relevantText = CurrentContext.GetText(startOffset, endOffset - startOffset);
			Match m = linkRegex.Match(relevantText.Text, relevantText.Offset, relevantText.Count);
			matchOffset = m.Success ? m.Index - relevantText.Offset + startOffset : -1;
			return m;
		}

19 View Source File : TemplatePass.cs
License : MIT License
Project Creator : alexismorin

void FetchCodeAreas( int offsetIdx, string begin, MasterNodePortCategory category, string body )
		{
			int areaBeginIndexes = body.IndexOf( begin );
			if( areaBeginIndexes > -1 )
			{
				int beginIdx = areaBeginIndexes + begin.Length;
				int endIdx = body.IndexOf( TemplatesManager.TemplateEndOfLine, beginIdx );
				int length = endIdx - beginIdx;

				string parameters = body.Substring( beginIdx, length );

				string[] parametersArr = parameters.Split( IOUtils.FIELD_SEPARATOR );

				string id = body.Substring( areaBeginIndexes, endIdx + TemplatesManager.TemplateEndOfLine.Length - areaBeginIndexes );
				string inParameters = parametersArr[ 0 ];
				string outParameters = ( parametersArr.Length > 1 ) ? parametersArr[ 1 ] : string.Empty;
				if( category == MasterNodePortCategory.Fragment )
				{
					string mainBodyName = string.Empty;
					int mainBodyLocalIndex = -1;

					Match mainBodyNameMatch = Regex.Match( body, TemplateHelperFunctions.FragmentPragmaPattern );
					if( mainBodyNameMatch != null && mainBodyNameMatch.Groups.Count == 2 )
					{
						mainBodyName = mainBodyNameMatch.Groups[ 1 ].Value;
						string pattern = string.Format( TemplateHelperFunctions.FunctionBodyStartPattern, mainBodyName );
						Match mainBodyIdMatch = Regex.Match( body, pattern );
						if( mainBodyIdMatch != null && mainBodyIdMatch.Groups.Count > 0 )
						{
							mainBodyLocalIndex = mainBodyIdMatch.Index;
						}

					}

					m_fragmentFunctionData = new TemplateFunctionData( mainBodyLocalIndex, mainBodyName, id, offsetIdx + areaBeginIndexes, inParameters, outParameters, category );
				}
				else
				{
					string mainBodyName = string.Empty;
					int mainBodyLocalIndex = -1;

					Match mainBodyNameMatch = Regex.Match( body, TemplateHelperFunctions.VertexPragmaPattern );
					if( mainBodyNameMatch != null && mainBodyNameMatch.Groups.Count == 2 )
					{
						mainBodyName = mainBodyNameMatch.Groups[ 1 ].Value;
						string pattern = string.Format( TemplateHelperFunctions.FunctionBodyStartPattern, mainBodyName );
						Match mainBodyIdMatch = Regex.Match( body, pattern );
						if( mainBodyIdMatch != null && mainBodyIdMatch.Groups.Count > 0 )
						{
							mainBodyLocalIndex = mainBodyIdMatch.Index;
						}
					}

					m_vertexFunctionData = new TemplateFunctionData( mainBodyLocalIndex, mainBodyName, id, offsetIdx + areaBeginIndexes, inParameters, outParameters, category );
				}
				m_templateProperties.AddId( body, id, true );
			}
		}

19 View Source File : Model.cs
License : MIT License
Project Creator : AgileoAutomation

private IEnumerable<replacedemblyName> GetFilteredReferencedreplacedemblies(replacedemblyPointer from)
        {
            return from
                .GetReferencedreplacedemblies()
                .Where(x => !filterRegexList
                                .Any(y => y.Match(x.Name).Success));
        }

19 View Source File : DatePattern.cs
License : MIT License
Project Creator : alexleen

public override bool TryValidate(IMessageBoxService messageBoxService)
        {
            if (string.IsNullOrEmpty(Value))
            {
                messageBoxService.ShowError("A valid date pattern must be replacedigned.");
                return false;
            }

            //https://stackoverflow.com/questions/62771/how-do-i-check-if-a-given-string-is-a-legal-valid-file-name-under-windows#comment52147867_62888
            Regex unspupportedRegex = new Regex("(^(PRN|AUX|NUL|CON|COM[1-9]|LPT[1-9]|(\\.+)$)(\\..*)?$)|(([\\x00-\\x1f\\\\?*:\";‌​|/<>])+)|([\\. ]+)", RegexOptions.IgnoreCase);

            Match m = unspupportedRegex.Match(Value);

            if (m.Success)
            {
                messageBoxService.ShowError($"Date pattern must not contain invalid characters: '{m.Value}'");
                return false;
            }

            return base.TryValidate(messageBoxService);
        }

19 View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744

private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dbParameters = new List<IDbDataParameter>();
            cmd.Transaction = _transaction;
            cmd.CommandText = sql;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (parameter is IDbDataParameter)
            {
                dbParameters.Add(parameter as IDbDataParameter);
            }
            else if (parameter is IEnumerable<IDbDataParameter> parameters)
            {
                dbParameters.AddRange(parameters);
            }
            else if (parameter is Dictionary<string, object> keyValues)
            {
                foreach (var item in keyValues)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            else if (parameter != null)
            {
                var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
                var values = handler(parameter);
                foreach (var item in values)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            if (dbParameters.Count > 0)
            {
                foreach (IDataParameter item in dbParameters)
                {
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    var pattern = [email protected]"in\s+([\@,\:,\?]?{item.ParameterName})";
                    var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
                    if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
                    {
                        var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
                        var list = new List<object>();
                        if (item.Value is IEnumerable<object> || item.Value is Array)
                        {
                            list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
                        }
                        else
                        {
                            list.Add(item.Value);
                        }
                        if (list.Count() > 0)
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
                            foreach (var iitem in list)
                            {
                                var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
                                var param = CreateParameter(cmd, key, iitem);
                                cmd.Parameters.Add(param);
                            }
                        }
                        else
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(item);
                    }
                }
            }
            if (Logging != null)
            {
                var parameters = new Dictionary<string, object>();
                foreach (IDbDataParameter item in cmd.Parameters)
                {
                    parameters.Add(item.ParameterName, item.Value);
                }
                Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
            }
        }

19 View Source File : TextWaitConditions.cs
License : MIT License
Project Creator : alfa-laboratory

public bool ToMatch(string regexPattern)
        {
            var regex = new Regex(regexPattern);
            return WaitFor(() => regex.Match(_webelement.Text).Success);
        }

19 View Source File : M3U8Downloader.cs
License : MIT License
Project Creator : aguang-xyz

public async Task DownloadAsync(Uri uri, string fileName)
        {
            using var client = new HttpClient();
            var content = await client.GetStringAsync(uri);
            
            var lines = content
                .AsLines()
                .Select(line =>
                {
                    if (string.IsNullOrWhiteSpace(line))
                    {
                        return line;
                    }

                    // Media encryption key may contain URI, see RFC8216 for more details.
                    // Link: https://datatracker.ietf.org/doc/html/rfc8216#section-4.3.2.4
                    if (line.StartsWith("#EXT-X-KEY:"))
                    {
                        var match = Regex.Match(line, "URI=\"([^\"]+)\"");

                        // Replace URI field if exists.
                        if (match.Groups.Count == 2)
                        {
                            var replacingUri = match.Groups[1].Value;
                            
                            string replacedUri;
                            if (replacingUri.StartsWith("http:") || replacingUri.StartsWith("https:"))
                            {
                                replacedUri = replacingUri;
                            }
                            else
                            {
                                replacedUri = new Uri(uri, replacingUri).ToString();
                            }

                            line = line.Replace(replacingUri,  ProxyService.GetProxyUrl(replacedUri));
                        }
                        
                        return line;
                    }

                    if (line.StartsWith("#"))
                    {
                        return line;
                    }

                    if (!line.StartsWith("http:") && !line.StartsWith("https:"))
                    {
                        line = new Uri(uri, line).ToString();
                    }

                    return ProxyService.GetProxyUrl(line);
                });

            await File.WriteAllLinesAsync(fileName, lines);
        }

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

public void ExtractTableData(string outPath, string dateTimeFormat)
        {
            Directory.CreateDirectory(outPath);
            
            foreach (var table in GetTableNames())
            {
                var path = Path.Combine(outPath, $"{table}.csv");

                Log.Debug("Extracting table {Table} to file: {Path}", table, path);

                using (var outFile = File.CreateText(path))
                using (var csv = new CsvWriter(outFile, CultureInfo.CurrentCulture))
                using (var cmd = _connection.CreateCommand())
                {
                    csv.Context.TypeConverterOptionsCache.GetOptions<DateTime>().Formats = new[] { dateTimeFormat };

                    cmd.CommandText = $"EVALUATE '{table}'";

                    try
                    {
                        using (var reader = cmd.ExecuteReader())
                        {
                            // Header
                            for (int i = 0; i < reader.FieldCount; i++)
                            {
                                var column = colNameRegex.Match(reader.GetName(i)).Groups[2].Value ?? reader.GetName(i);
                                csv.WriteField(column);
                            }
                
                            // Data
                            var recordsRead = 0;
                            while (reader.Read())
                            {
                                csv.NextRecord();
                                for (int i = 0; i < reader.FieldCount; i++)
                                {
                                    csv.WriteField(reader.GetValue(i));
                                }
                                recordsRead++;
                            }

                            Log.Information("Extracted {RecordCount} records from table {Table}", recordsRead, table);
                        }
                    }
                    catch (AdomdErrorResponseException ex)
                    {
                        Log.Debug(ex, "An error occurred reading from table {Table}", table);
                    }
                }

            }
        }

19 View Source File : ResponseExtensions.cs
License : Apache License 2.0
Project Creator : 0xFireball

public static Response FromPartialStream(this IResponseFormatter response, Request request, Stream stream,
            string contentType)
        {
            // Store the len
            var len = stream.Length;
            // Create the response now
            var res = response.FromStream(stream, contentType)
                .WithHeader("Connection", "Keep-alive")
                .WithHeader("Accept-ranges", "Bytes");
            // Use the partial status code
            res.StatusCode = HttpStatusCode.PartialContent;
            long startPos = 0;
            foreach (var s in request.Headers["Range"])
            {
                var start = s.Split('=')[1];
                var m = Regex.Match(start, @"(\d+)-(\d+)?");
                start = m.Groups[1].Value;
                var end = len - 1;
                if (!string.IsNullOrWhiteSpace(m.Groups[2]?.Value))
                {
                    end = Convert.ToInt64(m.Groups[2].Value);
                }

                startPos = Convert.ToInt64(start);
                var length = len - startPos;
                res.WithHeader("Content-range", "Bytes " + start + "-" + end + "/" + len);
                res.WithHeader("Content-length", length.ToString(CultureInfo.InvariantCulture));
            }
            stream.Seek(startPos, SeekOrigin.Begin);
            return res;
        }

19 View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : 2881099

void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
			if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
			var files = Directory.GetFiles(templateDirectory);
			foreach (var file in files) {
				var fi = new FileInfo(file);
				if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
					var outputExtension = "." + fi.Name.Split('.')[1];
					if (fi.Name.StartsWith("for-table.")) {
						foreach (var table in tables) {
							var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
							if (result.EndsWith("return;")) continue;
							var outputName = table.Name + outputExtension;
							var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
							if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
							var outputStream = Encoding.UTF8.GetBytes(result);
							var fullname = outputDirectory + "/" + outputName;
							if (File.Exists(fullname)) File.Delete(fullname);
							using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
								outfs.Write(outputStream, 0, outputStream.Length);
								outfs.Close();
							}
						}
						continue;
					} else {
						var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
						var outputName = fi.Name;
						var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
						if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
						var outputStream = Encoding.UTF8.GetBytes(result);
						var fullname = outputDirectory + "/" + outputName;
						if (File.Exists(fullname)) File.Delete(fullname);
						using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
							outfs.Write(outputStream, 0, outputStream.Length);
							outfs.Close();
						}
					}
				}
				File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
			}
			var dirs = Directory.GetDirectories(templateDirectory);
			foreach(var dir in dirs) {
				BuildEachDirectory(dir, outputDirectory +  dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
			}
		}

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

public static Page[] SortPages(List<Page> aList)
        {
            Page[] items = aList.ToArray();

            // Get the numeric values of the items.
            int num_items = items.Length;
            const string float_pattern = @"-?\d+\.?\d*";
            double[] values = new double[num_items];
            for (int i = 0; i < num_items; i++)
            {
                string match = Regex.Match(items[i].GetID(), float_pattern).Value;
                if (!double.TryParse(match, out double value))
                    value = double.MinValue;
                values[i] = value;
            }

            // Sort the items array using the keys to determine order.
            Array.Sort(values, items);
            return items;
        }

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

public static string CurrentSort(string sortExpression, string attribute)
		{
			if (string.IsNullOrEmpty(sortExpression) || string.IsNullOrEmpty(attribute))
			{
				return null;
			}

			var match = Regex.Match(sortExpression, "{0} (?<direction>ASC|DESC)".FormatWith(attribute), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);

			return match.Success ? match.Groups["direction"].Value.ToUpperInvariant() : null;
		}

19 View Source File : ItemGemstoneUpgradeParser.cs
License : GNU General Public License v3.0
Project Creator : AlanMorel

protected override List<ItemGemstoneUpgradeMetadata> Parse()
    {
        List<ItemGemstoneUpgradeMetadata> gems = new();
        foreach (PackFileEntry entry in Resources.XmlReader.Files)
        {
            if (!entry.Name.StartsWith("table/na/itemgemstoneupgrade"))
            {
                continue;
            }

            // Parse XML
            XmlDoreplacedent doreplacedent = Resources.XmlReader.GetXmlDoreplacedent(entry);
            XmlNodeList keys = doreplacedent.SelectNodes("/ms2/key");

            foreach (XmlNode key in keys)
            {
                ItemGemstoneUpgradeMetadata metadata = new();
                metadata.ItemId = int.Parse(key.Attributes["ItemId"].Value);
                metadata.GemLevel = byte.Parse(key.Attributes["GemLevel"].Value);
                _ = int.TryParse(key.Attributes["NexreplacedemID"]?.Value ?? "0", out metadata.NexreplacedemId);

                for (int i = 1; i < 5; i++)
                {
                    if (key.Attributes["IngredienreplacedemID" + i.ToString()] != null)
                    {
                        metadata.Ingredienreplacedems.Add(Regex.Match(key.Attributes["IngredienreplacedemID" + i.ToString()].Value, @"[a-zA-Z]+").Value);
                        metadata.IngredientAmounts.Add(int.Parse(key.Attributes["IngredientCount" + i.ToString()].Value));
                    }
                }
                gems.Add(metadata);
            }
        }
        return gems;
    }

See More Examples