Example #1
0
        public override IEnumerable<string> PotentialLocations(IEnumerable<string> locations, IDictionary<string, object> extra)
        {
            string languageName;
            if (!TryGetString(extra, "language", out languageName))
                return locations;

                var extension = languageName + ".spark";

            var slashPos = languageName.IndexOf('-');
            if (slashPos == -1)
            {
                return locations.SelectMany(
                    path => new[]
                             {
                                 Path.ChangeExtension(path, extension),
                                 path
                             });
            }

            var shortExtension = languageName.Substring(0, slashPos) + ".spark";
            return locations.SelectMany(
                    path => new[]
                             {
                                 Path.ChangeExtension(path, extension),
                                 Path.ChangeExtension(path, shortExtension),
                                 path
                             });
        }
        public Report GetReport(IEnumerable<Report> reports)
        {
            Log.InfoFormat("Merging {0} reports", reports.Count());

            var files = reports.SelectMany(x => x.Files)
                .GroupBy(x => x.Name)
                .Select(x => new File()
                {
                    Name = x.Key,
                    Annotations = x.SelectMany(y => y.Annotations).ToArray(),
                })
                .ToArray();

            var types = reports.SelectMany(x => x.Types).GroupBy(x => x.Name).Select(x => x.First()).OrderBy(x => x.Display).ToArray();
            var typeList = new List<TypeDefinition>(types);
            var allTypes = files.SelectMany(x => x.Annotations).Select(x => x.Type).Distinct();
            foreach (var type in allTypes.Where(x => types.All(y => !y.Name.Equals(x))))
            {
                typeList.Add(new TypeDefinition()
                {
                    Name = type,
                    Color = "#ff0000",
                    Background = "#f7dede",
                    Display = type,
                });
            }
            var used = new HashSet<string>(reports.SelectMany(x => x.Files).SelectMany(x => x.Annotations).Select(x => x.Type).Distinct());

            return new Report()
            {
                Files = files,
                Types = types.Where(x => used.Contains(x.Name)).ToArray(),
            };
        }
Example #3
0
        public IInstance Create(string name, string remarks, PhysicalAddress macAddress, IEnumerable<Command.Response.Device> roster)
        {
            Instance instance = new Instance(macAddress, name, remarks);

            instance.Observables = roster.SelectMany(device => CreateObservable(instance, device));
            instance.Actionables = roster.SelectMany(device => CreateActionable(instance, device));

            return instance;
        }
        private DbInterceptionContext(IEnumerable<DbInterceptionContext> copyFrom)
        {
            _dbContexts = copyFrom.SelectMany(c => c.DbContexts)
                                  .Distinct()
                                  .Where(c => !c.InternalContext.IsDisposed).ToList();

            _objectContexts = copyFrom.SelectMany(c => c.ObjectContexts)
                                      .Distinct()
                                      .Where(c => !c.IsDisposed).ToList();
        }
 public IEnumerable<UserStatistic> GetHelpsStatistic(IEnumerable<GameDb> games)
 {
     return Enumerable.Concat(
         games.SelectMany(x => x.HomeTeam.Members),
         games.SelectMany(x => x.GuestTeam.Members))
         .GroupBy(x => x.Id)
         .Select(x => new UserStatistic
         {
             Id = x.Key,
             Value = x.Sum(y => y.Help)
         });
 }
Example #6
0
        static void DbMetrics(string caption, IEnumerable<Order> orders)
        {
            int count = orders.Count();
            int lines = orders.SelectMany(ord => ord.Lines).Count();
            int totalQty = orders.SelectMany(ord => ord.Lines)
                    .Sum(line => line.Quantity);
            decimal totalValue = orders.SelectMany(ord => ord.Lines)
                    .Sum(line => line.Quantity * line.UnitPrice);

            Console.WriteLine("{0}\torders {1}; lines {2}; units {3}; value {4:C}",
                              caption, count, lines, totalQty, totalValue);
        }
        public CompositeEntitySchema(EntitySchema schema, IEnumerable<EntitySchema> ancestorSchemas, bool copyRelationProxiesFromSchema = false)
            : base(schema.Alias, schema.Name)
        {
            //TODO: Need to move this into a mapper, but not currently one available at the right level
            Id = schema.Id;
            SchemaType = SchemaType;
            AttributeGroups.AddRange(schema.AttributeGroups);
            AttributeDefinitions.AddRange(schema.AttributeDefinitions);
            UtcCreated = schema.UtcCreated;
            UtcModified = schema.UtcModified;
            UtcStatusChanged = schema.UtcStatusChanged;

            var inheritedDefsDict = new Dictionary<string, InheritedAttributeDefinition>();
            var inheritedDefs = ancestorSchemas
                .SelectMany(entitySchema => entitySchema.AttributeDefinitions.Select(definition => new InheritedAttributeDefinition(definition, entitySchema))).ToArray();
            foreach (var def in inheritedDefs)
            {
                if (!inheritedDefsDict.ContainsKey(def.Alias))
                    inheritedDefsDict.Add(def.Alias, def);
            }

            InheritedAttributeDefinitions = new EntityCollection<InheritedAttributeDefinition>(inheritedDefsDict.Values);

            // Need to only show the inherited groups that are exposed by the filtered inherited attribute definitions, but also include empty
            // groups so that they have a chance to have some definitions added
            var allLinkedGroups = ancestorSchemas.SelectMany(x => x.AttributeDefinitions.Select(y => new InheritedAttributeGroup(y.AttributeGroup, x)));
            var allKnownGroups = ancestorSchemas.SelectMany(x => x.AttributeGroups.Select(y => new InheritedAttributeGroup(y, x)));
            var unlinkedGroups = allKnownGroups.Except(allLinkedGroups);

            var inheritedGroups =
                InheritedAttributeDefinitions.Select(x => new InheritedAttributeGroup(x.AttributeGroup, x.Schema)).Union
                    (unlinkedGroups);

            InheritedAttributeGroups = new EntityCollection<InheritedAttributeGroup>(inheritedGroups);

            RelationProxies.LazyLoadDelegate = schema.RelationProxies.LazyLoadDelegate;
            XmlConfiguration = schema.XmlConfiguration;

            if (copyRelationProxiesFromSchema)
            {
                foreach (var proxies in schema.RelationProxies.GetManualParentProxies())
                {
                    RelationProxies.EnlistParent(proxies.Item.Source, proxies.Item.Type, proxies.Item.Ordinal, proxies.Item.MetaData.ToArray());
                }
                foreach (var proxies in schema.RelationProxies.GetManualChildProxies())
                {
                    RelationProxies.EnlistParent(proxies.Item.Source, proxies.Item.Type, proxies.Item.Ordinal, proxies.Item.MetaData.ToArray());
                }
            }
        }
