public static void ShowExample() { #region DATA PERSON p1 = new PERSON() { Name = "Martin Hromek" }; p1.PhoneNumbers = new List<PHONENUMBER>(); p1.PhoneNumbers.Add(new PHONENUMBER() { Number = "+420775656055" }); PERSON p2 = new PERSON() { Name = "Eva Brezovska" }; p2.PhoneNumbers = new List<PHONENUMBER>(); p2.PhoneNumbers.Add(new PHONENUMBER() { Number = "+420723195654" }); List<PERSON> list = new List<PERSON>(); list.Add(p1); list.Add(p2); #endregion // SELECT IEnumerable<IEnumerable<PHONENUMBER>> phoneList = list.Select(p => p.PhoneNumbers); // SELECT MANY Console.WriteLine("\nSelectMany:"); Console.WriteLine("Vstupni pole: phone list"); Console.WriteLine("Spojim [SelectMany] seznam telefonich cisle."); IEnumerable<PHONENUMBER> phonesList = list.SelectMany(p => p.PhoneNumbers); Console.WriteLine("SelectMany: {0}", string.Join(",", phonesList)); // SELECT MANY WITH ANONYMOUS CLASS var dictionary = list.SelectMany(p => p.PhoneNumbers, (parent, child) => new { name = parent.Name, parent.PhoneNumbers }); }
internal static IServiceProvider FindServiceProvider(Assembly[] assembliesToSearch = null) { var assemblies = new List<Assembly>(); if (assembliesToSearch != null && assembliesToSearch.Length > 0) { assemblies.AddRange(assembliesToSearch); } else { try { var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) assemblies.Add(entryAssembly); } catch {} } var serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes().Where(t => !t.IsInterface && !t.IsAbstract && typeof(IBootstrappedServiceProvider).IsAssignableFrom(t))); foreach (var serviceProviderType in serviceProviderTypes) { var bootstrapper = Activator.CreateInstance(serviceProviderType) as IServiceProvider; if (bootstrapper != null) return bootstrapper; } serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes() .Where(t => !t.IsInterface && !t.IsAbstract && typeof(IServiceProvider).IsAssignableFrom(t))); foreach (var serviceProviderType in serviceProviderTypes) { var bootstrapper = Activator.CreateInstance(serviceProviderType) as IServiceProvider; if (bootstrapper != null) return bootstrapper; } return new ActivatorServiceProvider(); }
public static IServiceProvider FindAndGetServiceProvider(ILoggerFactory loggerFactory, params Assembly[] assembliesToSearch) { var assemblies = new List<Assembly>(); if (assembliesToSearch != null && assembliesToSearch.Length > 0) { assemblies.AddRange(assembliesToSearch); } else { try { var entryAssembly = Assembly.GetEntryAssembly(); if (entryAssembly != null) assemblies.Add(entryAssembly); } catch { } } // try to find bootstrapped service providers first var serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes().Where(t => !t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsAbstract && typeof(IBootstrappedServiceProvider).IsAssignableFrom(t))); foreach (var serviceProviderType in serviceProviderTypes) { var serviceProvider = GetServiceProvider(serviceProviderType, loggerFactory); if (serviceProvider != null) return serviceProvider; } // find any service providers serviceProviderTypes = assemblies.SelectMany(a => a.GetTypes() .Where(t => !t.GetTypeInfo().IsInterface && !t.GetTypeInfo().IsAbstract && typeof(IServiceProvider).IsAssignableFrom(t))); foreach (var serviceProviderType in serviceProviderTypes) { var serviceProvider = GetServiceProvider(serviceProviderType, loggerFactory); if (serviceProvider != null) return serviceProvider; } return new ActivatorServiceProvider(); }
public SyncResponse Sync(string serverKey, List<PluginResource> discoveries = null, List<AnalyzerResult> metricResults = null, Dictionary<string, string> commandResults = null) { if (AgentContext.Current.PluginBlacklist != null) { discoveries = discoveries.Where(p => !AgentContext.Current.PluginBlacklist.Contains(p.Category, StringComparer.InvariantCultureIgnoreCase)).ToList(); } // build payload var payLoad = new SyncRequest(); payLoad.AddPluginResources(discoveries); payLoad.AddCommandResults(commandResults); if (metricResults != null && metricResults.Any()) { payLoad.AddCollectedMetrics(metricResults.SelectMany(r => r.Metrics).ToList()); payLoad.AddAnomalies(metricResults.SelectMany(r => r.Anomalies).ToList()); } payLoad.AddRegisteredCustomMetrics(); payLoad.AddUpdateConfig(); payLoad.AddAgentVersion(); Log.DebugFormat("Syncing payload with cloud service:\n{0}", JsonConvert.SerializeObject(payLoad, Formatting.Indented)); // send request var response = RestHelper.Post<JObject>("sync", new AggregatorAuthenticator(serverKey), r => r.AddBody(payLoad), r => { Log.ErrorFormat("Call to /sync resulted in an error with status code {0} ({1})", r.StatusCode, r.StatusDescription); }); // parse response if (response != null) { Log.DebugFormat("Received sync response from cloud:\n{0}", response.ToString(Formatting.Indented)); var syncResponse = new SyncResponse(); if (response["schedules"] != null) { var newSchedules = ParsePluginResourceSchedulesFromJson(response["schedules"]); if (newSchedules.Any()) { syncResponse.PluginResourcesSchedules = newSchedules; } } var newCommands = response["commands"]; if (newCommands != null && newCommands.Any()) { syncResponse.AdminCommands = ((IDictionary<string, JToken>)newCommands).ToDictionary(c => c.Key, c => c.Value.Value<string>()); } return syncResponse; } return null; }
public static DependencyGraph Filter(DependencyGraph graph, List<OutputEntry> warnings) { var projs = new HashSet<Library>(warnings.SelectMany(w => w.Projects) .Concat(warnings.SelectMany(w => w.Dependencies.SelectMany(d => new[] { d.Source, d.Target })))); var deps = new HashSet<Dependency>(warnings.SelectMany(w => w.Dependencies)); var filtered = new DependencyGraph(); filtered.AddVertexRange(projs); //filtered.AddEdgeRange(graph.Edges.Where(d => projs.Contains(d.Source) && projs.Contains(d.Target))); filtered.AddEdgeRange(deps); return filtered; }
/// <summary> /// Initializes the project rewriter by getting a list of actions that will be run /// </summary> /// <returns>A list of project actions to be run</returns> public ProjectResult Initialize() { ProjectActions projectActions = new ProjectActions(); try { var allReferences = _sourceFileResults?.SelectMany(s => s.References) .Union(_sourceFileResults.SelectMany(s => s.Children.OfType <UsingDirective>())?.Select(u => new Reference() { Namespace = u.Identifier, Assembly = u.Identifier }).Distinct()) .Union(ProjectConfiguration.AdditionalReferences.Select(r => new Reference { Assembly = r, Namespace = r })); RulesFileLoader rulesFileLoader = new RulesFileLoader(allReferences, ProjectConfiguration.RulesDir, ProjectConfiguration.TargetVersions, string.Empty, ProjectConfiguration.AssemblyDir); var projectRules = rulesFileLoader.Load(); RulesAnalysis walker = new RulesAnalysis(_sourceFileResults, projectRules, ProjectConfiguration.ProjectType); projectActions = walker.Analyze(); _projectReferences.ForEach(p => { projectActions.ProjectReferenceActions.Add(Config.Utils.GetRelativePath(ProjectConfiguration.ProjectPath, p)); }); _projectResult.ActionPackages = projectActions.PackageActions.Distinct().ToList(); _projectResult.MetaReferences = _metaReferences; foreach (var p in ProjectConfiguration.PackageReferences) { projectActions.PackageActions.Add(new PackageAction() { Name = p.Key, OriginalVersion = p.Value.Item1, Version = p.Value.Item2 }); } MergePackages(projectActions.PackageActions); projectActions.ProjectLevelActions = projectRules.ProjectTokens.SelectMany(p => p.ProjectLevelActions).Distinct().ToList(); projectActions.ProjectLevelActions.AddRange(projectRules.ProjectTokens.SelectMany(p => p.ProjectFileActions)); projectActions.ProjectRules = projectRules; _projectResult.ProjectActions = projectActions; _projectResult.FeatureType = ProjectConfiguration.ProjectType; } catch (Exception ex) { LogHelper.LogError(ex, "Error while initializing project {0}", ProjectConfiguration.ProjectPath); } return(_projectResult); }
private FileToWrite GetFileForNamespaceGroup(string @namespace, List<ToTypeScript> toTypeScripts) { bool containsControllers = toTypeScripts.Any(obj => obj.ObjectType == ObjectType.Controller); // add static import only if the files is going to contains controllers var extraImport = containsControllers ? new[] { $"import {{ RestApi, RequestConfig }} from '../Nimrod';" } : new string[0]; var imports = toTypeScripts .SelectMany(t => t.GetImports()) // do not write import for the same namespace .Where(import => import.Namespace != @namespace) .GroupBy(import => import.Namespace) .Select(grp => $"import * as {grp.Key.Replace('.', '_')} from './{ grp.Key}';") .OrderBy(importLine => importLine); var content = toTypeScripts.SelectMany(t => t.GetLines()); return new FileToWrite($"{@namespace}", extraImport.Concat(imports).Concat(content)); }
public void Run(List<SampleTri> mesh) { Parallel.ForEach(mesh.SelectMany(m => m.Samples).Distinct().ToList(), sample => { var neighbours = sample.DepthNeighbours(Depth); var colors = neighbours.Select(s => s.Color).OrderByDescending(c => c.Saturation).ToList(); sample.NewColor = colors.Last(); }); Parallel.ForEach(mesh.SelectMany(m => m.Samples).Distinct().ToList(), sample => { sample.Color = sample.NewColor; }); }
/// <summary> /// Executes the specified command and returns items of a specific type. /// </summary> /// <typeparam name="TObject">The type of the object.</typeparam> /// <param name="queries">The queries to run.</param> /// <returns>The resulting data</returns> public async Task <IEnumerable <dynamic> > ExecuteAsync <TObject>(IDictionary <IMappingSource, QueryData <TObject> > queries) where TObject : class { var KeyName = queries.Values.ToString(x => x + "_" + x.Source.Source.Name, "\n"); (queries?.Values ?.SelectMany(x => x.Parameters) ?.Distinct() ?? Array.Empty <IParameter>()) ?.ForEach(x => KeyName = x.AddParameter(KeyName)); if (QueryResults.IsCached(KeyName, Cache)) { return(QueryResults.GetCached(KeyName, Cache)?.SelectMany(x => x.ConvertValues <TObject>()) ?? Array.Empty <TObject>()); } var Results = new List <QueryResults>(); var FirstRun = true; var TempQueries = queries.Where(x => x.Value.Source.CanRead && x.Value.Source.GetChildMappings(typeof(TObject)).Any()); foreach (var Source in TempQueries.Where(x => x.Value.WhereClause.InternalOperator != null) .OrderBy(x => x.Key.Order)) { await GenerateQueryAsync(Results, FirstRun, Source).ConfigureAwait(false); FirstRun = false; } foreach (var Source in TempQueries.Where(x => x.Value.WhereClause.InternalOperator is null) .OrderBy(x => x.Key.Order)) { await GenerateQueryAsync(Results, FirstRun, Source).ConfigureAwait(false); FirstRun = false; } QueryResults.CacheValues(KeyName, Results, Cache); return(Results?.SelectMany(x => x.ConvertValues <TObject>())?.ToArray() ?? Array.Empty <TObject>()); }
static void Main() { var groups = new List<List<string[]>>(); var strings = File.ReadAllLines("Test.txt"); var n = 0; foreach (var l in strings) { if (l.StartsWith("[") && l.EndsWith("]")) { n = int.Parse(l.Trim('[', ']')) - 1; groups.Add(new List<string[]>()); continue; } groups[n].Add(l.Split('\t')); } var lines = groups.SelectMany(g => g); var ids = lines.Select(l => l[0]) .Distinct(); var paths = ids.Select(id => GetNodes(id, lines).Reverse()).ToList(); var pairs = paths.Select(p => Tuple.Create(p.Count(), GetPartCount(p, lines))) .ToList(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1(pairs)); }
public List<TextUnitScore> GetImportantTextUnits(List<Sentence> Sentences) { var textUnitFrequencyGrader = new Dictionary<TextUnit, long>(); foreach (var tu in Sentences.SelectMany(s => s.TextUnits)) { if (m_Rules.UnimportantWords.Contains(tu.FormattedValue)) { continue; } if (textUnitFrequencyGrader.ContainsKey(tu)) { textUnitFrequencyGrader[tu]++; } else { textUnitFrequencyGrader.Add(tu, 1); } } return textUnitFrequencyGrader.OrderByDescending(kvp => kvp.Value) .Select(kvp => new TextUnitScore {ScoredTextUnit = kvp.Key, Score = kvp.Value}) .ToList(); }
/// <summary> /// 获取指定命名空间下都类型集合 /// </summary> /// <param name="assemblys">命名空间<para>支持通配符</para></param> /// <returns></returns> public static List <Type> GetTypes(this List <string> assemblys) { return(assemblys?.SelectMany(x => { try { return Assembly.Load(x).GetTypes(); } catch (FileNotFoundException) { var result = Array.Empty <Type>(); if (x.IndexOfAny(new[] { '\\', '/', ':', '*', '"', '<', '>', '|' }) > -1) { var Files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, $"{x}.dll"); if (Files.Length > 0) { result = Files.SelectMany(F => Assembly.LoadFile(F).GetTypes()).ToArray(); } } else { var path = $"{AppDomain.CurrentDomain.BaseDirectory}{x}.dll"; if (File.Exists(path)) { result = Assembly.LoadFile(path).GetTypes(); } } return result; } }).ToList()); }
public override Population Run() { var m = GetOption("select_count", Math.Ceiling((double) (Population.Osobi.Count/20))); if (Population.Osobi.Count < m) return Population; var groups =new List < List<Unit> >(); var tempc = 0; var templ = new List<Unit>(); for (int i = 0; i < Population.Osobi.Count; i++) { var unit = Population.Osobi[i]; if (tempc>=m) { groups.Add(templ); templ=new List<Unit>(); tempc = 0; } templ.Add(unit); tempc++; } if (templ.Count > 0) { groups.Add(templ);templ=new List<Unit>();} var goods=groups.SelectMany(u => u.Where(u1 => u1.Function == u.Max(u2 => u2.Function))); Population.TempPopulation = goods.Select(u=>u.Id).ToList(); return Population; }
///<summary>Resolves the full path to the JS file that will be loaded by a call to require(). This will always return an existing file (not directory) on disk, or null.</summary> ///<param name="callerPath">The path to the directory containing the file that is calling require(). This must be an absolute path.</param> ///<param name="modulePath">The string passed to require(). This can be a relative path, a module name, or a path within a module name.</param> ///<returns>The path to the fully resolved file, after resolving default extensions, default directory files, and package.json.</returns> public async static Task<string> ResolveModule(string callerDirectory, string modulePath) { string rawPath = ResolvePath(callerDirectory, modulePath); // If we couldn't locate the module at all, or if we got an actual file, stop. if (rawPath == null || File.Exists(rawPath)) return rawPath; // Build a list of file-like paths to try with various extensions. // In order, try the original path, the 'package.json' main entry, // and any index file. // https://github.com/joyent/node/blob/master/lib/module.js#L155 var potentialPaths = new List<string> { rawPath }; // If the non-existent file is a directory, look inside. if (Directory.Exists(rawPath)) { var mainEntry = await GetPackageMain(rawPath).ConfigureAwait(false); if (mainEntry != null) { potentialPaths.Add(Path.Combine(rawPath, mainEntry)); potentialPaths.Add(Path.Combine(rawPath, mainEntry, "index")); } potentialPaths.Add(Path.Combine(rawPath, "index")); } // Don't try to resolve a path with a trailing / as a file. potentialPaths.RemoveAll(p => p.EndsWith("/", StringComparison.Ordinal)); // Try adding the default extensions to each potential path we've found, then give up. return potentialPaths.SelectMany(path => ModuleExtensions.Select(e => path + e)) .FirstOrDefault(File.Exists); }
public virtual async Task<CodeAction> GetFixAsync( ImmutableDictionary<Document, ImmutableArray<Diagnostic>> documentsAndDiagnosticsToFixMap, FixAllContext fixAllContext) { if (documentsAndDiagnosticsToFixMap != null && documentsAndDiagnosticsToFixMap.Any()) { fixAllContext.CancellationToken.ThrowIfCancellationRequested(); var documents = documentsAndDiagnosticsToFixMap.Keys.ToImmutableArray(); var fixesBag = new List<CodeAction>[documents.Length]; var options = new ParallelOptions() { CancellationToken = fixAllContext.CancellationToken }; Parallel.ForEach(documents, options, (document, state, index) => { fixAllContext.CancellationToken.ThrowIfCancellationRequested(); fixesBag[index] = new List<CodeAction>(); this.AddDocumentFixesAsync(document, documentsAndDiagnosticsToFixMap[document], fixesBag[index].Add, fixAllContext).Wait(fixAllContext.CancellationToken); }); if (fixesBag.Any(fixes => fixes.Count > 0)) { return await this.TryGetMergedFixAsync(fixesBag.SelectMany(i => i), fixAllContext).ConfigureAwait(false); } } return null; }
static void Main(string[] args) { const int NUMBER_OF_POSITIONS = 4; Console.Error.WriteLine("Using {0} positions", NUMBER_OF_POSITIONS); var allPositions = Enumerable.Range(0, NUMBER_OF_POSITIONS).ToArray(); var validValues = new List<int[][]> { Enumerable.Repeat(Enumerable.Range(0, 10).ToArray(), NUMBER_OF_POSITIONS).ToArray() }; logSolutions(validValues); int N = int.Parse(Console.ReadLine()); for (int i = 0; i < N; i++) { string[] inputs = Console.ReadLine().Split(' '); int[] guess = inputs[0].Select(x => int.Parse(x.ToString())).ToArray(); int bulls = int.Parse(inputs[1]); int cows = int.Parse(inputs[2]); Console.Error.WriteLine("guess {0} == {1} bulls + {2} cows", inputs[0], bulls, cows); validValues = validValues.SelectMany(possibility => solve(possibility, guess, bulls, cows, NUMBER_OF_POSITIONS - 1) ).ToList(); logSolutions(validValues); } var solution = string.Join("", validValues.Single().Select(x => x.Single()).ToArray()); Console.WriteLine(solution); Console.ReadLine(); }
protected List<PerformanceRecord> ExecuteWriteWithParallel(IEnumerable<TestData> data, int numberOfTransactions, int itemsPerTransaction, int numberOfThreads, Func<IEnumerator<TestData>, long, long, List<PerformanceRecord>> writeFunction, out long elapsedMilliseconds) { var countdownEvent = new CountdownEvent(numberOfThreads); var parallelData = SplitData(data, numberOfTransactions, itemsPerTransaction, numberOfThreads); var records = new List<PerformanceRecord>[numberOfThreads]; var sw = Stopwatch.StartNew(); for (int i = 0; i < numberOfThreads; i++) { ThreadPool.QueueUserWorkItem( state => { var index = (int)state; var pData = parallelData[index]; records[index] = writeFunction(pData.Enumerate(), pData.ItemsPerTransaction, pData.NumberOfTransactions); countdownEvent.Signal(); }, i); } countdownEvent.Wait(); sw.Stop(); elapsedMilliseconds = sw.ElapsedMilliseconds; return records .SelectMany(x => x) .ToList(); }
public ObjectCreator(Manifest manifest, FileSystem.FileSystem modFiles) { typeCache = new Cache<string, Type>(FindType); ctorCache = new Cache<Type, ConstructorInfo>(GetCtor); // Allow mods to load types from the core Game assembly, and any additional assemblies they specify. var assemblyList = new List<Assembly>() { typeof(Game).Assembly }; foreach (var path in manifest.Assemblies) { var data = modFiles.Open(path).ReadAllBytes(); // .NET doesn't provide any way of querying the metadata of an assembly without either: // (a) loading duplicate data into the application domain, breaking the world. // (b) crashing if the assembly has already been loaded. // We can't check the internal name of the assembly, so we'll work off the data instead var hash = CryptoUtil.SHA1Hash(data); Assembly assembly; if (!ResolvedAssemblies.TryGetValue(hash, out assembly)) { assembly = Assembly.Load(data); ResolvedAssemblies.Add(hash, assembly); } assemblyList.Add(assembly); } AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly; assemblies = assemblyList.SelectMany(asm => asm.GetNamespaces().Select(ns => Pair.New(asm, ns))).ToArray(); AppDomain.CurrentDomain.AssemblyResolve -= ResolveAssembly; }
protected override void UpdateLevelsValues(List<List<SamplePrimitive>> primitives, MobileObservableCollection<SampleUnit> samples) { var dataList = primitives.SelectMany(x => x.Select(y => !((bool)y.SampleValue))); var dataSum = dataList.Sum(x => Convert.ToInt32(x)); var dataCount = dataList.Count(); var p = 0.0; var np = 0.0; var delta = 0.0; if (samples.Any()) { p = (double) dataSum/dataCount; np = ParentPanel.SubgroupSize * p; delta = 3 * Math.Sqrt(np * (1 - p)); Mean = Math.Round(np, 2); UCL = Math.Round(Mean + delta, 2); LCL = Math.Round(Math.Max(Mean - delta, 0), 2); } foreach (var sample in samples) { sample.SetUCL(UCL); sample.SetMean(Mean); sample.SetLCL(LCL); sample.SetUCL(ParentPanel.CustomUCL, true); sample.SetLCL(ParentPanel.CustomLCL, true); sample.SetUSL(ParentPanel.USL); sample.SetLSL(ParentPanel.LSL); } }
public ScanIndex() { AssemblyTypes = new Dictionary<Assembly, List<Type>>(); TypeAssemblies = new Dictionary<Type, Assembly>(); ImplementorsOfType = new Dictionary<Type, List<Type>>(); TypeHierarchies = new Dictionary<Type, List<Type>>(); Closers = new Dictionary<Type, List<Type>>(); AssemblyExclusionList = new List<string>(); ReferenceLookup = new Dictionary<Assembly, List<Assembly>>(); ConfiguredSymbiotes = new Dictionary<Assembly, bool>(); SingleImplementations = new Dictionary<Type, Type>(); Scanner = new TypeScanner(); InitExclusions(); var initialList = new List<Assembly>( Scanner.GetAssembliesFromBaseDirectory().ToList() ); var references = initialList .SelectMany( GetReferenceList ) .ToList(); initialList.AddRange( references.Where( r => !initialList.Any( a => a.FullName.Equals( r.FullName ) ) ) ); var uniqueList = initialList.Distinct(); var filtered = uniqueList.Where( x => !AssemblyExclusionList.Any( e => x.FullName.StartsWith( e ) ) ); CompleteAssemblyList = new List<Assembly>( filtered.ToList() ); }
protected override MobileObservableCollection<SampleUnit> ConvertPrimitivesToSamples(List<List<SamplePrimitive>> primitives) { var newSource = new MobileObservableCollection<SampleUnit>(); for (var i = 0; i < primitives.Count; i++) { var data = primitives[i].Select(x => x.SampleValue).Cast<double>(); var commonItemId = (from s in primitives[i] group s by s.ItemId into gr orderby gr.Count() descending select gr).First().First().ItemId; var sampleValue = ProcessSubgroup(data); var subgroupSample = SpcManager.CreateSample(sampleValue, commonItemId, i); subgroupSample.SetXLabelValue(i, LabelValueDataTypes.Number); subgroupSample.SetSampleSize(data.Count()); newSource.Add(subgroupSample); } UpdateLevelsValues(primitives, newSource); YStep = (int)Math.Abs(primitives.SelectMany(l1 => l1.Select(l2 => l2.SampleValue)).Cast<double>().Range() / (3 * ParentPanel.HeightMultiplier)); return newSource; }
public void Write(List<PackageViewModel> packages, string file) { if (string.IsNullOrWhiteSpace(file)) { file = "packages.dgml"; } XNamespace ns = "http://schemas.microsoft.com/vs/2009/dgml"; var colors = new DgmlColorConfiguration(); var nodes = packages .Select( package => new XElement(ns + "Node", new XAttribute("Id", package.Id), new XAttribute("Label", string.Format("{0} ({1})", package.NugetId, package.LocalVersion)), new XAttribute("Background", GraphHelper.GenerateBackgroundColor(packages, package, colors)))) .ToList(); var links = (packages .SelectMany( package => package.Dependencies, (package, dep) => new XElement(ns + "Link", new XAttribute("Source", package.Id), new XAttribute("Target", packages.Any(x => x.NugetId == dep.NugetId && x.LocalVersion == dep.Version) ? packages.First(x => x.NugetId == dep.NugetId && x.LocalVersion == dep.Version).Id : string.Format("{0} ({1})", dep.NugetId, dep.Version))))) .ToList(); var document = new XDocument( new XDeclaration("1.0", "utf-8", string.Empty), new XElement(ns + "DirectedGraph", new XElement(ns + "Nodes", nodes), new XElement(ns + "Links", links))); document.Save(file); }
public List<GameStats> Apply(List<DeckStats> stats) { // filter by deck first if needed IEnumerable<GameStats> filtered = null; if (Deck != null) { filtered = stats.Where<DeckStats>(d => d.DeckId.Equals(Deck)).SelectMany(d => d.Games); } else { filtered = stats.SelectMany(d => d.Games).ToList<GameStats>(); } // region filter if (!Region.Equals(StatsRegion.All)) { filtered = filtered.Where<GameStats>(g => (int)g.Region == (int)Region); } // game mode filter if (!Mode.Equals(GameMode.All)) { filtered = filtered.Where<GameStats>(g => g.GameMode.Equals(Mode)); } // time filter var times = GetFilterTimes(TimeFrame); filtered = filtered.Where<GameStats>(g => g.StartTime >= times.Item1 && g.EndTime <= times.Item2); // finally sort by time return filtered.OrderByDescending<GameStats, DateTime>(g => g.EndTime).ToList<GameStats>(); }
/// <summary> /// Initializes a new instance of the <see cref="XElementExportProvider"/> class. /// Includes *.xml and *.config by default. /// </summary> /// <param name="path">The path. Defaults to Directory.GetCurrentDirectory()</param> /// <param name="filters">A list of additional file filters to include.</param> public XElementExportProvider(string path = null, IEnumerable<string> filters = null) { if (path == null) { path = Directory.GetCurrentDirectory(); } List<string> include = new List<string>(new[] { "*.xml", "*.config" }); if (filters != null) { foreach (string filter in filters.Where(filter => !string.IsNullOrWhiteSpace(filter)).Where(filter => !include.Contains(filter))) { include.Add(filter); } } List<string> xmlFiles = new List<string>(include.SelectMany(ext => Directory.GetFiles(path, ext))); _exportsDictionary = xmlFiles.Select(filePath => new FileInfo(filePath)).ToDictionary( fileInfo => fileInfo.Name, fileInfo => { ExportDefinition def = new ExportDefinition(fileInfo.Name, null); Export e = new Export(def, () => XElement.Load(fileInfo.FullName)); return e; }); }
public static Blockchain RandomBlockchain(RandomDataOptions options = default(RandomDataOptions)) { //TODO blockCount algorithm isn't exact var blockCount = random.Next((options != null ? options.BlockCount : null) ?? 100) + ((options != null ? options.MinimumBlockCount : null) ?? 1); var blockList = new List<Block>(blockCount); var chainedBlockList = new List<ChainedBlock>(blockCount); var previousBlockHash = UInt256.Zero; var totalWork = new BigInteger(0); for (var i = 0; i < blockCount; i++) { var block = RandomData.RandomBlock(options); block = block.With(Header: block.Header.With(PreviousBlock: previousBlockHash)); blockList.Add(block); previousBlockHash = block.Hash; totalWork += block.Header.CalculateWork(); chainedBlockList.Add(new ChainedBlock(block.Hash, block.Header.PreviousBlock, i, totalWork)); } var blockListHashes = blockList.Select(x => x.Hash).ToImmutableHashSet(); var utxo = blockList.SelectMany(block => block.Transactions.Select((tx, txIndex) => new UnspentTx(block.Hash, (UInt32)txIndex, tx.Hash, random.NextImmutableBitArray((options != null ? options.TxOutputCount : null) ?? 100)))) .ToImmutableDictionary(unspentTx => unspentTx.TxHash, unspentTx => unspentTx); return new Blockchain ( chainedBlockList.ToImmutableList(), blockListHashes, utxo ); }
public override List <CkanModule> LatestAvailableWithProvides( IRegistryQuerier registry, GameVersionCriteria crit, IEnumerable <CkanModule> installed = null, IEnumerable <CkanModule> toInstall = null ) { return(any_of?.SelectMany(r => r.LatestAvailableWithProvides(registry, crit, installed, toInstall)).ToList()); }
public byte[] GetBytes(float mul = 1.0f) { List<byte[]> data = new List<byte[]>(); data.Add(X.GetBytes(mul)); data.Add(Y.GetBytes(mul)); return data.SelectMany(_ => _).ToArray(); }
static void Main(string[] args) { // parse args string cwd = Environment.CurrentDirectory; var testdirs = new List<string>(); string phpexepath = Path.Combine(cwd, "php.exe"); foreach (var arg in args) { if (arg.EndsWith("php.exe", StringComparison.OrdinalIgnoreCase)) { phpexepath = arg; } else { testdirs.Add(Path.GetFullPath(Path.Combine(cwd, arg))); } } // run tests lazily var tests = testdirs .SelectMany(dir => ExpandTestDir(dir)); // output results foreach (var test in tests) { Console.Write($"{test} ... "); Console.WriteLine(TestCore(test, phpexepath)); } }
/// <summary> /// Gets the metro applications. /// </summary> /// <returns></returns> public static IEnumerable<MetroApplication> GetApplications() { var packages = new PackageManager() .FindPackagesForUser(WindowsIdentity.GetCurrent().User.Value); var metroPackages = new List<MetroPackage>(); foreach (var package in packages) { var metroPackage = new MetroPackage(package); if (metroPackage.Applications.Any()) { metroPackages.Add(new MetroPackage(package)); } } var metroApplications = metroPackages .SelectMany(package => package.Applications) .Where( application => !string.IsNullOrEmpty(application.AppUserModelId) && !string.IsNullOrEmpty(application.Name)); return metroApplications; }
private static void feed_Loaded(object sender, SyndicationResourceLoadedEventArgs e) { var feed = (RssFeed)sender; feed.Loaded -= feed_Loaded; Console.WriteLine("RSS Feed loaded at " + DateTime.UtcNow); List<string[]> allLines = new List<string[]>(); foreach (var rssItem in feed.Channel.Items) { string title = rssItem.Title; title = RemoveHtml(title); if (m_includeDescription) { string description = rssItem.Description; description = RemoveHtml(description); allLines.Add(new string[] { title + ": " + description }); } else { allLines.Add(new string[] { title }); } } lock (m_forecastFeedLines) { m_forecastFeedLines.Clear(); m_forecastFeedLines.AddRange(allLines.SelectMany(s => s)); } UpdateAllFeedLines(); }
protected COBSCodec() { } // not instantiable /** * Returns the encoded representation of the given bytes. * Inefficient method, but easy to use and understand. * * @param src the bytes to encode * @return the encoded bytes. */ public static byte[] encode(byte[] src) { List<byte[]> dest = new List<byte[]>(maxEncodedSize(src.Length)); encode(src, 0, src.Length, dest); dest.TrimExcess(); return dest.SelectMany(a => a).ToArray(); }
public Task Subscribe(Guid recordID, string group) { if (UserList.Any(x => x.User == Context.ConnectionId)) return null; Console.WriteLine("[{0}] Client '{1}' has been added to group {2}.", DateTime.Now.ToString("dd-mm-yyyy hh:MM:ss"), Context.ConnectionId, group); var adv = new AdvList { Name = @group, User = Context.ConnectionId, UserRecordID = recordID, ListOfLanes = new List<Guid>() }; List<CustomerHierarchy> chList = new List<CustomerHierarchy>(); if(!CustomerHierarchy.Load(recordID, out chList)) { Console.WriteLine("Error retrieving customer hierarchy for user " + User.LoadUser(recordID).DisplayName); } var listOfLanes = new List<Guid>(); adv.ListOfLanes = chList.SelectMany(x => x.Equipment.Select(e => e.RecordID)).Distinct().ToList(); UserList.Add(adv); Console.WriteLine("user list contains this many people on subscription" + UserList.Count()); return Groups.Add(Context.ConnectionId, group); }
private static async Task<IEnumerable<MethodCountInfo>> GetClassMethodCounts(string solutionFile) { var methodCounts = new List<IEnumerable<MethodCountInfo>>(); using (MSBuildWorkspace workspace = MSBuildWorkspace.Create()) { Solution solution = await workspace.OpenSolutionAsync(solutionFile); foreach (var project in solution.Projects) { Console.WriteLine("Processing: " + project.Name); var compilation = await project.GetCompilationAsync(); foreach (var syntaxTree in compilation.SyntaxTrees) { var methodCounter = new MethodCountingWalker(compilation.GetSemanticModel(syntaxTree)); methodCounter.Visit(syntaxTree.GetRoot()); methodCounts.Add(methodCounter.Counts()); } } } return methodCounts.SelectMany(seq => seq); }
public IEnumerable<Money> Eject(CashDeal inCash, ChangePool inReservedMoney) { try { if (inCash.UsedAmount == 0) { return inCash.RecevedMoney.ToList(); } var result = new List<KeyValuePair<Money, int>>(); this.EjectCore( inCash.ChangedAount, inReservedMoney.Items.OrderByDescending(pair => pair.Key.Value()), (m, totalCount, useCount) => { result.Add( new KeyValuePair<Money, int>(m, (int)useCount) ); } ); return result.SelectMany(r => Enumerable.Repeat(r.Key, r.Value)); } finally { inCash.RecevedMoney.Clear(); } }
private void SalvarReprovadasStagingConectSys(List <PassagemReprovadaEstacionamentoDto> passagensReprovadas, PassagensReprovadasParkResponse response, Guid execucaoId) { var sw = new Stopwatch(); sw.Start(); var transacoesRecusadas = passagensReprovadas?.Select(c => c.TransacaoEstacionamentoRecusada).ToList(); var transacoesEstacionamentoRecusadasLoteStaging = Mapper.Map <List <TransacaoEstacionamentoRecusadaLoteStaging> >(transacoesRecusadas); var idsTransacoes = transacoesRecusadas.Select(x => x.RegistroTransacaoId).ToList(); var detalhePassagens = passagensReprovadas?.SelectMany(c => c.TransacaoEstacionamentoRecusada.Detalhes).ToList(); var detalhePassagemEstacionamentoRecusadasStaging = new List <DetalheTransacaoEstacionamentoRecusadaLoteStaging>(); detalhePassagens.ForEach(x => detalhePassagemEstacionamentoRecusadasStaging.Add(Mapper.Map <DetalheTransacaoEstacionamentoRecusadaLoteStaging>(x))); try { TransactionContextHelper.ExecuteTransaction((reprovadas) => { Log.Debug($"ID: {execucaoId} - Início - Staging Passagens Reprovadas Park - ConectSys."); using (var datasourceConectSys = AdoDataSourceProvider.GetDataSource(DbConnectionDataSourceType.ConectSys)) { try { datasourceConectSys.Connection.BulkInsertTransacoes(transacoesEstacionamentoRecusadasLoteStaging, "TransacaoEstacionamentoRecusadaLoteStaging"); datasourceConectSys.Connection.BulkInsertTransacoes(detalhePassagemEstacionamentoRecusadasStaging, "DetalhePassagemEstacionamentoRecusadaLoteStaging"); response.QtdTransacaoEstacionamentoRecusadaStaging = transacoesEstacionamentoRecusadasLoteStaging.Count; response.QtdDetalhePassagemEstacionamentoRecusadaStaging = detalhePassagemEstacionamentoRecusadasStaging.Count; } catch (Exception ex) { Log.Fatal($"ID: {execucaoId} - Erro Fatal - Staging Passagens Reprovadas Park - ConectSys.", ex); response.SucessoStagingConectSys = false; } } Log.Debug($"ID: {execucaoId} - Fim - Staging Passagens Reprovadas Park - ConectSys."); }, passagensReprovadas); TransactionContextHelper.ExecuteTransaction((reprovadas) => { using (var dataSourceConectPark = new DbConnectionDataSource("ConectParkConnStr")) { var command = new AtualizarRegistroTransacaoProcessadoCommand(dataSourceConectPark); command.Execute(new AtualizarRegistroTransacaoProcessadoArgs { RegistroTransacaoIds = idsTransacoes }); } }, transacoesRecusadas); } catch (Exception ex) { Log.Fatal($"ID: {execucaoId} - Erro Fatal. Erro: {ex.Message}", ex); } sw.Stop(); response.TempoExecucaoStagingConectSys = sw.Elapsed; }
public IEnumerable <ContextInfoContent> GetContextInfoContent() { return(EnumerableExtensions.Stream( units?.SelectMany(u => u.GetContextInfoContent()), Improvement?.GetContextInfoContent(), Terrain?.GetContextInfoContent(), Deposit?.GetContextInfoContent() )); }
public async Task <IEnumerable <Coin> > GetItemsAsync(bool forceRefresh = false) { var exchanges = await Settings.ExchangeListAsync(); List <Dictionary <String, Coin> > saveData = new List <Dictionary <String, Coin> >(); List <Coin> newItems = new List <Coin>(); if (exchanges == null) { newItems.Add(new Coin() { CoinName = "Please Add." }); } else { //Parallel has odd issues in Mono.Net var tasks = new List <Task <Dictionary <string, Coin> > >(); foreach (var x in exchanges) { //Workaround, oddities with Async Parllel tasks.Add(Task.Factory.StartNew(async() => { var data = await LoadData.LoadCoinBalanceAsync(x); return(data); }).Unwrap()); } await Task.WhenAll(tasks.ToArray()); tasks.ForEach(x => saveData.Add(x.Result)); } var groupbyName = saveData?.SelectMany(x => x.Values).GroupBy(x => x.CoinName).OrderByDescending(x => x.Sum(c => c.AvaliableValue)); foreach (var coinGroup in groupbyName) { Coin x = new Coin() { CoinName = coinGroup.Key, AvaliableValue = coinGroup.Sum(c => c.AvaliableValue), OnOrderValue = coinGroup.Sum(c => c.OnOrderValue) }; if (x.AvaliableValue > 0 || x.OnOrderValue > 0) { newItems.Add(x); } } items = newItems; return(await Task.FromResult(newItems)); }
internal async Task <List <CartLineComponent> > Resolve(CommerceContext commerceContext, string category, bool includeSubCategories) { List <Order> allOrders = await orderResolver.Resolve(commerceContext); string categorySitecoreId = AsyncHelper.RunSync(() => GetSitecoreIdFromCommerceId(commerceContext, category)); return(allOrders?.SelectMany(x => x.Lines) .Where(line => HasCategory(includeSubCategories, line, categorySitecoreId)) .ToList()); }
/// <summary> /// Initializes the project rewriter by getting a list of actions that will be run /// </summary> /// <returns>A list of project actions to be run</returns> public ProjectResult Initialize() { ProjectActions projectActions = new ProjectActions(); try { var allReferences = _sourceFileResults?.SelectMany(s => s.References).Distinct(); RulesFileLoader rulesFileLoader = new RulesFileLoader(allReferences, RulesEngineConfiguration.RulesDir, RulesEngineConfiguration.TargetVersions, string.Empty, RulesEngineConfiguration.AssemblyDir); var projectRules = rulesFileLoader.Load(); RulesAnalysis walker = new RulesAnalysis(_sourceFileResults, projectRules); projectActions = walker.Analyze(); _projectReferences.ForEach(p => { projectActions.ProjectReferenceActions.Add(Config.Utils.GetRelativePath(RulesEngineConfiguration.ProjectPath, p)); }); _projectResult.ActionPackages = projectActions.PackageActions.Distinct().ToList(); _projectResult.MetaReferences = _metaReferences; foreach (var p in RulesEngineConfiguration.PackageReferences) { projectActions.PackageActions.Add(new PackageAction() { Name = p.Key, OriginalVersion = p.Value.Item1, Version = p.Value.Item2 }); } MergePackages(projectActions.PackageActions); projectActions.ProjectLevelActions = projectRules.ProjectTokens.SelectMany(p => p.ProjectLevelActions).Distinct().ToList(); projectActions.ProjectLevelActions.AddRange(projectRules.ProjectTokens.SelectMany(p => p.ProjectFileActions)); projectActions.ProjectRules = projectRules; _projectResult.ProjectActions = projectActions; } catch (Exception ex) { LogHelper.LogError(ex, "Error while initializing project {0}", RulesEngineConfiguration.ProjectPath); } return(_projectResult); }
public void ConfigurarDatasRelatorio(List <ControleFeriasNegocio.Dominio.Funcionario> funcionariosEmFerias = null) { if (funcionariosEmFerias == null) { funcionariosEmFerias = _FuncionariosFerias; } _Ferias = funcionariosEmFerias?.Where(f => !f.PeriodosFerias.IsNullOrEmpty()).SelectMany(f => f.PeriodosFerias)?.ToList(); DateTime[] datas = _Ferias?.SelectMany(p => DatasDoPeriodo(p))?.OrderBy(p => p).ToArray(); if (datas != null) { monthCalendar1.BoldedDates = datas; } }
public async Task RegisterNewProductAsync(Domain.Entities.Product product, List <RequestFile> photos, RequestFile profile) { const string profilePhotoName = nameof(product.ProfilePhoto); const string photosName = nameof(product.Photos); const string bucketName = nameof(profile.Bucket); const string nameOfPhotosName = nameof(RequestFile.Name); var productValidation = product.Validate(profilePhotoName, photosName); var profileValidation = profile.Validate(bucketName, nameOfPhotosName); var photosValidation = photos?.SelectMany(p => p.Validate(bucketName, nameOfPhotosName)); if (productValidation.IsValid() && profileValidation.IsValid() && photosValidation.IsValid()) { await _repository.CreateProductAsync(product); _uploader.FileUploaded += OnPhotoUploaded; profile.Name = $"{ProductName}-{product.Key}-{ProfileTypeName}-{profile.Key}".ToLower(); profile.Bucket = "store-lab-product-profile"; profile.Metadata = new Dictionary <string, string> { { ProductKeyName, product.Key }, { FileTypeName, ProfileTypeName } }; photos?.ForEach(p => { p.Name = $"{ProductName}-{product.Key}-{PhotoTypeName}-{p.Key}".ToLower(); p.Bucket = "store-lab-product-photos"; p.Metadata = new Dictionary <string, string> { { ProductKeyName, product.Key }, { FileTypeName, PhotoTypeName } }; }); await _uploader.UploadAsync(profile); await _uploader.UploadAllAsync(photos); var args = new RegisterNewProductEventArgs { Product = product }; ProductRegisted?.Invoke(this, args); } else { throw new EntityException(productValidation.Aggregate(profileValidation).Aggregate(photosValidation)); } }
public virtual StatsEmployees CalculateStats() { int countEmployees; decimal avgVacationDays; int diffJobTitles; EmployeesController employeesController = new(); List <Employee>? allEmployees = employeesController.GetAllEmployees()?.ToList(); countEmployees = allEmployees?.Count ?? 0; avgVacationDays = (decimal)(allEmployees?.Average(x => x.VacationDays) ?? 0); diffJobTitles = allEmployees?.SelectMany(x => x.JobTitle)?.Distinct()?.Count() ?? 0; return(new(countEmployees, avgVacationDays, diffJobTitles)); }
private void OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (e == null) { return; } var previousCol = _SelectedCascade; _SelectedCascade = (sender as DataTemplates.CascadeComponentXaml)?.Column ?? -1; ICard top = (_SelectedCascade >= 0) ? _Cards[_SelectedCascade].LastOrDefault() : CardEx.Empty; // card available to play of cascade (visually on bottom but called top) ICard previous = null; foreach (var c in _Cards?.SelectMany(z => z)?.Where(z => z.Selected)) { //if (c.Selected) previous = c; c.Selected = false; } previous = _SelectedCard; var current = e.CurrentSelection.FirstOrDefault() as ICard; if ((current != null) && (top == current)) // only allow top card in cascade to be selected { current.Selected = true; } if (previous == CardEx.Empty) { this.BackgroundColor = Color.Gray; // nothing previously selected } else if (previous == current) { this.BackgroundColor = Color.Gray; // same card } else if (previous.CanBePlacedOnSingle(current)) { this.BackgroundColor = Color.Green; // move is valid } else { this.BackgroundColor = Color.Yellow; // invalid move } _SelectedCard = current; RefreshView(); }
private void OnTimerElapsed(object sender, ElapsedEventArgs e) { //_timer.Stop(); using (var context = new CoreDBContext(new DbContextOptionsBuilder <CoreDBContext>().UseNpgsql(_connectionString).Options)) { List <Account> accounts = context?.Accounts? .Include(a => a.Subscriptions) .ThenInclude(s => s.Currency) .ToList(); List <SignalsDTO> signalsDTOs = new List <SignalsDTO>(); Dictionary <string, List <SignalsDTO> > userSignals = new Dictionary <string, List <SignalsDTO> >(accounts?.Count ?? 0); List <string> currencies = accounts?.SelectMany(x => x.Subscriptions?.Select(s => s?.Currency?.Name))?.Distinct()?.ToList(); foreach (var currency in currencies) { SignalsDTO signal = CheckSignals(currency).Result; if (signal != null) { signalsDTOs.Add(signal); } } foreach (var account in accounts) { foreach (var subscription in account?.Subscriptions) { if (currencies.Contains(subscription?.Currency?.Name)) { if (userSignals.TryGetValue(account?.Email, out var signals) == false) { signals = new List <SignalsDTO>(); userSignals.Add(account?.Email, signals); } if (signals.Exists(s => s.Symbol == subscription?.Currency?.Symbol) == false) { SignalsDTO signal = signalsDTOs.FirstOrDefault(s => s.Symbol == subscription?.Currency.Symbol); signals.Add(signal); } } } } SendSignals(userSignals); } }
/// <summary> /// If this fee has a <see cref="MaximumUsageCount" />, returns the number of allowed usages remaining for the specified <see cref="RegistrationInstance" /> /// </summary> /// <param name="registrationInstance">The registration instance.</param> /// <param name="otherRegistrants">The other registrants that have been registered so far in this registration</param> /// <returns></returns> public int?GetUsageCountRemaining(RegistrationInstance registrationInstance, List <RegistrantInfo> otherRegistrants) { if (!this.MaximumUsageCount.HasValue || registrationInstance == null) { return(null); } int?usageCountRemaining; var registrationInstanceId = registrationInstance.Id; var registrationInstanceFeesQuery = new RegistrationRegistrantFeeService(new RockContext()).Queryable().Where(a => a.RegistrationRegistrant.Registration.RegistrationInstanceId == registrationInstanceId); var feeUsedCount = registrationInstanceFeesQuery.Where(a => a.RegistrationTemplateFeeItemId == this.Id).Sum(a => ( int? )a.Quantity) ?? 0; // get a list of fees that the other registrants in this registrant entry have incurred so far List <FeeInfo> otherRegistrantsFees = otherRegistrants?.SelectMany(a => a.FeeValues).Where(a => a.Value != null && a.Key == this.RegistrationTemplateFeeId).SelectMany(a => a.Value).ToList(); // get the count of fees of this same fee item for other registrants int otherRegistrantsUsedCount = otherRegistrantsFees?.Where(a => a.RegistrationTemplateFeeItemId == this.Id).Sum(f => f.Quantity) ?? 0; usageCountRemaining = this.MaximumUsageCount.Value - feeUsedCount - otherRegistrantsUsedCount; return(usageCountRemaining); }
/// <summary> /// Get all rewards applied on line items and shipment into a single list /// </summary> /// <param name="orderShipment"></param> /// <returns></returns> protected List <Reward> GetAllRewards(List <Shipment> orderShipment) { var allRewards = new List <Reward>(); if (orderShipment.Any()) { var shipmentRewards = Enumerable.Empty <Reward>(); var lineItemRewards = Enumerable.Empty <Reward>(); shipmentRewards = orderShipment.SelectMany(s => s.Rewards); if (orderShipment?.SelectMany(s => s.LineItems?.SelectMany(l => l.Rewards)) != null) { lineItemRewards = orderShipment .SelectMany(t => t.LineItems .SelectMany(l => l.Rewards)); } allRewards = shipmentRewards .Concat(lineItemRewards) .ToList(); } return(allRewards); }
private void SalvarAprovadasStagingConectSys(List <PassagemAprovadaEstacionamentoDto> passagensAprovadas, PassagensAprovadasParkResponse response, Guid execucaoId) { try { var transacoes = passagensAprovadas?.Select(c => c.TransacaoEstacionamento).ToList(); var transacaoStaging = Mapper.Map <List <TransacaoPassagemEstacionamentoLoteStaging> >(transacoes); var idsTransacoes = transacoes.Select(x => x.RegistroTransacaoId).ToList(); var extratos = passagensAprovadas?.Select(c => c.Extrato).ToList(); var extratosStaging = Mapper.Map <List <ExtratoLoteStaging> >(extratos); var conveniadoInformacoes = passagensAprovadas?.Select(c => c.ConveniadoInformacoesRPS).ToList(); var conveniadoInformacoesStaging = Mapper.Map <List <ConveniadoInformacoesRpsLoteStaging> >(conveniadoInformacoes); var detalhePassagens = passagensAprovadas?.SelectMany(c => c.TransacaoEstacionamento.Detalhes).ToList(); var detalhePassagemStaging = new List <DetalhePassagemEstacionamentoLoteStaging>(); detalhePassagens.ForEach(x => detalhePassagemStaging.Add(Mapper.Map <DetalhePassagemEstacionamentoLoteStaging>(x))); var pistaInformacoes = passagensAprovadas?.Select(c => c.PistaInformacoesRPS).ToList(); var pistaInformacoesRpsStaging = Mapper.Map <List <PistaInformacoesRPSLoteStaging> >(pistaInformacoes); TransactionContextHelper.ExecuteTransaction((aprovadas) => { Log.Debug($"ID: {execucaoId} - Início - Staging Passagens Aprovadas Park - ConectSys."); using (var datasourceConectSys = AdoDataSourceProvider.GetDataSource(DbConnectionDataSourceType.ConectSys)) { try { datasourceConectSys.Connection.BulkInsert(transacaoStaging, "TransacaoPassagemEstacionamentoStaging"); datasourceConectSys.Connection.BulkInsert(extratosStaging, "ExtratoLoteStaging"); datasourceConectSys.Connection.BulkInsert(detalhePassagemStaging, "DetalhePassagemEstacionamentoStaging"); datasourceConectSys.Connection.BulkInsert(conveniadoInformacoesStaging, "ConveniadoInformacoesRPSStaging"); datasourceConectSys.Connection.BulkInsert(pistaInformacoesRpsStaging, "PistaInformacoesRpsStaging"); response.QtdConveniadoInformacoesRPSStaging = conveniadoInformacoesStaging.Count; response.QtdDetalhePassagemEstacionamentoStaging = detalhePassagemStaging.Count; response.QtdPistaInformacoesRPSStaging = pistaInformacoesRpsStaging.Count; response.QtdTransacaoPassagemEstacionamentoStaging = transacaoStaging.Count; } catch (Exception ex) { Log.Fatal($"ID: {execucaoId} - Erro Fatal - Staging Passagem Aprovadas Park - ConectSys", ex); response.SucessoStagingConectSys = false; } } Log.Debug($"ID: {execucaoId} - Fim - Staging Passagens Aprovadas Park - ConectSys"); }, passagensAprovadas); TransactionContextHelper.ExecuteTransaction((aprovadas) => { using (var dataSourceConectPark = new DbConnectionDataSource("ConectParkConnStr")) { var command = new AtualizarRegistroTransacaoProcessadoCommand(dataSourceConectPark); command.Execute(new AtualizarRegistroTransacaoProcessadoArgs { RegistroTransacaoIds = idsTransacoes }); } }, passagensAprovadas); } catch (Exception ex) { Log.Fatal($"ID: {execucaoId} - Erro Fatal. Erro: {ex.Message}", ex); } }
/// <summary> /// Returns column name and tooltip for the extra fields in publication overview /// </summary> public static List <VersionedExtraPropertiesColumnInfo> GetExtraPropertiesNames() { return(_instances?.SelectMany(p => p.GetExtraPropertiesNames() ?? new List <VersionedExtraPropertiesColumnInfo>()).ToList()); }
public IEnumerable <INotificationEto> GetDomainEvents() { return(changeTracker?.SelectMany(e => e.GetDomainEvents())); }
internal TryCatch <PartitionedQueryExecutionInfoInternal> TryGetPartitionedQueryExecutionInfoInternal( SqlQuerySpec querySpec, PartitionKeyDefinition partitionKeyDefinition, bool requireFormattableOrderByQuery, bool isContinuationExpected, bool allowNonValueAggregateQuery, bool hasLogicalPartitionKey) { if (querySpec == null || partitionKeyDefinition == null) { return(TryCatch <PartitionedQueryExecutionInfoInternal> .FromResult(DefaultInfoInternal)); } string queryText = JsonConvert.SerializeObject(querySpec); List <string> paths = new List <string>(partitionKeyDefinition.Paths); List <string[]> pathParts = new List <string[]>(); paths.ForEach(path => { pathParts.Add(PathParser.GetPathParts(path).ToArray()); }); string[] allParts = pathParts.SelectMany(parts => parts).ToArray(); uint[] partsLengths = pathParts.Select(parts => (uint)parts.Length).ToArray(); PartitionKind partitionKind = partitionKeyDefinition.Kind; this.Initialize(); byte[] buffer = new byte[InitialBufferSize]; uint errorCode; uint serializedQueryExecutionInfoResultLength; unsafe { fixed(byte *bytePtr = buffer) { errorCode = ServiceInteropWrapper.GetPartitionKeyRangesFromQuery( this.serviceProvider, queryText, requireFormattableOrderByQuery, isContinuationExpected, allowNonValueAggregateQuery, hasLogicalPartitionKey, allParts, partsLengths, (uint)partitionKeyDefinition.Paths.Count, partitionKind, new IntPtr(bytePtr), (uint)buffer.Length, out serializedQueryExecutionInfoResultLength); if (errorCode == DISP_E_BUFFERTOOSMALL) { buffer = new byte[serializedQueryExecutionInfoResultLength]; fixed(byte *bytePtr2 = buffer) { errorCode = ServiceInteropWrapper.GetPartitionKeyRangesFromQuery( this.serviceProvider, queryText, requireFormattableOrderByQuery, isContinuationExpected, allowNonValueAggregateQuery, hasLogicalPartitionKey, // has logical partition key allParts, partsLengths, (uint)partitionKeyDefinition.Paths.Count, partitionKind, new IntPtr(bytePtr2), (uint)buffer.Length, out serializedQueryExecutionInfoResultLength); } } } } string serializedQueryExecutionInfo = Encoding.UTF8.GetString(buffer, 0, (int)serializedQueryExecutionInfoResultLength); Exception exception = Marshal.GetExceptionForHR((int)errorCode); if (exception != null) { DefaultTrace.TraceInformation("QueryEngineConfiguration: " + this.queryengineConfiguration); string errorMessage; if (string.IsNullOrEmpty(serializedQueryExecutionInfo)) { errorMessage = $"Message: Query service interop parsing hit an unexpected exception: {exception.ToString()}"; } else { errorMessage = "Message: " + serializedQueryExecutionInfo; } return(TryCatch <PartitionedQueryExecutionInfoInternal> .FromException(new Exception(errorMessage))); } PartitionedQueryExecutionInfoInternal queryInfoInternal = JsonConvert.DeserializeObject <PartitionedQueryExecutionInfoInternal>( serializedQueryExecutionInfo, new JsonSerializerSettings { DateParseHandling = DateParseHandling.None }); return(TryCatch <PartitionedQueryExecutionInfoInternal> .FromResult(queryInfoInternal)); }
public Requerimento ImportarPessoas(Requerimento requerimento, List <Pessoa> pessoasRelacionadas, BancoDeDados bancoInterno) { try { #region Fisica Pessoa aux; List <Pessoa> pessoas = requerimento.Pessoas.Where(x => x.IsFisica && pessoasRelacionadas.Exists(z => z.CPFCNPJ == x.CPFCNPJ)).ToList(); pessoas.Where(x => x.SelecaoTipo == (int)eExecutorTipo.Credenciado).ToList().ForEach(r => { _busPessoa.AlterarConjuge(_busPessoa.ObterId(r.CPFCNPJ), bancoInterno); }); pessoas.Where(x => x.SelecaoTipo == (int)eExecutorTipo.Credenciado).ToList().ForEach(r => { aux = _busPessoa.Importar(r, bancoInterno, true); r.InternoId = aux.InternoId; }); pessoas.Where(x => x.SelecaoTipo == (int)eExecutorTipo.Interno).ToList().ForEach(r => { r.InternoId = _busPessoa.ObterId(r.CPFCNPJ, bancoInterno); }); #endregion #region Juridica List <Pessoa> juridicas = requerimento.Pessoas.Where(x => x.IsJuridica && pessoasRelacionadas.Exists(z => z.CPFCNPJ == x.CPFCNPJ)).ToList(); juridicas.SelectMany(x => x.Juridica.Representantes).ToList().ForEach(r => { aux = pessoas.FirstOrDefault(y => y.CPFCNPJ == r.CPFCNPJ); if (aux != null && aux.InternoId.HasValue) { r.Id = aux.InternoId.GetValueOrDefault(); } }); juridicas.Where(x => x.SelecaoTipo == (int)eExecutorTipo.Credenciado).ToList().ForEach(r => { aux = _busPessoa.Importar(r, bancoInterno); r.InternoId = aux.InternoId; }); juridicas.Where(x => x.SelecaoTipo == (int)eExecutorTipo.Interno).ToList().ForEach(r => { r.InternoId = _busPessoa.ObterId(r.CPFCNPJ, bancoInterno); }); #endregion pessoas.AddRange(juridicas); if (pessoas != null && pessoas.Count > 0) { pessoas.Where(x => x.IsFisica && x.Fisica.ConjugeId > 0).ToList().ForEach(r => { aux = pessoas.FirstOrDefault(y => y.CPFCNPJ == r.Fisica.ConjugeCPF); if (aux != null) { r.Fisica.ConjugeId = aux.InternoId.GetValueOrDefault(); _busPessoa.AlterarConjugeEstadoCivil(r.InternoId.GetValueOrDefault(), r.Fisica.ConjugeId.Value, bancoInterno); } }); requerimento.Interessado.Id = pessoas.Where(y => y.Id == requerimento.Interessado.Id).FirstOrDefault().InternoId.GetValueOrDefault(); requerimento.Responsaveis.Where(x => x.Representantes != null).SelectMany(z => z.Representantes).ToList().ForEach(r => { r.Id = pessoas.Where(y => y.Id == r.Id).FirstOrDefault().InternoId.GetValueOrDefault(); }); requerimento.Responsaveis.ForEach(r => { aux = pessoas.FirstOrDefault(y => y.CPFCNPJ == r.CpfCnpj); if (aux != null && aux.InternoId.HasValue) { r.Id = aux.InternoId.GetValueOrDefault(); } }); } requerimento.Pessoas = pessoas; } catch (Exception exc) { Validacao.AddErro(exc); } return(requerimento); }
public FltRetModApplyModel GetRetModApply(int rmid) { FltRetModApplyEntity fltRetModApply = _fltRetModApplyDal.Find <FltRetModApplyEntity>(rmid); List <FltRetModFlightApplyEntity> fltRetModFlightApplyEntities = _fltRetModFlightApplyDal.Query <FltRetModFlightApplyEntity>(n => n.Rmid == rmid).ToList(); List <FltRetModApplyLogEntity> fltRetModApplyLogEntities = _fltRetModApplyLogDal.Query <FltRetModApplyLogEntity>(n => n.Rmid == rmid).ToList(); FltRetModApplyModel fltRetModApplyModel = Mapper.Map <FltRetModApplyEntity, FltRetModApplyModel>(fltRetModApply); fltRetModApplyModel.DetailList = Mapper.Map <List <FltRetModFlightApplyEntity>, List <FltRetModFlightApplyModel> >( fltRetModFlightApplyEntities); fltRetModApplyModel.LogList = Mapper.Map <List <FltRetModApplyLogEntity>, List <FltRetModApplyLogModel> >( fltRetModApplyLogEntities); List <SearchCityModel> cityModels = AportInfo?.CountryList.SelectMany(n => n.CityList).ToList(); List <SearchAirportModel> airportModels = cityModels?.SelectMany(n => n.AirportList).ToList(); #region 乘机人信息 List <int> pidList = fltRetModApplyModel.DetailList.Select(n => n.Pid).ToList(); List <FltPassengerEntity> passengerEntities = _fltPassengerDal.Query <FltPassengerEntity>(n => pidList.Any(x => x == n.PId)).ToList(); #endregion //4.获取仓等信息 List <FltClassNameModel> classNameModels = _getClassNameBll.GetFlightClassName(); fltRetModApplyModel.DetailList.ForEach(n => { FltFlightEntity orderFlightEntity = _fltFlightDal.Query <FltFlightEntity>(x => x.OrderId == fltRetModApplyModel.OrderId && x.Sequence == n.Sequence) .FirstOrDefault(); if (orderFlightEntity != null) { if (!n.TackoffTime.HasValue) { n.TackoffTime = orderFlightEntity.TackoffTime; } if (string.IsNullOrEmpty(n.FlightNo)) { n.FlightNo = orderFlightEntity.FlightNo; } } string dport = n.Dport.ToLower(); if (fltRetModApplyModel.OrderType == "R" && orderFlightEntity != null) { dport = orderFlightEntity.Dport.ToLower(); } SearchAirportModel airportModel = airportModels.Find(x => x.AirportCode.ToLower() == dport); if (airportModel != null) { n.DportName = airportModel.AirportName; SearchCityModel cityModel = cityModels.Find(x => x.CityCode.ToLower() == airportModel.CityCode.ToLower()); n.DportCity = cityModel.CityName; } string aport = n.Aport.ToLower(); if (fltRetModApplyModel.OrderType == "R" && orderFlightEntity != null) { aport = orderFlightEntity.Aport.ToLower(); } SearchAirportModel airportModel2 = airportModels.Find(x => x.AirportCode.ToLower() == aport); if (airportModel2 != null) { n.AportName = airportModel2.AirportName; SearchCityModel cityModel2 = cityModels.Find(x => x.CityCode.ToLower() == airportModel2.CityCode.ToLower()); n.AportCity = cityModel2.CityName; } FltPassengerModel passengerModel = Mapper.Map <FltPassengerEntity, FltPassengerModel>(passengerEntities.Find(x => x.PId == n.Pid)); n.PassengerModel = passengerModel; if (fltRetModApplyModel.OrderType == "R") { n.PassengerModel.RefundTicketNo = n.TicketNo; } if (n.ChoiceReasonId.HasValue) { n.ChoiceReason = PolicyReasonList?.Find(x => x.Id == n.ChoiceReasonId.Value)?.Reason; } FltClassNameModel classNameModel = classNameModels.Find( x => !string.IsNullOrEmpty(x.MClass) && !string.IsNullOrEmpty(n.Class) && x.MClass.ToLower() == n.Class.ToLower() && !string.IsNullOrEmpty(x.AirlineCode) && !string.IsNullOrEmpty(n.FlightNo) && x.AirlineCode.ToLower() == n.FlightNo.Substring(0, 2).ToLower()); if (classNameModel != null) { n.ClassName = classNameModel.ClassName; } }); return(fltRetModApplyModel); }
/// <summary> /// 根据订单号获取订单信息 /// </summary> /// <param name="orderId"></param> /// <returns></returns> public FltOrderInfoModel GetFltOrderById(int orderId) { FltOrderEntity fltOrderEntity = _fltOrderDal.Find <FltOrderEntity>(orderId); if (fltOrderEntity == null) { return(null); } //1.根据订单号 获取航段信息 List <FltFlightEntity> flightEntities = _fltFlightDal.Query <FltFlightEntity>(n => n.OrderId == orderId, true).ToList(); //2.根据订单号 获取乘机人信息 List <FltPassengerEntity> passengerEntities = _fltPassengerDal.Query <FltPassengerEntity>(n => n.OrderId == orderId, true).ToList(); //3.根据订单号 获取成本中心 FltCorpCostCenterEntity costCenterEntity = _fltCorpCostCenterDal.Query <FltCorpCostCenterEntity>(n => n.Orderid == orderId, true).FirstOrDefault(); //4.获取仓等信息 List <FltClassNameModel> classNameModels = _getClassNameBll.GetFlightClassName(); //5.获取机场信息 List <SearchCityModel> cityModels = AportInfo?.CountryList.SelectMany(n => n.CityList).ToList(); List <SearchAirportModel> airportModels = cityModels?.SelectMany(n => n.AirportList).ToList(); //6.机票订单扩展表 FltOrderUnionEntity fltOrderUnionEntity = _fltOrderUnionDal.Find <FltOrderUnionEntity>(orderId); FltOrderInfoModel result = Mapper.Map <FltOrderEntity, FltOrderInfoModel>(fltOrderEntity); if (!string.IsNullOrEmpty(costCenterEntity?.Depart)) { result.CostCenter = costCenterEntity.Depart; } if (fltOrderUnionEntity?.ProjectId != null && ProjectNameList != null) { ProjectNameModel projectNameModel = ProjectNameList.Find(n => n.ProjectId == fltOrderUnionEntity.ProjectId.Value); result.ProjectName = projectNameModel?.ProjectName; } //result.CorpPolicy = fltOrderUnionEntity?.CorpPolicy; result.PassengerList = Mapper.Map <List <FltPassengerEntity>, List <FltPassengerModel> >( passengerEntities.FindAll(n => n.OrderId == fltOrderEntity.OrderId)); result.FlightList = Mapper.Map <List <FltFlightEntity>, List <FltFlightModel> >( flightEntities.FindAll(n => n.OrderId == fltOrderEntity.OrderId)); result.PassengerList.ForEach(n => { if (n.InsCompanyId.HasValue) { n.InsuranceName = InsuranceCompanyList?.Find(x => x.CompanyID == n.InsCompanyId.Value)?.ProductName; } }); #region 行程信息 result.CorpPolicy = string.Empty; result.ChoiceReason = string.Empty; foreach (var n in result.FlightList) { if (!string.IsNullOrEmpty(n.CorpPolicy) && n.CorpPolicy.ToLower() != "undefined") { result.CorpPolicy += ";" + n.CorpPolicy; } if (!string.IsNullOrEmpty(n.ChoiceReason) && n.ChoiceReason.ToLower() != "undefined") { result.ChoiceReason += ";" + n.ChoiceReason; } SearchAirportModel airportModel = airportModels?.Find(x => x.AirportCode.ToLower() == n.Dport.ToLower()); if (airportModel != null) { n.DportName = airportModel.AirportLongName; SearchCityModel cityModel = cityModels.Find(x => x.CityCode.ToLower() == airportModel.CityCode.ToLower()); n.DportCity = cityModel.CityName; } SearchAirportModel airportModel2 = airportModels?.Find(x => x.AirportCode.ToLower() == n.Aport.ToLower()); if (airportModel2 != null) { n.AportName = airportModel2.AirportLongName; SearchCityModel cityModel2 = cityModels.Find(x => x.CityCode.ToLower() == airportModel2.CityCode.ToLower()); n.AportCity = cityModel2.CityName; } FltClassNameModel classNameModel = classNameModels.Find( x => !string.IsNullOrEmpty(x.MClass) && !string.IsNullOrEmpty(n.Class) && x.MClass.ToLower() == n.Class.ToLower() && !string.IsNullOrEmpty(x.AirlineCode) && !string.IsNullOrEmpty(n.AirlineNo) && x.AirlineCode.ToLower() == n.AirlineNo.ToLower()); if (classNameModel != null) { n.ClassName = classNameModel.ClassName; n.ClassEnName = classNameModel.ClassEnName; } } if (!string.IsNullOrEmpty(result.CorpPolicy)) { result.CorpPolicy = result.CorpPolicy.Substring(1); } if (!string.IsNullOrEmpty(result.ChoiceReason)) { result.ChoiceReason = result.ChoiceReason.Substring(1); } #endregion return(result); }
/// <summary> /// Returns column name and tooltip for the extra fields in publication overview /// </summary> public static IEnumerable <VersionedExtraPropertiesColumnInfo> GetExtraPropertyNames() { return(_services?.SelectMany(p => p.GetExtraPropertiesNames() ?? Enumerable.Empty <VersionedExtraPropertiesColumnInfo>()).ToList()); }
public Task <ResultList <TicketCoreModel> > List(FilterModel model) => ResultList <TicketCoreModel> .TryAsync(async() => { var isAdmin = generalDataService.User.Permissions.Any(p => p == (int)PermissionType.Admin); var tickets = new List <Ticket>(); if (isAdmin) { var list = await _repository.ListAsNoTrackingAsync <Ticket>(i => (string.IsNullOrEmpty(model.Keyword) || model.Keyword == i.Title) && (model.UserId == null || i.UserId == model.UserId.Value) && (model.CreationDate == null || model.CreationDate.Value.ToString("d") == i.CreationDate.ToString("d")), new PagingModel { PageSize = 1000, PageNumber = 0 }, t => t.Comment); tickets = list.Items.ToList(); } else { var list = await _repository.ListAsNoTrackingAsync <Ticket>(i => i.UserId == generalDataService.User.Id && (string.IsNullOrEmpty(model.Keyword) || model.Keyword == i.Title), new PagingModel { PageSize = 1000, PageNumber = 0 }, t => t.Comment); tickets = list.Items.ToList(); tickets = tickets.Where(t => t.Title != "Survey").ToList(); } if (tickets == null) { return(ResultList <TicketCoreModel> .Failed(Error.WithData(1000, new[] { "Tickets Not Found" }))); } var users = (await _membershipServiceApi.SystemUserApiService.ListByIds(tickets .Select(a => a.UserId) .Union(tickets .Select(a => a.RepresentativeId != null ? a.RepresentativeId.Value : Guid.Empty) .Where(a => a != Guid.Empty)).Union(tickets?.SelectMany(t => t.Comment)?.Select(t => t.UserId)) .ToList())).Data; var ticketModels = tickets.OrderBy(t => t.CreationDate).Reverse().Take(model.PageSize) .Skip(model.PageSize *model.PageNumber).Select(ticket => new TicketCoreModel { Id = ticket.Id, Title = ticket.Title, Text = ticket.Text, User = users.FirstOrDefault(u => u.Id == ticket.UserId), Representative = users.FirstOrDefault(u => u.Id == ticket.RepresentativeId), BlobId = ticket.BlobId, Active = ticket.Active, CreationDate = ticket.CreationDate, Priority = (TicketPriority)ticket.Priority, Comment = ticket.Comment?.Select(c => new CommentCoreModel { Id = c.Id, BlobId = c.BlobId, CreationDate = c.CreationDate, Text = c.Text, User = users.FirstOrDefault(u => u.Id == c.UserId) }).ToList(), }); return(ResultList <TicketCoreModel> .Successful(ticketModels)); });
public List <string> GetIdentifiers() => Results? .SelectMany(g => g.GetIdentifiers()) .Distinct() .ToList() ?? new List <string>();
public NaiveSolver(string inputFileName, string outputFileName, char delimiter) { // Model initializations int D; // the duration of the simulation, in seconds int I; // the number of intersections (with IDs from 0 to I -1) int S; // the number of streets int V; // the number of cars int F; // the bonus points for each car that reaches its destination before time D List <Street> streets = new List <Street>(); List <CarPath> carPathes = new List <CarPath>(); List <IntersectionSchedule> schedules = new List <IntersectionSchedule>(); /************************************************************************************** * Input loading **************************************************************************************/ Console.WriteLine("Input loading... " + inputFileName); string inputFilePath = Path.Combine(Directory.GetCurrentDirectory(), inputFileName); string[] lines = File.ReadAllLines(inputFilePath); // Metadata parsing string[] line0 = lines[0].Split(delimiter); D = int.Parse(line0[0]); I = int.Parse(line0[1]); S = int.Parse(line0[2]); V = int.Parse(line0[3]); F = int.Parse(line0[4]); // Streets parsing for (int i = 1; i <= S; i++) { string[] lineStreet = lines[i].Split(delimiter); Street newStreet = new Street() { B = int.Parse(lineStreet[0]), E = int.Parse(lineStreet[1]), Name = lineStreet[2], L = int.Parse(lineStreet[3]) }; streets.Add(newStreet); } // Pathes parsing for (int i = S + 1; i <= S + V; i++) { string[] lineCarPath = lines[i].Split(delimiter); CarPath newCarPath = new CarPath() { P = int.Parse(lineCarPath[0]), Streets = new List <string>() }; for (int j = 1; j <= newCarPath.P; j++) { newCarPath.Streets.Add(lineCarPath[j]); } carPathes.Add(newCarPath); } /************************************************************************************** * Solver **************************************************************************************/ // Remove unused streets List <string> usefullStreets = carPathes.SelectMany(cP => cP.Streets).Distinct().ToList(); // Initialize Intersection (Schedules) for (int i = 0; i < I; i++) { schedules.Add(new IntersectionSchedule() { i = i, Ei = 0, GreenLightSchedules = new List <GreenlightSchedule>() }); } // Fill intersections with incoming streets foreach (Street street in streets) { if (usefullStreets.Contains(street.Name) && schedules[street.E].GreenLightSchedules.Where(g => g.StreetName == street.Name).Count() == 0) // If the intersection doesn't have this incoming street yet { // Order will be updated (but almost no impact) schedules[street.E].GreenLightSchedules.Add(new GreenlightSchedule() // Only "E" (stop of a street) is an incoming street of an intersection { Duration = 1, // This will be updated with weighted value StreetName = street.Name }); schedules[street.E].Ei++; } } // Clean schedules schedules = schedules.Where(s => s.GreenLightSchedules.Count() > 0).ToList(); // Give more duration to busy streets int maxGreenDuration = 6; // Building weight map Dictionary <string, int> streetPathCounter = new Dictionary <string, int>(); foreach (CarPath carPath in carPathes) { foreach (string streetName in carPath.Streets) { if (!streetPathCounter.ContainsKey(streetName)) { streetPathCounter.Add(streetName, 1); } else { streetPathCounter[streetName]++; } } } foreach (IntersectionSchedule intersect in schedules) { int maxWeight = 0; foreach (GreenlightSchedule gLS in intersect.GreenLightSchedules) { if (streetPathCounter[gLS.StreetName] > maxWeight) { maxWeight = streetPathCounter[gLS.StreetName]; } } foreach (GreenlightSchedule gLS in intersect.GreenLightSchedules) { gLS.Duration = (int)Math.Ceiling((float)streetPathCounter[gLS.StreetName] / (float)maxWeight * maxGreenDuration); Math.Clamp(gLS.Duration, 1, maxGreenDuration); } } // Sort greenlights (almost no impact) foreach (IntersectionSchedule intersect in schedules) { intersect.GreenLightSchedules = intersect.GreenLightSchedules.OrderByDescending(gLS => gLS.Duration).ToList(); } /************************************************************************************** * Output **************************************************************************************/ Console.WriteLine("Output to file..."); using (StreamWriter outputFile = new StreamWriter(Path.Combine(Directory.GetCurrentDirectory(), outputFileName))) { outputFile.WriteLine(schedules.Count); foreach (IntersectionSchedule schedule in schedules) { outputFile.WriteLine(schedule.i); outputFile.WriteLine(schedule.Ei); foreach (GreenlightSchedule greenLightSchedule in schedule.GreenLightSchedules) { outputFile.WriteLine(greenLightSchedule.StreetName + " " + greenLightSchedule.Duration); } } } Console.WriteLine("Done..."); Console.WriteLine(Path.Combine(Directory.GetCurrentDirectory(), outputFileName)); }
public virtual IEnumerable<string> GetAvailableResources() { lock (stores) return stores.SelectMany(s => s.GetAvailableResources()).ExcludeSystemFileNames(); }
/// <summary> /// Query query /// </summary> /// <param name="query"></param> public SqlStatement CreateQuery <TModel>(IEnumerable <KeyValuePair <String, Object> > query, String tablePrefix, bool skipJoins, params ColumnMapping[] selector) { var tableType = m_mapper.MapModelType(typeof(TModel)); var tableMap = TableMapping.Get(tableType); List <TableMapping> scopedTables = new List <TableMapping>() { tableMap }; bool skipParentJoin = true; SqlStatement selectStatement = null; KeyValuePair <SqlStatement, List <TableMapping> > cacheHit; if (skipJoins) { selectStatement = new SqlStatement($" FROM {tableMap.TableName} AS {tablePrefix}{tableMap.TableName} "); } else { if (!s_joinCache.TryGetValue($"{tablePrefix}.{typeof(TModel).Name}", out cacheHit)) { selectStatement = new SqlStatement($" FROM {tableMap.TableName} AS {tablePrefix}{tableMap.TableName} "); Stack <TableMapping> fkStack = new Stack <TableMapping>(); fkStack.Push(tableMap); // Always join tables? do { var dt = fkStack.Pop(); foreach (var jt in dt.Columns.Where(o => o.IsAlwaysJoin)) { var fkTbl = TableMapping.Get(jt.ForeignKey.Table); var fkAtt = fkTbl.GetColumn(jt.ForeignKey.Column); selectStatement.Append($"INNER JOIN {fkAtt.Table.TableName} AS {tablePrefix}{fkAtt.Table.TableName} ON ({tablePrefix}{jt.Table.TableName}.{jt.Name} = {tablePrefix}{fkAtt.Table.TableName}.{fkAtt.Name}) "); if (!scopedTables.Contains(fkTbl)) { fkStack.Push(fkTbl); } scopedTables.Add(fkAtt.Table); } } while (fkStack.Count > 0); // Add the heavy work to the cache lock (s_joinCache) if (!s_joinCache.ContainsKey($"{tablePrefix}.{typeof(TModel).Name}")) { s_joinCache.Add($"{tablePrefix}.{typeof(TModel).Name}", new KeyValuePair <SqlStatement, List <TableMapping> >(selectStatement.Build(), scopedTables)); } } else { selectStatement = cacheHit.Key.Build(); scopedTables = cacheHit.Value; } } // Column definitions var columnSelector = selector; if (selector == null || selector.Length == 0) { columnSelector = scopedTables.SelectMany(o => o.Columns).ToArray(); } // columnSelector = scopedTables.SelectMany(o => o.Columns).ToArray(); List <String> flatNames = new List <string>(); var columnList = String.Join(",", columnSelector.Select(o => { var rootCol = tableMap.GetColumn(o.SourceProperty); skipParentJoin &= rootCol != null; if (!flatNames.Contains(o.Name)) { flatNames.Add(o.Name); return($"{tablePrefix}{o.Table.TableName}.{o.Name} AS {o.Name}"); } else if (skipParentJoin) { return($"{tablePrefix}{rootCol.Table.TableName}.{rootCol.Name}"); } else { return($"{tablePrefix}{o.Table.TableName}.{o.Name}"); } })); selectStatement = new SqlStatement($"SELECT {columnList} ").Append(selectStatement); // We want to process each query and build WHERE clauses - these where clauses are based off of the JSON / XML names // on the model, so we have to use those for the time being before translating to SQL List <KeyValuePair <String, Object> > workingParameters = new List <KeyValuePair <string, object> >(query); // Where clause SqlStatement whereClause = new SqlStatement(); List <SqlStatement> cteStatements = new List <SqlStatement>(); // Construct while (workingParameters.Count > 0) { var parm = workingParameters.First(); workingParameters.RemoveAt(0); // Match the regex and process var propertyPredicate = QueryPredicate.Parse(parm.Key); if (propertyPredicate == null) { throw new ArgumentOutOfRangeException(parm.Key); } // Next, we want to construct the var otherParms = workingParameters.Where(o => QueryPredicate.Parse(o.Key).ToString(QueryPredicatePart.PropertyAndCast) == propertyPredicate.ToString(QueryPredicatePart.PropertyAndCast)).ToArray(); // Remove the working parameters if the column is FK then all parameters if (otherParms.Any() || !String.IsNullOrEmpty(propertyPredicate.Guard) || !String.IsNullOrEmpty(propertyPredicate.SubPath)) { foreach (var o in otherParms) { workingParameters.Remove(o); } // We need to do a sub query IEnumerable <KeyValuePair <String, Object> > queryParms = new List <KeyValuePair <String, Object> >() { parm }.Union(otherParms); // Grab the appropriate builder var subProp = typeof(TModel).GetQueryProperty(propertyPredicate.Path, true); if (subProp == null) { throw new MissingMemberException(propertyPredicate.Path); } // Link to this table in the other? // Is this a collection? if (!this.m_hacks.Any(o => o.HackQuery(this, selectStatement, whereClause, typeof(TModel), subProp, tablePrefix, propertyPredicate, parm.Value, scopedTables))) { if (typeof(IList).GetTypeInfo().IsAssignableFrom(subProp.PropertyType.GetTypeInfo())) // Other table points at this on { var propertyType = subProp.PropertyType.StripGeneric(); // map and get ORM def'n var subTableType = m_mapper.MapModelType(propertyType); var subTableMap = TableMapping.Get(subTableType); var linkColumns = subTableMap.Columns.Where(o => scopedTables.Any(s => s.OrmType == o.ForeignKey?.Table)); var linkColumn = linkColumns.Count() > 1 ? linkColumns.FirstOrDefault(o => propertyPredicate.SubPath.StartsWith("source") ? o.SourceProperty.Name != "SourceUuid" : o.SourceProperty.Name == "SourceUuid") : linkColumns.FirstOrDefault(); // Link column is null, is there an assoc attrib? SqlStatement subQueryStatement = new SqlStatement(); var subTableColumn = linkColumn; string existsClause = String.Empty; if (linkColumn == null) { var tableWithJoin = scopedTables.Select(o => o.AssociationWith(subTableMap)).FirstOrDefault(); linkColumn = tableWithJoin.Columns.SingleOrDefault(o => scopedTables.Any(s => s.OrmType == o.ForeignKey?.Table)); var targetColumn = tableWithJoin.Columns.SingleOrDefault(o => o.ForeignKey?.Table == subTableMap.OrmType); subTableColumn = subTableMap.GetColumn(targetColumn.ForeignKey.Column); // The sub-query statement needs to be joined as well var lnkPfx = IncrementSubQueryAlias(tablePrefix); subQueryStatement.Append($"SELECT {lnkPfx}{tableWithJoin.TableName}.{linkColumn.Name} FROM {tableWithJoin.TableName} AS {lnkPfx}{tableWithJoin.TableName} WHERE "); existsClause = $"{lnkPfx}{tableWithJoin.TableName}.{targetColumn.Name}"; //throw new InvalidOperationException($"Cannot find foreign key reference to table {tableMap.TableName} in {subTableMap.TableName}"); } // Local Table var localTable = scopedTables.Where(o => o.GetColumn(linkColumn.ForeignKey.Column) != null).FirstOrDefault(); if (String.IsNullOrEmpty(existsClause)) { existsClause = $"{tablePrefix}{localTable.TableName}.{localTable.GetColumn(linkColumn.ForeignKey.Column).Name}"; } // Guards var guardConditions = queryParms.GroupBy(o => QueryPredicate.Parse(o.Key).Guard); int nGuards = 0; foreach (var guardClause in guardConditions) { var subQuery = guardClause.Select(o => new KeyValuePair <String, Object>(QueryPredicate.Parse(o.Key).ToString(QueryPredicatePart.SubPath), o.Value)).ToList(); // TODO: GUARD CONDITION HERE!!!! if (!String.IsNullOrEmpty(guardClause.Key)) { StringBuilder guardCondition = new StringBuilder(); var clsModel = propertyType; while (clsModel.GetTypeInfo().GetCustomAttribute <ClassifierAttribute>() != null) { var clsProperty = clsModel.GetRuntimeProperty(clsModel.GetTypeInfo().GetCustomAttribute <ClassifierAttribute>().ClassifierProperty); clsModel = clsProperty.PropertyType.StripGeneric(); var redirectProperty = clsProperty.GetCustomAttribute <SerializationReferenceAttribute>()?.RedirectProperty; if (redirectProperty != null) { clsProperty = clsProperty.DeclaringType.GetRuntimeProperty(redirectProperty); } guardCondition.Append(clsProperty.GetCustomAttributes <XmlElementAttribute>().First().ElementName); if (typeof(IdentifiedData).GetTypeInfo().IsAssignableFrom(clsModel.GetTypeInfo())) { guardCondition.Append("."); } } subQuery.Add(new KeyValuePair <string, object>(guardCondition.ToString(), guardClause.Key.Split('|'))); } // Generate method var prefix = IncrementSubQueryAlias(tablePrefix); var genMethod = typeof(QueryBuilder).GetGenericMethod("CreateQuery", new Type[] { propertyType }, new Type[] { subQuery.GetType(), typeof(String), typeof(bool), typeof(ColumnMapping[]) }); // Sub path is specified if (String.IsNullOrEmpty(propertyPredicate.SubPath) && "null".Equals(parm.Value)) { subQueryStatement.And($" {existsClause} NOT IN ("); } else { subQueryStatement.And($" {existsClause} IN ("); } nGuards++; existsClause = $"{prefix}{subTableColumn.Table.TableName}.{subTableColumn.Name}"; if (subQuery.Count(p => !p.Key.Contains(".")) == 0) { subQueryStatement.Append(genMethod.Invoke(this, new Object[] { subQuery, prefix, true, new ColumnMapping[] { subTableColumn } }) as SqlStatement); } else { subQueryStatement.Append(genMethod.Invoke(this, new Object[] { subQuery, prefix, false, new ColumnMapping[] { subTableColumn } }) as SqlStatement); } //// TODO: Check if limiting the the query is better //if (guardConditions.Last().Key != guardClause.Key) // subQueryStatement.Append(" INTERSECT "); } // Unwind guards while (nGuards-- > 0) { subQueryStatement.Append(")"); } if (subTableColumn != linkColumn) { whereClause.And($"{tablePrefix}{localTable.TableName}.{localTable.GetColumn(linkColumn.ForeignKey.Column).Name} IN (").Append(subQueryStatement).Append(")"); } else { whereClause.And(subQueryStatement); } } else // this table points at other { var subQuery = queryParms.Select(o => new KeyValuePair <String, Object>(QueryPredicate.Parse(o.Key).ToString(QueryPredicatePart.SubPath), o.Value)).ToList(); TableMapping tableMapping = null; var subPropKey = typeof(TModel).GetQueryProperty(propertyPredicate.Path); // Get column info PropertyInfo domainProperty = scopedTables.Select(o => { tableMapping = o; return(m_mapper.MapModelProperty(typeof(TModel), o.OrmType, subPropKey)); })?.FirstOrDefault(o => o != null); ColumnMapping linkColumn = null; // If the domain property is not set, we may have to infer the link if (domainProperty == null) { var subPropType = m_mapper.MapModelType(subProp.PropertyType); // We find the first column with a foreign key that points to the other !!! linkColumn = scopedTables.SelectMany(o => o.Columns).FirstOrDefault(o => o.ForeignKey?.Table == subPropType); } else { linkColumn = tableMapping.GetColumn(domainProperty); } var fkTableDef = TableMapping.Get(linkColumn.ForeignKey.Table); var fkColumnDef = fkTableDef.GetColumn(linkColumn.ForeignKey.Column); // Create the sub-query SqlStatement subQueryStatement = null; var subSkipJoins = subQuery.Count(o => !o.Key.Contains(".") && o.Key != "obsoletionTime") == 0; if (String.IsNullOrEmpty(propertyPredicate.CastAs)) { var genMethod = typeof(QueryBuilder).GetGenericMethod("CreateQuery", new Type[] { subProp.PropertyType }, new Type[] { subQuery.GetType(), typeof(string), typeof(bool), typeof(ColumnMapping[]) }); subQueryStatement = genMethod.Invoke(this, new Object[] { subQuery, null, subSkipJoins, new ColumnMapping[] { fkColumnDef } }) as SqlStatement; } else // we need to cast! { var castAsType = new OpenIZ.Core.Model.Serialization.ModelSerializationBinder().BindToType("OpenIZ.Core.Model", propertyPredicate.CastAs); var genMethod = typeof(QueryBuilder).GetGenericMethod("CreateQuery", new Type[] { castAsType }, new Type[] { subQuery.GetType(), typeof(String), typeof(bool), typeof(ColumnMapping[]) }); subQueryStatement = genMethod.Invoke(this, new Object[] { subQuery, null, false, new ColumnMapping[] { fkColumnDef } }) as SqlStatement; } cteStatements.Add(new SqlStatement($"{tablePrefix}cte{cteStatements.Count} AS (").Append(subQueryStatement).Append(")")); //subQueryStatement.And($"{tablePrefix}{tableMapping.TableName}.{linkColumn.Name} = {sqName}{fkTableDef.TableName}.{fkColumnDef.Name} "); //selectStatement.Append($"INNER JOIN {tablePrefix}cte{cteStatements.Count - 1} ON ({tablePrefix}{tableMapping.TableName}.{linkColumn.Name} = {tablePrefix}cte{cteStatements.Count - 1}.{fkColumnDef.Name})"); whereClause.And($"{tablePrefix}{tableMapping.TableName}.{linkColumn.Name} IN (SELECT {tablePrefix}cte{cteStatements.Count - 1}.{fkColumnDef.Name} FROM {tablePrefix}cte{cteStatements.Count - 1})"); } } } else if (!this.m_hacks.Any(o => o.HackQuery(this, selectStatement, whereClause, typeof(TModel), typeof(TModel).GetQueryProperty(propertyPredicate.Path), tablePrefix, propertyPredicate, parm.Value, scopedTables))) { whereClause.And(CreateWhereCondition(typeof(TModel), propertyPredicate.Path, parm.Value, tablePrefix, scopedTables)); } } // Return statement SqlStatement retVal = new SqlStatement(); if (cteStatements.Count > 0) { retVal.Append("WITH "); foreach (var c in cteStatements) { retVal.Append(c); if (c != cteStatements.Last()) { retVal.Append(","); } } } retVal.Append(selectStatement.Where(whereClause)); return(retVal); }
static void Main(string[] args) { // The requirement // We are having a Customer class and Order class, // A Customer may generate any number of orders // In the following Line we do have a List of customers who are having the list of orders he / she has created inside the Customer Class //public List<Order> AllOrdersList = new List<Order>(); // The question is if we want to see all the orders (only) for particular set of Customers // Select in LINQ will help you only to some extent // Let's see how it is // Let's generate sample data for 3 customers List <Customer> LstCustomer = new List <Customer>() { new Customer("Cust 1", "CUS1", "Active", new List <Order>() { new Order(100, DateTime.Now, "New"), new Order(101, DateTime.Now.AddDays(-2), "InProgress"), new Order(102, DateTime.Now, "New"), new Order(103, DateTime.Now.AddDays(-10), "Complete") }), new Customer("Cust 2", "CUS2", "Active", new List <Order>() { new Order(120, DateTime.Now, "New"), new Order(121, DateTime.Now.AddDays(-2), "InProgress"), new Order(122, DateTime.Now, "New"), new Order(123, DateTime.Now.AddDays(-10), "Complete") }), new Customer("Cust 3", "CUS3", "InActive", new List <Order>() { new Order(130, DateTime.Now, "OnHold"), new Order(131, DateTime.Now.AddDays(-2), "InProgress"), new Order(132, DateTime.Now, "OnHold"), new Order(133, DateTime.Now.AddDays(-10), "Complete") }) }; var selectResult = LstCustomer.Select(X => X.OrderList); // As a output you will get a lit of lists i.e List<List<Order>> // To dig deeper in this // We are implementing Select Many in this var selectManyResult = LstCustomer.SelectMany(X => X.OrderList); // The output is really awesome, as this is returning the list of Orders alone // Let's add more filters to this // Getting only the "New" orders var selectManyResul2 = LstCustomer .SelectMany(X => X.OrderList) .Where(X => X.OrderStatus == "New"); // Adding more filters // Getting the Active Customers and // Getting only the "New" orders from those var selectManyResult3 = LstCustomer .Where(X => X.CusotmerStatus == "Active") .SelectMany(X => X.OrderList) .Where(X => X.OrderStatus == "New"); }