System.Collections.Generic.ICollection.Contains(string)

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

613 Examples 7

19 Source : LProjectDependencies.cs
with MIT License
from 3F

protected void BuildOrder()
        {
            bool h(string id)
            {
                map[id].ForEach(dep => h(dep));
                if(!order.Contains(id)) {
                    order.Add(id);
                }
                return true;
            };

            foreach(KeyValuePair<string, HashSet<string>> project in map)
            {
                h(project.Key);
                if(!order.Contains(project.Key)) {
                    order.Add(project.Key);
                }
            }
        }

19 Source : ResourceProperties.cs
with MIT License
from actions

public Boolean DeleteAllExcept(ISet<String> names)
        {
            ArgumentUtility.CheckEnumerableForNullOrEmpty(names, nameof(names));

            Boolean removed = false;
            if (m_items?.Count > 0)
            {
                foreach (var propertyName in m_items.Keys.Where(x => !names.Contains(x)).ToArray())
                {
                    removed |= Delete(propertyName);
                }
            }

            return removed;
        }

19 Source : DiagnosticWalker.cs
with GNU General Public License v3.0
from Acumatica

private bool IsMethodForbidden(IMethodSymbol symbol)
			{
				return symbol.ContainingType?.OriginalDefinition != null
				       && symbol.ContainingType.OriginalDefinition.InheritsFromOrEquals(_pxContext.PXCache.Type)
				       && MethodNames.Contains(symbol.Name);
			}

19 Source : DataTableExtensions.cs
with MIT License
from Adoxio

public static void ExportToCsv(this DataTable table, string name, HttpContext context, IList<string> hideColumns = null)
		{
			context.Response.Clear();
			context.Response.ClearHeaders();
			context.Response.ClearContent();
			context.Response.Charset = Encoding.UTF8.WebName;
			context.Response.ContentEncoding = Encoding.UTF8;
			context.Response.BinaryWrite(Encoding.UTF8.GetPreamble());
			
			if (hideColumns == null)
			{
				hideColumns = new List<string>();
			}

			var columns = table.Columns.Cast<DataColumn>().Where(column => !hideColumns.Contains(column.Caption)).ToList();

			foreach (var column in columns)
			{
				context.Response.Write(EncodeCommaSeperatedValue(column.Caption));
			}

			context.Response.Write(Environment.NewLine);

			foreach (DataRow row in table.Rows)
			{
				foreach (var column in columns)
				{
					context.Response.Write(EncodeCommaSeperatedValue(row[column.ColumnName].ToString()));
				}

				context.Response.Write(Environment.NewLine);
			}

			context.Response.ContentType = "text/csv";

			context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + name);

			context.Response.End();
		}

19 Source : CecilifierContext.cs
with MIT License
from adrianoc

public bool HasFlag(string name)
        {
            return flags.Contains(name);
        }

19 Source : CompilerInjectedAttributesIgnorer.cs
with MIT License
from adrianoc

public bool VisitMissing(TypeDefinition source, ModuleDefinition target)
        {
            return toBeIgnored.Contains(source.FullName) || typeVisitor.VisitMissing(source, target);
        }

19 Source : Whitelist.cs
with MIT License
from AElfProject

public bool ContainsreplacedemblyNameReference(replacedemblyNameReference replacedemblyNameReference)
        {
            return _replacedemblies.Keys.Contains(replacedemblyNameReference.Name);
        }

19 Source : CollectionEx.cs
with Mozilla Public License 2.0
from agebullhu

public static void AddOnce(this IList<string> em, string value)
        {
            if (!string.IsNullOrWhiteSpace(value) && !em.Contains(value))
            {
                em.Add(value);
            }
        }

19 Source : AuditGetLastUpdate.cs
with MIT License
from akaskela