Example #8
0
 private GenerationTransaction CreateGenerationTransaction(IEnumerable<Transaction> transactions, uint height, ulong nonce)
 {
     var antshares = Blockchain.Default.GetUnspentAntShares().GroupBy(p => p.ScriptHash, (k, g) => new
     {
         ScriptHash = k,
         Amount = g.Sum(p => p.Value)
     }).OrderBy(p => p.Amount).ThenBy(p => p.ScriptHash).ToArray();
     Fixed8 amount_in = transactions.SelectMany(p => p.References.Values.Where(o => o.AssetId == Blockchain.AntCoin.Hash)).Sum(p => p.Value);
     Fixed8 amount_out = transactions.SelectMany(p => p.Outputs.Where(o => o.AssetId == Blockchain.AntCoin.Hash)).Sum(p => p.Value);
     Fixed8 amount_sysfee = transactions.Sum(p => p.SystemFee);
     Fixed8 quantity = Blockchain.Default.GetQuantityIssued(Blockchain.AntCoin.Hash);
     List<TransactionOutput> outputs = new List<TransactionOutput>
     {
         new TransactionOutput
         {
             AssetId = Blockchain.AntCoin.Hash,
             Value = amount_in - amount_out - amount_sysfee,
             ScriptHash = wallet.GetContracts().First().ScriptHash
         }
     };
     if (height % Blockchain.MintingInterval == 0 && antshares.Length > 0)
     {
         ulong n = nonce % (ulong)antshares.Sum(p => p.Amount).GetData();
         ulong line = 0;
         int i = -1;
         do
         {
             line += (ulong)antshares[++i].Amount.GetData();
         } while (line <= n);
         outputs.Add(new TransactionOutput
         {
             AssetId = Blockchain.AntCoin.Hash,
             Value = Fixed8.FromDecimal((Blockchain.AntCoin.Amount - (quantity - amount_sysfee)).ToDecimal() * Blockchain.GenerationFactor),
             ScriptHash = antshares[i].ScriptHash
         });
     }
     return new GenerationTransaction
     {
         Nonce = (uint)(nonce % (uint.MaxValue + 1ul)),
         Attributes = new TransactionAttribute[0],
         Inputs = new TransactionInput[0],
         Outputs = outputs.GroupBy(p => p.ScriptHash, (k, g) => new TransactionOutput
         {
             AssetId = Blockchain.AntCoin.Hash,
             Value = g.Sum(p => p.Value),
             ScriptHash = k
         }).Where(p => p.Value != Fixed8.Zero).ToArray(),
         Scripts = new Script[0]
     };
 }
Example #9
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ValidationResult"/> class.
 /// </summary>
 /// <param name="elementResults">The element results.</param>
 /// <param name="fieldResults">The field results.</param>
 /// <param name="childResults">The child results.</param>
 public ValidationResult(IEnumerable<ValidationElementResult> elementResults, IEnumerable<IValidationFieldResult> fieldResults, IEnumerable<ValidationResult> childResults)
 {
     ElementDirectResults = elementResults.ToList();
     ElementDirectFailures = elementResults.Where(result => result.Result.CountsAsFailure).ToList();
     ElementResults = childResults.SelectMany(res => res.ElementResults).Union(elementResults.ToList()).ToList();
     ElementFailures = ElementResults.Where(result => result.Result.CountsAsFailure);
     Results = childResults.SelectMany(res => res.Failures).Union(fieldResults.ToList()).ToList();
     Failures = Results.Where(result => result.CountsAsFailure);
     ElementResultsCount = ElementResults.AsBindable().Count();
     ElementFailureCount = ElementFailures.AsBindable().Count();
     ResultsCount = Results.AsBindable().Count();
     FailureCount = Failures.AsBindable().Count();
     IsSuccessful = FailureCount.Project(count => count == 0);
 }
Example #10
0
        private static ModelValidationDescriptor CreateCompositeDescription(IEnumerable<IModelValidator> validators)
        {
            var rules =
                validators.SelectMany(v => v.Description.Rules);

            return new ModelValidationDescriptor(rules);
        }
        public GraphViewModel(IEnumerable<MixedResult> results)
        {
            Nodes = new List<Node>();
            Links = new List<Link>();

            Links = results.Select(r => r.Relationships.Select(rel => new Link
                                   {
                                       Source = Convert.ToString(rel.StartNodeReference.Id),
                                       Target = Convert.ToString(rel.EndNodeReference.Id),
                                       Type = rel.TypeKey
                                   }).ToList())
                           .ToList()
                           .SelectMany(x => x.Select(l => l))
                           .ToList();

            ((List<Node>) Nodes).AddRange(
                results.SelectMany(r => r.Nodes.Select(node => Cast(node.Data, node.Reference.Id.ToString()))));

            var dict = new Dictionary<string, Node>();
            foreach (var node in Nodes)
            {
                if (!dict.ContainsKey(node.Id))
                    dict.Add(node.Id, node);
            }
            Nodes = dict.Values.ToList();
        }
