public static string ConstructErrorString(IDictionary<string, IList<ModelValidationError>> errors) { List<string> errorList = new List<string>(); foreach (var x in errors.SelectMany(p => p.Value.Select(e => new { Property = p.Key, Properties = e.MemberNames.ToList(), Error = e.ErrorMessage }))) { errorList.Add(string.Format("Error with property {0}: {1}", x.Property, x.Error)); } string errorString = string.Join("\n\n", errorList); return errorString; }
public bool CanMigrate(IDictionary<string, List<MigrationStep>> steps) { foreach (MigrationStep step in steps.SelectMany(row => row.Value).OrderBy(row => row.Version)) { MigrationReference migrationReference = step.MigrationReference; IMigrationFactory migrationFactory = _migrationFactoryChooser.ChooseFactory(migrationReference); IDatabaseMigration migration = migrationFactory.CreateMigration(migrationReference); step.DatabaseMigration = migration; _migrationInitializer.InitializeMigration(migration); } _log.Info("All migrations are initialized."); return true; }
private static void WriteStats(StreamWriter sw, IDictionary<File, string> files, TypeDefinition[] types, int total) { var stats = files.SelectMany(x => x.Key.Annotations).Select(x => x.Type) .GroupBy(x => x) .Select(x => new {Type = types.First(y => y.Name == x.Key).Display, Count = x.Count()}) .OrderBy(x => x.Type) .ToArray(); foreach (var stat in stats) { sw.WriteLine("<tr><th>{0}:</th><td>{1}</td></tr>", WebUtility.HtmlEncode(stat.Type), stat.Count); } if (stats.Length != 1) { sw.WriteLine("<tr><th>Total:</th><td>{0}</td></tr>", total); } }
// ReSharper restore UnusedMember.Local public Genie(IDictionary<string, AnswerStatistic> answerStatistics, int answeringChoicesCount) { this.answerStatistics = answerStatistics; this.answeringChoicesCount = answeringChoicesCount; answersGuessedCount = answerStatistics.Sum(s => s.Value.AnswerCount); questionStatistics = answerStatistics.SelectMany(s => s.Value.AnsweredQuestionsById) .GroupBy(p => p.Key) .ToDictionary(g => g.Key, g => new QuestionStatistic { ChoicesFrequencies = g.Aggregate(new int[answeringChoicesCount], (curr, p) => { for (int i = 0; i < answeringChoicesCount; i++) { curr[i] += p.Value.ChoicesFrequencies[i]; } return curr; }) }); }
public void Migrate(IDictionary<string, List<MigrationStep>> steps) { foreach (MigrationStep step in steps.SelectMany(row => row.Value).OrderBy(row => row.Version)) { _log.Info(step); using (Machine.Core.LoggingUtilities.Log4NetNdc.Push("{0}", step.MigrationReference.Name)) { _configuration.ActiveConfigurationKey = step.MigrationReference.ConfigurationKey; if (!_configuration.ShowDiagnostics) { IDbTransaction transaction = null; try { transaction = _transactionProvider.Begin(); step.Apply(); if (step.Reverting) { _schemaStateManager.SetMigrationVersionUnapplied(step.Version, _configuration.Scope); } else { _schemaStateManager.SetMigrationVersionApplied(step.Version, _configuration.Scope); } _log.InfoFormat("Comitting"); transaction.Commit(); } catch (Exception) { if (transaction != null) { _log.InfoFormat("Rollback"); transaction.Rollback(); } throw; } finally { _configuration.ActiveConfigurationKey = null; } } } } }
private static void Validate(IDictionary <int, IEnumerable <PropertyInfo> > props) { var properties = new List <string>(); var message = "Found identifier properties with same order number"; properties.AddRange(props .Where(x => x.Value.Count() > 1) .SelectMany(x => x.Value) .Select(prop => prop.Name)); if (properties.Count > 0) { throw new InvalidIdentityException(message, properties.ToArray()); } message = "Class must have an Identifier"; if (props.SelectMany(x => x.Value).Count() < 1) { throw new InvalidIdentityException(message); } }
public static RequestDetails SendRequest(this WebHost webHost, string urlPath, IDictionary<string, IEnumerable<string>> postData) { var physicalPath = Bleroy.FluentPath.Path.Get(webHost.PhysicalDirectory); var details = new RequestDetails { HostName = webHost.HostName, UrlPath = urlPath, Page = physicalPath .Combine(urlPath.TrimStart('/', '\\')) .GetRelativePath(physicalPath), }; if (!string.IsNullOrEmpty(webHost.Cookies)) { details.RequestHeaders.Add("Cookie", webHost.Cookies); } if (postData != null) { var requestBodyText = postData .SelectMany(kv => kv.Value.Select(v => new { k = kv.Key, v })) .Select((kv, n) => new { p = HttpUtility.UrlEncode(kv.k) + "=" + HttpUtility.UrlEncode(kv.v), n }) .Aggregate("", (a, x) => a + (x.n == 0 ? "" : "&") + x.p); details.PostData = Encoding.Default.GetBytes(requestBodyText); } webHost.Execute(() => { var output = new StringWriter(); var worker = new Worker(details, output); HttpRuntime.ProcessRequest(worker); details.ResponseText = output.ToString(); }); string setCookie; if (details.ResponseHeaders.TryGetValue("Set-Cookie", out setCookie)) { Trace.WriteLine(string.Format("Set-Cookie: {0}", setCookie)); webHost.Cookies = (webHost.Cookies + ';' + setCookie.Split(';').FirstOrDefault()).Trim(';'); } return details; }
public void ResourceDiff_GetByRelationships() { // Arrange var dbResources = new HashSet <Dummy>(_allResources.Select(resource => new Dummy { Id = resource.Id }).ToList()); var diffs = new DiffableResourceHashSet <Dummy>(_allResources, dbResources, _relationships, null); // Act IDictionary <RelationshipAttribute, HashSet <Dummy> > toOnes = diffs.GetByRelationship <ToOne>(); IDictionary <RelationshipAttribute, HashSet <Dummy> > toManies = diffs.GetByRelationship <ToMany>(); IDictionary <RelationshipAttribute, HashSet <Dummy> > notTargeted = diffs.GetByRelationship <NotTargeted>(); IDictionary <RelationshipAttribute, HashSet <Dummy> > allRelationships = diffs.AffectedRelationships; // Assert AssertRelationshipDictionaryGetters(allRelationships, toOnes, toManies, notTargeted); List <Dummy> allResourcesWithAffectedRelationships = allRelationships.SelectMany(pair => pair.Value).ToList(); _noRelationshipsResources.ToList().ForEach(resource => { Assert.DoesNotContain(resource, allResourcesWithAffectedRelationships); }); DiffableResourceHashSet <Dummy> requestResourcesFromDiff = diffs; requestResourcesFromDiff.ToList().ForEach(resource => { Assert.Contains(resource, _allResources); }); IEnumerable <Dummy> databaseResourcesFromDiff = diffs.GetDiffs().Select(pair => pair.DatabaseValue); databaseResourcesFromDiff.ToList().ForEach(resource => { Assert.Contains(resource, dbResources); }); }
public void CleanupPackagesFolder() { var unusedPackages = _localPackageRepository .GetPackages() .ToList() .Where(x => !_loadedMsBuildNuGetProjects .SelectMany(y => y.Value.GetInstalledPackagesAsync(new CancellationToken()).Result) .Select(y => y.PackageIdentity) .Any(y => y.Id == x.Id && y.Version.ToString() == x.Version.ToString())) .ToArray(); foreach (IPackage package in unusedPackages) { var pathToDelete = Path.Combine(_packagesFolder, $"{package.Id}.{package.Version}"); // One would think Directory.Delete(path, recursive: true) would do the job, well // it regularly fails, and looking online it seems the solution is try/catches with // retries and recursive deletes. Well guess what, Nuget has one of those // monstrosities already, hooray! LocalResourceUtils.DeleteDirectoryTree(pathToDelete, new List <string>()); } }
GetDatasetValuesByConditionId( [CanBeNull] DataQualityCategory category, [NotNull] ISession session) { var result = new Dictionary <int, List <DatasetTestParameterValue> >(); IDictionary <int, HashSet <int> > dsParamsByQualityCondition = GetDatasetParameterIdsByQualityConditionId(session, category); if (dsParamsByQualityCondition.Count == 0) { return(result); } // flatmap to get the complete parameter id list var allDsParamIds = new HashSet <int>( dsParamsByQualityCondition.SelectMany(pair => pair.Value)); Dictionary <int, DatasetTestParameterValue> datasetValuesById = GetDatasetTestParameterValuesById(session, allDsParamIds); foreach (KeyValuePair <int, HashSet <int> > pair in dsParamsByQualityCondition) { var values = new List <DatasetTestParameterValue>(); foreach (int paramValId in pair.Value) { DatasetTestParameterValue value; if (datasetValuesById.TryGetValue(paramValId, out value)) { values.Add(value); } } result.Add(pair.Key, values); } return(result); }
internal void LogMissingKeys() { var allIds = consumedKeys.SelectMany(x => x.Value).ToArray(); var missed = new List <string>(); for (var i = 0; i < Program.ProcessesCount; i++) { for (var j = 0; j < Program.WorkCountPerProcess; j++) { var keyJ = $"{i}-{j}"; if (allIds.Contains(keyJ) == false) { missed.Add(keyJ); } for (var k = 0; k < Program.ExtraWorkCountPerProcess; k++) { var keyK = $"{i}-{j}-{k}"; if (allIds.Contains(keyK) == false) { missed.Add(keyK); } } } } if (missed.Any()) { logger.LogError("Missing {0} messages: {1}", missed.Count, string.Join(", ", missed)); } else { logger.LogInformation("No missed messages"); } }
public static IDictionary <TNewKey, TResult> Transpose <TOldKey, TNewKey, TValue, TResult>( this IDictionary <TOldKey, IDictionary <TNewKey, TValue> > dictionary, Func <IDictionary <TOldKey, TValue>, TResult> selector ) { if (dictionary == null) { throw new ArgumentNullException(nameof(dictionary)); } if (selector == null) { throw new ArgumentNullException(nameof(selector)); } return(dictionary .SelectMany( pair => pair.Value, (pair, value) => new { OldKey = pair.Key, NewKey = value.Key, value.Value } ).GroupBy( arg => arg.NewKey, (key, enumerable) => new { Key = key, Value = enumerable.ToDictionary( arg => arg.OldKey, arg => arg.Value ) } ).ToDictionary( arg => arg.Key, arg => selector(arg.Value) )); }
private IEnumerable <Artist> CreateAlbumsWithManyArtists(IDictionary <string, List <string> > albumsWithMultipleArtists) { List <Artist> result = new List <Artist>(); var artistNames = albumsWithMultipleArtists.SelectMany(kvp => kvp.Value).Distinct(); //create artists first Dictionary <string, Artist> artistsCache = new Dictionary <string, Artist>(); foreach (var a in artistNames) { var artist = new Artist() { Name = a }; artistsCache[a] = artist; result.Add(artist); } //enumerate albums foreach (var kvp in albumsWithMultipleArtists) { var album = new Album() { Name = kvp.Key }; foreach (var artistName in kvp.Value) { var cachedArtist = artistsCache[artistName]; album.Artists.Add(cachedArtist); cachedArtist.Albums.Add(album); } } return(result); }
internal static string NormalizeLanguage(string language) { if (string.IsNullOrWhiteSpace(language)) { throw new ArgumentNullException(nameof(language), "Language can't be empty"); } else if (!availableLanguages.Keys.Concat(availableLanguages.SelectMany(p => p.Value)) .Any(l => l.Equals(language, StringComparison.OrdinalIgnoreCase))) { throw new ArgumentException($"Language {language} is not a valid option. Options are {AvailableLanguagesList}"); } var klanguage = availableLanguages.Keys.FirstOrDefault(k => k.Equals(language, StringComparison.OrdinalIgnoreCase)); if (!string.IsNullOrEmpty(klanguage)) { return(klanguage); } else { return(availableLanguages.First(p => p.Value.Any(v => v.Equals(language, StringComparison.OrdinalIgnoreCase))).Key); } }
public string ResultEvaluation(IDictionary <ClassType, List <CustomImage <ClassType> > > imgDictionary) { var result = new StringBuilder(); var total = 0; foreach (var key in imgDictionary.Keys) { int guessedImages = 0; foreach (var customImage in imgDictionary[key]) { guessedImages += DefineImage(customImage) == key ? 1 : 0; } total += guessedImages; result.Append(string.Format("\n{0}: {1}", key, ((double)guessedImages * 100 / imgDictionary[key].Count).ToString("F"))); } result.Append(string.Format("\nВсего: {0}", ((double)total * 100 / imgDictionary.SelectMany(x => x.Value).Count()).ToString("F"))); return(result.ToString()); }
public SyntaxNode ToSyntaxNode(SyntaxNode parent) { var dictListNode = new ListNode(parent, new List <SyntaxNode>()); dictListNode.Children.Add(new IdentifierNode(dictListNode, "dict")); var listNode = new ListNode(dictListNode, new List <SyntaxNode>()); listNode.Children.AddRange(_map .SelectMany(kvp => { //TODO If kvp.Key is SyntaxNode, then quote it? SyntaxNode key = kvp.Key.ToSyntaxNode(dictListNode); //TODO if kvp.Value is SyntaxNode, then quote it? SyntaxNode val = kvp.Value.ToSyntaxNode(dictListNode); return(new[] { key, val }); }) .ToList() ); dictListNode.Children.Add(listNode); return(dictListNode); }
protected void RenderPrivileges(string setFor, IDictionary <string, IDictionary <string, IEnumerable <ACLModel> > > privileges) { var rows = privileges.SelectMany(p => p.Value.SelectMany(v => v.Value.Select(a => new { @for = setFor, right = v.Key, key = a.OverrideKey, identifiers = string.Join(" ", a.RequiredIdentifiers.OrderBy(i => i)) } ) ) ) .OrderBy(r => r.@for) .ThenBy(r => r.right) .ThenBy(r => r.key); Table("Privileges", rows ); }
public async Task <Result> HMSet(ISession session, string key, IDictionary <string, string> fieldValues) { try { var parameters = fieldValues.SelectMany(kvp => new [] { kvp.Key, kvp.Value }).ToArray(); var command = new BasicCommandBuilder(RedisCommands.HMSET) .WithKey(key) .WithParameters(parameters) .ToString(); var response = await SendCommandAndReadResponseAsync(session, command); var responseString = response[0]?.ToString(); return(IsResponseOk(responseString) ? Result.Ok() : Result.Fail(responseString)); } catch (Exception ex) { return(Result.Fail(ex.Message, ex)); } }
public static ILookup <TKey, TElement> ToLookup <TKey, TElement>(this IEnumerable <IDocument> documents, string keyMetadataKey, string elementMetadataKey) { // Get a mapping of all documents with the key to their values IDictionary <IDocument, IEnumerable <TKey> > documentValues = documents.ToDocumentDictionary <TKey>(keyMetadataKey); // Now invert the dictionary to a lookup of values to documents return(documentValues .SelectMany(x => x.Value) .Distinct() .SelectMany(x => documentValues .Where(y => y.Value.Contains(x)) .Select(y => { IEnumerable <TElement> values; return new KeyValuePair <TKey, IEnumerable <TElement> >( x, y.Key.MetadataAs <IEnumerable <TElement> >().TryGetValue(elementMetadataKey, out values) ? values : null); }) .Where(y => y.Value != null) .SelectMany(y => y.Value.Select(z => new KeyValuePair <TKey, TElement>(y.Key, z))) ) .Distinct() .ToLookup(x => x.Key, x => x.Value)); }
public static RequestDetails SendRequest(this WebHost webHost, string urlPath, IDictionary <string, IEnumerable <string> > postData, string requestMethod = null) { var physicalPath = Bleroy.FluentPath.Path.Get(webHost.PhysicalDirectory); bool isHomepage = urlPath == "/"; if (!isHomepage) { urlPath = StripVDir(urlPath, webHost.VirtualDirectory); } var details = new RequestDetails { HostName = webHost.HostName, UrlPath = urlPath.Replace('\\', '/'), }; int queryIndex = urlPath.IndexOf('?'); if (queryIndex >= 0) { details.UrlPath = urlPath.Substring(0, queryIndex).Replace('\\', '/'); details.Query = urlPath.Substring(queryIndex + 1); } var physicalFilePath = physicalPath.Combine(details.UrlPath.TrimStart('/', '\\')); details.Page = (isHomepage ? "" : physicalFilePath.GetRelativePath(physicalPath).ToString()); if (!File.Exists(physicalFilePath)) { details.Page = details.Page.Replace('\\', '/'); } if (!string.IsNullOrEmpty(webHost.Cookies)) { details.RequestHeaders.Add("Cookie", webHost.Cookies); } details.RequestHeaders.Add("Accept-Charset", "utf-8"); if (postData != null) { var requestBodyText = postData .SelectMany(kv => kv.Value.Select(v => new { k = kv.Key, v })) .Select((kv, n) => new { p = HttpUtility.UrlEncode(kv.k) + "=" + HttpUtility.UrlEncode(kv.v), n }) .Aggregate("", (a, x) => a + (x.n == 0 ? "" : "&") + x.p); if (requestMethod == "POST") { details.PostData = Encoding.Default.GetBytes(requestBodyText); } else { details.Query = requestBodyText; } } webHost.Execute(() => { var output = new StringWriter(); var worker = new Worker(details, output); HttpRuntime.ProcessRequest(worker); details.ResponseText = output.ToString(); }); string setCookie; if (details.ResponseHeaders.TryGetValue("Set-Cookie", out setCookie)) { // Trace.WriteLine(string.Format("Set-Cookie: {0}", setCookie)); var cookieName = setCookie.Split(';')[0].Split('=')[0]; DateTime expires; if (!string.IsNullOrEmpty(webHost.Cookies) && setCookie.Contains("expires=") && DateTime.TryParse(setCookie.Split(new[] { "expires=" }, 2, StringSplitOptions.None)[1].Split(';')[0], out expires) && expires < DateTime.Now) { // remove // Trace.WriteLine(string.Format("Removing cookie: {0}", cookieName)); webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*;?", cookieName), ""); } else if (!string.IsNullOrEmpty(webHost.Cookies) && Regex.IsMatch(webHost.Cookies, string.Format("\b{0}=", cookieName))) { // replace // Trace.WriteLine(string.Format("Replacing cookie: {0}", cookieName)); webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*(;?)", cookieName), string.Format("{0}$1", setCookie.Split(';')[0])); } else { // add // Trace.WriteLine(string.Format("Adding cookie: {0}", cookieName)); webHost.Cookies = (webHost.Cookies + ';' + setCookie.Split(';').FirstOrDefault()).Trim(';'); } // Trace.WriteLine(string.Format("Cookie jar: {0}", webHost.Cookies)); } return(details); }
public static IEnumerable <TValue> AllValues <TKey, TValue>( this IDictionary <TKey, List <TValue> > source) { return(source.SelectMany(item => item.Value)); }
public IEnumerable <IType> GetHandlerTypes() { return(_resourceHandlers.SelectMany(x => x.Value).Distinct()); }
public static T[] Flatten <T>(this IDictionary <Figure, MoveSequence[]> moves, Func <Figure, MoveSequence, T> builder) { return(moves.SelectMany(figureMoves => figureMoves.Value .Select(m => builder(figureMoves.Key, m))).ToArray()); }
public bool FileExists(string path) => fileSystem.SelectMany(f => f.Value.Select(v => v)) .Where(fod => fod.isDirectory == false) .Any(fod => fod.path == path.ToUpperInvariant());
IEnumerable <HexKeyValuePair <TPriority, TValue> > Enumerable() { return(_list.SelectMany(l => l.Value.Select(i => new HexKeyValuePair <TPriority, TValue>(l.Key, i)))); }
private IEnumerable<TranslationCategory> GetCategories(IDictionary<string, TranslationFile> translation) { return translation.SelectMany(pair => pair.Value.TranslationCategories); }
public IEnumerable <string> Roster() => _grades .SelectMany(gradePair => gradePair.Value, (gradePair, student) => new { Grade = gradePair.Key, Student = student }) .OrderBy(g => g.Grade).ThenBy(g => g.Student) .Select(g => g.Student);
private IOrderedEnumerable<MigrationStep> sort(IDictionary<string, List<MigrationStep>> steps) { if (steps.SelectMany(row => row.Value).Any(x => x.Reverting)) return steps.SelectMany(row => row.Value).OrderByDescending(row => row.Version); else return steps.SelectMany(row => row.Value).OrderBy(row => row.Version); }
public static IEnumerable <EventBean> CreateEnumerable(IDictionary <Object, ISet <EventBean> > window) { return(window.SelectMany(entry => entry.Value)); }
public IEnumerable <Fact> GetFacts() => _recordedFacts.Concat(_aggregates.SelectMany(x => x.Value.GetChanges().Select(e => new Fact(x.Key, e))));
public string ResultEvaluation(IDictionary<ClassType, List<CustomImage<ClassType>>> imgDictionary) { var result = new StringBuilder(); var total = 0; foreach (var key in imgDictionary.Keys) { int guessedImages = 0; foreach (var customImage in imgDictionary[key]) { guessedImages += DefineImage(customImage) == key ? 1 : 0; } total += guessedImages; result.Append(string.Format("\n{0}: {1}", key, ((double)guessedImages * 100 / imgDictionary[key].Count).ToString("F"))); } result.Append(string.Format("\nВсего: {0}", ((double)total * 100 / imgDictionary.SelectMany(x => x.Value).Count()).ToString("F"))); return result.ToString(); }
public void renderCollidingFaces(ModelGeometry collisionGeometry, IDictionary<Face, uint> collidingFaces, Camera camera, uint min, uint max) { if (collidingFaces.Count > 0) { // fill vertex buffer with collision geometry and set on device { float range = Math.Max(max - min, 0.0001f); var data = collidingFaces.SelectMany(face => { var colour = new Vector3((face.Value - min)/range); return new[] { collisionGeometry.vertices[face.Key.v1], collisionGeometry.normals[face.Key.n1], colour, collisionGeometry.vertices[face.Key.v2], collisionGeometry.normals[face.Key.n2], colour, collisionGeometry.vertices[face.Key.v3], collisionGeometry.normals[face.Key.n3], colour }; }); mCollidingFacesVertices.SetData<Vector3>(data.ToArray()); mGraphicsDevice.SetVertexBuffer(mCollidingFacesVertices); } // enable alpha blending var previousBlendState = mGraphicsDevice.BlendState; mGraphicsDevice.BlendState = mAlphaBlendState; // draw mCollisionsShader.Parameters["WorldViewProjection"].SetValue(camera.viewMatrix * camera.projectionMatrix); mCollisionsShader.CurrentTechnique.Passes[0].Apply(); mGraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, collidingFaces.Count); // restore previous blend mode mGraphicsDevice.BlendState = previousBlendState; } }
private static IEnumerable <Entity> GetEntities(string utterance, IDictionary <string, object> entities) { if (entities == null || entities.Count == 0) { return(null); } IEnumerable <Entity> getEntitiesForType(string type, object instances, JToken metadata) { if (instances is JArray instancesJson) { var typeMetadata = metadata?[type]; return(instancesJson .Zip( typeMetadata, (instance, instanceMetadata) => getEntitiesRecursive(type, instance, instanceMetadata)) .SelectMany(e => e)); } return(Array.Empty <Entity>()); } IEnumerable <Entity> getEntitiesRecursive(string entityType, JToken entityJson, JToken entityMetadata) { var startIndex = entityMetadata.Value <int>("startIndex"); var length = entityMetadata.Value <int>("length"); var score = entityMetadata.Value <double?>("score"); var matchText = utterance.Substring(startIndex, length); var matchIndex = 0; var currentStart = 0; while ((currentStart = utterance.IndexOf(matchText, currentStart, StringComparison.Ordinal)) != startIndex) { ++matchIndex; currentStart++; } var entityValue = PruneMetadata(entityJson); if (entityJson is JObject entityJsonObject && entityJsonObject.TryGetValue("$instance", out var innerMetadata)) { var children = ((IDictionary <string, JToken>)entityJsonObject) .SelectMany(pair => getEntitiesForType(pair.Key, pair.Value, innerMetadata)); foreach (var child in children) { yield return(child); } } yield return(new Entity(entityType, entityValue, matchText, matchIndex) .WithScore(score)); } var globalMetadata = default(JToken); if (entities.TryGetValue("$instance", out var metadataValue) && metadataValue is JToken metadataJson) { globalMetadata = metadataJson; } else { throw new InvalidOperationException("Expected top-level metadata for entities."); } return(entities.SelectMany(pair => getEntitiesForType(pair.Key, pair.Value, globalMetadata))); }
private static IEnumerable <TranslationCategory> GetCategories(IDictionary <string, TranslationFile> translation) { return(translation.SelectMany(pair => pair.Value.TranslationCategories)); }
/// <summary> /// Creates a new assignment with the given data. /// </summary> public TestDatabaseBuilder AddAssignment( string classroomName, string assignmentGroupName, string assignmentName, IDictionary<string, DateTime> sectionDueDates, IDictionary<string, string[]> questionsByCategory) { var classroom = _buildContext.Classrooms .Include(c => c.Sections) .Single(c => c.Name == classroomName); var sections = classroom.Sections .ToDictionary(s => s.Name, s => s.Id); var allQuestions = _buildContext.Questions .Include(q => q.QuestionCategory) .ToList() .GroupBy(q => q.QuestionCategory.Name) .ToDictionary(group => group.Key, group => group.ToDictionary(q => q.Name, q => q.Id)); var assignment = new Assignment() { ClassroomId = classroom.Id, Name = assignmentName, GroupName = assignmentGroupName, DueDates = sectionDueDates.Select ( kvp => new AssignmentDueDate() { SectionId = sections[kvp.Key], DueDate = kvp.Value } ).ToList(), Questions = questionsByCategory.SelectMany ( qs => qs.Value, (kvp, questionName) => new AssignmentQuestion() { QuestionId = allQuestions[kvp.Key][questionName], Points = 1.0 } ).ToList() }; _buildContext.Assignments.Add(assignment); _buildContext.SaveChanges(); return this; }
public virtual IEnumerator <EventBean> GetEnumerator() { return(PropertyIndex.SelectMany(entry => entry.Value).GetEnumerator()); }
public static bool SerializeSafe(this IZipper _Zipper, IDictionary<string, string> idic, string iFilename, string ipassword) { return _Zipper.Zipp(idic.SelectMany(kvp => new string[] { kvp.Key, kvp.Value }), iFilename, ipassword); }
public static RequestDetails SendRequest(this WebHost webHost, string urlPath, IDictionary<string, IEnumerable<string>> postData, string requestMethod = null) { var physicalPath = Bleroy.FluentPath.Path.Get(webHost.PhysicalDirectory); bool isHomepage = urlPath == "/"; if (!isHomepage) urlPath = StripVDir(urlPath, webHost.VirtualDirectory); var details = new RequestDetails { HostName = webHost.HostName, UrlPath = urlPath.Replace('\\', '/'), }; int queryIndex = urlPath.IndexOf('?'); if (queryIndex >= 0) { details.UrlPath = urlPath.Substring(0, queryIndex).Replace('\\', '/'); details.Query = urlPath.Substring(queryIndex + 1); } var physicalFilePath = physicalPath.Combine(details.UrlPath.TrimStart('/', '\\')); details.Page = (isHomepage ? "" : physicalFilePath.GetRelativePath(physicalPath).ToString()); if (!File.Exists(physicalFilePath)) details.Page = details.Page.Replace('\\', '/'); if (!string.IsNullOrEmpty(webHost.Cookies)) { details.RequestHeaders.Add("Cookie", webHost.Cookies); } if (postData != null) { var requestBodyText = postData .SelectMany(kv => kv.Value.Select(v => new { k = kv.Key, v })) .Select((kv, n) => new { p = HttpUtility.UrlEncode(kv.k) + "=" + HttpUtility.UrlEncode(kv.v), n }) .Aggregate("", (a, x) => a + (x.n == 0 ? "" : "&") + x.p); if (requestMethod == "POST") details.PostData = Encoding.Default.GetBytes(requestBodyText); else details.Query = requestBodyText; } webHost.Execute(() => { var output = new StringWriter(); var worker = new Worker(details, output); HttpRuntime.ProcessRequest(worker); details.ResponseText = output.ToString(); }); string setCookie; if (details.ResponseHeaders.TryGetValue("Set-Cookie", out setCookie)) { Trace.WriteLine(string.Format("Set-Cookie: {0}", setCookie)); var cookieName = setCookie.Split(';')[0].Split('=')[0]; DateTime expires; if (!string.IsNullOrEmpty(webHost.Cookies) && setCookie.Contains("expires=") && DateTime.TryParse(setCookie.Split(new[] { "expires=" }, 2, StringSplitOptions.None)[1].Split(';')[0], out expires) && expires < DateTime.Now) { // remove Trace.WriteLine(string.Format("Removing cookie: {0}", cookieName)); webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*;?", cookieName), ""); } else if (!string.IsNullOrEmpty(webHost.Cookies) && Regex.IsMatch(webHost.Cookies, string.Format("\b{0}=", cookieName))) { // replace Trace.WriteLine(string.Format("Replacing cookie: {0}", cookieName)); webHost.Cookies = Regex.Replace(webHost.Cookies, string.Format("{0}=[^;]*(;?)", cookieName), string.Format("{0}$1", setCookie.Split(';')[0])); } else { // add Trace.WriteLine(string.Format("Adding cookie: {0}", cookieName)); webHost.Cookies = (webHost.Cookies + ';' + setCookie.Split(';').FirstOrDefault()).Trim(';'); } Trace.WriteLine(string.Format("Cookie jar: {0}", webHost.Cookies)); } return details; }
public static List <V1ServicePort> GetHostPorts(this IDictionary <string, IList <PortBinding> > ports) => ports.SelectMany(port => ExtractHostPorts(port.Key, port.Value)).ToList();
public IList<PackageOperation> ResolveOperations(IEnumerable<IPackage> packages, out IList<IPackage> packagesByDependencyOrder, bool allowPrereleaseVersionsBasedOnPackage = false) { _packagesByDependencyOrder = new Dictionary<string, IList<IPackage>>(); _operations.Clear(); Marker.Clear(); _packagesToKeep.Clear(); Debug.Assert(Operations is List<PackageOperation>); foreach (var package in packages) { if (!_operations.Contains(package, PackageAction.Install)) { var allowPrereleaseVersions = _allowPrereleaseVersions; try { if (allowPrereleaseVersionsBasedOnPackage) { // Update _allowPrereleaseVersions before walking a package if allowPrereleaseVersionsBasedOnPackage is set to true // This is mainly used when bulk resolving operations for reinstalling packages _allowPrereleaseVersions = _allowPrereleaseVersions || !package.IsReleaseVersion(); } Walk(package); } finally { _allowPrereleaseVersions = allowPrereleaseVersions; } } } // Flatten the dictionary to create a list of all the packages. Only this item the packages visited first during the walk will appear on the list. Also, only retain distinct elements IEnumerable<IPackage> allPackagesByDependencyOrder = _packagesByDependencyOrder.SelectMany(p => p.Value).Distinct(); // Only retain the packages for which the operations are being resolved for packagesByDependencyOrder = allPackagesByDependencyOrder.Where(p => packages.Any(q => p.Id == q.Id && p.Version == q.Version)).ToList(); Debug.Assert(packagesByDependencyOrder.Count == packages.Count()); _packagesByDependencyOrder.Clear(); _packagesByDependencyOrder = null; return Operations.Reduce(); }
/// <summary>Provides a list of the scheduled tasks for the debugger to consume.</summary> /// <returns>An enumerable of all tasks currently scheduled.</returns> protected override IEnumerable <Task> GetScheduledTasks() { // Serialize the contents of the blocking collection of tasks for the debugger return(_tasks.SelectMany(pair => pair.Value.ToArray())); }
public IEnumerable <SqlScript> GetScripts(IConnectionManager connectionManager) { return(_scripts.SelectMany(tmpl => _values.Select(v => new LazySqlScript(GetScriptName(tmpl.Key, v), GetScriptContent(tmpl.Value, v))))); }
public async Task <IHostProvider> GetProviderAsync(InputArguments input) { IHostProvider provider; // // Try and locate a specified provider // if (_context.Settings.ProviderOverride is string providerId) { _context.Trace.WriteLine($"Host provider override was set id='{providerId}'"); if (!StringComparer.OrdinalIgnoreCase.Equals(Constants.ProviderIdAuto, providerId)) { provider = _hostProviders .SelectMany(x => x.Value) .FirstOrDefault(x => StringComparer.OrdinalIgnoreCase.Equals(x.Id, providerId)); if (provider is null) { _context.Trace.WriteLine($"No host provider was found with ID '{providerId}'.. falling back to auto-detection."); _context.Streams.Error.WriteLine($"warning: a host provider override was set but no such provider '{providerId}' was found. Falling back to auto-detection."); } else { return(provider); } } } // // Try and locate a provider by supported authorities // else if (_context.Settings.LegacyAuthorityOverride is string authority) { _context.Trace.WriteLine($"Host provider authority override was set authority='{authority}'"); _context.Streams.Error.WriteLine("warning: the `credential.authority` and `GCM_AUTHORITY` settings are deprecated."); _context.Streams.Error.WriteLine($"warning: see {Constants.HelpUrls.GcmAuthorityDeprecated} for more information."); if (!StringComparer.OrdinalIgnoreCase.Equals(Constants.AuthorityIdAuto, authority)) { provider = _hostProviders .SelectMany(x => x.Value) .FirstOrDefault(x => x.SupportedAuthorityIds.Contains(authority, StringComparer.OrdinalIgnoreCase)); if (provider is null) { _context.Trace.WriteLine($"No host provider was found with authority '{authority}'.. falling back to auto-detection."); _context.Streams.Error.WriteLine($"warning: a supported authority override was set but no such provider supporting authority '{authority}' was found. Falling back to auto-detection."); } else { return(provider); } } } // // Auto-detection // Perform auto-detection network probe and remember the result // _context.Trace.WriteLine("Performing auto-detection of host provider."); var uri = input.GetRemoteUri(); if (uri is null) { throw new Exception("Unable to detect host provider without a remote URL"); } var probeTimeout = TimeSpan.FromMilliseconds(_context.Settings.AutoDetectProviderTimeout); _context.Trace.WriteLine($"Auto-detect probe timeout is {probeTimeout.TotalSeconds} ms."); HttpResponseMessage probeResponse = null; async Task <IHostProvider> MatchProviderAsync(HostProviderPriority priority) { if (_hostProviders.TryGetValue(priority, out ICollection <IHostProvider> providers)) { _context.Trace.WriteLine($"Checking against {providers.Count} host providers registered with priority '{priority}'."); // Try matching using the static Git input arguments first (cheap) if (providers.TryGetFirst(x => x.IsSupported(input), out IHostProvider match)) { return(match); } // Try matching using the HTTP response from a query to the remote URL (expensive). // The user may have disabled this feature with a zero or negative timeout for performance reasons. // We only probe the remote once and reuse the same response for all providers. if (probeTimeout.TotalMilliseconds > 0) { if (probeResponse is null) { _context.Trace.WriteLine("Querying remote URL for host provider auto-detection."); using (HttpClient client = _context.HttpClientFactory.CreateClient()) { client.Timeout = probeTimeout; try { probeResponse = await client.HeadAsync(uri); } catch (TaskCanceledException) { _context.Streams.Error.WriteLine($"warning: auto-detection of host provider took too long (>{probeTimeout.TotalMilliseconds}ms)"); _context.Streams.Error.WriteLine($"warning: see {Constants.HelpUrls.GcmAutoDetect} for more information."); } catch (Exception ex) { // The auto detect probing failed for some other reason. // We don't particular care why, but we should not crash! _context.Streams.Error.WriteLine($"warning: failed to probe '{uri}' to detect provider"); _context.Streams.Error.WriteLine($"warning: {ex.Message}"); _context.Streams.Error.WriteLine($"warning: see {Constants.HelpUrls.GcmAutoDetect} for more information."); } } } if (providers.TryGetFirst(x => x.IsSupported(probeResponse), out match)) { return(match); } } } return(null); } // Match providers starting with the highest priority IHostProvider match = await MatchProviderAsync(HostProviderPriority.High) ?? await MatchProviderAsync(HostProviderPriority.Normal) ?? await MatchProviderAsync(HostProviderPriority.Low) ?? throw new Exception("No host provider available to service this request."); // If we ended up making a network call then set the host provider explicitly // to avoid future calls! if (probeResponse != null) { IGitConfiguration gitConfig = _context.Git.GetConfiguration(); var keyName = string.Format(CultureInfo.InvariantCulture, "{0}.{1}.{2}", Constants.GitConfiguration.Credential.SectionName, uri.ToString().TrimEnd('/'), Constants.GitConfiguration.Credential.Provider); try { _context.Trace.WriteLine($"Remembering host provider for '{uri}' as '{match.Id}'..."); gitConfig.Set(GitConfigurationLevel.Global, keyName, match.Id); } catch (Exception ex) { _context.Trace.WriteLine("Failed to set host provider!"); _context.Trace.WriteException(ex); _context.Streams.Error.WriteLine("warning: failed to remember result of host provider detection!"); _context.Streams.Error.WriteLine($"warning: try setting this manually: `git config --global {keyName} {match.Id}`"); } } return(match); }
public static TKey[] ToChoiceArray <TKey>(this IDictionary <TKey, int> dictionary) { return(dictionary.SelectMany(kvp => Enumerable.Repeat(kvp.Key, kvp.Value)).ToArray()); }
public static IDictionary<string, int> Transform(IDictionary<int, IList<string>> input) { return input.SelectMany(kvp => kvp.Value.Select(c => new KeyValuePair<string, int>(c.ToLower(), kvp.Key))) .ToDictionary(p => p.Key, p => p.Value); }
/// <summary> /// Finds generic types dependencies between states. /// </summary> /// <param name="result">The initial generic types dependencies</param> private void FixGenericTypes(IDictionary<IAutomataState<MethodInfo>, ICollection<Type>> result) { int? currentGenericTypes = null; int? previousGenericTypes; // TODO: This part sucks, feel free to rewrite it. do { foreach (IAutomataState<MethodInfo> state in mAutomata) { // Finds all missing generic types returned by // non generic methods. var nonGenericMethodsTypeGenericParameters = (from method in mAlphabet where !method.IsGenericMethod let transitedState = state.Transit(method) where transitedState.IsValid from genericType in result[transitedState] select genericType); // Finds all missing generic types returned by // generic methods. var genericMethodsTypeGenericParameters = from method in mAlphabet where method.IsGenericMethod let transitedState = state.Transit(method) where transitedState.IsValid from genericType in result[transitedState].Except(method.GetGenericArguments(), new ToStringComparer<Type>()) select genericType; result[state] = nonGenericMethodsTypeGenericParameters .Union(genericMethodsTypeGenericParameters) .Union(result[state], new ToStringComparer<Type>()).ToList(); } previousGenericTypes = currentGenericTypes; currentGenericTypes = result.SelectMany(x => x.Value).Count(); } while (previousGenericTypes != currentGenericTypes); }
private void CleanCache(IDictionary<char, List<Mesh>> cache, bool empty) { if (empty) { //Discard everything in this cache foreach (var mesh in cache.SelectMany(item => item.Value)) { //We're sharing buffers, so disposing them now would be very bad! Set them to null to make sure they're not disposed mesh.IndexBuffer = null; mesh.VertexBuffer = null; //Dispose the mesh mesh.Dispose(); } cache.Clear(); } else { //Find all keys with an empty cache foreach (var item in cache) if (item.Value.Count == 0) _cleanup.Add(item.Key); //Remove all the useless keys foreach (var character in _cleanup) cache.Remove(character); _cleanup.Clear(); } }