protected DataTable BuildDataTable(CodeActivityContext context, IWorkflowContext workflowContext, IOrganizationService service)
        {
            DataTable table = new DataTable() { TableName = workflowContext.PrimaryEnreplacedyName };
            table.Columns.AddRange(new DataColumn[] { new DataColumn("Attribute"), new DataColumn("Old Value"), new DataColumn("New Value") });

            RetrieveRecordChangeHistoryRequest request = new RetrieveRecordChangeHistoryRequest()
            {
                Target = new EnreplacedyReference(workflowContext.PrimaryEnreplacedyName, workflowContext.PrimaryEnreplacedyId),
                PagingInfo = new PagingInfo() { Count = 100, PageNumber = 1 }
            };
            RetrieveRecordChangeHistoryResponse response = service.Execute(request) as RetrieveRecordChangeHistoryResponse;
            
            if (response != null && response.AuditDetailCollection.Count > 0)
            {
                string onlyIfField = LastUpdateWithThisField.Get(context);
                AttributeAuditDetail detail = null;
                for (int i = 0; i < response.AuditDetailCollection.Count; i++)
                {
                    AttributeAuditDetail thisDetail = response.AuditDetailCollection[i] as AttributeAuditDetail;
                    if (thisDetail != null && (String.IsNullOrEmpty(onlyIfField) ||
                        (thisDetail.OldValue.Attributes.Keys.Contains(onlyIfField) ||
                        thisDetail.NewValue.Attributes.Keys.Contains(onlyIfField))))
                    {
                        detail = thisDetail;
                        break;
                    }
                }

                if (detail != null && detail.NewValue != null && detail.OldValue != null)
                {
                    Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest retrieveEnreplacedyRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
                    {
                        EnreplacedyFilters = EnreplacedyFilters.Attributes,
                        LogicalName = workflowContext.PrimaryEnreplacedyName
                    };
                    Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse retrieveEnreplacedyResponse = service.Execute(retrieveEnreplacedyRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
                    EnreplacedyMetadata metadata = retrieveEnreplacedyResponse.EnreplacedyMetadata;

                    var details = detail.NewValue.Attributes.Keys.Union(detail.OldValue.Attributes.Keys)
                        .Distinct()
                        .Select(a => new
                        {
                            AttributeName = a,
                            DisplayName = this.GetDisplayLabel(metadata, a),
                            OldValue = String.Empty,
                            NewValue = String.Empty
                        })
                        .OrderBy(a => a.DisplayName);

                    foreach (var item in details)
                    {
                        DataRow newRow = table.NewRow();
                        newRow["Attribute"] = item.DisplayName;
                        newRow["Old Value"] = GetDisplayValue(detail.OldValue, item.AttributeName);
                        newRow["New Value"] = GetDisplayValue(detail.NewValue, item.AttributeName);
                        table.Rows.Add(newRow);
                    }
                }
            }
            return table;
        }

19 Source : VariablesList.cs
with MIT License
from alaabenfatma

private void RenameNodes(ref VariableItem item)
        {
            foreach (var node in Host.Nodes)
                if (item.DsOfNodes.Contains(node.Id))
                    if (node.Types == NodeTypes.VariableGet)
                        node.OutputPorts[0].Text = "Return " + item.Name;

                    else if (node.Types == NodeTypes.VariableSet)
                    {
                        node.InputPorts[0].Text = item.Name;
                        var get = node as Get;
                        get?.Update(item.Name);
                    }
            foreach (var nodeItem in item.NodesTreeItems)
                if (nodeItem.NodeName.Contains("Set "))
                    nodeItem.NodeName = "Set " + item.Name;
                else
                    nodeItem.NodeName = "Get " + item.Name;
        }

19 Source : DefaultRetryPolicy.cs
with MIT License
from aliyunmq

public override bool RetryForException(IExecutionContext executionContext, Exception exception)
        {            
            // An IOException was thrown by the underlying http client.
            if (exception is IOException)
            {
                // Don't retry IOExceptions that are caused by a ThreadAbortException
                if (IsInnerException<ThreadAbortException>(exception))
                    return false;

                // Retry all other IOExceptions
                return true;
            }

            // A AliyunServiceException was thrown by ErrorHandler
            var serviceException = exception as AliyunServiceException;
            if (serviceException != null)
            {
                /*
                * For 500 internal server errors and 503 service
                * unavailable errors, we want to retry, but we need to use
                * an exponential back-off strategy so that we don't overload
                * a server with a flood of retries. If we've surpreplaceded our
                * retry limit we handle the error response as a non-retryable
                * error and go ahead and throw it back to the user as an exception.
                */
                if (serviceException.StatusCode == HttpStatusCode.InternalServerError ||
                    serviceException.StatusCode == HttpStatusCode.ServiceUnavailable)
                {
                    return true;
                }

                /*
                 * Throttling is reported as a 400 or 503 error from services. To try and
                 * smooth out an occasional throttling error, we'll pause and retry,
                 * hoping that the pause is long enough for the request to get through
                 * the next time.
                */
                if ((serviceException.StatusCode == HttpStatusCode.BadRequest ||
                    serviceException.StatusCode == HttpStatusCode.ServiceUnavailable))
                {
                    string errorCode = serviceException.ErrorCode;
                    if (this.ErrorCodesToRetryOn.Contains(errorCode))
                    {
                        return true;
                    }
                }

                WebException webException;
                if (IsInnerException<WebException>(exception, out webException))
                {
                    if (this.WebExceptionStatusesToRetryOn.Contains(webException.Status))
                    {
                        return true;
                    }
                }
            }

            return false;
        }

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

private void TraverseModel(string parentPath, string parentTypeName, string propertyName, JsonSchema currentJsonSchema, bool isRequired, ISet<string> alreadyVisitedTypes, JsonSchema parentJsonSchema, string parentXpath)
        {
            string sanitizedPropertyName = SanitizeName(propertyName);
            string xPath;
            string path;
            int index = 0;
            do
            {
                path = (string.IsNullOrEmpty(parentPath) ? string.Empty : parentPath + ".") + sanitizedPropertyName;
                xPath = (string.IsNullOrEmpty(parentXpath) ? "/" : parentXpath + "/") + propertyName;
                if (++index >= 2)
                {
                    path += index.ToString();
                    xPath += index.ToString();
                }
            }
            while (elements.ContainsKey(path));

            // exclude elements that does not start with firstPropertyName
            if (!path.StartsWith(firstPropertyName))
            {
                return;
            }

            string minItems = "0";
            string maxItems = "1";

            TypeKeyword currentJsonSchemaType = currentJsonSchema.Get<TypeKeyword>();

            if (currentJsonSchemaType != null && currentJsonSchemaType.Value == JsonSchemaType.Array)
            {
                List<JsonSchema> items = currentJsonSchema.Items();
                path += multiplicityString;
                FollowRef(path, items[0], alreadyVisitedTypes, xPath); // TODO fix multiple item types. It now uses only the first

                double? minItemsValue = currentJsonSchema.MinItems();
                double? maxItemsValue = currentJsonSchema.MaxItems();

                if (minItemsValue.HasValue)
                {
                    minItems = minItemsValue.ToString();
                }

                maxItems = "*";
                if (maxItemsValue.HasValue && maxItemsValue.Value != MagicNumberMaxOccurs)
                {
                    maxItems = maxItemsValue.ToString();
                }
            }
            else if (currentJsonSchemaType != null && currentJsonSchemaType.Value == JsonSchemaType.Object)
            {   
                if (alreadyVisitedTypes.Contains(sanitizedPropertyName))
                {
                    return;
                }

                ISet<string> currentlyVisitedTypes = new HashSet<string>(alreadyVisitedTypes);
                currentlyVisitedTypes.Add(sanitizedPropertyName);
                if (currentJsonSchema.Properties() != null)
                {
                    foreach (KeyValuePair<string, JsonSchema> def in currentJsonSchema.Properties())
                    {
                        TraverseModel(path, sanitizedPropertyName, def.Key, def.Value, IsRequired(def.Key, currentJsonSchema), currentlyVisitedTypes, currentJsonSchema, xPath);
                    }
                }                
            }
            else
            {
                FollowRef(path, currentJsonSchema, alreadyVisitedTypes, xPath);
                if (isRequired)
                {
                    minItems = "1";
                }
            }

            JsonObject result = new JsonObject();

            string inputType = "Field";
            string xsdType = currentJsonSchema.OtherData.TryGetString("@xsdType");

            result.Add("ID", RemoveStarsFromPath(path));

            string parentElement = ExtractParent(path);
            if (parentElement != null)
            {
                result.Add("ParentElement", RemoveStarsFromPath(parentElement));
            }

            string xsdValueType = FollowValueType(currentJsonSchema);

            string typeName = ExtractTypeNameFromSchema(currentJsonSchema);
            if (typeName != null)
            {
                result.Add("TypeName", SanitizeName(typeName));
            }
            else
            {
                result.Add("TypeName", sanitizedPropertyName);
            }

            result.Add("Name", sanitizedPropertyName);

            string fixedValue = null;
            JsonValue fixedValueJson = currentJsonSchema.Const();
            if (fixedValueJson != null)
            {
                fixedValue = fixedValueJson.String;
            }

            if (xsdType != null && xsdType.Equals("XmlAttribute"))
            {
                inputType = "Attribute";
            }
            else if ((currentJsonSchemaType == null && xsdValueType == null) || (currentJsonSchemaType != null && (currentJsonSchemaType.Value == JsonSchemaType.Object || currentJsonSchemaType.Value == JsonSchemaType.Array)))
            {
                inputType = "Group";
            }

            int maxOccursParsed = maxItems.Equals("*") ? MagicNumberMaxOccurs : int.Parse(maxItems);

            if ((!inputType.Equals("Group") && string.IsNullOrEmpty(fixedValue)) || (inputType.Equals("Group") && maxOccursParsed > 1))
            {
                string dataBindingNameWithoutFirstPropertyName = $"{parentXpath}/{propertyName}".Replace("/" + firstPropertyName + "/", string.Empty);
                string dataBindingName = dataBindingNameWithoutFirstPropertyName.Replace("/", ".");
                result.Add("DataBindingName", dataBindingName);
            }

            result.Add("XPath", xPath);

            result.Add("Restrictions", ExtractRestrictions(xsdValueType, currentJsonSchema));

            result.Add("Type", inputType);

            if (!string.IsNullOrEmpty(xsdValueType))
            {
                result.Add("XsdValueType", char.ToUpper(xsdValueType[0]) + xsdValueType.Substring(1)); // Uppercase first character
            }

            if (path.EndsWith(".value"))
            {
                result.Add("Texts", ExtractTexts(parentElement.Split(".").Last(), parentJsonSchema));
                result.Add("IsTagContent", true);
            }
            else
            {
                result.Add("Texts", ExtractTexts(propertyName, currentJsonSchema));
            }

            result.Add("CustomProperties", new JsonObject()); // ??

            result.Add("MaxOccurs", maxOccursParsed);
            result.Add("MinOccurs", int.Parse(minItems));

            result.Add("XName", propertyName);

            if (fixedValue != null)
            {
                result.Add("FixedValue", fixedValue);
            }

            string jsonSchemaPointer = "#/properties/" + propertyName;
            if (parentElement != null)
            {
                jsonSchemaPointer = "#/definitions/" + parentTypeName + "/properties/" + propertyName;
            }

            result.Add("JsonSchemaPointer", jsonSchemaPointer);

            string cardinality = "[" + minItems + ".." + maxItems + "]";
            string displayString = RemoveLastStar(path) + " : " + cardinality + " " + SanitizeName(typeName);
            result.Add("DisplayString", displayString);

            // TODO ..., XmlSchemaReference
            elements.Add(RemoveStarsFromPath(path), result);
        }

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

private void FollowRef(string path, JsonSchema jSchema, ISet<string> alreadyVisitedTypes, string parentXpath)
        {
            string reference = jSchema.Ref();
            if (reference != null)
            {
                string typeName = ExtractTypeNameFromDefinitionReference(reference);
                JsonSchema schema = definitions.GetValueOrDefault(typeName);
                if (schema != null)
                {
                    if (alreadyVisitedTypes.Contains(typeName))
                    {
                        return;
                    }

                    ISet<string> currentlyVisitedTypes = new HashSet<string>(alreadyVisitedTypes);
                    currentlyVisitedTypes.Add(typeName);

                    if (schema.Properties() != null)
                    {
                        foreach (KeyValuePair<string, JsonSchema> def in schema.Properties())
                        {
                            TraverseModel(path, typeName, def.Key, def.Value, IsRequired(def.Key, schema), currentlyVisitedTypes, jSchema, parentXpath);
                        }
                    }
                    else if (schema.OneOf() != null)
                    {
                        foreach (JsonSchema oneOfSchema in schema.OneOf())
                        {
                            if (oneOfSchema.Ref() != null)
                            {
                                FollowRef(path, oneOfSchema, currentlyVisitedTypes, parentXpath);
                            }
                            else if (oneOfSchema.Properties() != null)
                            {
                                foreach (KeyValuePair<string, JsonSchema> def in oneOfSchema.Properties())
                                {
                                    TraverseModel(path, typeName, def.Key, def.Value, IsRequired(def.Key, oneOfSchema), currentlyVisitedTypes, jSchema, parentXpath);
                                }
                            }
                        }
                    }
                    else if (schema.AllOf() != null)
                    {
                        foreach (JsonSchema allOfSchema in schema.AllOf())
                        {
                            if (allOfSchema.Ref() != null)
                            {
                                FollowRef(path, allOfSchema, currentlyVisitedTypes, parentXpath);
                            }
                            else if (allOfSchema.Properties() != null)
                            {
                                foreach (KeyValuePair<string, JsonSchema> def in allOfSchema.Properties())
                                {
                                    TraverseModel(path, typeName, def.Key, def.Value, IsRequired(def.Key, allOfSchema), currentlyVisitedTypes, jSchema, parentXpath);
                                }
                            }
                        }
                    }
                }
            }
        }

19 Source : IssueSelector.cs
with Apache License 2.0
from AmpScm

private void Reload()
        {
            issuesView1.ClearItems();
            ICollection<string> issues = new List<string>();
            foreach (TextMarker im in _issueWalker)
            {
                // skip duplicate items
                if (!issues.Contains(im.Value))
                {
                    issuesView1.Items.Add(new IssuesViewItem(issuesView1, im.Value));
                    issues.Add(im.Value);
                }
            }
        }

19 Source : LogRevisionItem.cs
with Apache License 2.0
from AmpScm

private string GetIssueText()
        {
            StringBuilder sb = null;
            ICollection<string> issueList = new List<string>();
            foreach (TextMarker issue in Issues)
            {
                if (!issueList.Contains(issue.Value))
                {
                    if (sb == null)
                        sb = new StringBuilder();
                    else
                        sb.Append(',');

                    sb.Append(issue.Value);
                    issueList.Add(issue.Value);
                }
            }
            return sb != null ? sb.ToString() : "";
        }

19 Source : Util.cs
with MIT License
from anastasios-stamoulis

static void summary(C.Function rootFunction, List<string> entries, ISet<string> visited) {
      if (visited == null) {
        visited = new HashSet<string>();
      }

      if (rootFunction.IsComposite) {
        summary(rootFunction.RootFunction, entries, visited);
        return;
      }

      if (visited.Contains(rootFunction.Uid)) {
        return;
      }
      visited.Add(rootFunction.Uid);

      var numParameters = 0;
      foreach (var rootInput in rootFunction.Inputs) {
        if (rootInput.IsParameter && !rootInput.IsConstant) {
          numParameters += rootInput.Shape.TotalSize;
        }
        if ((rootInput.Owner == null) || visited.Contains(rootInput.Owner.Uid)) { continue; }
        summary(rootInput.Owner, entries, visited);
      }
      for (int i = 0; i < rootFunction.Outputs.Count; i++) {
        var line = $"{rootFunction.Name,-29}{rootFunction.Outputs[i].Shape.replacedtring(),-26}{numParameters}";
        entries.Add(line);
      }
      entries.Add(underscores);
    }

19 Source : JsonData.cs
with MIT License
from AnotherEnd15

public Boolean ContainsKey(String key) {
            EnsureDictionary();
            return this.inst_object.Keys.Contains(key);
        }

19 Source : AccountController.cs
with MIT License
from anteatergames

private async Task SetStaffRoles(ApplicationUser user)
        {
            IList<string> userRoles = await _userManager.GetRolesAsync(user);

            bool userIsMember = userRoles.Contains(Roles.Member.ToString());

            if (!userIsMember)
            {
                await _userManager.AddToRoleAsync(user, Roles.Member.ToString());
            }

            if (user.UserName.Equals("programad"))
            {
                bool userIsAdmin = userRoles.Contains(Roles.Administrator.ToString());

                if (!userIsAdmin)
                {
                    await _userManager.AddToRoleAsync(user, Roles.Administrator.ToString());
                }
            }
        }

19 Source : AmqpSubscriptionTracker.cs
with Apache License 2.0
from apache

public bool IsActiveExclusiveDurableSub(String subscriptionName)
        {
            return exclusiveDurableSubs.Contains(subscriptionName);
        }

19 Source : ExcelDataValidationFormulaList.cs
with Apache License 2.0
from Appdynamics

bool ICollection<string>.Contains(string item)
            {
                return _items.Contains(item);
            }

19 Source : VkTracksService.cs
with Apache License 2.0
from artemshuba

public async Task<(List<AudioPost> Posts, string NextFrom)> GetNews(int count = 50, string nextFrom = null)
        {
            (List<AudioPost> Posts, string NextFrom) result = (null, null);

            try
            {
                var response = await _vk.News.Get(filters: "post", count: count, startFrom: nextFrom);

                if (response?.Items.IsNullOrEmpty() == false)
                {
                    var audioIds = new List<string>();
                    var posts = new List<AudioPost>();
                    var postAudioMatches = new Dictionary<string, IList<string>>();

                    foreach (var newsEntry in response.Items)
                    {
                        var attachments = newsEntry.Attachments;

                        //if there are no attachments of this post, but there is repost history, take attachments from last repost
                        if (attachments.IsNullOrEmpty() && !newsEntry.CopyHistory.IsNullOrEmpty())
                            attachments = newsEntry.CopyHistory.Last().Attachments;

                        if (attachments.IsNullOrEmpty())
                            continue;

                        var ids = attachments.Where(a => a is VkAudioAttachment).Select(a => $"{a.OwnerId}_{a.Id}").ToList();
                        audioIds.AddRange(ids);

                        var post = new AudioPost();
                        post.Id = newsEntry.Id.ToString();
                        post.Text = newsEntry.Text;
                        post.PostUri = new Uri($"http://vk.com/wall{newsEntry.SourceId}_{post.Id}");
                        post.AuthorUri = new Uri(string.Format("https://vk.com/{0}{1}", newsEntry.Author is VkGroup ? "club" : "id", newsEntry.Author.Id));

                        var imageUrl = newsEntry.Attachments?.OfType<VkPhotoAttachment>().FirstOrDefault()?.SourceMax;
                        if (!string.IsNullOrEmpty(imageUrl))
                            post.ImageUri = new Uri(imageUrl);

                        post.Author = newsEntry.Author;
                        post.Date = newsEntry.Date;
                        posts.Add(post);

                        postAudioMatches.Add(post.Id, ids);
                    }

                    if (audioIds.Count == 0)
                        return result;

                    var tracks = new List<IAudio>();

                    var audioIdsChunks = audioIds.Split(100); //split ids by chunks of 100 ids (api restriction)
                    foreach (var audioIdsChunk in audioIdsChunks)
                    {
                        var resultAudios = await _vk.Audio.GetById(audioIdsChunk.ToList());
                        if (!resultAudios.IsNullOrEmpty())
                            tracks.AddRange(ProcessTracks(resultAudios));
                    }

                    foreach (var post in posts)
                    {
                        post.Tracks = tracks.Where(t => postAudioMatches[post.Id].Contains($"{t.OwnerId}_{t.Id}")).ToList();
                    }

                    result.Posts = posts.Where(p => p.Tracks.Count > 0).ToList();
                    result.NextFrom = response.NextFrom;
                }
            }
            catch (VkInvalidTokenException)
            {
                Messenger.Default.Send(new MessageUserAuthChanged { IsLoggedIn = false });
            }

            return result;
        }

19 Source : VkTracksService.cs
with Apache License 2.0
from artemshuba

public async Task<(List<AudioPost> Posts, int TotalCount)> GetWallPosts(int count = 300, int offset = 0, long ownerId = 0)
        {
            (List<AudioPost> Posts, int TotalCount) result = (null, 0);

            try
            {
                var response = await _vk.Wall.Get(ownerId: ownerId, filter: "all", count: count, offset: offset);

                if (response?.Items.IsNullOrEmpty() == false)
                {
                    var audioIds = new List<string>();
                    var posts = new List<AudioPost>();
                    var postAudioMatches = new Dictionary<string, IList<string>>();

                    foreach (var newsEntry in response.Items)
                    {
                        var attachments = newsEntry.Attachments;

                        //if there are no attachments of this post, but there is repost history, take attachments from last repost
                        if (attachments.IsNullOrEmpty() && !newsEntry.CopyHistory.IsNullOrEmpty())
                            attachments = newsEntry.CopyHistory.Last().Attachments;

                        if (attachments.IsNullOrEmpty())
                            continue;

                        var ids = attachments.Where(a => a is VkAudioAttachment).Select(a => $"{a.OwnerId}_{a.Id}").ToList();
                        audioIds.AddRange(ids);

                        var post = new AudioPost();
                        post.Id = newsEntry.Id.ToString();
                        post.Text = newsEntry.Text;
                        post.PostUri = new Uri($"http://vk.com/wall{newsEntry.SourceId}_{post.Id}");
                        post.AuthorUri = new Uri(string.Format("https://vk.com/{0}{1}", newsEntry.Author is VkGroup ? "club" : "id", newsEntry.Author.Id));

                        var imageUrl = newsEntry.Attachments?.OfType<VkPhotoAttachment>().FirstOrDefault()?.SourceMax;
                        if (!string.IsNullOrEmpty(imageUrl))
                            post.ImageUri = new Uri(imageUrl);

                        post.Author = newsEntry.Author;
                        post.Date = newsEntry.Date;
                        posts.Add(post);

                        postAudioMatches.Add(post.Id, ids);
                    }

                    if (audioIds.Count == 0)
                        return result;

                    var tracks = new List<IAudio>();

                    var audioIdsChunks = audioIds.Split(100); //split ids by chunks of 100 ids (api restriction)
                    foreach (var audioIdsChunk in audioIdsChunks)
                    {
                        var resultAudios = await _vk.Audio.GetById(audioIdsChunk.ToList());
                        if (!resultAudios.IsNullOrEmpty())
                            tracks.AddRange(ProcessTracks(resultAudios));
                    }

                    foreach (var post in posts)
                    {
                        post.Tracks = tracks.Where(t => postAudioMatches[post.Id].Contains($"{t.OwnerId}_{t.Id}")).ToList();
                    }

                    result.Posts = posts.Where(p => p.Tracks.Count > 0).ToList();
                    response.TotalCount = response.TotalCount;
                }
            }
            catch (VkInvalidTokenException)
            {
                Messenger.Default.Send(new MessageUserAuthChanged { IsLoggedIn = false });
            }

            return result;
        }

19 Source : PermissionRepository.cs
with MIT License
from ASF-Framework

public async Task<IList<Permission>> GetList(IList<string> ids)
        {
            var list = await _dbContext.Permissions.Where(w => ids.Contains(w.Id)).ToListAsync();
            list = list == null ? new List<PermissionModel>() : list;
            return Mapper.Map<List<Permission>>(list);
        }

19 Source : CachingPermissionRepository.cs
with MIT License
from ASF-Framework

public async Task<IList<Permission>> GetList(IList<string> ids)
        {
            var list = await this.GetList();
            return list.Where(w => ids.Contains(w.Id)).ToList();
        }

19 Source : MockTagFilter.cs
with MIT License
from AshleighAdams

async Task<bool> ITagFilter.PreplacedesFilter(TaggedVersion taggedVersion)
		{
			return !BlockTags.Contains(taggedVersion.Tag.Name);
		}

19 Source : Worker.cs
with GNU General Public License v3.0
from asimmon

private void ExecuteTick()
        {
            var playerActions = new ConcurrentDictionary<string, string>(StringComparer.Ordinal);
            var playerLatencies = new ConcurrentDictionary<string, TimeSpan>(StringComparer.Ordinal);

            using (var threadGroup = new ThreadGroup())
            {
                this._playerIds.ShuffleInPlace(this._rng);

                foreach (var (playerId, process) in this._processes)
                {
                    if (process.HasExited)
                    {
                        this.HandleExitedProcess(playerId);
                    }
                    else if (this._simulator.State.Players.TryGetValue(playerId, out var player) && !player.IsAlive)
                    {
                        // Dead players can no longer play
                    }
                    else
                    {
                        var threadState = new ThreadState(playerId, this._simulator.State, process, playerActions, playerLatencies);
                        threadGroup.ExecuteThread(this.ExecuteTick, threadState);
                    }
                }

                this.Debug(this._simulator.State.Tick, null, "Waiting for all players to send their actions");
                threadGroup.WaitForCompletion(this._tickDuration);

                var validPlayerActions = new Dictionary<string, string>();

                foreach (var (playerId, _) in this._processes)
                {
                    if (playerActions.TryGetValue(playerId, out var playerAction))
                    {
                        if (ValidPlayerActions.Contains(playerAction))
                        {
                            validPlayerActions[playerId] = playerAction;
                        }
                        else
                        {
                            var error = string.IsNullOrEmpty(playerAction) ? "Did not receive action in time (1)" : "Not a valid action: " + playerAction.Trim();
                            this.AddPlayerError(playerId, error);
                        }
                    }
                    else if (this._processes[playerId].HasExited)
                    {
                        this.HandleExitedProcess(playerId);
                    }
                }

                this.Debug(this._simulator.State.Tick, null, $"Executing tick with {validPlayerActions.Count} valid player actions after waiting {threadGroup.Elapsed.TotalSeconds:F4} seconds");
                this._simulator.ExecuteTick(validPlayerActions, playerLatencies);

                this.Debug(this._simulator.State.Tick, null, "Tiles: " + this._simulator.State.Tiles);
            }
        }

19 Source : AuthServerTests.cs
with Apache License 2.0
from aspnet

public void AuthServerHappyPathConfiguration(IAppBuilder app)
        {
            app.UseErrorPage();
            app.UseOAuthAuthorizationServer(new OAuthAuthorizationServerOptions
            {
                AuthorizeEndpointPath = new PathString("/AuthorizeEndpoint"),
                TokenEndpointPath = new PathString("/TokenEndpoint"),
                AllowInsecureHttp = true,
                Provider = new OAuthAuthorizationServerProvider
                {
                    //Authorize endpoint
                    OnValidateClientRedirectUri = (context) =>
                    {
                        context.OwinContext.Set<bool>("OnValidateClientRedirectUri", true);
                        if (context.RedirectUri.Contains("invalid_uri_displayerror"))
                        {
                            context.Options.ApplicationCanDisplayErrors = false;
                            context.Rejected();
                        }
                        else if (context.RedirectUri.Contains("invalid_uri_preplacedonerror"))
                        {
                            context.Options.ApplicationCanDisplayErrors = true;
                            context.SetError("custom.error", "custom.errordescription", "custom.erroruri");
                        }
                        else if (context.ClientId == "123")
                        {
                            context.Validated();
                        }
                        return Task.FromResult(0);
                    },
                    OnValidateAuthorizeRequest = (context) =>
                    {
                        context.OwinContext.Set<bool>("OnValidateAuthorizeRequest", true);

                        if (context.AuthorizeRequest.State == "invalidstate")
                        {
                            context.SetError("state.invalid", "state.invaliddescription", "state.invaliduri");
                        }
                        else if (context.AuthorizeRequest.State == "validstate" || context.AuthorizeRequest.State == null)
                        {
                            context.Validated();
                        }

                        if (context.AuthorizeRequest.Scope == null || context.AuthorizeRequest.Scope.Count != 1 || !context.AuthorizeRequest.Scope.Contains("scope1"))
                        {
                            context.Rejected();
                        }

                        return Task.FromResult(0);
                    },
                    OnAuthorizeEndpoint = (context) =>
                    {
                        var owinContext = context.OwinContext;
                        if (!owinContext.Get<bool>("OnMatchEndpoint") || !owinContext.Get<bool>("OnValidateClientRedirectUri") || !owinContext.Get<bool>("OnValidateAuthorizeRequest"))
                        {
                            //This will make sure no token is sent back
                            owinContext.Response.StatusCode = 400;
                        }
                        else
                        {
                            var claim = new Claim(ClaimTypes.Name, "OnAuthorizeEndpointInvoked");
                            var idenreplacedy = new ClaimsIdenreplacedy(new Claim[] { claim }, context.Options.AuthenticationType);
                            owinContext.Authentication.SignIn(idenreplacedy);
                            context.RequestCompleted();
                        }
                        return Task.FromResult(0);
                    },

                    //Common
                    OnMatchEndpoint = (context) =>
                    {
                        context.OwinContext.Set<bool>("OnMatchEndpoint", true);
                        return Task.FromResult(0);
                    },

                    //Token endpoint
                    OnValidateClientAuthentication = context =>
                    {
                        string clientId;
                        string clientSecret;
                        if (context.TryGetBasicCredentials(out clientId, out clientSecret) ||
                            context.TryGetFormCredentials(out clientId, out clientSecret))
                        {
                            if (clientId == "123" && clientSecret == "secret123")
                            {
                                context.Validated();
                            }
                        }
                        return Task.FromResult(0);
                    },
                    OnValidateTokenRequest = context =>
                        {
                            context.Validated();
                            return Task.FromResult(0);
                        },
                    OnGrantAuthorizationCode = context =>
                        {
                            context.Validated();
                            return Task.FromResult(0);
                        },
                    OnTokenEndpoint = context =>
                        {
                            context.AdditionalResponseParameters.Add("param1", "value1");
                            context.AdditionalResponseParameters.Add("param2", "value2");
                            context.RequestCompleted();
                            return Task.FromResult(0);
                        },
                    OnGrantResourceOwnerCredentials = context =>
                        {
                            if (context.UserName == "user1" && context.Preplacedword == "preplacedword1")
                            {
                                var scope = context.Scope;
                                if (scope.Count == 3 && scope.Contains("scope1") && scope.Contains("scope2") && scope.Contains("scope3"))
                                {
                                    var claim = new Claim(ClaimTypes.Name, "OnGrantResourceOwnerCredentials");
                                    var idenreplacedy = new ClaimsIdenreplacedy(new Claim[] { claim }, context.Options.AuthenticationType);
                                    context.Validated(idenreplacedy);
                                }
                            }

                            return Task.FromResult(0);
                        },
                    OnGrantClientCredentials = context =>
                        {
                            var scope = context.Scope;
                            if (scope.Count == 3 && scope.Contains("scope1") && scope.Contains("scope2") && scope.Contains("scope3"))
                            {
                                var claim = new Claim(ClaimTypes.Name, "OnGrantResourceOwnerCredentials");
                                var idenreplacedy = new ClaimsIdenreplacedy(new Claim[] { claim }, context.Options.AuthenticationType);
                                context.Validated(idenreplacedy);
                            }
                            return Task.FromResult(0);
                        },
                    OnGrantRefreshToken = context =>
                        {
                            //Bug# https://github.com/Katana/katana/issues/592
                            //var scope = context.Scope;
                            //if (scope.Count == 3 && scope.Contains("scope1") && scope.Contains("scope2") && scope.Contains("scope3"))
                            {
                                var claim = new Claim(ClaimTypes.Name, "OnGrantRefreshToken");
                                var idenreplacedy = new ClaimsIdenreplacedy(new Claim[] { claim }, context.Options.AuthenticationType);
                                context.Validated(idenreplacedy);
                            }
                            return Task.FromResult(0);
                        }
                },
                AuthorizationCodeProvider = new AuthenticationTokenProvider
                {
                    OnCreate = context =>
                    {
                        context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
                        _authenticationCodes[context.Token] = context.SerializeTicket();
                    },
                    OnReceive = context =>
                        {
                            string value;
                            if (_authenticationCodes.TryRemove(context.Token, out value))
                            {
                                context.DeserializeTicket(value);
                            }
                        }
                },
                RefreshTokenProvider = new AuthenticationTokenProvider
                {
                    OnCreate = context =>
                    {
                        context.SetToken(Guid.NewGuid().ToString("n") + Guid.NewGuid().ToString("n"));
                        _refreshTokens[context.Token] = context.SerializeTicket();
                    },
                    OnReceive = context =>
                    {
                        string value;
                        if (_refreshTokens.TryRemove(context.Token, out value))
                        {
                            context.DeserializeTicket(value);
                        }
                    }
                },
            });
            
            //app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            //app.Use((context, next) =>
            //{
            //    if(context.Request.User != null && context.Request.User.Idenreplacedy.IsAuthenticated)
            //    {
            //        return context.Response.WriteAsync("BearerTokenRead");
            //    }

            //    return next.Invoke();
            //});

            app.Run(context =>
            {
                if (context.Get<string>("oauth.Error") == "custom.error" &&
                    context.Get<string>("oauth.ErrorDescription") == "custom.errordescription" &&
                    context.Get<string>("oauth.ErrorUri") == "custom.erroruri")
                {
                    return context.Response.WriteAsync("Custom error page");
                }
                else
                {
                    return context.Response.WriteAsync("FAILURE");
                }
            });
        }

19 Source : ClaimCollector.cs
with Apache License 2.0
from authlete

static string[] NormalizeClaimLocales(string[] claimLocales)
        {
            if (claimLocales == null || claimLocales.Length == 0)
            {
                return null;
            }

            // From 5.2. Claims Languages and Scripts in OpenID
            // Connect Core 1.0
            //
            //   However, since BCP47 language tag values are case
            //   insensitive, implementations SHOULD interpret the
            //   language tag values supplied in a case insensitive
            //   manner.
            //
            ISet<string> claimLocaleSet =
                new HashSet<string>(StringComparer.OrdinalIgnoreCase);

            // Normalized list.
            IList<string> list = new List<string>();

            // Loop to drop empty and duplicate claim locales.
            foreach (string claimLocale in claimLocales)
            {
                // If the claim locale is empty.
                if (string.IsNullOrEmpty(claimLocale))
                {
                    continue;
                }

                // If the claim locale is a duplicate.
                if (claimLocaleSet.Contains(claimLocale))
                {
                    continue;
                }

                claimLocaleSet.Add(claimLocale);
                list.Add(claimLocale);
            }

            int size = list.Count;

            if (size == 0)
            {
                return null;
            }

            if (size == claimLocales.Length)
            {
                // No change.
                return claimLocales;
            }

            // Convert the list to an array.
            var array = new string[size];
            list.CopyTo(array, 0);

            return array;
        }

19 Source : BimProjectFoldersApi.cs
with MIT License
from Autodesk-Forge

public IList<string> GetNestedSubFolderIds(string projectId, string folderId)
        {
            if (projectId.StartsWith("b.") == false)
            {
                projectId = "b." + projectId;
            }

            try
            {
                //instantiate the list of ids
                IList<string> folderIds = new List<string>();

                //get the subfolders within the folder
                IList<Folder> subFolders = GetSubFolders(projectId, folderId);

                //check for null
                if (subFolders != null)
                {
                    //process each subfolder
                    foreach (Folder folder in subFolders)
                    {
                        ////clean the id
                        //string id = Uri.EscapeDataString(folder.id);
                        //add it to the list of subfolder ids
                        if (!folderIds.Contains(folder.id))
                        {
                            folderIds.Add(folder.id);
                        }
                        //now process the sub-subfolders within this subfolder
                        IList<string> subSubfolders = GetNestedSubFolderIds(projectId, folder.id);

                        //process each sub-subfolder
                        foreach (string subId in subSubfolders)
                        {
                            ////clean the id
                            //string sid = Uri.EscapeDataString(subId);
                            //add it to the list of subfolder ids
                            if (!folderIds.Contains(subId))
                            {
                                folderIds.Add(subId);
                            }
                        }
                    }
                }

                return folderIds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

19 Source : BimProjectFoldersApi.cs
with MIT License
from Autodesk-Forge

public IList<string> GetNestedSubFolderIds(string projectId, string folderId)
        {
            if (projectId.StartsWith("b.") == false)
            {
                projectId = "b." + projectId;
            }

            try
            {
                //instantiate the list of ids
                IList<string> folderIds = new List<string>();

                //get the subfolders within the folder
                IList<Folder> subFolders = GetSubFolders(projectId, folderId);

                //check for null
                if (subFolders != null)
                {
                    //process each subfolder
                    foreach (Folder folder in subFolders)
                    {
                        ////clean the id
                        //string id = Uri.EscapeDataString(folder.id);
                        //add it to the list of subfolder ids
                        if (!folderIds.Contains(folder.id))
                        {
                            folderIds.Add(folder.id);
                        }
                        //now process the sub-subfolders within this subfolder
                        IList<string> subSubfolders = GetNestedSubFolderIds(projectId, folder.id);

                        //process each sub-subfolder
                        foreach (string subId in subSubfolders)
                        {
                            ////clean the id
                            //string sid = Uri.EscapeDataString(subId);
                            //add it to the list of subfolder ids
                            if (!folderIds.Contains(subId))
                            {
                                folderIds.Add(subId);
                            }
                        }
                    }
                }

                return folderIds;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

19 Source : CognitoUserStore.IUserRoleStore.cs
with Apache License 2.0
from aws

public virtual async Task<bool> IsInRoleAsync(TUser user, string roleName, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            if (user == null)
            {
                throw new ArgumentNullException(nameof(user));
            }

            var userRoles = await GetRolesAsync(user, cancellationToken).ConfigureAwait(false);
            return userRoles.Contains(roleName);
        }

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

public override async Task ExecuteAsync()
        {
            var accessToken = await GetAccessTokenAsync();

            // get all of the accounts
            const string accountUrl = "https://api.aweber.com/1.0/accounts";
            var accounts = await GetCollectionAsync<Account>(accessToken, accountUrl);

            // get all sharing integration uri's for twitter and facebook
            // these are used to create a broadcast that will post to twitter or facebook
            // see broadcast example here: https://github.com/aweber/public-api-examples/tree/master/csharp/AWeber.Examples.CreateScheduleBroadcast
            var integrations = await GetCollectionAsync<Integration>(accessToken, accounts.First().IntegrationsCollectionLink);
            Console.WriteResponse(ConsoleColor.Green, "Integrations:");
            foreach (var integration in integrations)
            {
                if (TwitterAndFacebookIntegrations.Contains(integration.ServiceName.ToLower()))
                {
                    Console.WriteResponse(ConsoleColor.Green, string.Format("Service Name: {0}, Login: {1}, Self Link: {2}", integration.ServiceName, integration.Login, integration.SelfLink));
                }
            }
        }

19 Source : AWSXRaySDKUtils.cs
with Apache License 2.0
from aws

internal static bool IsBlacklistedOperation(String serviceName, string operation)
        {
            if (string.Equals(serviceName, XRayServiceName) && WhitelistedOperations.Contains(operation))
            {
                return true;
            }
            return false;
        }

19 Source : WorkspaceBuilderHelper.cs
with Apache License 2.0
from aws

private ProjectreplacedysisResult BuildIncremental(string WorkspacePath)
        {
            Queue<string> queue = new Queue<string>();
            ISet<string> existing = new HashSet<string>();

            queue.Enqueue(WorkspacePath);
            existing.Add(WorkspacePath);

            /*
             * We need to resolve all the project dependencies to avoid compilation errors.
             * If we have compilation errors, we might miss some of the semantic values.
             */
            while (queue.Count > 0)
            {
                var path = queue.Dequeue();
                Logger.LogInformation("Building: " + path);

                IProjectreplacedyzer projectreplacedyzer = _replacedyzerManager.GetProject(path);
                IreplacedyzerResult replacedyzerResult = projectreplacedyzer.Build(GetEnvironmentOptions(projectreplacedyzer.ProjectFile)).FirstOrDefault();

                if (replacedyzerResult == null)
                {
                    Logger.LogDebug("Building complete for {0} - {1}", path, "Fail");
                    return new ProjectreplacedysisResult()
                    {
                        Projectreplacedyzer = projectreplacedyzer
                    };
                }

                if(!DictreplacedysisResult.ContainsKey(replacedyzerResult.ProjectGuid))
                {
                    DictreplacedysisResult[replacedyzerResult.ProjectGuid] = replacedyzerResult;
                    projectreplacedyzer.AddToWorkspace(_workspaceIncremental);

                    foreach (var pref in replacedyzerResult.ProjectReferences)
                    {
                        if (!existing.Contains(pref))
                        {
                            existing.Add(pref);
                            queue.Enqueue(pref);
                        }
                    }                   
                }
            }
            
            Project project = _workspaceIncremental.CurrentSolution?.Projects.FirstOrDefault(x => x.FilePath.Equals(WorkspacePath));
            Logger.LogDebug("Building complete for {0} - {1}", WorkspacePath, DictreplacedysisResult[project.Id.Id].Succeeded ? "Success" : "Fail");
            return new ProjectreplacedysisResult()
            {
                Project = project,
                replacedyzerResult = DictreplacedysisResult[project.Id.Id],
                Projectreplacedyzer = _replacedyzerManager.Projects.Values.FirstOrDefault(p => p.ProjectGuid.Equals(project.Id.Id))
            };
        }

19 Source : WorkspaceBuilderHelper.cs
with Apache License 2.0
from aws

public void Build()
        {
            /* Uncomment the below code to debug issues with msbuild */
            /*var writer = new StreamWriter(Console.OpenStandardOutput());
            writer.AutoFlush = true;

            Console.SetOut(writer);
            Console.SetError(writer);*/

            if (IsSolutionFile())
            {
                Logger.LogInformation("Loading the Workspace (Solution): " + WorkspacePath);

                replacedyzerManager replacedyzerManager = new replacedyzerManager(WorkspacePath,
                   new replacedyzerManagerOptions
                   {
                       LogWriter = _writer
                   });

                Logger.LogInformation("Loading the Solution Done: " + WorkspacePath);

                // replacedyzerManager builds the projects based on their dependencies
                // After this, code does not depend on Buildalyzer                
                BuildSolution(replacedyzerManager);
            }
            else
            {
                replacedyzerManager replacedyzerManager = new replacedyzerManager(new replacedyzerManagerOptions
                {
                    LogWriter = _writer
                });

                var dict = new Dictionary<Guid, IreplacedyzerResult>();
                using (AdhocWorkspace workspace = new AdhocWorkspace())
                {
                    Queue<string> queue = new Queue<string>();
                    ISet<string> existing = new HashSet<string>();

                    queue.Enqueue(WorkspacePath);
                    existing.Add(WorkspacePath);

                    /*
                     * We need to resolve all the project dependencies to avoid compilation errors.
                     * If we have compilation errors, we might miss some of the semantic values.
                     */
                    while (queue.Count > 0)
                    {
                        var path = queue.Dequeue();
                        Logger.LogInformation("Building: " + path);

                        IProjectreplacedyzer projectreplacedyzer = replacedyzerManager.GetProject(path);
                        IreplacedyzerResults replacedyzerResults = projectreplacedyzer.Build(GetEnvironmentOptions(projectreplacedyzer.ProjectFile));
                        IreplacedyzerResult replacedyzerResult = replacedyzerResults.First();

                        if (replacedyzerResult == null)
                        {
                            FailedProjects.Add(new ProjectreplacedysisResult()
                            {
                                Projectreplacedyzer = projectreplacedyzer
                            });
                        }

                        dict[replacedyzerResult.ProjectGuid] = replacedyzerResult;
                        replacedyzerResult.AddToWorkspace(workspace);

                        foreach (var pref in replacedyzerResult.ProjectReferences)
                        {
                            if (!existing.Contains(pref))
                            {
                                existing.Add(pref);
                                queue.Enqueue(pref);
                            }
                        }
                    }

                    foreach (var project in workspace.CurrentSolution.Projects)
                    {
                        try
                        {
                            var result = dict[project.Id.Id];

                            var projectreplacedyzer = replacedyzerManager.Projects.Values.FirstOrDefault(p =>
                                p.ProjectGuid.Equals(project.Id.Id));

                            Projects.Add(new ProjectreplacedysisResult()
                            {
                                Project = project,
                                replacedyzerResult = result,
                                Projectreplacedyzer = projectreplacedyzer
                            });
                        }
                        catch (Exception ex)
                        {
                            Logger.LogDebug(ex.StackTrace);
                        }
                    }
                }
            }

            Logger.LogDebug(_sb.ToString());
            _writer.Flush();
            _writer.Close();
            ProcessLog(_writer.ToString());
        }

19 Source : KustoSDKClient.cs
with MIT License
from Azure

private string GetBackupClusterName(string cluster)
        {
            string backupCluster = cluster;

            if (string.IsNullOrWhiteSpace(cluster))
            {
                return backupCluster;
            }

            if (cluster.EndsWith(DataProviderConstants.kustoFollowerClusterSuffix, StringComparison.OrdinalIgnoreCase))
            {
                backupCluster = cluster.Trim().Replace(DataProviderConstants.kustoFollowerClusterSuffix, string.Empty, StringComparison.OrdinalIgnoreCase);
            }
            else if (FailoverClusterMapping.Keys.Contains(cluster))
            {
                backupCluster = FailoverClusterMapping[cluster];
            }

            return backupCluster;
        }

19 Source : ModulesManager.cs
with The Unlicense
from BAndysc

public bool ShouldLoad(replacedembly module)
        {
            var requiredCore = module
                .GetCustomAttributes(typeof(ModuleRequiresCoreAttribute), false)
                .Cast<ModuleRequiresCoreAttribute>()
                .FirstOrDefault();
            if (requiredCore != null)
            {
                if (currentCoreSettings.CurrentCore == null)
                    return false;

                if (!requiredCore.cores.Contains(currentCoreSettings.CurrentCore))
                    return false;
            }

            var name = module.GetName().Name!;
            if (ignoredModules.Contains(name))
                return false;

            if (blockedModules.Contains(name))
                return false;
            
            foreach (var block in module
                .GetCustomAttributes(typeof(ModuleBlocksOtherAttribute), false)
                .Cast<ModuleBlocksOtherAttribute>())
                blockedModules.Add(block.otherModule);

            return true;
        }

19 Source : Node.cs
with GNU General Public License v3.0
from BardMusicPlayer

void OnZeroTierEvent(IntPtr msgPtr)
        {
            zts_event_msg_t msg = (zts_event_msg_t)Marshal.PtrToStructure(msgPtr, typeof(zts_event_msg_t));
            Event newEvent = null;

            // Node

            if (msg.node != IntPtr.Zero) {
                zts_node_info_t details = (zts_node_info_t)Marshal.PtrToStructure(msg.node, typeof(zts_node_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                _id = details.node_id;
                _primaryPort = details.primary_port;
                _secondaryPort = details.secondary_port;
                _tertiaryPort = details.tertiary_port;
                _versionMajor = details.ver_major;
                _versionMinor = details.ver_minor;
                _versionRev = details.ver_rev;
                _isOnline = Convert.ToBoolean(zts_node_is_online());

                if (msg.event_code == Constants.EVENT_NODE_UP) {
                    newEvent.Name = "EVENT_NODE_UP";
                }
                if (msg.event_code == Constants.EVENT_NODE_ONLINE) {
                    newEvent.Name = "EVENT_NODE_ONLINE";
                }
                if (msg.event_code == Constants.EVENT_NODE_OFFLINE) {
                    newEvent.Name = "EVENT_NODE_OFFLINE";
                }
                if (msg.event_code == Constants.EVENT_NODE_DOWN) {
                    newEvent.Name = "EVENT_NODE_DOWN";
                }
                if (msg.event_code == Constants.ZTS_EVENT_NODE_FATAL_ERROR) {
                    newEvent.Name = "EVENT_NODE_FATAL_ERROR";
                }
            }

            // Network

            if (msg.network != IntPtr.Zero) {
                zts_net_info_t net_info = (zts_net_info_t)Marshal.PtrToStructure(msg.network, typeof(zts_net_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;

                // Update network info as long as we aren't tearing down the network
                if (msg.event_code != Constants.EVENT_NETWORK_DOWN) {
                    ulong networkId = net_info.net_id;
                    NetworkInfo ni = _networks.GetOrAdd(networkId, new NetworkInfo());

                    newEvent.NetworkInfo = ni;
                    newEvent.NetworkInfo.Id = net_info.net_id;
                    newEvent.NetworkInfo.MACAddress = net_info.mac;
                    newEvent.NetworkInfo.Name = System.Text.Encoding.UTF8.GetString(net_info.name);
                    newEvent.NetworkInfo.Status = net_info.status;
                    newEvent.NetworkInfo.Type = net_info.type;
                    newEvent.NetworkInfo.MTU = net_info.mtu;
                    newEvent.NetworkInfo.DHCP = net_info.dhcp;
                    newEvent.NetworkInfo.Bridge = Convert.ToBoolean(net_info.bridge);
                    newEvent.NetworkInfo.BroadcastEnabled = Convert.ToBoolean(net_info.broadcast_enabled);

                    zts_core_lock_obtain();

                    // Get replacedigned addresses

                    ConcurrentDictionary<string, IPAddress> newAddrsDict =
                        new ConcurrentDictionary<string, IPAddress>();
                    IntPtr addrBuffer = Marshal.AllocHGlobal(ZeroTier.Constants.INET6_ADDRSTRLEN);
                    int addr_count = zts_core_query_addr_count(networkId);

                    for (int idx = 0; idx < addr_count; idx++) {
                        zts_core_query_addr(networkId, idx, addrBuffer, ZeroTier.Constants.INET6_ADDRSTRLEN);
                        // Convert buffer to managed string
                        string str = Marshal.PtrToStringAnsi(addrBuffer);
                        IPAddress addr = IPAddress.Parse(str);
                        newAddrsDict[addr.ToString()] = addr;
                    }

                    // Update addresses in NetworkInfo object

                    // TODO: This update block works but could use a re-think, I think.
                    // Step 1. Remove addresses not present in new concurrent dict.
                    if (! ni._addrs.IsEmpty) {
                        foreach (string key in ni._addrs.Keys) {
                            if (! newAddrsDict.Keys.Contains(key)) {
                                ni._addrs.TryRemove(key, out _);
                            }
                        }
                    }
                    else {
                        ni._addrs = newAddrsDict;
                    }
                    // Step 2. Add addresses not present in existing concurrent dict.
                    foreach (string key in newAddrsDict.Keys) {
                        if (! ni._addrs.Keys.Contains(key)) {
                            ni._addrs[key] = newAddrsDict[key];
                        }
                    }

                    Marshal.FreeHGlobal(addrBuffer);
                    addrBuffer = IntPtr.Zero;

                    // Get managed routes

                    ConcurrentDictionary<string, RouteInfo> newRoutesDict =
                        new ConcurrentDictionary<string, RouteInfo>();
                    IntPtr targetBuffer = Marshal.AllocHGlobal(ZeroTier.Constants.INET6_ADDRSTRLEN);
                    IntPtr viaBuffer = Marshal.AllocHGlobal(ZeroTier.Constants.INET6_ADDRSTRLEN);

                    int route_count = zts_core_query_route_count(networkId);

                    ushort flags = 0, metric = 0;

                    for (int idx = 0; idx < route_count; idx++) {
                        zts_core_query_route(
                            networkId,
                            idx,
                            targetBuffer,
                            viaBuffer,
                            ZeroTier.Constants.INET6_ADDRSTRLEN,
                            ref flags,
                            ref metric);

                        // Convert buffer to managed string

                        try {
                            string targetStr = Marshal.PtrToStringAnsi(targetBuffer);
                            IPAddress targetAddr = IPAddress.Parse(targetStr);
                            string viaStr = Marshal.PtrToStringAnsi(viaBuffer);
                            IPAddress viaAddr = IPAddress.Parse(viaStr);
                            RouteInfo route = new RouteInfo(targetAddr, viaAddr, flags, metric);
                            // Add to NetworkInfo object
                            newRoutesDict[targetStr] = route;
                        }
                        catch {
                            Console.WriteLine("error while parsing route");
                        }
                    }

                    // TODO: This update block works but could use a re-think, I think.
                    // Step 1. Remove routes not present in new concurrent dict.
                    if (! ni._routes.IsEmpty) {
                        foreach (string key in ni._routes.Keys) {
                            if (! newRoutesDict.Keys.Contains(key)) {
                                ni._routes.TryRemove(key, out _);
                            }
                        }
                    }
                    else {
                        ni._routes = newRoutesDict;
                    }
                    // Step 2. Add routes not present in existing concurrent dict.
                    foreach (string key in newRoutesDict.Keys) {
                        if (! ni._routes.Keys.Contains(key)) {
                            ni._routes[key] = newRoutesDict[key];
                        }
                    }

                    Marshal.FreeHGlobal(targetBuffer);
                    Marshal.FreeHGlobal(viaBuffer);
                    targetBuffer = IntPtr.Zero;
                    viaBuffer = IntPtr.Zero;

                    // Get multicast subscriptions

                    zts_core_lock_release();

                    // Update synthetic "readiness" value
                    ni.transportReady = (route_count > 0) && (addr_count > 0) ? true : false;
                }   // EVENT_NETWORK_DOWN

                if (msg.event_code == Constants.EVENT_NETWORK_NOT_FOUND) {
                    newEvent.Name = "EVENT_NETWORK_NOT_FOUND " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_REQ_CONFIG) {
                    newEvent.Name = "EVENT_NETWORK_REQ_CONFIG " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_ACCESS_DENIED) {
                    newEvent.Name = "EVENT_NETWORK_ACCESS_DENIED " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_READY_IP4) {
                    newEvent.Name = "EVENT_NETWORK_READY_IP4 " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_READY_IP6) {
                    newEvent.Name = "EVENT_NETWORK_READY_IP6 " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_DOWN) {
                    newEvent.Name = "EVENT_NETWORK_DOWN " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_CLIENT_TOO_OLD) {
                    newEvent.Name = "EVENT_NETWORK_CLIENT_TOO_OLD " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_REQ_CONFIG) {
                    newEvent.Name = "EVENT_NETWORK_REQ_CONFIG " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_OK) {
                    newEvent.Name = "EVENT_NETWORK_OK " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_ACCESS_DENIED) {
                    newEvent.Name = "EVENT_NETWORK_ACCESS_DENIED " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_READY_IP4_IP6) {
                    newEvent.Name = "EVENT_NETWORK_READY_IP4_IP6 " + net_info.net_id.ToString("x16");
                }
                if (msg.event_code == Constants.EVENT_NETWORK_UPDATE) {
                    newEvent.Name = "EVENT_NETWORK_UPDATE " + net_info.net_id.ToString("x16");
                }
            }

            // Route

            if (msg.route != IntPtr.Zero) {
                zts_route_info_t route_info =
                    (zts_route_info_t)Marshal.PtrToStructure(msg.route, typeof(zts_route_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.RouteInfo = default;   // new RouteInfo();

                if (msg.event_code == Constants.EVENT_ROUTE_ADDED) {
                    newEvent.Name = "EVENT_ROUTE_ADDED";
                }
                if (msg.event_code == Constants.EVENT_ROUTE_REMOVED) {
                    newEvent.Name = "EVENT_ROUTE_REMOVED";
                }
            }

            // Peer

            if (msg.peer != IntPtr.Zero) {
                zts_peer_info_t peer_info = (zts_peer_info_t)Marshal.PtrToStructure(msg.peer, typeof(zts_peer_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.PeerInfo = default;   // new PeerInfo();

                if (peer_info.role == Constants.PEER_ROLE_PLANET) {
                    newEvent.Name = "PEER_ROLE_PLANET";
                }
                if (msg.event_code == Constants.EVENT_PEER_DIRECT) {
                    newEvent.Name = "EVENT_PEER_DIRECT";
                }
                if (msg.event_code == Constants.EVENT_PEER_RELAY) {
                    newEvent.Name = "EVENT_PEER_RELAY";
                }
                // newEvent = new ZeroTier.Core.Event(msg.event_code,"EVENT_PEER_UNREACHABLE");
                if (msg.event_code == Constants.EVENT_PEER_PATH_DISCOVERED) {
                    newEvent.Name = "EVENT_PEER_PATH_DISCOVERED";
                }
                if (msg.event_code == Constants.EVENT_PEER_PATH_DEAD) {
                    newEvent.Name = "EVENT_PEER_PATH_DEAD";
                }
            }

            // Address

            if (msg.addr != IntPtr.Zero) {
                zts_addr_info_t unmanagedDetails =
                    (zts_addr_info_t)Marshal.PtrToStructure(msg.addr, typeof(zts_addr_info_t));
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.AddressInfo = default;   // new AddressInfo();

                if (msg.event_code == Constants.EVENT_ADDR_ADDED_IP4) {
                    newEvent.Name = "EVENT_ADDR_ADDED_IP4";
                }
                if (msg.event_code == Constants.EVENT_ADDR_ADDED_IP6) {
                    newEvent.Name = "EVENT_ADDR_ADDED_IP6";
                }
                if (msg.event_code == Constants.EVENT_ADDR_REMOVED_IP4) {
                    newEvent.Name = "EVENT_ADDR_REMOVED_IP4";
                }
                if (msg.event_code == Constants.EVENT_ADDR_REMOVED_IP6) {
                    newEvent.Name = "EVENT_ADDR_REMOVED_IP6";
                }
            }

            // Storage

            if (msg.cache != IntPtr.Zero) {
                newEvent = new Event();
                newEvent.Code = msg.event_code;
                // newEvent.AddressInfo = default;   // new AddressInfo();

                if (msg.event_code == Constants.EVENT_STORE_IDENreplacedY_SECRET) {
                    newEvent.Name = "EVENT_STORE_IDENreplacedY_SECRET";
                }
                if (msg.event_code == Constants.EVENT_STORE_IDENreplacedY_PUBLIC) {
                    newEvent.Name = "EVENT_STORE_IDENreplacedY_PUBLIC";
                }
                if (msg.event_code == Constants.EVENT_STORE_PLANET) {
                    newEvent.Name = "EVENT_STORE_PLANET";
                }
                if (msg.event_code == Constants.EVENT_STORE_PEER) {
                    newEvent.Name = "EVENT_STORE_PEER";
                }
                if (msg.event_code == Constants.EVENT_STORE_NETWORK) {
                    newEvent.Name = "EVENT_STORE_NETWORK";
                }
            }

            // Preplaced the converted Event to the managed callback (visible to user)
            if (newEvent != null) {
                _managedCallback(newEvent);
            }
        }

19 Source : DBDrugLookupDelegate.cs
with Apache License 2.0
from bcgov

public IList<DrugProduct> GetDrugProductsByDIN(IList<string> drugIdentifiers)
        {
            this.logger.LogDebug($"Getting list of drug products from DB");
            this.logger.LogTrace($"Identifiers {JsonSerializer.Serialize(drugIdentifiers)}");
            IList<string> uniqueDrugIdentifers = drugIdentifiers.Distinct().ToList();
            IList<DrugProduct> retVal = this.dbContext.DrugProduct
                                            .Include(c => c.Company)
                                            .Include(a => a.ActiveIngredient)
                                            .Include(f => f.Form)
                                            .Where(dp => uniqueDrugIdentifers.Contains(dp.DrugIdentificationNumber))
                                            .AsEnumerable()
                                            .GroupBy(dp => dp.DrugIdentificationNumber)
                                            .Select(drug => drug.OrderByDescending(o => o.LastUpdate).First())
                                            .ToList();
            this.logger.LogDebug("Finished getting list of drug products from DB");
            this.logger.LogTrace($"Products: {JsonSerializer.Serialize(retVal)}");
            return retVal;
        }

19 Source : DBDrugLookupDelegate.cs
with Apache License 2.0
from bcgov

public IList<PharmaCareDrug> GetPharmaCareDrugsByDIN(IList<string> drugIdentifiers)
        {
            this.logger.LogDebug($"Getting list of pharmacare drug products from DB");
            this.logger.LogTrace($"Identifiers {JsonSerializer.Serialize(drugIdentifiers)}");
            IList<string> uniqueDrugIdentifers = drugIdentifiers.Distinct().ToList();
            DateTime now = DateTime.UtcNow;
            IList<PharmaCareDrug> retVal = this.dbContext.PharmaCareDrug
                .Where(dp => uniqueDrugIdentifers.Contains(dp.DINPIN) && (now > dp.EffectiveDate && now <= dp.EndDate))
                .AsEnumerable()
                .GroupBy(pcd => pcd.DINPIN).Select(g => g.OrderByDescending(p => p.EndDate).First())
                .ToList();

            this.logger.LogDebug("Finished getting list of pharmacare drug products from DB");
            this.logger.LogTrace($"Products: {JsonSerializer.Serialize(retVal)}");
            return retVal;
        }

19 Source : SettingSearcher.cs
with GNU Lesser General Public License v3.0
from BepInEx

public static void CollectSettings(out IEnumerable<SettingEntryBase> results, out List<string> modsWithoutSettings, bool showDebug)
        {
            modsWithoutSettings = new List<string>();

            try
            {
                results = GetBepInExCoreConfig();
            }
            catch (Exception ex)
            {
                results = Enumerable.Empty<SettingEntryBase>();
                ConfigurationManager.Logger.LogError(ex);
            }

            foreach (var plugin in Utils.FindPlugins())
            {
                var type = plugin.GetType();

                var pluginInfo = plugin.Info.Metadata;

                if (type.GetCustomAttributes(typeof(BrowsableAttribute), false).Cast<BrowsableAttribute>()
                    .Any(x => !x.Browsable))
                {
                    modsWithoutSettings.Add(pluginInfo.Name);
                    continue;
                }

                var detected = new List<SettingEntryBase>();

                detected.AddRange(GetPluginConfig(plugin).Cast<SettingEntryBase>());

                detected.AddRange(LegacySettingSearcher.GetLegacyPluginConfig(plugin).Cast<SettingEntryBase>());

                detected.RemoveAll(x => x.Browsable == false);

                if (!detected.Any())
                    modsWithoutSettings.Add(pluginInfo.Name);

                // Allow to enable/disable plugin if it uses any update methods ------
                if (showDebug && type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Any(x => _updateMethodNames.Contains(x.Name)))
                {
                    // todo make a different clreplaced for it and fix access modifiers?
                    var enabledSetting = LegacySettingEntry.FromNormalProperty(plugin, type.GetProperty("enabled"), pluginInfo, plugin);
                    enabledSetting.DispName = "!Allow plugin to run on every frame";
                    enabledSetting.Description = "Disabling this will disable some or all of the plugin's functionality.\nHooks and event-based functionality will not be disabled.\nThis setting will be lost after game restart.";
                    enabledSetting.IsAdvanced = true;
                    detected.Add(enabledSetting);
                }

                if (detected.Any())
                {
#pragma warning disable 618 // Disable obsolete warning
                    var isAdvancedPlugin = type.GetCustomAttributes(typeof(AdvancedAttribute), false).Cast<AdvancedAttribute>().Any(x => x.IsAdvanced);
#pragma warning restore 618
                    if (isAdvancedPlugin)
                        detected.ForEach(entry => entry.IsAdvanced = true);

                    results = results.Concat(detected);
                }
            }
        }

19 Source : CommandParser.cs
with GNU Lesser General Public License v2.1
from BepInEx

public static Arguments Parse(string[] args, IList<string> registeredValueKeys = null)
		{
			registeredValueKeys ??= new List<string>();

			Dictionary<string, string> switches = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			List<string> values = new List<string>();

			string previousSwitch = null;
			bool valuesOnly = false;

			foreach (string arg in args)
			{
				if (arg == "--")
				{
					// no more switches, only values
					valuesOnly = true;

					continue;
				}

				if (valuesOnly)
				{
					values.Add(arg);
					continue;
				}

				if (arg.StartsWith("-")
				    || arg.StartsWith("--"))
				{
					if (previousSwitch != null)
						switches.Add(previousSwitch, string.Empty);

					if (arg.StartsWith("--"))
						previousSwitch = arg.Substring(2);
					else
						previousSwitch = arg.Substring(1);

					if (!registeredValueKeys.Contains(previousSwitch))
					{
						switches.Add(previousSwitch, string.Empty);
						previousSwitch = null;
					}

					continue;
				}

				if (previousSwitch != null)
				{
					switches.Add(previousSwitch, arg);
					previousSwitch = null;
				}
				else
				{
					values.Add(arg);
				}
			}

			if (previousSwitch != null)
				switches.Add(previousSwitch, string.Empty);

			return new Arguments(switches, values);
		}

19 Source : ChangedValueDescriptorCollection.cs
with MIT License
from bing-framework

public void Populate(IEnumerable<ChangedValueDescriptor> descriptors)
        {
            if (descriptors == null || !descriptors.Any())
                return;
            var filtedDiscriptors = descriptors.Where(x => !_changedNameList.Contains(x.PropertyName)).ToList();
            if (!filtedDiscriptors.Any())
                return;
            foreach (var item in filtedDiscriptors)
                Add(item);
        }

19 Source : JsonWebTokenCustomerAuthorizeMiddleware.cs
with MIT License
from bing-framework

public async Task Invoke(HttpContext context)
        {
            // 如果是匿名访问路径,则直接跳过
            if (_anonymousPathList.Contains(context.Request.Path.Value))
            {
                await _next(context);
                return;
            }

            var result = context.Request.Headers.TryGetValue("Authorization", out var authStr);
            if (!result || string.IsNullOrWhiteSpace(authStr.ToString()))
                throw new UnauthorizedAccessException("未授权,请传递Header头的Authorization参数");
            // 校验以及自定义校验
            result = _tokenValidator.Validate(authStr.ToString().Substring("Bearer ".Length).Trim(), _options,
                _validatePayload);
            if (!result)
                throw new UnauthorizedAccessException("验证失败,请查看传递的参数是否正确或是否有权限访问该地址。");
            await _next(context);
        }

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

bool IDictionary<string, T>.ContainsKey(string key) => _names.Contains(key);

19 Source : Index.cs
with MIT License
from bleroy

public async IAsyncEnumerable<Result> Query(
            Action<Query> queryFactory,
            [EnumeratorCancellation] CancellationToken cancellationToken)
        {
            var results = new List<Result>();
            var query = new Query(Fields);
            var matchingFields = new Dictionary<FieldReference, MatchData>();
            var termFieldCache = new HashSet<string>();
            var requiredMatches = new Dictionary<string, ISet<string>>();
            var prohibitedMatches = new Dictionary<string, ISet<string>>();

            // To support field level boosts a query vector is created per
            // field. An empty vector is eagerly created to support negated
            // queries.
            var queryVectors = new Dictionary<string, Vector>();
            foreach (string field in Fields)
            {
                queryVectors[field] = new Vector();
            }

            queryFactory(query);

            for (int i = 0; i < query.Clauses.Count; i++)
            {
                if (cancellationToken.IsCancellationRequested) yield break;

                Clause clause = query.Clauses[i];
                ISet<string> clauseMatches = Set<string>.Empty;

                // Unless the pipeline has been disabled for this term, which is
                // the case for terms with wildcards, we need to preplaced the clause
                // term through the search pipeline. A pipeline returns an array
                // of processed terms. Pipeline functions may expand the preplaceded
                // term, which means we may end up performing multiple index lookups
                // for a single query term.
                await foreach (string term in clause.UsePipeline
                    ? Pipeline.RunString(
                        clause.Term,
                        new TokenMetadata
                        {
                            { "fields", clause.Fields }
                        },
                        cancellationToken)
                    : new[] { clause.Term }.ToAsyncEnumerable(cancellationToken))
                {

                    if (cancellationToken.IsCancellationRequested) yield break;

                    // Each term returned from the pipeline needs to use the same query
                    // clause object, e.g. the same boost and or edit distance. The
                    // simplest way to do this is to re-use the clause object but mutate
                    // its term property.
                    clause = clause.WithTerm(term);

                    // From the term in the clause we create a token set which will then
                    // be used to intersect the indexes token set to get a list of terms
                    // to lookup in the inverted index.
                    var termTokenSet = TokenSet.FromClause(clause);
                    TokenSet expandedTerms = TokenSet.Intersect(termTokenSet);

                    // If a term marked as required does not exist in the tokenSet it is
                    // impossible for the search to return any matches.We set all the field
                    // scoped required matches set to empty and stop examining any further
                    // clauses.
                    if (!expandedTerms.Any() && clause.Presence == QueryPresence.Required)
                    {
                        foreach (string field in clause.Fields)
                        {
                            if (cancellationToken.IsCancellationRequested) yield break;

                            if (!requiredMatches.ContainsKey(field))
                            {
                                requiredMatches.Add(field, Set<string>.Empty);
                            }
                        }

                        break;
                    }

                    foreach (string expandedTerm in expandedTerms.ToEnumeration())
                    {
                        if (cancellationToken.IsCancellationRequested) yield break;

                        // For each term get the posting and termIndex, this is required for building the query vector.
                        InvertedIndexEntry posting = InvertedIndex[expandedTerm];
                        int termIndex = posting.Index;

                        foreach (string field in clause.Fields)
                        {
                            if (cancellationToken.IsCancellationRequested) yield break;

                            // For each field that this query term is scoped by (by default
                            // all fields are in scope) we need to get all the doreplacedent refs
                            // that have this term in that field.
                            //
                            // The posting is the entry in the invertedIndex for the matching
                            // term from above.
                            // For each field that this query term is scoped by (by default
                            // all fields are in scope) we need to get all the doreplacedent refs
                            // that have this term in that field.
                            //
                            // The posting is the entry in the invertedIndex for the matching
                            // term from above.
                            FieldMatches fieldPosting = posting[field];
                            ICollection<string> matchingDoreplacedentRefs = fieldPosting.Keys;
                            string termField = expandedTerm + '/' + field;
                            var matchingDoreplacedentSet = new Set<string>(matchingDoreplacedentRefs);

                            // if the presence of this term is required ensure that the matching
                            // doreplacedents are added to the set of required matches for this clause.
                            if (clause.Presence == QueryPresence.Required)
                            {
                                clauseMatches = clauseMatches.Union(matchingDoreplacedentSet);

                                if (!requiredMatches.ContainsKey(field))
                                {
                                    requiredMatches.Add(field, Set<string>.Complete);
                                }
                            }

                            // if the presence of this term is prohibited ensure that the matching
                            // doreplacedents are added to the set of prohibited matches for this field,
                            // creating that set if it does not yet exist.
                            if (clause.Presence == QueryPresence.Prohibited)
                            {
                                if (!prohibitedMatches.ContainsKey(field))
                                {
                                    prohibitedMatches.Add(field, Set<string>.Empty);
                                }

                                prohibitedMatches[field] = prohibitedMatches[field].Union(matchingDoreplacedentSet);

                                // Prohibited matches should not be part of the query vector used for
                                // similarity scoring and no metadata should be extracted so we continue
                                // to the next field.
                                continue;
                            }

                            // The query field vector is populated using the termIndex found for
                            // the term and a unit value with the appropriate boost applied.
                            // Using upsert because there could already be an entry in the vector
                            // for the term we are working with.In that case we just add the scores
                            // together.
                            queryVectors[field].Upsert(
                                termIndex,
                                clause.Boost,
                                (a, b) => a + b);

                            // If we've already seen this term, field combo then we've already collected
                            // the matching doreplacedents and metadata, no need to go through all that again.
                            if (termFieldCache.Contains(termField)) continue;

                            foreach (string matchingDoreplacedentRef in matchingDoreplacedentRefs)
                            {
                                if (cancellationToken.IsCancellationRequested) yield break;

                                // All metadata for this term/field/doreplacedent triple
                                // are then extracted and collected into an instance
                                // of lunr.MatchData ready to be returned in the query
                                // results.
                                var matchingFieldRef = new FieldReference(matchingDoreplacedentRef, field);
                                FieldMatchMetadata metadata = fieldPosting[matchingDoreplacedentRef];
                                
                                if (!matchingFields.TryGetValue(matchingFieldRef, out MatchData? fieldMatch))
                                {
                                    matchingFields.Add(
                                        matchingFieldRef,
                                        new MatchData(expandedTerm, field, metadata));
                                }
                                else
                                {
                                    fieldMatch.Add(expandedTerm, field, metadata);
                                }
                            }

                            termFieldCache.Add(termField);
                        }
                    }
                }

                // If the presence was required we need to update the requiredMatches field sets.
                // We do this after all fields for the term have collected their matches because
                // the clause terms presence is required in _any_ of the fields not _all_ of the
                // fields.
                if (clause.Presence == QueryPresence.Required)
                {
                    foreach (string field in clause.Fields)
                    {
                        if (cancellationToken.IsCancellationRequested) yield break;

                        requiredMatches[field] = requiredMatches[field].Intersect(clauseMatches);
                    }
                }
            }

            // Need to combine the field scoped required and prohibited
            // matching doreplacedents into a global set of required and prohibited
            // matches.
            ISet<string> allRequiredMatches = Set<string>.Complete;
            ISet<string> allProhibitedMatches = Set<string>.Empty;

            foreach (string field in Fields)
            {
                if (cancellationToken.IsCancellationRequested) yield break;

                if (requiredMatches.ContainsKey(field))
                {
                    allRequiredMatches = allRequiredMatches.Intersect(requiredMatches[field]);
                }

                if (prohibitedMatches.ContainsKey(field))
                {
                    allProhibitedMatches = allProhibitedMatches.Union(prohibitedMatches[field]);
                }
            }

            string[] matchingFieldRefs
                = matchingFields.Keys.Select(k => k.ToString()).ToArray();
            var matches = new Dictionary<string, Result>();

            // If the query is negated (contains only prohibited terms)
            // we need to get _all_ fieldRefs currently existing in the
            // index. This is only done when we know that the query is
            // entirely prohibited terms to avoid any cost of getting all
            // fieldRefs unnecessarily.
            //
            // Additionally, blank MatchData must be created to correctly
            // populate the results.
            if (query.IsNegated)
            {
                matchingFieldRefs = FieldVectors.Keys.ToArray();

                foreach (string matchingFieldRef in matchingFieldRefs)
                {
                    if (cancellationToken.IsCancellationRequested) yield break;

                    var fieldRef = FieldReference.FromString(matchingFieldRef);
                    matchingFields.Add(fieldRef, MatchData.Empty);
                }
            }

            foreach (string fieldRefString in matchingFieldRefs)
            {

                if (cancellationToken.IsCancellationRequested) yield break;

                // Currently we have doreplacedent fields that match the query, but we
                // need to return doreplacedents.The matchData and scores are combined
                // from multiple fields belonging to the same doreplacedent.
                //
                // Scores are calculated by field, using the query vectors created
                // above, and combined into a final doreplacedent score using addition.
                var fieldRef = FieldReference.FromString(fieldRefString);
                string docRef = fieldRef.DoreplacedentReference;

                if (!allRequiredMatches.Contains(docRef)) continue;
                if (allProhibitedMatches.Contains(docRef)) continue;

                Vector fieldVector = FieldVectors[fieldRefString];
                double score = queryVectors[fieldRef.FieldName].Similarity(fieldVector);

                if (matches.TryGetValue(docRef, out Result? docMatch))
                {
                    docMatch.Score += score;
                    docMatch.MatchData.Combine(matchingFields[fieldRef]);
                }
                else
                {
                    var match = new Result(
                        doreplacedentReference: docRef,
                        score,
                        matchData: matchingFields[fieldRef]
                    );
                    matches.Add(docRef, match);
                    if (cancellationToken.IsCancellationRequested) yield break;
                    results.Add(match);
                }
            }

            foreach (Result match in results.OrderByDescending(r => r.Score))
            {
                if (cancellationToken.IsCancellationRequested) yield break;
                yield return match;
            }
        }

19 Source : StopWordFilterBase.cs
with MIT License
from bleroy

public virtual bool IsStopWord(string word) => StopWords.Contains(word);

19 Source : ArrayBehaviorTests.cs
with MIT License
from bleroy

[Test]
        public void UsingArrayWithVarietyOfCollectionInterfaces() {
            dynamic array = new Clay(new InterfaceProxyBehavior(), new ArrayBehavior());

            array.Add("a", "b", "c", "d");

            ICollection<string> collectionString = array;

            replacedert.That(collectionString.Contains("e"), Is.False);
            collectionString.Add("e");
            replacedert.That(collectionString.Contains("e"), Is.True);
            replacedert.That(collectionString.Count, Is.EqualTo(5));

            replacedert.That(collectionString.Count(), Is.EqualTo(5));


            IList<string> listString = array;
            replacedert.That(listString.IndexOf("b++"), Is.EqualTo(-1));
            replacedert.That(listString.IndexOf("c"), Is.EqualTo(2));
            listString.Insert(2, "b++");
            replacedert.That(listString.IndexOf("b++"), Is.EqualTo(2));
            replacedert.That(listString.IndexOf("c"), Is.EqualTo(3));
            listString.RemoveAt(2);
            replacedert.That(listString.IndexOf("b++"), Is.EqualTo(-1));
            replacedert.That(listString.IndexOf("c"), Is.EqualTo(2));

            replacedert.That(listString[1], Is.EqualTo("b"));
            replacedert.That(listString[2], Is.EqualTo("c"));
        }

19 Source : Connection.cs
with GNU General Public License v3.0
from bonarr

private bool ExcludeMessage(Message message)
        {
            if (String.IsNullOrEmpty(message.Filter))
            {
                return false;
            }

            string[] exclude = message.Filter.Split('|');

            return exclude.Any(signal => Idenreplacedy.Equals(signal, StringComparison.OrdinalIgnoreCase) ||
                                                    _signals.Contains(signal) ||
                                                    _groups.Contains(signal));
        }

19 Source : Subscription.cs
with GNU General Public License v3.0
from bonarr

private bool AddEventCore(string key)
        {
            lock (EventKeys)
            {
                if (EventKeys.Contains(key))
                {
                    return false;
                }

                EventKeys.Add(key);
                return true;
            }
        }

See More Examples