Example #12
0
        public static IEnumerable<MenuItemGroupInfo> CalculateMenuGroups(IEnumerable<Ticket> tickets, IEnumerable<MenuItem> menuItems)
        {
            var menuItemInfoGroups =
                from c in tickets.SelectMany(x => x.Orders.Select(y => new { Ticket = x, Order = y }))
                join menuItem in menuItems on c.Order.MenuItemId equals menuItem.Id
                group c by menuItem.GroupCode into grp
                select new MenuItemGroupInfo
                {
                    GroupName = grp.Key,
                    Quantity = grp.Sum(y => y.Order.Quantity),
                    Amount = grp.Sum(y => CalculateOrderTotal(y.Ticket, y.Order))
                };

            var result = menuItemInfoGroups.ToList().OrderByDescending(x => x.Amount);

            var sum = menuItemInfoGroups.Sum(x => x.Amount);
            foreach (var menuItemInfoGroup in result)
            {
                if (sum > 0)
                    menuItemInfoGroup.Rate = (menuItemInfoGroup.Amount * 100) / sum;
                if (string.IsNullOrEmpty(menuItemInfoGroup.GroupName))
                    menuItemInfoGroup.GroupName = Localization.Properties.Resources.UndefinedWithBrackets;
            }

            var qsum = menuItemInfoGroups.Sum(x => x.Quantity);
            foreach (var menuItemInfoGroup in result)
            {
                if (qsum > 0)
                    menuItemInfoGroup.QuantityRate = (menuItemInfoGroup.Quantity * 100) / qsum;
                if (string.IsNullOrEmpty(menuItemInfoGroup.GroupName))
                    menuItemInfoGroup.GroupName = Localization.Properties.Resources.UndefinedWithBrackets;
            }

            return result;
        }
 public static IEnumerable<Error> Validate(
     this IEnumerable<SpecificationProperty> specProps,
     IEnumerable<Func<IEnumerable<SpecificationProperty>,
     IEnumerable<Error>>> rules)
 {
     return rules.SelectMany(rule => rule(specProps));
 }
Example #14
0
        public static IEnumerable<ProviderIdentity> ScanForProviders(IEnumerable<Assembly> sourceAssemblies)
        {
            var referencedAssemblies = sourceAssemblies
                .SelectMany(a => a.GetReferencedAssemblies())
                .Select(a =>
                {
                    try
                    {
                        return Assembly.Load(a.FullName);
                    }
                    catch
                    {
                        return null;
                    }
                })
                .Where(a => a != null);

            var toScan = Enumerable.Concat(sourceAssemblies, referencedAssemblies)
                .Distinct()
                .ToList();

            return toScan
                .SelectMany(a => a.GetTypes())
                .Where(t => typeof(EventSource).IsAssignableFrom(t) && !t.IsAbstract)
                .Select(t => ProviderIdentity.FromType(t));
        }
Example #15
0
        public static IEnumerable<IndexRange> ChunkRangesBySize(IEnumerable<IndexRange> extents, int pageSizeInBytes)
        {
            var extentRanges = extents.SelectMany(e => e.PartitionBy(pageSizeInBytes));
            var extentQueue = new Queue<IndexRange>(extentRanges);

            if (extentQueue.Count == 0)
            {
                yield break;
            }

            // move to next start position
            do
            {
                var result = extentQueue.Dequeue();
                while (result.Length < pageSizeInBytes && extentQueue.Count > 0)
                {
                    var nextRange = extentQueue.Peek();
                    if (!nextRange.Abuts(result))
                    {
                        break;
                    }
                    var mergedRange = nextRange.Merge(result);
                    if (mergedRange.Length <= pageSizeInBytes)
                    {
                        result = mergedRange;
                        extentQueue.Dequeue();
                    }
                    else
                    {
                        break;
                    }
                }
                yield return result;
            } while (extentQueue.Count > 0);
        }
Example #16
0
 private IEnumerable<CstNode> CreateRejectedNodes(
         IEnumerable<CstNode> csts, ICollection<CstNode> acceptedNodes) {
     var uppermostNodes = csts
             .SelectMany(cst => LearningExperimentUtil
                     .GetUppermostNodesByNames(cst, SelectedNodeNames));
     return uppermostNodes.Where(node => !acceptedNodes.Contains(node));
 }
Example #17
0
 private void VerifySeedAcceptedNodes(
         IEnumerable<CstNode> seedCsts, ICollection<CstNode> uppermostSeedAcceptedNodes,
         LearningExperiment oracle) {
     var anotherUppermostSeedAcceptedNodes = seedCsts
             .SelectMany(cst => LearningExperimentUtil
                     .GetUppermostNodesByNames(cst, SelectedNodeNames))
             .Where(oracle.ProtectedIsAcceptedUsingOracle)
             .ToList();
     var b1 = !uppermostSeedAcceptedNodes.All(oracle.IsAcceptedUsingOracle);
     var b2 = anotherUppermostSeedAcceptedNodes
             .Select(node => node.AncestorWithSingleChild())
             .Any(e => !uppermostSeedAcceptedNodes.Contains(e));
     var b3 = uppermostSeedAcceptedNodes.Count != anotherUppermostSeedAcceptedNodes.Count;
     Console.WriteLine("Initial: " + string.Join(", ", oracle.OracleNames));
     Console.WriteLine("Learned: " + string.Join(", ", SelectedNodeNames));
     if (b1 || b2 || b3) {
         Console.WriteLine("--------------------------------------------------");
         foreach (var e in uppermostSeedAcceptedNodes) {
             Console.WriteLine(e);
         }
         Console.WriteLine("--------------------------------------------------");
         foreach (var e in anotherUppermostSeedAcceptedNodes) {
             Console.WriteLine(e);
         }
         throw new Exception("Wrong Oracle.");
     }
 }
        public ValidationPlan(Type type, IEnumerable<ValidationStep> steps)
        {
            _type = type;
            _steps = steps;

            _fieldRules = new Lazy<ClassFieldValidationRules>(() => _steps.SelectMany(step => step.Rules).OfType<ClassFieldValidationRules>().SingleOrDefault());
        }
Example #19
0
 public IEnumerable<Type> GetMessageTypesHandledBy(Type openGenericHandlerType, IEnumerable<Type> handlerTypes)
 {
     return handlerTypes
         .SelectMany(h => h.GetGenericInterfacesClosing(openGenericHandlerType).Select(gi => gi.GetGenericArguments().First()))
         .OrderBy(m => m.Name)
         .Distinct();
 }
Example #20
0
 async System.Threading.Tasks.Task
#endif
            LoadModules(IEnumerable<string> patterns)
        {
#if PCL
            throw new NotImplementedException();
#else
            var plugins = KernelConfiguration.Components.GetAll<IModuleLoaderPlugin>();

            var fileGroups = patterns
#if !WINRT
                .SelectMany(pattern => GetFilesMatchingPattern(pattern))
                .GroupBy(filename => Path.GetExtension(filename).ToLowerInvariant());
#else
                .GroupBy(filename => GetExtension(filename).ToLowerInvariant());
#endif          

            foreach (var fileGroup in fileGroups)
            {
                string extension = fileGroup.Key;
                IModuleLoaderPlugin plugin = plugins.Where(p => p.SupportedExtensions.Contains(extension)).FirstOrDefault();

                if (plugin != null)
#if WINRT
                    await 
#endif               
                    plugin.LoadModules(fileGroup);
            }
#endif
        }
Example #21
0
 public override void ComposeFilters(IEnumerable<User> users)
 {
     var roles = users.SelectMany(u => u.UserRoles.Select(r => r.RoleType).Distinct());
     var roleNames = roles.Select(r => r.ToString()).ToList();
     roleNames.RemoveAll(r => r == UserRoleType.Admin.ToString());
     ComposeFilterItems(roleNames);
 }
Example #22
0
    public static bool MoveAndDig(Unit digger, IEnumerable<Point> targets)
    {
        Bb.ReadBoard();
        var passable = Solver.GetPassable();
        var moveTargets = targets.SelectMany(t => Pather.GetNeighbors(t, passable)).ToBitArray();
        moveTargets.And(targets.ToBitArray().Not());

        if (digger.MovementLeft == 0)
        {
            if (Dig(digger, targets, GetDiggableAndUnDug()))
            {
                return true;
            }
            return false;
        }

        var steps = Solver.GetWalkingSteps(digger.ToPoint(), moveTargets);
        if (steps == null)
        {
            return false;
        }
        foreach (var step in steps)
        {
            if (digger.MovementLeft > 0)
            {
                digger.move(step.x, step.y);
            }
        }
        Dig(digger, targets, GetDiggableAndUnDug());
        return true;
    }
 private static void ScanAssemblies(
     IEnumerable<Assembly> assemblies,
     RegistrationBuilder rb,
     Action<ICustomizersHolder> customizerMutator)
 {
     ScanTypes(assemblies.SelectMany(a => a.GetLoadableTypes()), rb, customizerMutator);
 }
Example #24
0
        private static void AddLinkHeaders(NancyContext context, IEnumerable<Tuple<string, IEnumerable<Tuple<IResponseProcessor, ProcessorMatch>>>> compatibleHeaders, Response response)
        {
            var linkProcessors = new Dictionary<string, MediaRange>();

            var compatibleHeaderMappings =
                compatibleHeaders.SelectMany(m => m.Item2).SelectMany(p => p.Item1.ExtensionMappings);

            foreach (var compatibleHeaderMapping in compatibleHeaderMappings)
            {
                if (!compatibleHeaderMapping.Item2.Matches(response.ContentType))
                {
                    linkProcessors[compatibleHeaderMapping.Item1] = compatibleHeaderMapping.Item2;
                }
            }

            if (!linkProcessors.Any())
            {
                return;
            }

            var baseUrl =
                context.Request.Url.BasePath + "/" + Path.GetFileNameWithoutExtension(context.Request.Url.Path);

            var links = linkProcessors.Keys
                .Select(lp => string.Format("<{0}.{1}>; rel=\"{2}\"", baseUrl, lp, linkProcessors[lp]))
                .Aggregate((lp1, lp2) => lp1 + "," + lp2);

            response.Headers["Link"] = links;
        }
Example #25
0
        static IEnumerable<Type> GetTypesOfMessagesHandledByRebus(IEnumerable<Assembly> assemblies)
        {
            return assemblies
                .SelectMany(assembly => assembly.GetTypes())
                .SelectMany(type => type.GetInterfaces()
                    .Select(@interface => new
                    {
                        Type = type,
                        Interface = @interface
                    }))
                .Where(a => IsGenericRebusHandler(a.Interface))
                .Select(a =>
                {
                    var genericTypeArguments = a.Interface.GenericTypeArguments;

                    if (genericTypeArguments.Length != 1)
                    {
                        throw new ApplicationException(string.Format("The type {0} implements {1}, which was detected to be a Rebus message handler - but it has {2} generic type arguments which is not what we expected: {3}",
                            a.Type, a.Interface, genericTypeArguments.Length, string.Join(", ", genericTypeArguments.Select(t => t.FullName))));
                    }

                    return genericTypeArguments[0];
                })
                .Distinct();
        }
Example #26
0
        public IEnumerable<ChatHour> GetChatHoursFromChats(IEnumerable<Chat> chats)
        {
            return chats
                .SelectMany(
                    chat => GetSpanningHours(chat)
                        .Select(time =>
                            new
                            {
                                Chat = chat,
                                Time = time
                            }))
                .GroupBy(obj => obj.Time.Hour)
                .Select(group => new ChatHour
                {
                    Hour = group.First().Time.Hour,
                    ChatsByDay = new DayCollection(group.Select(item => item.Chat))
                });

            /*return chats.GroupBy(chat => chat.ChatDate.Hour)
                .Select(group =>
                    new ChatHour
                    {
                        Hour = group.Key,
                        ChatsByDay = new DayCollection(group)
                    });*/
        }
Example #27
0
		public static IEnumerable<Type> GetSubtypes( Type inspectedType, IEnumerable<Assembly> assemblies )
		{
			var assemblyTypes = assemblies.SelectMany( asm => asm.GetExportedTypes() ).Where( t => t != null && t != inspectedType );

			if ( inspectedType.IsInterface )
			{
				// todo: generic interfaces
				var implementers = assemblyTypes.Where( t => inspectedType.IsAssignableFrom( t ) );
				foreach ( var implementer in implementers )
				{
					if ( implementer.BaseType == null )
						yield return implementer;
					else if ( !implementer.BaseType.IsAssignableFrom( inspectedType ) )
						yield return implementer;

					// base type implements the interface, so this type is not directly related
				}
			}
			else
			{
				var subTypes = assemblyTypes.Where( asmType => asmType.BaseType == inspectedType );
				foreach ( var type in subTypes )
					yield return type;
			}
		}
Example #28
0
		//Adapted from: https://stackoverflow.com/questions/9262464/tool-to-show-assembly-dependencies
		public static void PoC(IEnumerable<AssemblyDefinition> assemblies, TextWriter writer, IEnumerable<string> searchfolders)
		{
			var resolver = new DefaultAssemblyResolver();
			searchfolders.ToList().ForEach(x => resolver.AddSearchDirectory(x));

			//writer.WriteLine("digraph Dependencies {");
			var loaded = assemblies
				.SelectMany(a => a.Modules.Cast<ModuleDefinition>())
				.SelectMany(m => m.AssemblyReferences.Cast<AssemblyNameReference>())
				.Distinct()
				.Select(asm => {
					var dllname = asm.Name + ".dll";
					//Console.WriteLine("Probing for {0}", dllname);
					try { return AssemblyDefinition.ReadAssembly(dllname); }
					catch { } 
					try { return resolver.Resolve(asm.FullName); }
					catch { }

					return null;
				})
				.Where(assembly => assembly != null)
				.ToList();

			//loaded.ForEach(a => a.MainModule.ReadSymbols());

			loaded.Select(x => x.FullName).Distinct().OrderBy(x => x).ToList().ForEach(x => writer.WriteLine("{0}", x));
			/*loaded.ForEach(a =>
				{
					foreach (var r in a.MainModule.AssemblyReferences.Cast<AssemblyNameReference>())
						writer.WriteLine(@"""{0}"" -> ""{1}"";", r.Name, a.Name.Name);
				} );*/

			//writer.WriteLine("}");
		}
 public override bool TestCondition(IEnumerable<Part> sectionParts)
 {
     if (sectionParts.AnyHasModule<ModuleGenerator>()) return true;
     var solarPanels = sectionParts.SelectMany(part => part.FindModulesImplementing<ModuleDeployableSolarPanel>());
     if (solarPanels.Any(panel => !panel.sunTracking)) return true;
     return false;
 }
Example #30
0
 public ResidentSecurity(IEnumerable<IResourceAuthProvider> providers)
 {
     _providers = providers;
     _roleToClaims = new Dictionary<string, IEnumerable<Claim>>();
     _systemRoles = new HashSet<Claim>(_providers
             .SelectMany(x => x.RoleNames)
             .Distinct()
             .Select(x => new Claim(SystemRoles.RoleClaimType, x)));
     foreach (var roleClaim in Roles)
     {
         _roleToClaims.Add(roleClaim.Value,
             _providers
             .SelectMany(x => x.Claims(roleClaim.Value)
                 .Distinct()));
     }
 }
Example #31
0
 public CommandRevertException(IEnumerable <CommandRevertException> revertExceptions)
     : base(MessageTemplate, revertExceptions.SelectMany(revertException => revertException.InnerExceptions))
 {
 }
Example #32
0
 public void Update(IEnumerable <Vertex> vertices)
 {
     Update(vertices.SelectMany(v => v.Data).ToArray());
 }
Example #33
0
 public static IEnumerable <A> Justs <A>(this IEnumerable <Maybe <A> > maybes)
 {
     return(maybes.SelectMany(m => m.Enumerable()));
 }
Example #34
0
        //TODO
        //public static IEnumerable<JObject> DescendantsAndSelf<T>(this IEnumerable<T> source) where T : JContainer
        //{
        //  ValidationUtils.ArgumentNotNull(source, "source");

        //  return source.SelectMany(j => j.DescendantsAndSelf());
        //}

        /// <summary>
        /// Returns a collection of child properties of every object in the source collection.
        /// </summary>
        /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JObject"/> that contains the source collection.</param>
        /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JProperty"/> that contains the properties of every object in the source collection.</returns>
        public static IJEnumerable <JProperty> Properties(this IEnumerable <JObject> source)
        {
            ValidationUtils.ArgumentNotNull(source, "source");

            return(source.SelectMany(d => d.Properties()).AsJEnumerable());
        }
Example #35
0
 /// <summary>
 /// Standard relational cross product operator betwen two sets.
 /// </summary>
 public static IEnumerable <Edge> Product(IEnumerable <int> lhs, IEnumerable <int> rhs)
 {
     return(lhs.SelectMany(i => rhs.Select(j => new Edge(i, j))));
 }
Example #36
0
 // Gets supported diagnostics from analyzers that are fixable by a given code fixer
 private IEnumerable <DiagnosticDescriptor> GetDiagnosticDescriptorsForCodeFixer(CodeFixProvider fixer) =>
 _allAnalyzers.SelectMany(a => a.SupportedDiagnostics).Where(d => fixer.FixableDiagnosticIds.Contains(d.Id));
Example #37
0
 public static IEnumerable <ITypedElement> DescendantsAndSelf(this IEnumerable <ITypedElement> elements) =>
 elements.SelectMany(e => e.DescendantsAndSelf());
Example #38
0
 public static IEnumerable <ITypedElement> Children(this IEnumerable <ITypedElement> nodes, string name = null) =>
 nodes.SelectMany(n => n.Children(name));
 /// <summary>
 /// Returns all descendants of a set of nodes.
 /// </summary>
 /// <param name="nodes">A list of nodes.</param>
 /// <returns>The descendants (children and by recursion all children of the children) of the node passed into
 /// <paramref name="nodes"/></returns>
 /// <returns>The descendants of all nodes passed into <paramref name="nodes"/>, aggregated into a single list.</returns>
 public static IEnumerable <ISourceNode> Descendants(this IEnumerable <ISourceNode> nodes) =>
 nodes == null ? throw Error.ArgumentNull(nameof(nodes)) :
       nodes.SelectMany(n => n.Descendants());
 /// <summary>
 /// Returns the direct children of a set of nodes.
 /// </summary>
 /// <param name="node">A list of nodes.</param>
 /// <param name="name"> Optional.The name filter for the children. Can be omitted to not filter by name.</param>
 /// <returns>The children of all nodes passed into <paramref name="node"/>, aggregated into a single list.</returns>
 public static IEnumerable <ISourceNode> Children(this IEnumerable <ISourceNode> node, string name = null) =>
 node == null ? throw Error.ArgumentNull(nameof(node)) :
       node.SelectMany(n => n.Children(name));
Example #41
0
        /// <summary>
        /// Returns a collection of tokens that contains the ancestors of every token in the source collection.
        /// </summary>
        /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JToken"/>.</typeparam>
        /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
        /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the ancestors of every node in the source collection.</returns>
        public static IJEnumerable <JToken> Ancestors <T>(this IEnumerable <T> source) where T : JToken
        {
            ValidationUtils.ArgumentNotNull(source, "source");

            return(source.SelectMany(j => j.Ancestors()).AsJEnumerable());
        }
Example #42
0
        //TODO
        //public static IEnumerable<JObject> AncestorsAndSelf<T>(this IEnumerable<T> source) where T : JObject
        //{
        //  ValidationUtils.ArgumentNotNull(source, "source");

        //  return source.SelectMany(j => j.AncestorsAndSelf());
        //}

        /// <summary>
        /// Returns a collection of tokens that contains the descendants of every token in the source collection.
        /// </summary>
        /// <typeparam name="T">The type of the objects in source, constrained to <see cref="JContainer"/>.</typeparam>
        /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
        /// <returns>An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the descendants of every node in the source collection.</returns>
        public static IJEnumerable <JToken> Descendants <T>(this IEnumerable <T> source) where T : JContainer
        {
            ValidationUtils.ArgumentNotNull(source, "source");

            return(source.SelectMany(j => j.Descendants()).AsJEnumerable());
        }
Example #43
0
        /// <summary>
        /// This function creates CustomNodeDefinition.
        /// </summary>
        /// <param name="functionId">Custom node unique ID</param>
        /// <param name="displayName">Custom node name</param>
        /// <param name="nodeModels">Nodes inside custom node</param>
        public CustomNodeDefinition(
            Guid functionId,
            string displayName = "",
            IEnumerable <NodeModel> nodeModels = null)
        {
            if (functionId == Guid.Empty)
            {
                throw new ArgumentException(@"FunctionId invalid.", "functionId");
            }

            nodeModels = nodeModels ?? new List <NodeModel>();

            #region Find outputs

            // Find output elements for the node

            var outputs = nodeModels.OfType <Output>().ToList();

            var topMost = new List <Tuple <int, NodeModel> >();

            List <string> outNames;
            returns = new List <Tuple <string, string> >();

            // if we found output nodes, add select their inputs
            // these will serve as the function output
            if (outputs.Any())
            {
                topMost.AddRange(
                    outputs.Where(x => x.InPorts[0].IsConnected).Select(x => Tuple.Create(0, x as NodeModel)));
                returns = outputs.Select(x => x.Return).ToList();
            }
            else
            {
                // if there are no explicitly defined output nodes
                // get the top most nodes and set THEM as the output
                IEnumerable <NodeModel> topMostNodes = nodeModels.Where(node => node.IsTopMostNode);

                var rtnPorts =
                    //Grab multiple returns from each node
                    topMostNodes.SelectMany(
                        topNode =>
                        //If the node is a recursive instance...
                        topNode is Function && (topNode as Function).Definition.FunctionId == functionId
                        // infinity output
                                ? new[] { new { portIndex = 0, node = topNode, name = "∞" } }
                        // otherwise, grab all ports with connected outputs and package necessary info
                                : topNode.OutPorts
                        .Select(
                            (port, i) =>
                            new { portIndex = i, node = topNode, name = port.Name })
                        .Where(x => !topNode.OutPorts[x.portIndex].IsConnected));

                foreach (var rtnAndIndex in rtnPorts.Select((rtn, i) => new { rtn, idx = i }))
                {
                    topMost.Add(Tuple.Create(rtnAndIndex.rtn.portIndex, rtnAndIndex.rtn.node));
                    var outName = rtnAndIndex.rtn.name ?? rtnAndIndex.idx.ToString();
                    returns.Add(new Tuple <string, string>(outName, string.Empty));
                }
            }

            var nameDict = new Dictionary <string, int>();
            foreach (var name in returns.Select(p => p.Item1))
            {
                if (nameDict.ContainsKey(name))
                {
                    nameDict[name]++;
                }
                else
                {
                    nameDict[name] = 0;
                }
            }

            nameDict = nameDict.Where(x => x.Value != 0).ToDictionary(x => x.Key, x => x.Value);

            returns.Reverse();

            var returnKeys = new List <string>();
            for (int i = 0; i < returns.Count(); ++i)
            {
                var info = returns[i];
                int amt;
                var name = info.Item1;

                if (nameDict.TryGetValue(name, out amt))
                {
                    nameDict[name] = amt - 1;
                    var newName = string.IsNullOrEmpty(name) ? amt + ">" : name + amt;

                    returnKeys.Add(newName);
                    returns[i] = new Tuple <string, string>(newName, info.Item2);
                }
                else
                {
                    returnKeys.Add(name);
                }
            }

            returnKeys.Reverse();
            returns.Reverse();

            #endregion

            #region Find inputs

            //Find function entry point, and then compile
            var inputNodes = nodeModels.OfType <Symbol>().ToList();
            var parameters = inputNodes.Select(x => new TypedParameter(
                                                   x.GetAstIdentifierForOutputIndex(0).Value,
                                                   x.Parameter.Type,
                                                   x.Parameter.DefaultValue,
                                                   null,
                                                   x.Parameter.Summary));
            var displayParameters = inputNodes.Select(x => x.Parameter.Name);

            #endregion

            FunctionBody       = nodeModels.Where(node => !(node is Symbol));
            DisplayName        = displayName;
            FunctionId         = functionId;
            Parameters         = parameters;
            ReturnKeys         = returnKeys;
            DisplayParameters  = displayParameters;
            OutputNodes        = topMost.Select(x => x.Item2.GetAstIdentifierForOutputIndex(x.Item1));
            DirectDependencies = nodeModels
                                 .OfType <Function>()
                                 .Select(node => node.Definition)
                                 .Where(def => def.FunctionId != functionId)
                                 .Distinct();
            ReturnType = ProtoCore.TypeSystem.BuildPrimitiveTypeObject(PrimitiveType.Var);
        }
Example #44
0
        /// <summary>
        /// Returns a collection of converted child tokens of every array in the source collection.
        /// </summary>
        /// <param name="source">An <see cref="IEnumerable{T}"/> of <see cref="JToken"/> that contains the source collection.</param>
        /// <typeparam name="U">The type to convert the values to.</typeparam>
        /// <typeparam name="T">The source collection type.</typeparam>
        /// <returns>An <see cref="IEnumerable{T}"/> that contains the converted values of every node in the source collection.</returns>
        public static IEnumerable <U> Children <T, U>(this IEnumerable <T> source) where T : JToken
        {
            ValidationUtils.ArgumentNotNull(source, "source");

            return(source.SelectMany(c => c.Children()).Convert <JToken, U>());
        }
Example #45
0
 private static IEnumerable <Type> FromCheckedAssemblies(IEnumerable <Assembly> assemblies)
 {
     return(assemblies.SelectMany <Assembly, Type>(new Func <Assembly, IEnumerable <Type> >(TypeFinder.GetTypes)));
 }
Example #46
0
 /// <summary>Gets the distinct member names.</summary>
 public static ISet <string> GetMemberNames(this IEnumerable <ValidationResult> validationResults)
 {
     Guard.NotNull(validationResults, nameof(validationResults));
     return(new HashSet <string>(validationResults.SelectMany(validationResult => validationResult.MemberNames)));
 }
Example #47
0
 public IEnumerable <string> Filter(IEnumerable <string> words)
 {
     return(words.SelectMany(x => x.Split(' ')).Select(x => x.Trim(BannedChars).ToUpper())
            .Where(x => !bannedWords.Contains(x)));
 }
Example #48
0
        public override bool SendRequest(RockContext rockContext, Workflow workflow, AttributeCache personAttribute, AttributeCache ssnAttribute, AttributeCache requestTypeAttribute, AttributeCache billingCodeAttribute, out List <string> errorMessages)
        {
            errorMessages = new List <string>();

            rockContext.SaveChanges();

            // Check to make sure workflow is not null
            if (workflow == null || workflow.Id == 0)
            {
                errorMessages.Add("The 'Protect My Ministry' background check provider requires a valid persisted workflow.");
                return(false);
            }

            workflow.LoadAttributes();

            // Get the person that the request is for
            Person person = null;

            if (personAttribute != null)
            {
                Guid?personAliasGuid = workflow.GetAttributeValue(personAttribute.Key).AsGuidOrNull();
                if (personAliasGuid.HasValue)
                {
                    person = new PersonAliasService(rockContext).Queryable()
                             .Where(p => p.Guid.Equals(personAliasGuid.Value))
                             .Select(p => p.Person)
                             .FirstOrDefault();
                    person.LoadAttributes(rockContext);
                }
            }

            if (person == null)
            {
                errorMessages.Add("The 'Protect My Ministry' background check provider requires the workflow to have a 'Person' attribute that contains the person who the background check is for.");
                return(false);
            }

            string billingCode = workflow.GetAttributeValue(billingCodeAttribute.Key);
            Guid?  campusGuid  = billingCode.AsGuidOrNull();

            if (campusGuid.HasValue)
            {
                var campus = CampusCache.Read(campusGuid.Value);
                if (campus != null)
                {
                    billingCode = campus.Name;
                }
            }
            string            ssn         = Encryption.DecryptString(workflow.GetAttributeValue(ssnAttribute.Key));
            DefinedValueCache requestType = DefinedValueCache.Read(workflow.GetAttributeValue(requestTypeAttribute.Key).AsGuid());

            if (requestType == null)
            {
                errorMessages.Add("Unknown request type.");
                return(false);
            }

            int orderId = workflow.Id;

            string requestTypePackageName = requestType.GetAttributeValue("PMMPackageName").Trim();

            BackgroundCheck bgCheck = getBgCheck(rockContext, workflow, person.PrimaryAliasId.Value);

            List <string[]> SSNTraceCounties = null;

            if (requestTypePackageName.Equals("PLUS", StringComparison.OrdinalIgnoreCase) && !String.IsNullOrWhiteSpace(bgCheck.ResponseData))
            {
                IEnumerable <XElement> transactions                = XDocument.Parse(bgCheck.ResponseData).Root.Elements("Transaction");
                IEnumerable <XElement> OrderXMLs                   = transactions.SelectMany(x => x.Elements("OrderXML"));
                IEnumerable <XElement> Orders                      = OrderXMLs.Select(x => x.Element("Order")).Where(x => x != null);
                IEnumerable <XElement> OrderDetails                = Orders.SelectMany(x => x.Elements("OrderDetail"));
                IEnumerable <XElement> SSNTraces                   = OrderDetails.Where(x => x.Attribute("ServiceCode")?.Value == "SSNTrace" && x.Element("Status") != null);
                IEnumerable <XElement> SSNTraceResults             = SSNTraces.Select(x => x.Element("Result"));
                IEnumerable <XElement> SSNTraceIndividuals         = SSNTraceResults.SelectMany(x => x.Elements("Individual"));
                IEnumerable <XElement> SSNTraceIndividualsToSearch = SSNTraceIndividuals.Where(x => x.Element("EndDate") == null || x.Element("EndDate").Element("Year") == null || (x.Element("EndDate").Element("Year").Value.AsInteger() > (DateTime.Now.Year - 8)));
                SSNTraceCounties = SSNTraceIndividualsToSearch.Where(x => x.Element("County") != null && x.Element("State") != null).Select(x => new string[] { x.Element("County").Value, x.Element("State").Value }).ToList();
            }

            XElement xTransaction = makeBGRequest(bgCheck, ssn, requestType, billingCode, SSNTraceCounties);

            saveTransaction(rockContext, bgCheck, xTransaction);
            handleTransaction(rockContext, bgCheck, xTransaction);
            return(true);

            //catch (Exception ex)
            //{
            //    ExceptionLogService.LogException(ex, null);
            //    errorMessages.Add(ex.Message);
            //    return false;
            //}
        }
 GetLoadablePublicConcreteTypesImplementing <T>(this IEnumerable <Assembly> assemblies) => assemblies
 .SelectMany(assembly => assembly.GetLoadablePublicConcreteTypeImplementing <T>()).ToImmutableArray();
Example #50
0
 private IEnumerable <string> GetModuleNames(IEnumerable <Node> roots) => roots
 .SelectMany(r => r.TraverseBreadthFirst(n => n.IsModule ? Enumerable.Empty <Node>() : n.Children))
 .Where(n => n.IsModule)
 .Concat(_builtins.Children)
 .Select(n => n.FullModuleName);
 public static IEnumerable <TOutput> SelectManySafe <TInput, TOutput>(this IEnumerable <TInput> source, Func <TInput, IEnumerable <TOutput> > func)
 {
     return(source.SelectMany(x => func(x) ?? Enumerable.Empty <TOutput>()));
 }
Example #52
0
 public static void WriteDepsTo(this IEnumerable <LibraryExport> exports, string path)
 {
     File.WriteAllLines(path, exports.SelectMany(GenerateLines));
 }
Example #53
0
 public WordsFilter(IEnumerable <string> linesOfBannedWords)
 {
     bannedWords = linesOfBannedWords.SelectMany(x => x.Split(' '))
                   .Select(x => x.ToUpper()).ToArray();
 }
 private IEnumerable <ISymbol> Tokenize(IEnumerable <string> contentFragments, bool markup)
 {
     return(contentFragments.SelectMany(fragment => Tokenize(fragment, markup)));
 }
Example #55
0
 public static IEnumerable <T> OfComponentImplementing <T>(this IEnumerable <RectTransform> This)
 {
     return(This.SelectMany(g => g.GetComponents <T>()));
 }
 public void NumberOfFilesTest()
 {
     Assert.AreEqual(5, assembliesWithoutPreprocessing.SelectMany(a => a.Classes).SelectMany(a => a.Files).Distinct().Count(), "Wrong number of files");
 }
Example #57
0
 public static IEnumerable <IEnumerable <T> > GetCombinations <T>(this IEnumerable <T> elements, int k)
 {
     return(k == 0 ? new[] { new T[0] } :
            elements.SelectMany((e, i) =>
                                elements.Skip(i + 1).GetCombinations(k - 1).Select(c => (new[] { e }).Concat(c))));
 }
Example #58
0
        public static IEnumerable <ISensorReportItem> GetReportFromSessionSensorData(IEnumerable <ISessionSensorData> sessionsSensorData, double startTime = 0, double endTime = double.PositiveInfinity)
        {
            if (sessionsSensorData == null || !sessionsSensorData.Any() || sessionsSensorData.Any(session => session == null))
            {
                return(Enumerable.Empty <ISensorReportItem>());
            }

            var sensorReportItems = new List <ISensorReportItem>();

            try
            {
                foreach (var item in Enum.GetValues(typeof(EReportSensorName)).Cast <EReportSensorName>())
                {
                    switch (item)
                    {
                    case EReportSensorName.CpuUsage when HasValues(sessionsSensorData, session => session.CpuUsage, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.CpuMaxThreadUsage when HasValues(sessionsSensorData, session => session.CpuMaxThreadUsage, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.CpuPower when HasValues(sessionsSensorData, session => session.CpuPower, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.CpuTemp when HasValues(sessionsSensorData, session => session.CpuTemp, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.CpuMaxClock when HasValues(sessionsSensorData, session => session.CpuMaxClock, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.GpuUsage when HasValues(sessionsSensorData, session => session.GpuUsage, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.GpuPower when HasValues(sessionsSensorData, session => session.GpuPower, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.GpuTemp when HasValues(sessionsSensorData, session => session.GpuTemp, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.VRamUsage when HasValues(sessionsSensorData, session => session.VRamUsage, out var values):
                        AddSensorEntry(item, Math.Round(values.Average()), values.Min(), values.Max());

                        break;

                    case EReportSensorName.RamUsage when HasValues(sessionsSensorData, session => session.RamUsage, out var values):
                        AddSensorEntry(item, Math.Round(values.Average(), 2), Math.Round(values.Min(), 2), Math.Round(values.Max(), 2));

                        break;
                    }
                }

                return(sensorReportItems);
            }
            catch { return(sensorReportItems); }

            bool HasValues <T>(IEnumerable <ISessionSensorData> sessionSensorData, Func <ISessionSensorData, IEnumerable <T> > selector, out List <T> values)
            {
                values = new List <T>();
                var measureTimes   = sessionSensorData.SelectMany(x => x.MeasureTime).ToArray();
                var selectedValues = sessionsSensorData.SelectMany(selector).ToArray();

                for (int i = 0; i < selectedValues.Count(); i++)
                {
                    var measureTime = measureTimes[i];
                    if (measureTime >= startTime && measureTime <= endTime)
                    {
                        values.Add(selectedValues[i]);
                    }
                }
                return(values.Any());
            }

            void AddSensorEntry(EReportSensorName sensorName, double avg, double min, double max)
            {
                sensorReportItems.Add(new SensorReportItem
                {
                    Name         = sensorName.GetAttribute <DescriptionAttribute>().Description,
                    MinValue     = min,
                    AverageValue = avg,
                    MaxValue     = max
                });
            }
        }
Example #59
0
 private IEnumerable <KeyBinding> FlattenKeyBindings(IDictionary <string, ICollection <KeyBinding> > commandKeyBindings, IEnumerable <ShellProfile> profiles, IEnumerable <SshProfile> sshprofiles)
 {
     return(commandKeyBindings.Values.SelectMany(k => k).Concat(profiles.SelectMany(x => x.KeyBindings).Concat(sshprofiles.SelectMany(x => x.KeyBindings))));
 }
Example #60
0
 private static List <DiagnosticAnalyzer> GetAnalyzers(IEnumerable <Assembly> assemblies)
 {
     return(assemblies.SelectMany(a => GetAnalyzers(a)).ToList());
 }