public IList <string> GetModuleNames() { var ussp = GetUserSearchPathPackagesAsync(CancellationToken.None).WaitAndUnwrapExceptions(); var ssp = _factory.GetImportableModulesAsync(CancellationToken.None).WaitAndUnwrapExceptions(); var bmn = _builtinModuleNames; if (bmn == null && _builtinModule != null) { var builtinModules = (_builtinModule as IBuiltinPythonModule)?.GetAnyMember("__builtin_module_names__"); bmn = _builtinModuleNames = (builtinModules as AstPythonStringLiteral)?.Value?.Split(',') ?? Array.Empty <string>(); } IEnumerable <string> names = null; if (ussp != null) { names = ussp.Keys; } if (ssp != null) { names = names?.Union(ssp.Keys) ?? ssp.Keys; } if (bmn != null) { names = names?.Union(bmn) ?? bmn; } return(names.MaybeEnumerate().ToArray()); }
public async static Task SendMailAsync(string from, IEnumerable<string> mailto, string subject, string message, string attachFile = null) { using (var mail = new MailMessage {From = new MailAddress(from)}) using (var client = new SmtpClient { DeliveryFormat = SmtpDeliveryFormat.International }) { client.Host = ConfigurationManager.AppSettings.Get("smtp.host") ?? client.Host; client.Port = Convert.ToInt32(ConfigurationManager.AppSettings.Get("smtp.port") ?? client.Port.ToString()); client.Timeout = Convert.ToInt32(ConfigurationManager.AppSettings.Get("smtp.timeout") ?? client.Timeout.ToString()); var enableSsl = ConfigurationManager.AppSettings.Get("smtp.enableSSL"); if (enableSsl.IsNotEmpty()) client.EnableSsl = enableSsl.ToLower() == "true" || enableSsl == "1"; var smtpUser = ConfigurationManager.AppSettings.Get("smtp.userName"); var smtpPassword = ConfigurationManager.AppSettings.Get("smtp.password"); if (smtpUser != null && smtpPassword != null) client.Credentials = new NetworkCredential(smtpUser, smtpPassword); foreach (var email in mailto.Union(new[] { ConfigurationManager.AppSettings.Get("smtp.administrator") }).Where(x => x.IsNotEmpty())) { if (mail.To.Count == 0) mail.To.Add(new MailAddress(email)); mail.Bcc.Add(new MailAddress(email)); } mail.Subject = subject; mail.Body = message; mail.SubjectEncoding = Encoding.UTF8; mail.BodyEncoding = Encoding.UTF8; if (!string.IsNullOrEmpty(attachFile)) mail.Attachments.Add(new Attachment(attachFile)); await client.SendMailAsync(mail); } }
public bool HasRefactoring() { refactorings = Enumerable.Empty<IManualRefactoring>(); SyntaxTree treeBefore = SyntaxTree.ParseCompilationUnit(before); SyntaxTree treeAfter = SyntaxTree.ParseCompilationUnit(after); // Get the classes in the code before and after. var classesBefore = treeBefore.GetRoot().DescendantNodes().Where(n => n.Kind == SyntaxKind.ClassDeclaration); var classesAfter = treeAfter.GetRoot().DescendantNodes().Where(n => n.Kind == SyntaxKind.ClassDeclaration); // Get the pairs of class declaration in the code before and after var paris = GetClassDeclarationPairs(classesBefore, classesAfter); foreach (var pair in paris) { var detector = new InClassExtractMethodDetector((ClassDeclarationSyntax)pair.Key, (ClassDeclarationSyntax)pair.Value); detector.SetSyntaxTreeBefore(treeBefore); detector.SetSyntaxTreeAfter(treeAfter); if(detector.HasRefactoring()) { refactorings = refactorings.Union(detector.GetRefactorings()); return true; } } return false; }
public override void CompileDynamicLibrary(string outputFile, IEnumerable<string> sources, IEnumerable<string> includePaths, IEnumerable<string> libraries, IEnumerable<string> libraryPaths) { string[] array = sources.ToArray<string>(); string text = NativeCompiler.Aggregate(array.Select(new Func<string, string>(base.ObjectFileFor)), " ", " " + Environment.NewLine); string includePathsString = NativeCompiler.Aggregate(includePaths.Union(this.m_IncludePaths), "/I \"", "\" "); string text2 = NativeCompiler.Aggregate(libraries.Union(this.m_Libraries), " ", " "); string text3 = NativeCompiler.Aggregate(libraryPaths.Union(this.m_Settings.LibPaths), "/LIBPATH:\"", "\" "); this.GenerateEmptyPdbFile(outputFile); NativeCompiler.ParallelFor<string>(array, delegate(string file) { this.Compile(file, includePathsString); }); string contents = string.Format(" {0} {1} {2} /DEBUG /INCREMENTAL:NO /MACHINE:{4} /DLL /out:\"{3}\" /DEF:\"{5}\" ", new object[] { text, text2, text3, outputFile, this.m_Settings.MachineSpecification, this.m_DefFile }); string tempFileName = Path.GetTempFileName(); File.WriteAllText(tempFileName, contents); base.Execute(string.Format("@{0}", tempFileName), "C:\\Program Files (x86)\\Microsoft Visual Studio 10.0\\VC\\bin\\link.exe"); }
public override IEnumerable<ContentItem> AppendChildren(IEnumerable<ContentItem> previousChildren, Query query) { if(query.Interface != Interfaces.Managing) return previousChildren; return previousChildren.Union(nodes.GetChildren(query.Parent.Path)); }
private static int TryToComposeLine(IEnumerable<int>[] numbersArray, int level, IEnumerable<int> restrictedArrays, IEnumerable<int> restrictedNumbers, int mustStartWith) { if (level == 0) { for (int i = 0; i < numbersArray.Length; ++i ) { foreach (var number in numbersArray[i]) { var result = TryToComposeLine(numbersArray, 1, new[] { i }, new[] { number }, number % 100); if (result > 0) return result; } } } for (int i = 0; i < numbersArray.Length; ++i) { if (restrictedArrays.Contains(i)) continue; foreach (var number in numbersArray[i]) { if (restrictedNumbers.Contains(number) || number / 100 != mustStartWith) continue; var result = TryToComposeLine(numbersArray, level + 1, restrictedArrays.Union(new[] {i}), restrictedNumbers.Union(new[] {number}), number % 100); if (result > 0) return result; } } int count = 0; int[] ar = restrictedArrays.ToArray(); foreach (var restrictedNumber in restrictedNumbers) { Console.Write(ar[count] + ":" + restrictedNumber + "=>"); ++count; } if (level > 5) { // Check. var a = restrictedNumbers.ToArray(); if (a[0] / 100 != a[5] % 100) { Console.WriteLine("EPIC FAIL"); return -1; } Console.WriteLine(); return restrictedNumbers.Sum(); } Console.WriteLine("FAIL"); return -1; }
public AggregateValidationResult(IEnumerable<ValidationResult> validationResults, params IEnumerable<ValidationResult>[] additionalValidationResults) { _validationResults = validationResults .Union(additionalValidationResults .SelectMany(x => x)); FailedValidators = _validationResults.Where(x => !x.IsValid()); }
public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { Guard.AgainstNullArgument("references", references); Guard.AgainstNullArgument("scriptPackSession", scriptPackSession); references.PathReferences.UnionWith(scriptPackSession.References); SessionState<Evaluator> sessionState; if (!scriptPackSession.State.ContainsKey(SessionKey)) { Logger.Debug("Creating session"); var context = new CompilerContext(new CompilerSettings { AssemblyReferences = references.PathReferences.ToList() }, new ConsoleReportPrinter()); var evaluator = new Evaluator(context); var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct(); var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs); MonoHost.SetHost((ScriptHost)host); evaluator.ReferenceAssembly(typeof(MonoHost).Assembly); evaluator.InteractiveBaseClass = typeof(MonoHost); sessionState = new SessionState<Evaluator> { References = new AssemblyReferences(references.PathReferences, references.Assemblies), Namespaces = new HashSet<string>(), Session = evaluator }; ImportNamespaces(allNamespaces, sessionState); scriptPackSession.State[SessionKey] = sessionState; } else { Logger.Debug("Reusing existing session"); sessionState = (SessionState<Evaluator>)scriptPackSession.State[SessionKey]; var newReferences = sessionState.References == null ? references : references.Except(sessionState.References); foreach (var reference in newReferences.PathReferences) { Logger.DebugFormat("Adding reference to {0}", reference); sessionState.Session.LoadAssembly(reference); } sessionState.References = new AssemblyReferences(references.PathReferences, references.Assemblies); var newNamespaces = sessionState.Namespaces == null ? namespaces : namespaces.Except(sessionState.Namespaces); ImportNamespaces(newNamespaces, sessionState); } Logger.Debug("Starting execution"); var result = Execute(code, sessionState.Session); Logger.Debug("Finished execution"); return result; }
public override Control Reconcile(IEnumerable<PricingItem> mlpSource_, IEnumerable<PricingItem> dsSource_) { var allCodes = mlpSource_.Union(dsSource_).Select(x => x.SymmetryCode).Distinct(); var lines = new System.ComponentModel.BindingList<CloseItem>(); foreach (var symcode in allCodes) { var line = new CloseItem(); line.SymmetryCode = symcode; { var mlpitem = mlpSource_.Where(x => x.SymmetryCode.Equals(symcode)).FirstOrDefault(); if (mlpitem != null) line.MLPPrice = mlpitem.Value; } { var dsItem = dsSource_.Where(x => x.SymmetryCode.Equals(symcode)).FirstOrDefault(); if (dsItem != null) line.DSPrice = dsItem.Value; } lines.Add(line); } var grid = lines.DisplayInGrid(m_name,displayInShowForm_:false); grid.SetHeaderClickSort(); return grid; }
public ContextConfiguration() { //get all types that inheret from EntityTypeConfiguration or ComplexTypeConfiguration var maps = from t in Assembly.GetExecutingAssembly().GetTypes() where t.BaseType != null && t.BaseType.IsGenericType let baseDef = t.BaseType.GetGenericTypeDefinition() where baseDef == typeof(EntityTypeConfiguration<>) || baseDef == typeof(ComplexTypeConfiguration<>) select Activator.CreateInstance(t); configurations = maps; //get all types that inheret from EntityWithTypedId without entity itself dbsets = from t in Assembly.GetExecutingAssembly().GetTypes() where t.BaseType != null && t.BaseType.IsGenericType && !t.IsAbstract && t != typeof(Entity) let baseDef = t.BaseType.GetGenericTypeDefinition() where baseDef == typeof(EntityWithTypedId<>) select t; //+get all types that inheret from Entity dbsets = dbsets.Union( from t in Assembly.GetExecutingAssembly().GetTypes() where t.IsSubclassOf(typeof(Entity)) && !t.IsAbstract select t ); }
/// <summary> /// Set tags to the specified <paramref name="file"/>. /// </summary> /// <returns>The task to process it.</returns> /// <param name="file">File to tag.</param> /// <param name="tags">Tags to set.</param> /// <param name="clear">If set to <c>true</c> replace existing tags with ne <paramref name="tags"/>.</param> public Task TagAsync(FileInfo file, IEnumerable<string> tags, bool clear) { return Task.Factory.StartNew(() => { ImageFile imagefile = ImageFile.FromFile(file.FullName); string tagsValue; if (clear) { tagsValue = tags.Distinct(StringComparer.CurrentCultureIgnoreCase).Join(";"); } else { List<string> existingTags = new List<string>(); ExifProperty existingTagsValue; if (imagefile.Properties.TryGetValue(ExifTag.WindowsKeywords, out existingTagsValue)) existingTags = existingTagsValue.Value.ToString().Split(';').ToList(); tagsValue = tags.Union(existingTags).Distinct(StringComparer.CurrentCultureIgnoreCase).Join(";"); } imagefile.Properties.Set(ExifTag.WindowsKeywords, tagsValue); imagefile.Save(file.FullName); }); }
public VisualNetwork(GraphicsDevice graphicsDevice, IEnumerable<Neuron> sensoryNeurons, IEnumerable<Neuron> interNeurons, IEnumerable<Neuron> responsiveNeurons) { this.SensoryNeurons = sensoryNeurons; this.InterNeurons = interNeurons; this.ResponsiveNeurons = responsiveNeurons; this.Neurons = sensoryNeurons.Union(interNeurons).Union(responsiveNeurons).ToArray(); }
public bool TryGetScope(IEnumerable <TKey> toRead, IEnumerable <TKey> toWrite, TimeSpan timeout, out IDisposable scope) { //instead of using initial r/w keys, we find sub-graphs by them and use its keys to lock on var toWrite2 = _nodes.GetAllAscendants(toWrite).ToList(); var toRead2 = _nodes.GetAllDescendants(toRead?.Union(toWrite2) ?? toWrite2).ToList(); return(_dict.TryGetScope(toRead2, toWrite2, timeout, out scope)); }
public IEnumerable<Feat> GenerateWith(CharacterClass characterClass, Race race, Dictionary<string, Stat> stats, Dictionary<string, Skill> skills, BaseAttack baseAttack, IEnumerable<Feat> preselectedFeats) { var additionalFeats = GetAdditionalFeats(characterClass, race, stats, skills, baseAttack, preselectedFeats); var allButBonusFeats = preselectedFeats.Union(additionalFeats); var bonusFeats = GetBonusFeats(characterClass, race, stats, skills, baseAttack, allButBonusFeats); return additionalFeats.Union(bonusFeats); }
public RazorDocumentManager([ImportMany]params IRazorDocumentSource[] documentSources) { _documentSources = (documentSources ?? Enumerable.Empty<IRazorDocumentSource>()); // Always add the plain Razor Template file source at the end of the list _documentSources = _documentSources.Union(new [] { new RazorTemplateFileSource() }); Encoding = Encoding.UTF8; }
public void LoadConversation(User contact, IEnumerable<Message> conversation) { ChatSessionViewModel chatSession; if(_chatSessions.TryGetValue(contact.Name, out chatSession)) { var union = conversation.Union(chatSession.Conversation); chatSession.Conversation = new ObservableCollection<Message>(union); } }
public void UpdateSettings(ScreenAssistantSettings settings) { SHGetKnownFolderPath(FolderIdSavedGames, (uint)KnownFolderFlag.DEFAULT_PATH, IntPtr.Zero, out var pPath); string path = Marshal.PtrToStringUni(pPath); Marshal.FreeCoTaskMem(pPath); if (path == null) { return; } var gameSettingsFolderPath = Path.Combine(path, StudioName, GameFolderName); var localPath = Path.Combine(gameSettingsFolderPath, LocalFolderName); var profilePath = Path.Combine(gameSettingsFolderPath, ProfileFolderName); var settingsFilePath = Path.Combine(localPath, ConfigFileName); var videoConfigFilePath = Path.Combine(localPath, VideoConfigFileName); var profileConfigFilePath = Path.Combine(profilePath, ProfileConfigFileName); IEnumerable <string> settingsFromFiles = null; if (File.Exists(settingsFilePath)) { settingsFromFiles = File.ReadAllLines(settingsFilePath); } if (File.Exists(videoConfigFilePath)) { var videoSettings = File.ReadAllLines(videoConfigFilePath); var videoSettingsFiltered = videoSettings.Skip(2).Take(videoSettings.Length - 3); settingsFromFiles = settingsFromFiles?.Union(videoSettingsFiltered) ?? videoSettingsFiltered; } if (File.Exists(profileConfigFilePath)) { var profileSettings = File.ReadAllLines(profileConfigFilePath); settingsFromFiles = settingsFromFiles?.Union(profileSettings) ?? profileSettings; } var recognizedConfig = ReadConfig(settingsFromFiles); recognizedConfig.UpdateSettings(settings); }
protected override IEnumerable<Tuple<object, object>> GroupEqualObjects(IEnumerable<object> newArray, IEnumerable<object> oldArray) { return newArray.Union(oldArray).Distinct(_sameObjectComparer) .Select(elem => new { newItem = newArray.FirstOrDefault(x => _sameObjectComparer.Equals(x, elem)), oldItem = oldArray.FirstOrDefault(x => _sameObjectComparer.Equals(x, elem)) }) .Select(x => new Tuple<object, object>(x.newItem, x.oldItem)); }
public ScriptResult Execute(string code, string[] scriptArgs, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { Guard.AgainstNullArgument("scriptPackSession", scriptPackSession); Logger.Debug("Starting to create execution components"); Logger.Debug("Creating script host"); var distinctReferences = references.Union(scriptPackSession.References).Distinct().ToList(); SessionState<Session> sessionState; if (!scriptPackSession.State.ContainsKey(SessionKey)) { var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts), scriptArgs); Logger.Debug("Creating session"); var session = ScriptEngine.CreateSession(host); foreach (var reference in distinctReferences) { Logger.DebugFormat("Adding reference to {0}", reference); session.AddReference(reference); } foreach (var @namespace in namespaces.Union(scriptPackSession.Namespaces).Distinct()) { if (@namespace.Contains("ScriptCs.ReplCommand.Pack")) continue; Logger.DebugFormat("Importing namespace {0}", @namespace); session.ImportNamespace(@namespace); } sessionState = new SessionState<Session> { References = distinctReferences, Session = session }; scriptPackSession.State[SessionKey] = sessionState; } else { Logger.Debug("Reusing existing session"); sessionState = (SessionState<Session>)scriptPackSession.State[SessionKey]; var newReferences = sessionState.References == null || !sessionState.References.Any() ? distinctReferences : distinctReferences.Except(sessionState.References); if (newReferences.Any()) { foreach (var reference in newReferences) { Logger.DebugFormat("Adding reference to {0}", reference); sessionState.Session.AddReference(reference); } sessionState.References = newReferences; } } Logger.Debug("Starting execution"); var result = Execute(code, sessionState.Session); Logger.Debug("Finished execution"); return result; }
public IEnumerable<List<GameObject>> GetActionsWithNecessaryObjects(IEnumerable<GameObject> objects, Hero hero) { var allObjects = objects.Union(hero.GetContainerItems()).Distinct(); var stones = allObjects.Where(o => o is Rock).Take(2).ToList(); if (stones.Count == 2) { yield return stones; } }
public double GetJaccardSimilarity(IEnumerable<int> s1, IEnumerable<int> s2) { if (s1.Count() < ShingleSize || s2.Count() < ShingleSize) { return double.NaN; } int cap = s1.Intersect(s2).Count(); int cup = s1.Union(s2).Count(); return (double)cap / cup; }
public IEnumerable<List<GameObject>> GetActionsWithNecessaryObjects(IEnumerable<GameObject> objects, Hero hero) { var allObjects = objects.Union(hero.GetContainerItems()).Distinct(); var branch = allObjects.FirstOrDefault(ao => ao is Branch); var stone = allObjects.FirstOrDefault(ao => ao.Properties.Contains(Property.Cutter)); if (branch != null && stone != null) { yield return new List<GameObject> { branch, stone }; } }
public void Execute(string code, IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { var host = _scriptHostFactory.CreateScriptHost(new ScriptPackManager(scriptPackSession.Contexts)); var session = _scriptEngine.CreateSession(host); foreach (var reference in references.Union(scriptPackSession.References).Distinct()) session.AddReference(reference); foreach (var @namespace in namespaces.Union(scriptPackSession.Namespaces).Distinct()) session.ImportNamespace(@namespace); Execute(code, session); }
private SessionState<object> GetSession(IEnumerable<string> references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { var distinctReferences = references.Union(scriptPackSession.References).Distinct().Select(x => x.Replace(".dll", "")).ToList(); var distinctNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct().ToList(); var sessionState = new SessionState<object> { References = distinctReferences, Namespaces = distinctNamespaces }; scriptPackSession.State[SessionKey] = sessionState; return sessionState; }
public IEnumerable<List<GameObject>> GetActionsWithNecessaryObjects(IEnumerable<GameObject> objects, Hero hero) { var allObjects = objects.Union(hero.GetContainerItems()).Distinct(); var branches = allObjects.Where(ao => ao is Branch).Select(ao => ao).Take(2).ToList(); var plant = allObjects.FirstOrDefault(ao => ao is Plant); if (branches.Count == 2 && plant != null) { branches.Add(plant); yield return branches.ToList(); } }
public IList <string> GetModuleNames() { var ussp = GetUserSearchPathPackages(); var ssp = _factory.GetImportableModules(); var bmn = _builtinModuleNames; IEnumerable <string> names = null; if (ussp != null) { names = ussp.Keys; } if (ssp != null) { names = names?.Union(ssp.Keys) ?? ssp.Keys; } if (bmn != null) { names = names?.Union(bmn) ?? bmn; } return(names.MaybeEnumerate().ToArray()); }
///<summary> /// Initializes an instance of the ElementReferenceProperty. This is usually created by the <see cref="SectionViewModel"/>. ///</summary> ///<param name="serviceProvider">The service provide used within the Enterprise Library configuration system.</param> ///<param name="lookup">The element lookup registry.</param> ///<param name="parent">The <see cref="ElementViewModel"/> on which this property is attached.</param> ///<param name="declaringProperty">The descriptor declaring this property.</param> ///<param name="additionalAttributes">Additional attributes to apply to the reference proeprty.</param> ///<exception cref="ArgumentException">Thrown if the declaring property <see cref="PropertyDescriptor.PropertyType"/> is not a <see cref="string"/> type.</exception> public ElementReferenceProperty(IServiceProvider serviceProvider, ElementLookup lookup, ElementViewModel parent, PropertyDescriptor declaringProperty, IEnumerable<Attribute> additionalAttributes) : base(serviceProvider, parent, declaringProperty, additionalAttributes.Union(new Attribute[]{new ValidationAttribute(typeof(ElementReferenceValidator))})) { if (declaringProperty.PropertyType != typeof(string)) throw new ArgumentException(Resources.ReferencePropertyInvalidType); this.lookup = lookup; this.changeScopePropertyWatcher = new ChangeScopePropertyWatcher(); this.changeScopePropertyWatcher.ChangeScopePropertyChanged += new EventHandler(ChangeScopePropertyWatcherChangeScopePropertyChanged); referenceAttribute = base.Attributes.OfType<ReferenceAttribute>().FirstOrDefault(); Debug.Assert(referenceAttribute != null); ((INotifyCollectionChanged)ValidationResults).CollectionChanged += ValidationCollectionChanged; }
public override IEnumerable<ContentItem> AppendChildren(IEnumerable<ContentItem> previousChildren, Query query) { IEnumerable<ContentItem> items; if (!query.OnlyPages.HasValue) items = query.Parent.Children; else if (query.OnlyPages.Value) items = query.Parent.Children.FindPages(); else items = query.Parent.Children.FindParts(); if (query.Filter != null) items = items.Where(query.Filter); return previousChildren.Union(items); }
public override void CompileDynamicLibrary(string outFile, IEnumerable<string> sources, IEnumerable<string> includePaths, IEnumerable<string> libraries, IEnumerable<string> libraryPaths) { // ISSUE: object of a compiler-generated type is created // ISSUE: variable of a compiler-generated type GccCompiler.\u003CCompileDynamicLibrary\u003Ec__AnonStorey73 libraryCAnonStorey73 = new GccCompiler.\u003CCompileDynamicLibrary\u003Ec__AnonStorey73(); // ISSUE: reference to a compiler-generated field libraryCAnonStorey73.\u003C\u003Ef__this = this; string[] array = sources.ToArray<string>(); // ISSUE: reference to a compiler-generated field libraryCAnonStorey73.includeDirs = includePaths.Aggregate<string, string>(string.Empty, (Func<string, string, string>) ((current, sourceDir) => current + "-I" + sourceDir + " ")); string empty = string.Empty; string str = NativeCompiler.Aggregate(libraryPaths.Union<string>((IEnumerable<string>) this.m_Settings.LibPaths), "-L", " "); // ISSUE: reference to a compiler-generated method NativeCompiler.ParallelFor<string>(array, new System.Action<string>(libraryCAnonStorey73.\u003C\u003Em__FD)); this.ExecuteCommand(this.m_Settings.LinkerPath, string.Format("-shared {0} -o {1}", (object) this.m_Settings.MachineSpecification, (object) outFile), ((IEnumerable<string>) array).Where<string>(new Func<string, bool>(NativeCompiler.IsSourceFile)).Select<string, string>(new Func<string, string>(((NativeCompiler) this).ObjectFileFor)).Aggregate<string>((Func<string, string, string>) ((buff, s) => buff + " " + s)), str, empty); }
public static MockWorkItem Create(this MockWorkItemStore store, IEnumerable <KeyValuePair <string, object> > values = null) { var project = store.Projects[0]; var wit = project.WorkItemTypes[0]; var tp = new KeyValuePair <string, object>(CoreFieldRefNames.TeamProject, project.Name); var wp = new KeyValuePair <string, object>(CoreFieldRefNames.WorkItemType, wit.Name); var a = new[] { tp, wp }; values = values?.Union(a) ?? a; var wi = (MockWorkItem)wit.NewWorkItem(values); store.BatchSave(wi); return(wi); }
public ReferencesViewModel(IEnumerable<AssemblyReference> loadedReferences, IEnumerable<string> recentReferenceLocations) { Log.Info(() => string.Format("Loaded references: {0}", string.Join(", ", loadedReferences))); var standardReferences = new StandardReferencesLocator().GetStandardReferences().ToArray(); var recentReferences = (recentReferenceLocations ?? Enumerable.Empty<string>()).Where(File.Exists).Select(x => new AssemblyReference(x) { IsRecent = true }).ToArray(); var allReferences = loadedReferences.Union(standardReferences).Union(recentReferences).ToArray(); StandardReferences = new SearchableReferencesViewModel(standardReferences); StandardReferences.References.ItemPropertyChanged += StandardReferences_ListChanged; RecentReferences = new SearchableReferencesViewModel(recentReferences); RecentReferences.References.ItemPropertyChanged += RecentReferences_ListChanged; InstalledReferences = new SearchableReferencesViewModel(allReferences.Where(r => r.IsInstalled)); }
/// <summary> /// Start configuration of messages bus and scan for message handlers in the supplied assemblies. /// </summary> /// <param name="cfg"></param> /// <param name="assemblies"></param> /// <param name="messageHandlerConvention"></param> /// <returns></returns> public static MessageBusConfiguration MessageBus(this BaseConfiguration cfg, IEnumerable<Assembly> assemblies, IMessageHandlerConvention messageHandlerConvention = null) { if (cfg.ContainsKey(MessageBus_SettingsKey)) throw new InvalidOperationException("You should not configure MessageBus twice."); cfg.Set(MessageBus_SettingsKey, true); Condition.Requires(assemblies, "assemblies").IsNotNull(); // Also scan core message handlers assemblies = assemblies.Union(new Assembly[] { Assembly.GetExecutingAssembly() }); MessageDispatcher dispatcher = MessageBusConfigurationExtensions.GetDispatcher(cfg); dispatcher.RegisterMessageHandlers(assemblies, messageHandlerConvention ?? new DefaultMessageHandlerConvention()); return new MessageBusConfiguration(cfg); }
/// <summary> /// Returns all of the transmission elements attached to the DynamicTopologicalNode /// </summary> /// <param name="includeTransformers"></param> /// <returns></returns> public IEnumerable<Terminal> ConnectedBranches(bool includeTransformers) { if (connectedBranches == null) { connectedBranches = new HashSet<Terminal>(); foreach (ConnectivityNode node in this.nodes.ConnectivityNodes.Values) { //have to create a new variable in order to prevent IEnumerable<Terminal> terms = node.Where (x => x.ParentEquipment.EquipmentType == EquipmentTopoTypes.Conductor || x.ParentEquipment.Type == "TransformerEnd"); connectedBranches = connectedBranches.Union(terms); } } return connectedBranches; }
public override IEnumerable<TexturePackage> CreatePackages(IEnumerable<string> sourceRoots, IEnumerable<string> additionalPackages, IEnumerable<string> blacklist, IEnumerable<string> whitelist) { var blist = blacklist.Select(x => x.EndsWith(".wad") ? x.Substring(0, x.Length - 4) : x).Where(x => !String.IsNullOrWhiteSpace(x)).ToList(); var wlist = whitelist.Select(x => x.EndsWith(".wad") ? x.Substring(0, x.Length - 4) : x).Where(x => !String.IsNullOrWhiteSpace(x)).ToList(); var wads = sourceRoots.Union(additionalPackages) .Where(Directory.Exists) .SelectMany(x => Directory.GetFiles(x, "*.wad", SearchOption.TopDirectoryOnly)) .Union(additionalPackages.Where(x => x.EndsWith(".wad") && File.Exists(x))) .GroupBy(Path.GetFileNameWithoutExtension) .Select(x => x.First()) .Where(x => !blist.Any(b => String.Equals(Path.GetFileNameWithoutExtension(x) ?? x, b, StringComparison.InvariantCultureIgnoreCase))); if (wlist.Any()) { wads = wads.Where(x => wlist.Contains(Path.GetFileNameWithoutExtension(x) ?? x, StringComparer.InvariantCultureIgnoreCase)); } return wads.AsParallel().Select(CreatePackage).Where(x => x != null); }
public override void CompileDynamicLibrary(string outFile, IEnumerable<string> sources, IEnumerable<string> includePaths, IEnumerable<string> libraries, IEnumerable<string> libraryPaths) { string[] array = sources.ToArray<string>(); string includeDirs = includePaths.Aggregate(string.Empty, (string current, string sourceDir) => current + "-I" + sourceDir + " "); string empty = string.Empty; string text = NativeCompiler.Aggregate(libraryPaths.Union(this.m_Settings.LibPaths), "-L", " "); NativeCompiler.ParallelFor<string>(array, delegate(string file) { this.Compile(file, includeDirs); }); string arg_F7_1 = this.m_Settings.LinkerPath; string[] expr_8E = new string[4]; expr_8E[0] = string.Format("-shared {0} -o {1}", this.m_Settings.MachineSpecification, outFile); expr_8E[1] = array.Where(new Func<string, bool>(NativeCompiler.IsSourceFile)).Select(new Func<string, string>(base.ObjectFileFor)).Aggregate((string buff, string s) => buff + " " + s); expr_8E[2] = text; expr_8E[3] = empty; base.ExecuteCommand(arg_F7_1, expr_8E); }
//public static string GetMostRecentOpusCoverFile(this MusicStyles musicStyle, MusicOptions musicOptions, Work work, string opusPath = null) //{ // return musicStyle.GetMostRecentOpusCoverFile(musicOptions, work.Artist.Type, work.Artist.Name, opusPath ??= work.Name); //} public static string GetMostRecentOpusCoverFile(this Work work, MusicOptions musicOptions) { //var musicFiles = work.Tracks.SelectMany(t => t.MusicFiles) // .Where(mf => !mf.IsGenerated).AsEnumerable(); var folders = new List <string>(); foreach (var mf in work.Tracks.SelectMany(t => t.MusicFiles) .Where(mf => !mf.IsGenerated)) { var pathFragments = new List <string>(new string[] { mf.DiskRoot, mf.StylePath }); if (work.Type == OpusType.Collection) { pathFragments.Add("Collections"); } pathFragments.AddRange(mf.OpusPath.Split("\\")); //if(mf.IsMultiPart) //{ // pathFragments.Add(mf.PartName); //} folders.Add(Path.Combine(pathFragments.ToArray())); } IEnumerable <string> imageFiles = null; try { foreach (var pattern in musicOptions.CoverFilePatterns) { foreach (var path in folders) { imageFiles = imageFiles?.Union(Directory.EnumerateFiles(path, pattern, SearchOption.AllDirectories)) ?? Directory.EnumerateFiles(path, pattern, SearchOption.AllDirectories); } } return(imageFiles.OrderByDescending(x => new FileInfo(x).LastWriteTime).FirstOrDefault()); } catch (Exception xe) { log.Error(xe, $"called with [W-{work.Id}] {work.Name}, imagefiles: {imageFiles?.Count().ToString() ?? "null"}"); } return(null); }
public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable <string> namespaces, ScriptPackSession scriptPackSession) { if (scriptPackSession == null) { throw new ArgumentNullException("scriptPackSession"); } if (references == null) { throw new ArgumentNullException("references"); } _log.Debug("Starting to create execution components"); _log.Debug("Creating script host"); var executionReferences = new AssemblyReferences(references.Assemblies, references.Paths); executionReferences.Union(scriptPackSession.References); ScriptResult scriptResult; SessionState <ScriptState> sessionState; var isFirstExecution = !scriptPackSession.State.ContainsKey(SessionKey); if (isFirstExecution) { var host = _scriptHostFactory.CreateScriptHost( new ScriptPackManager(scriptPackSession.Contexts), scriptArgs); ScriptLibraryWrapper.SetHost(host); _log.Debug("Creating session"); var hostType = host.GetType(); ScriptOptions = ScriptOptions.AddReferences(hostType.Assembly); var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct(); foreach (var reference in executionReferences.Paths) { _log.DebugFormat("Adding reference to {0}", reference); ScriptOptions = ScriptOptions.AddReferences(reference); } foreach (var assembly in executionReferences.Assemblies) { _log.DebugFormat("Adding reference to {0}", assembly.FullName); ScriptOptions = ScriptOptions.AddReferences(assembly); } foreach (var @namespace in allNamespaces) { _log.DebugFormat("Importing namespace {0}", @namespace); ScriptOptions = ScriptOptions.AddNamespaces(@namespace); } sessionState = new SessionState <ScriptState> { References = executionReferences, Namespaces = new HashSet <string>(allNamespaces) }; scriptPackSession.State[SessionKey] = sessionState; scriptResult = Execute(code, host, sessionState); } else { _log.Debug("Reusing existing session"); sessionState = (SessionState <ScriptState>)scriptPackSession.State[SessionKey]; if (sessionState.References == null) { sessionState.References = new AssemblyReferences(); } if (sessionState.Namespaces == null) { sessionState.Namespaces = new HashSet <string>(); } var newReferences = executionReferences.Except(sessionState.References); foreach (var reference in newReferences.Paths) { _log.DebugFormat("Adding reference to {0}", reference); ScriptOptions = ScriptOptions.AddReferences(reference); sessionState.References = sessionState.References.Union(new[] { reference }); } foreach (var assembly in newReferences.Assemblies) { _log.DebugFormat("Adding reference to {0}", assembly.FullName); ScriptOptions = ScriptOptions.AddReferences(assembly); sessionState.References = sessionState.References.Union(new[] { assembly }); } var newNamespaces = namespaces.Except(sessionState.Namespaces); foreach (var @namespace in newNamespaces) { _log.DebugFormat("Importing namespace {0}", @namespace); ScriptOptions = ScriptOptions.AddNamespaces(@namespace); sessionState.Namespaces.Add(@namespace); } if (string.IsNullOrWhiteSpace(code)) { return(ScriptResult.Empty); } scriptResult = Execute(code, sessionState.Session, sessionState); } return(scriptResult); //todo handle namespace failures //https://github.com/dotnet/roslyn/issues/1012 }
private static string[] GetUsings(IEnumerable <string> usings) => usings.Union(new string[] { Xunit }).ToArray();
private Tuple <IAssociationSpecImmutable[], ImmutableDictionary <string, ITypeSpecBuilder> > FindAndCreateFieldSpecs(IObjectSpecImmutable spec, ImmutableDictionary <string, ITypeSpecBuilder> metamodel) { // now create fieldSpecs for value properties, for collections and for reference properties IList <PropertyInfo> collectionProperties = FacetFactorySet.FindCollectionProperties(properties, ClassStrategy).Where(pi => !FacetFactorySet.Filters(pi, ClassStrategy)).ToList(); var result1 = CreateCollectionSpecs(collectionProperties, spec, metamodel); IEnumerable <IAssociationSpecImmutable> collectionSpecs = result1.Item1; metamodel = result1.Item2; // every other accessor is assumed to be a reference property. IList <PropertyInfo> allProperties = FacetFactorySet.FindProperties(properties, ClassStrategy).Where(pi => !FacetFactorySet.Filters(pi, ClassStrategy)).ToList(); IEnumerable <PropertyInfo> refProperties = allProperties.Except(collectionProperties); var result = CreateRefPropertySpecs(refProperties, spec, metamodel); var refSpecs = result.Item1; metamodel = result.Item2; return(new Tuple <IAssociationSpecImmutable[], ImmutableDictionary <string, ITypeSpecBuilder> >(collectionSpecs.Union(refSpecs).ToArray(), metamodel)); }
public static bool IsWrapped(this String text, IEnumerable <String> openBrackets, IEnumerable <String> closeBrackets, out String openingBracket, out String closingBracket) { if (text.Length < 2) { openingBracket = null; closingBracket = null; return(false); } int stage = 1; openingBracket = null; closingBracket = null; HashSet <string> openSet = openBrackets.ToHashSet(); int depth = 0; SymbolFinder finder = new SymbolFinder(openBrackets.Union(closeBrackets)); string symb = ""; int text_lastIndex = text.Length - 1; char c; char?next; for (int i = 0; i < text.Length; i++) { c = text[i]; next = i == text_lastIndex ? null : (char?)text[i + 1]; symb = finder.Find(c, next); if (stage == 1) { if (openSet.Contains(symb)) { if (symb.Length - 1 != i) { return(false); } // what this block does: // - sets openingBracket and closingBracket to their apropriate values. // - increments stage to 2 // - increments depth // get index of openBracket and set openingBracket int index = 0; foreach (String bracket in openBrackets) { if (bracket == symb) { openingBracket = bracket; break; } index++; } // // set closing bracket try { closingBracket = closeBrackets.ElementAt(index); } catch (ArgumentOutOfRangeException e) { throw new BracketDisparityException(); } depth++; stage = 2; } } else { if (openingBracket == symb) { depth++; } if (closingBracket == symb) { depth--; } if (i == text_lastIndex) { return(depth == 0); } else if (depth == 0) { openingBracket = ""; closingBracket = ""; return(false); } } } openingBracket = ""; closingBracket = ""; return(false); }
/// <summary> /// Get active policies for the specified securable type /// </summary> public IEnumerable <IPolicyInstance> GetPolicies(object securable) { List <AdoSecurityPolicyInstance> result = null; if (result == null) { using (DataContext context = this.m_configuration.Provider.GetReadonlyConnection()) { try { context.Open(); // Security device if (securable is Core.Model.Security.SecurityDevice sd) { var query = context.CreateSqlStatement <DbSecurityDevicePolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityDevicePolicy)) .AutoJoin <DbSecurityPolicy, DbSecurityDevicePolicy>(); if (securable is DevicePrincipal dp) { query.AutoJoin <DbSecurityDevice, DbSecurityDevice>() .Where(o => o.PublicId == dp.Identity.Name); var retVal = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityDevicePolicy> >(query) .AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); var appClaim = dp.Identities.OfType <Server.Core.Security.ApplicationIdentity>().SingleOrDefault()?.FindAll(SanteDBClaimTypes.Sid).SingleOrDefault() ?? dp.FindAll(SanteDBClaimTypes.SanteDBApplicationIdentifierClaim).SingleOrDefault(); // There is an application claim so we want to add the application policies - most restrictive if (appClaim != null) { var claim = Guid.Parse(appClaim.Value); var aquery = context.CreateSqlStatement <DbSecurityApplicationPolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityApplicationPolicy)) .AutoJoin <DbSecurityPolicy, DbSecurityApplicationPolicy>() .Where(o => o.SourceKey == claim); retVal.AddRange(context.Query <CompositeResult <DbSecurityPolicy, DbSecurityApplicationPolicy> >(aquery).AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable))); } result = retVal; } else { result = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityDevicePolicy> >(query.Where(o => o.SourceKey == sd.Key)) .AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); } } else if (securable is Core.Model.Security.SecurityRole sr) { var query = context.CreateSqlStatement <DbSecurityRolePolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityRolePolicy)) .AutoJoin <DbSecurityPolicy, DbSecurityRolePolicy>() .Where(o => o.SourceKey == sr.Key); result = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityRolePolicy> >(query) .AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); } else if (securable is Core.Model.Security.SecurityApplication sa) { var query = context.CreateSqlStatement <DbSecurityApplicationPolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityApplicationPolicy)) .AutoJoin <DbSecurityPolicy, DbSecurityApplicationPolicy>(); if (securable is ApplicationPrincipal ap) { query.AutoJoin <DbSecurityApplication, DbSecurityApplication>() .Where(o => o.PublicId == ap.Identity.Name); } else { query.Where(o => o.SourceKey == sa.Key); } result = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityApplicationPolicy> >(query) .AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); } else if (securable is IPrincipal || securable is IIdentity) { var identity = (securable as IPrincipal)?.Identity ?? securable as IIdentity; IEnumerable <CompositeResult <DbSecurityPolicy, DbSecurityPolicyActionableInstance> > retVal = null; SqlStatement query = null; if (!(identity is Server.Core.Security.ApplicationIdentity) && !(identity is DeviceIdentity)) // Is this a user based claim? { // Role policies query = context.CreateSqlStatement <DbSecurityRolePolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityPolicyActionableInstance)) .InnerJoin <DbSecurityRolePolicy, DbSecurityPolicy>(o => o.PolicyKey, o => o.Key) .InnerJoin <DbSecurityRolePolicy, DbSecurityUserRole>(o => o.SourceKey, o => o.RoleKey) .InnerJoin <DbSecurityUserRole, DbSecurityUser>(o => o.UserKey, o => o.Key) .Where <DbSecurityUser>(o => o.UserName.ToLower() == identity.Name.ToLower()); retVal = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityPolicyActionableInstance> >(query).AsEnumerable(); } // Claims principal, then we want device and app SID if (securable is IClaimsPrincipal cp) { var appClaim = cp.Identities.OfType <Server.Core.Security.ApplicationIdentity>().SingleOrDefault()?.FindAll(SanteDBClaimTypes.Sid).SingleOrDefault() ?? cp.FindAll(SanteDBClaimTypes.SanteDBApplicationIdentifierClaim).SingleOrDefault(); var devClaim = cp.Identities.OfType <Server.Core.Security.DeviceIdentity>().SingleOrDefault()?.FindAll(SanteDBClaimTypes.Sid).SingleOrDefault() ?? cp.FindAll(SanteDBClaimTypes.SanteDBDeviceIdentifierClaim).SingleOrDefault(); IEnumerable <CompositeResult <DbSecurityPolicy, DbSecurityPolicyActionableInstance> > appDevClaim = null; // There is an application claim so we want to add the application policies - most restrictive if (appClaim != null) { var claim = Guid.Parse(appClaim.Value); query = context.CreateSqlStatement <DbSecurityApplicationPolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityPolicyActionableInstance)) .AutoJoin <DbSecurityPolicy, DbSecurityApplicationPolicy>() .Where(o => o.SourceKey == claim); if (retVal != null) { var usrPolKeys = retVal.AsEnumerable().Select(o => o.Object2.PolicyKey).ToArray(); // App grant only overrides those policies which already exist on user query.And <DbSecurityApplicationPolicy>(o => usrPolKeys.Contains(o.PolicyKey)); } var appResults = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityPolicyActionableInstance> >(query); appDevClaim = appDevClaim?.Union(appResults) ?? appResults; } // There is an device claim so we want to add the device policies - most restrictive if (devClaim != null) { var claim = Guid.Parse(devClaim.Value); query = context.CreateSqlStatement <DbSecurityDevicePolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityPolicyActionableInstance)) .AutoJoin <DbSecurityPolicy, DbSecurityDevicePolicy>() .Where(o => o.SourceKey == claim); if (retVal != null) { var usrPolKeys = retVal.Select(o => o.Object2.PolicyKey).ToArray(); // Dev grant only overrides those policies which already exist on user query.And <DbSecurityDevicePolicy>(o => usrPolKeys.Contains(o.PolicyKey)); } var devResults = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityPolicyActionableInstance> >(query); appDevClaim = appDevClaim?.Union(devResults) ?? devResults; } if (appDevClaim != null) { retVal = retVal?.Union(appDevClaim) ?? appDevClaim; } } result = retVal.AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); this.m_traceSource.TraceEvent(EventLevel.Verbose, "Principal {0} effective policy set {1}", identity?.Name, String.Join(",", result.Select(o => $"{o.Policy.Oid} [{o.Rule}]"))); } else if (securable is Core.Model.Acts.Act pAct) { var query = context.CreateSqlStatement <DbActSecurityPolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbActSecurityPolicy)) .AutoJoin <DbSecurityPolicy, DbActSecurityPolicy>() .Where(o => o.SourceKey == pAct.Key); result = context.Query <CompositeResult <DbSecurityPolicy, DbActSecurityPolicy> >(query) .AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); } else if (securable is Core.Model.Entities.Entity pEntity) { var query = context.CreateSqlStatement <DbEntitySecurityPolicy>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbEntitySecurityPolicy)) .AutoJoin <DbSecurityPolicy, DbEntitySecurityPolicy>() .Where(o => o.SourceKey == pEntity.Key); result = context.Query <CompositeResult <DbSecurityPolicy, DbEntitySecurityPolicy> >(query) .AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); } else if (securable is SecurityUser pUser) { // Join for policies var query = context.CreateSqlStatement <DbSecurityUserRole>().SelectFrom(typeof(DbSecurityPolicy), typeof(DbSecurityRolePolicy)) .InnerJoin <DbSecurityUserRole, DbSecurityRolePolicy>( o => o.RoleKey, o => o.SourceKey ) .InnerJoin <DbSecurityRolePolicy, DbSecurityPolicy>( o => o.PolicyKey, o => o.Key ) .Where <DbSecurityUserRole>(o => o.UserKey == pUser.Key); result = context.Query <CompositeResult <DbSecurityPolicy, DbSecurityRolePolicy> >(query) .AsEnumerable().Select(o => new AdoSecurityPolicyInstance(o.Object2, o.Object1, securable)).ToList(); } else { result = new List <AdoSecurityPolicyInstance>(); } } catch (Exception e) { this.m_traceSource.TraceEvent(EventLevel.Error, "Error getting active policies for {0} : {1}", securable, e); throw new Exception($"Error getting active policies for {securable}", e); } } } return(result); }
/// <summary> /// Produces the set union of two sequences by using a specified equality comparer. /// </summary> /// <typeparam name="TSource">The type of the elements of the input sequences.</typeparam> /// <param name="first">A sequence whose distinct elements form the first set for the union.</param> /// <param name="second">A sequence whose distinct elements form the second set for the union.</param> /// <param name="comparerFactory">The definition of a comparer to compare elements.</param> public static IEnumerable <TSource> Union <TSource>(this IEnumerable <TSource> first, IEnumerable <TSource> second, Func <EqualityComparerBuilder <TSource>, IEqualityComparer <TSource> > comparerFactory) { var comparer = comparerFactory(EqualityComparerBuilder.For <TSource>()); return(first.Union(second, comparer)); }
public static IEnumerable <T> Union <T>(this IEnumerable <T> target, T value) { return(target.Union(new [] { value })); }
private static IEnumerable <DateTime> UnionRowKeys(IEnumerable <DateTime> source1, IEnumerable <DateTime> source2) { return(source1?.Union(source2) ?? source2); }
private SarifLog CreatePartitionLog(T partitionValue) { SarifLog partitionLog; if (deepClone) { // Save time and space by not cloning the runs unless and until necessary. We will // only need to clone the runs that have results in this partition. IList <Run> originalRuns = originalLog.Runs; originalLog.Runs = null; partitionLog = originalLog.DeepClone(); originalLog.Runs = originalRuns; } else { partitionLog = new SarifLog(originalLog.SchemaUri, originalLog.Version, runs: null, originalLog.InlineExternalProperties, originalLog.Properties); } partitionLog.Runs = new List <Run>(); partitionLog.SetProperty(PartitionValuePropertyName, partitionValue); var artifactIndexRemappingDictionaries = new List <Dictionary <int, int> >(); for (int iOriginalRun = 0; iOriginalRun < partitionRunInfos.Count; ++iOriginalRun) { // Are there results for this run in this partition? if (partitionRunInfos[iOriginalRun].ResultDictionary.TryGetValue(partitionValue, out List <Result> results)) { // Yes, so we'll need a copy of the original run in which the results, and // certain run-level collections such as Run.Artifacts, have been replaced. Run originalRun = originalLog.Runs[iOriginalRun]; Run partitionRun; if (deepClone) { // Save time and space by only cloning the necessary results and associated // collection elements. We already cloned the relevant results in VisitResult. IList <Result> originalResults = originalRun.Results; IList <Artifact> originalArtifacts = originalRun.Artifacts; originalRun.Results = null; originalRun.Artifacts = null; partitionRun = originalRun.DeepClone(); originalRun.Results = originalResults; originalRun.Artifacts = originalArtifacts; } else { partitionRun = new Run(originalRun.Tool, originalRun.Invocations, originalRun.Conversion, originalRun.Language, originalRun.VersionControlProvenance, originalRun.OriginalUriBaseIds, artifacts: null, originalRun.LogicalLocations, originalRun.Graphs, results: null, originalRun.AutomationDetails, originalRun.RunAggregates, originalRun.BaselineGuid, originalRun.RedactionTokens, originalRun.DefaultEncoding, originalRun.DefaultSourceLanguage, originalRun.NewlineSequences, originalRun.ColumnKind, originalRun.ExternalPropertyFileReferences, originalRun.ThreadFlowLocations, originalRun.Taxonomies, originalRun.Addresses, originalRun.Translations, originalRun.Policies, originalRun.WebRequests, originalRun.WebResponses, originalRun.SpecialLocations, originalRun.Properties); } partitionRun.Results = results; // Construct a mapping from the indices in the original run to the indices // in the partition run. This includes both the indices relevant to the // results in this partition, and indices that appear in all partitions // because they are mentioned outside of any result (we refer to these as // "global" indices). IEnumerable <int> allPartitionArtifactIndices = partitionRunInfos[iOriginalRun].GlobalArtifactIndices; if (partitionRunInfos[iOriginalRun].ArtifactIndicesDictionary.TryGetValue(partitionValue, out HashSet <int> partitionResultArtifactIndices)) { allPartitionArtifactIndices = allPartitionArtifactIndices.Union(partitionResultArtifactIndices); } var partitionArtifactIndexRemappingDictionary = new Dictionary <int, int>(); artifactIndexRemappingDictionaries.Add(partitionArtifactIndexRemappingDictionary); List <int> allPartitionArtifactIndicesList = allPartitionArtifactIndices .OrderBy(index => index) .ToList(); int numPartitionIndices = 0; foreach (int originalIndex in allPartitionArtifactIndicesList) { partitionArtifactIndexRemappingDictionary.Add(originalIndex, numPartitionIndices++); } // Copy the artifacts corresponding to the complete set of indices. var artifacts = new List <Artifact>(); foreach (int originalIndex in allPartitionArtifactIndicesList) { Artifact originalArtifact = originalRun.Artifacts[originalIndex]; Artifact partitionArtifact = deepClone ? originalArtifact.DeepClone() : new Artifact(originalArtifact); artifacts.Add(partitionArtifact); } if (artifacts.Any()) { partitionRun.Artifacts = artifacts; } partitionLog.Runs.Add(partitionRun); } } // Traverse the entire log, fixing the index mappings for indices that appear // in the remapping dictionaries. var remappingVisitor = new PartitionedIndexRemappingVisitor(artifactIndexRemappingDictionaries); remappingVisitor.VisitSarifLog(partitionLog); return(partitionLog); }
private static List <T> Union <T>(IEnumerable <T> first, IEnumerable <T> second) { return(first.Union(second).ToList()); }
public override void onTick(Tick <int> currTickTemp) { DateTime latestDateTime = currTickTemp.DateTime; lock (ssList) { do { InitComment(); foreach (StrategyState currSS in ssList) { try { Tick <int> currSymbolTick; currSymbolTick = new Tick <int>(); currSymbolTick.Ask = Meta.MarketInfo(currSS.cparam.Symbol, MarketInfoType.MODE_ASK); currSymbolTick.Bid = Meta.MarketInfo(currSS.cparam.Symbol, MarketInfoType.MODE_BID); currSymbolTick.DateTime = Convertor.SecondsToDateTime(Meta.MarketInfo(currSS.cparam.Symbol, MarketInfoType.MODE_TIME)); currSymbolTick.volume = 1; if (latestDateTime < currSymbolTick.DateTime) { latestDateTime = currSymbolTick.DateTime; } //currSS.UpdateDaylight(currSymbolTick.DateTime); if (!TestingMode && Math.Abs((currSymbolTick.DateTime - latestDateTime).TotalMinutes) > 3) { AddComment(currSS.cparam.Symbol + ": time lag is too much."); continue; } int average = (currSymbolTick.Ask + currSymbolTick.Bid) / 2; if (!UpdateHappyPrice(currSymbolTick, currSS)) { continue; } int diffPips = average - currSS.happyPrice; AddComment(string.Format("Diff in Pips = {0} ", diffPips)); currSS.spreadAnalyzer.EvaluateSpread(currSymbolTick); AddComment(string.Format("Spread = {0} ", currSS.spreadAnalyzer.AverageSpread)); if (currSS.spreadAnalyzer.AverageSpread * 1.7f > currSS.cparam.OpenOrderShift) { AddComment("Spread Filter WARNING!\n"); continue; } bool isTimeOn = currSS.tradeTime.IsSystemON(currSymbolTick); bool closeTimeAll = currSS.closeAllTime.IsSystemON(currSymbolTick); AddComment(string.Format("Open season = {0}\n", isTimeOn)); IEnumerable <Order> ordersBuy = OrderOperation.GetBuyMarketOrders().Where(p => p.Symbol == currSS.cparam.Symbol && p.Comment.StartsWith(currSS.cparam.IdentityComment)); IEnumerable <Order> ordersSell = OrderOperation.GetSellMarketOrders().Where(p => p.Symbol == currSS.cparam.Symbol && p.Comment.StartsWith(currSS.cparam.IdentityComment)); if (ordersBuy.Any() || ordersSell.Any()) { if (!closeTimeAll) { foreach (Order currOrder in ordersBuy.Union(ordersSell).ToArray()) { OrderOperation.CloseOrder(currOrder); } } AddComment("Order has been opened\n"); if (this.TestingMode) { if (ordersBuy.Any() && average >= currSS.happyPrice) { foreach (Order currOrder in ordersBuy.ToArray()) { OrderOperation.CloseOrder(currOrder); } } if (ordersSell.Any() && average <= currSS.happyPrice) { foreach (Order currOrder in ordersSell.ToArray()) { OrderOperation.CloseOrder(currOrder); } } } else { if (ordersBuy.Any() && GetLatestHigh(currSS.cparam.Symbol) >= currSS.happyPrice) { foreach (Order currOrder in ordersBuy.ToArray()) { OrderOperation.CloseOrder(currOrder); } } if (ordersSell.Any() && GetLatestLow(currSS.cparam.Symbol) <= currSS.happyPrice) { foreach (Order currOrder in ordersSell.ToArray()) { OrderOperation.CloseOrder(currOrder); } } } continue; } if (!isTimeOn) { continue; } if (diffPips > currSS.cparam.OpenOrderShift) { int orderId = Meta.OrderSend(currSS.cparam.Symbol, OrderType.Market, OrderSide.Sell, GetVolume(currSS), currSymbolTick.Bid, 0, 0, currSS.cparam.NewUniqueComment()); if (orderId > 0) { Meta.OrderModify(orderId, currSymbolTick.Bid, 0, currSS.happyPrice, OrderType.Market); } } if (-diffPips > currSS.cparam.OpenOrderShift) { int orderId = Meta.OrderSend(currSS.cparam.Symbol, OrderType.Market, OrderSide.Buy, GetVolume(currSS), currSymbolTick.Ask, 0, 0, currSS.cparam.NewUniqueComment()); if (orderId > 0) { Meta.OrderModify(orderId, currSymbolTick.Bid, 0, currSS.happyPrice, OrderType.Market); } } } catch (HistoryNotAvailableExceptions exc) { logger.AddMessage("tick = {0}\r\n {1}\n", currTickTemp.DateTime.ToLongTimeString(), exc); throw; } catch (Exception exc) { AddComment(exc.ToString()); } } ShowComment(); }while (!TestingMode); } }
public static IEnumerable <T> UnionWith <T>(this IEnumerable <T> first, params T[] second) { return(first.Union(second)); }
public List <CariDetayYeni> CariDetayREski(int musteriID, int gun) { // cari detay için // service_faturas -onaylanmış servis kararları- cariye işlenmiş zaten // faturas'ta sadece turu fatura olanlar // sonra da müşteri ödeme ve tahsilat hareketleri DateTime tarih = DateTime.Now.AddDays(-gun); IEnumerable <CariDetayYeni> hesaplar = from s in db.servicehesaps where s.iptal == false && (s.MusteriID == musteriID || s.tamirci_id == musteriID) && s.Onay_tarih >= tarih && s.Yekun > 0 select new CariDetayYeni { //müşteri hesabı için servis toplamlarını kullanacağım //o yüzden burada hesaplara sıfır yazdım MusteriID = (int)s.MusteriID, aciklama = s.Aciklama, musteriAdi = s.customer.Ad, borc = s.tamirci_id == musteriID ? s.toplam_maliyet : null, //alacak = s.tamirci_id == musteriID ? 0 : s.Yekun, alacak = null, tarih = (DateTime)s.Onay_tarih, islem = s.IslemParca, konu = s.adet + " Adet" + s.cihaz_adi, kullanici = s.updated == null ? s.inserted : (s.inserted + "-" + s.updated) }; IEnumerable <CariDetayYeni> servis = from s in db.services where s.iptal == false && (s.CustID == musteriID || s.usta_id == musteriID) && s.AcilmaZamani >= tarih && s.KapanmaZamani != null && s.service_faturas.Yekun > 0 select new CariDetayYeni { //hakedişin prim oranlarına göre hesaplanması gerek //service faturasta triggerla yapılıyor MusteriID = (int)s.CustID, aciklama = s.Aciklama, musteriAdi = s.customer.Ad, borc = s.usta_id == musteriID ? (decimal)(s.service_faturas.toplam_fark) : 0, alacak = s.usta_id == musteriID ? 0 : s.service_faturas.Yekun, tarih = (DateTime)s.AcilmaZamani, islem = s.Baslik, konu = s.urun.Cinsi, kullanici = s.updated == null ? s.inserted : (s.inserted + "-" + s.updated) }; IEnumerable <CariDetayYeni> odeme_tahsilat = from o in db.musteriodemelers where o.iptal == false && o.Musteri_ID == musteriID && o.OdemeTarih >= tarih // orderby o.OdemeTarih descending select new CariDetayYeni { MusteriID = o.Musteri_ID, aciklama = o.Aciklama, musteriAdi = o.customer.Ad, borc = o.tahsilat_odeme == "tahsilat" ? o.OdemeMiktar : 0, alacak = o.tahsilat_odeme == "odeme" ? o.OdemeMiktar : 0, tarih = o.OdemeTarih, islem = o.tahsilat_turu, konu = o.tahsilat_turu == "iade" ? "Ürün iadesi" : (o.tahsilat_turu == "Nakit" ? "Kasa" : (o.pos_id == null ? (o.banka_id == null ? (o.kart_id == null ? "-" : o.kart_tanims.kart_adi) : o.banka.banka_adi) : o.pos_tanims.pos_adi)), kullanici = o.updated == null ? o.inserted : (o.inserted + "-" + o.updated) }; IEnumerable <CariDetayYeni> internet_fatura = (from o in db.faturas where o.iptal == false && o.MusteriID == musteriID && (o.tur == "Fatura" || o.tur == "Devir") && o.sattis_tarih >= tarih //orderby o.sattis_tarih descending select new CariDetayYeni { MusteriID = (int)o.MusteriID, aciklama = "Geçerlilik-" + o.son_odeme_tarihi.ToString(), musteriAdi = o.ad, borc = o.tutar, alacak = 0, tarih = (DateTime)o.sattis_tarih, islem = o.tur == "Fatura" ? "Kredi Yükleme" : "Devir", konu = o.tur == "Fatura" ? "İnternet Abonelik" : "Devreden Cari", kullanici = o.updated == null ? o.inserted : (o.inserted + "-" + o.updated) }); return(odeme_tahsilat.Union(servis).Union(internet_fatura).Union(hesaplar).OrderByDescending(x => x.tarih).ToList()); }
public static async Task <IEnumerable <T> > Union <T>(this IEnumerable <T> @this, Task <IEnumerable <T> > second) => @this.Union((await second).OrEmpty());
private Requires DisjointnessRequires(IEnumerable <Variable> paramVars, HashSet <Variable> frame) { return(new Requires(false, Expr.And(linearTypeChecker.DisjointnessExprForEachDomain(paramVars.Union(frame))))); }
private void Init(IEnumerable <IValueGenerator> generators) { _generators = generators?.Union(_defaultGenerators).ToList() ?? _defaultGenerators; }
public IEnumerable <string> ExpandViewLocations(ViewLocationExpanderContext context, IEnumerable <string> viewLocations) { return(_directoryLocations.Union(viewLocations)); }
public static Task <IEnumerable <T> > Union <T>(this IEnumerable <T> @this, IEnumerable <Task <T> > second) => @this.Union(second.AwaitAll());
public override CompletionSet GetCompletions(IGlyphService glyphService) { var start1 = _stopwatch.ElapsedMilliseconds; IEnumerable <CompletionResult> members = null; IEnumerable <CompletionResult> replMembers = null; var interactiveWindow = _snapshot.TextBuffer.GetInteractiveWindow(); var pyReplEval = interactiveWindow?.Evaluator as IPythonInteractiveIntellisense; var analysis = GetAnalysisEntry(); string text; SnapshotSpan statementRange; if (!GetPrecedingExpression(out text, out statementRange)) { return(null); } else if (string.IsNullOrEmpty(text)) { if (analysis != null) { lock (_analyzer) { var location = VsProjectAnalyzer.TranslateIndex( statementRange.Start.Position, statementRange.Snapshot, analysis ); var parameters = Enumerable.Empty <CompletionResult>(); var sigs = VsProjectAnalyzer.GetSignaturesAsync(_serviceProvider, View, _snapshot, Span).WaitOrDefault(1000); if (sigs != null && sigs.Signatures.Any()) { parameters = sigs.Signatures .SelectMany(s => s.Parameters) .Select(p => p.Name) .Distinct() .Select(n => new CompletionResult(n, PythonMemberType.Field)); } members = (analysis.Analyzer.GetAllAvailableMembersAsync(analysis, location, _options.MemberOptions).WaitOrDefault(1000) ?? new CompletionResult[0]) .Union(parameters, CompletionComparer.MemberEquality); } } if (pyReplEval == null) { var expansions = _serviceProvider.GetPythonToolsService().GetExpansionCompletions(100); if (expansions != null) { // Expansions should come first, so that they replace our keyword // completions with the more detailed snippets. if (members != null) { members = expansions.Union(members, CompletionComparer.MemberEquality); } else { members = expansions; } } } if (pyReplEval != null) { replMembers = pyReplEval.GetMemberNames(string.Empty); } } else { if (analysis != null && (pyReplEval == null || !pyReplEval.LiveCompletionsOnly)) { lock (_analyzer) { var location = VsProjectAnalyzer.TranslateIndex( statementRange.Start.Position, statementRange.Snapshot, analysis ); members = analysis.Analyzer.GetMembersAsync(analysis, text, location, _options.MemberOptions).WaitOrDefault(1000); } } if (pyReplEval != null && _analyzer.ShouldEvaluateForCompletion(text)) { Debug.Assert(pyReplEval.Analyzer == _analyzer); replMembers = pyReplEval.GetMemberNames(text); } } if (replMembers != null) { if (members != null) { members = members.Union(replMembers, CompletionComparer.MemberEquality); } else { members = replMembers; } } var end = _stopwatch.ElapsedMilliseconds; if (/*Logging &&*/ (end - start1) > TooMuchTime) { if (members != null) { var memberArray = members.ToArray(); members = memberArray; Trace.WriteLine(String.Format("{0} lookup time {1} for {2} members", this, end - start1, members.Count())); } else { Trace.WriteLine(String.Format("{0} lookup time {1} for zero members", this, end - start1)); } } if (members == null) { // The expression is invalid so we shouldn't provide // a completion set at all. return(null); } var start = _stopwatch.ElapsedMilliseconds; var result = new FuzzyCompletionSet( "Python", "Python", Span, members.Select(m => PythonCompletion(glyphService, m)), _options, CompletionComparer.UnderscoresLast, matchInsertionText: true ); end = _stopwatch.ElapsedMilliseconds; if (/*Logging &&*/ (end - start1) > TooMuchTime) { Trace.WriteLine(String.Format("{0} completion set time {1} total time {2}", this, end - start, end - start1)); } return(result); }
private async Task HandleResponseAsync(HttpState programState, DefaultCommandInput <ICoreParseResult> commandInput, IConsoleManager consoleManager, HttpResponseMessage response, bool echoRequest, string headersTargetFile, string bodyTargetFile, CancellationToken cancellationToken) { RequestConfig requestConfig = new RequestConfig(_preferences); ResponseConfig responseConfig = new ResponseConfig(_preferences); string protocolInfo; if (echoRequest) { string hostString = response.RequestMessage.RequestUri.Scheme + "://" + response.RequestMessage.RequestUri.Host + (!response.RequestMessage.RequestUri.IsDefaultPort ? ":" + response.RequestMessage.RequestUri.Port : ""); consoleManager.WriteLine($"Request to {hostString}...".SetColor(requestConfig.AddressColor)); consoleManager.WriteLine(); string method = response.RequestMessage.Method.ToString().ToUpperInvariant().SetColor(requestConfig.MethodColor); string pathAndQuery = response.RequestMessage.RequestUri.PathAndQuery.SetColor(requestConfig.AddressColor); protocolInfo = $"{"HTTP".SetColor(requestConfig.ProtocolNameColor)}{"/".SetColor(requestConfig.ProtocolSeparatorColor)}{response.Version.ToString().SetColor(requestConfig.ProtocolVersionColor)}"; consoleManager.WriteLine($"{method} {pathAndQuery} {protocolInfo}"); IEnumerable <KeyValuePair <string, IEnumerable <string> > > requestHeaders = response.RequestMessage.Headers; if (response.RequestMessage.Content != null) { requestHeaders = requestHeaders.Union(response.RequestMessage.Content.Headers); } foreach (KeyValuePair <string, IEnumerable <string> > header in requestHeaders.OrderBy(x => x.Key)) { string headerKey = header.Key.SetColor(requestConfig.HeaderKeyColor); string headerSep = ":".SetColor(requestConfig.HeaderSeparatorColor); string headerValue = string.Join(";".SetColor(requestConfig.HeaderValueSeparatorColor), header.Value.Select(x => x.Trim().SetColor(requestConfig.HeaderValueColor))); consoleManager.WriteLine($"{headerKey}{headerSep} {headerValue}"); } consoleManager.WriteLine(); List <string> responseOutput = new List <string>(); if (response.RequestMessage.Content != null) { await FormatBodyAsync(commandInput, programState, consoleManager, response.RequestMessage.Content, responseOutput, _preferences, cancellationToken).ConfigureAwait(false); } consoleManager.WriteLine(); consoleManager.WriteLine($"Response from {hostString}...".SetColor(requestConfig.AddressColor)); consoleManager.WriteLine(); foreach (string responseLine in responseOutput) { consoleManager.WriteLine(responseLine); } } protocolInfo = $"{"HTTP".SetColor(responseConfig.ProtocolNameColor)}{"/".SetColor(responseConfig.ProtocolSeparatorColor)}{response.Version.ToString().SetColor(responseConfig.ProtocolVersionColor)}"; string status = ((int)response.StatusCode).ToString().SetColor(responseConfig.StatusCodeColor) + " " + response.ReasonPhrase.SetColor(responseConfig.StatusReasonPhraseColor); consoleManager.WriteLine($"{protocolInfo} {status}"); IEnumerable <KeyValuePair <string, IEnumerable <string> > > responseHeaders = response.Headers; if (response.Content != null) { responseHeaders = responseHeaders.Union(response.Content.Headers); } List <string> headerFileOutput = null; List <string> bodyFileOutput = null; if (headersTargetFile != null) { headerFileOutput = new List <string>(); } foreach (KeyValuePair <string, IEnumerable <string> > header in responseHeaders.OrderBy(x => x.Key)) { string headerKey = header.Key.SetColor(responseConfig.HeaderKeyColor); string headerSep = ":".SetColor(responseConfig.HeaderSeparatorColor); string headerValue = string.Join(";".SetColor(responseConfig.HeaderValueSeparatorColor), header.Value.Select(x => x.Trim().SetColor(responseConfig.HeaderValueColor))); consoleManager.WriteLine($"{headerKey}{headerSep} {headerValue}"); headerFileOutput?.Add($"{header.Key}: {string.Join(";", header.Value.Select(x => x.Trim()))}"); } if (bodyTargetFile != null) { bodyFileOutput = new List <string>(); } consoleManager.WriteLine(); if (response.Content != null) { await FormatBodyAsync(commandInput, programState, consoleManager, response.Content, bodyFileOutput, _preferences, cancellationToken).ConfigureAwait(false); } if (headersTargetFile != null && !string.Equals(headersTargetFile, bodyTargetFile, StringComparison.Ordinal)) { headerFileOutput.Add(""); IEnumerable <string> allOutput = headerFileOutput.Concat(bodyFileOutput); _fileSystem.WriteAllLinesToFile(headersTargetFile, allOutput); } else { if (headersTargetFile != null && headerFileOutput != null) { _fileSystem.WriteAllLinesToFile(headersTargetFile, headerFileOutput); } if (bodyTargetFile != null && bodyFileOutput != null) { _fileSystem.WriteAllLinesToFile(bodyTargetFile, bodyFileOutput); } } consoleManager.WriteLine(); }
private IEnumerable <dynamic> CalcDay(IEnumerable <dynamic> hours, int contractHour, DateTime day) { List <dynamic> result = new List <dynamic>(); DateTime start = day.Date.AddHours(contractHour); DateTime end = day.Date.AddDays(1).AddHours(contractHour - 1); hours = hours.Where(h => h.date >= start && h.date <= end); var count = hours.Where(h => h.s1.StartsWith(Glossary.Qn)).Count(); if (count == 0) { log(string.Format("суточная запись {0:dd.MM.yy} по часовым архивам {1:dd.MM.yy HH:mm} — {2:dd.MM.yy HH:mm} НЕ расчитана", day, start, end)); return(result); } if (count < 24) { log(string.Format("недостаточное количество часовых архивов ({0} из 24) за сутки {1:dd.MM.yy}. Попытка использовать архивы локальной БД", count, day)); var dates = hours.Select(h => (DateTime)h.date).ToArray(); var localHour = getRange("Hour", start, end).Where(h => !dates.Contains((DateTime)h.date)); log(string.Format("из локальной БД прочитано {0} часовых архивов за сутки {1:dd.MM.yy}", localHour.Where(h => h.s1.StartsWith(Glossary.Qn)).Count(), day)); hours = hours.Union(localHour); } if (count > 24) { log(string.Format("количество часовых архивов {0} из 24 за сутки {1:dd.MM.yy}", count, day)); } if (count == 24) { log(string.Format("количество часовых архивов {0} из 24 за сутки {1:dd.MM.yy}", count, day)); } foreach (var x in hours.GroupBy(g => g.s1)) { if (x.Key.StartsWith(Glossary.Qn) || x.Key.StartsWith(Glossary.Qw)) { result.Add(MakeDayRecord(x.Key, x.GroupBy(y => y.date).Select(y => y.Max(z => (double)z.d1)).Sum(y => y), x.First().s2, day)); continue; } if (x.Key.StartsWith(Glossary.Vn) || x.Key.StartsWith(Glossary.Vw) || x.Key.StartsWith(Glossary.Twork)) { result.Add(MakeDayRecord(x.Key, x.Select(y => (double)y.d1).Max(y => y), x.First().s2, day)); continue; } if (x.Key.StartsWith(Glossary.T) || x.Key.StartsWith(Glossary.P)) { result.Add(MakeDayRecord(x.Key, x.GroupBy(y => y.date).Select(y => y.Max(z => (double)z.d1)).Average(y => y), x.First().s2, day)); continue; } } log(string.Format("рассчитана суточная запись {0:dd.MM.yy} по часовым архивам {1:dd.MM.yy HH:mm} — {2:dd.MM.yy HH:mm}", day, start, end)); return(result); }
protected override IEnumerable <Entity> Combine(IEnumerable <Entity> entities) { return(entities.Union()); }
public List <CariDetayx> CariDetayR(int musteriID, int gun) { // cari detay için // service_faturas -onaylanmış servis kararları- cariye işlenmiş zaten // faturas'ta sadece turu fatura olanlar // sonra da müşteri ödeme ve tahsilat hareketleri //tamircinin ve ustanın hesaplarını da ekliyoruz DateTime tarih = DateTime.Now.AddDays(-gun); IEnumerable <CariDetayx> odeme_tahsilat = (from o in db.musteriodemelers where o.iptal == false && o.Musteri_ID == musteriID && o.OdemeTarih >= tarih // orderby o.OdemeTarih descending select new CariDetayx { MusteriID = o.Musteri_ID, aciklama = o.Aciklama, musteriAdi = o.customer.Ad, tutar = o.OdemeMiktar, maliyet = null, tarih = o.OdemeTarih, islem = o.tahsilat_odeme == "tahsilat" ? (o.tahsilat_turu == "iade" ? "Cihaz İadesi" : (o.tahsilat_turu == "borc" ? "Borç Alındı" : o.tahsilat_odeme)) : (o.tahsilat_turu == "iade" ? "Cihaz İadesi" : (o.tahsilat_turu == "borc" ? "Borç Verildi" : o.tahsilat_odeme)), islem_turu = o.tahsilat_turu, islem_adres = o.pos_id == null ? (o.banka_id == null ? (o.kart_id == null ? "-" : o.kart_tanims.kart_adi) : o.banka.banka_adi) : o.pos_tanims.pos_adi, cesit = o.tahsilat_turu == "iade" ? "iade" : o.tahsilat_odeme, masraf_tipi = o.masraf_id == null ? "Standart" : o.masraf_tipi, islem_tarihi = o.islem_tarihi }); IEnumerable <CariDetayx> internet_fatura = (from o in db.faturas where o.iptal == false && o.MusteriID == musteriID && (o.tur == "Fatura" || o.tur == "Devir") && o.sattis_tarih >= tarih //orderby o.sattis_tarih descending select new CariDetayx { MusteriID = (int)o.MusteriID, aciklama = "Geçerlilik-" + o.bakiye, musteriAdi = o.ad, tutar = o.tutar, maliyet = null, tarih = (DateTime)o.sattis_tarih, islem = o.tur == "Fatura" ? "Kredi Yükleme" : "Devir", islem_turu = o.tur == "Fatura" ? "İnternet Abonelik" : "Devreden Cari", islem_adres = "", cesit = "fatura", masraf_tipi = "internet fatura", islem_tarihi = o.islem_tarihi }); IEnumerable <CariDetayx> servis = from s in db.services where s.iptal == false && (s.CustID == musteriID || s.usta_id == musteriID) && s.AcilmaZamani >= tarih && s.service_faturas.Yekun > 0 select new CariDetayx { MusteriID = (int)s.CustID, aciklama = s.Baslik, musteriAdi = s.customer.Ad, tutar = s.service_faturas.Yekun, maliyet = s.service_faturas.toplam_maliyet, tarih = s.AcilmaZamani, islem = String.IsNullOrEmpty(s.service_faturas.service_tur) ? "Servis" : "Servis-Cihaz", islem_turu = s.service_tips.tip_ad, islem_adres = s.usta_id == null ? "Servis Toplamı" : " Servis Toplamı Usta", cesit = "servis", masraf_tipi = "cihaz-servis", islem_tarihi = s.AcilmaZamani }; IEnumerable <CariDetayx> hesaplar = from s in db.servicehesaps where s.iptal == false && (s.MusteriID == musteriID || s.tamirci_id == musteriID) && s.Onay_tarih >= tarih && s.Yekun > 0 select new CariDetayx { MusteriID = (int)s.MusteriID, aciklama = s.Aciklama, musteriAdi = s.customer.Ad, tutar = s.Yekun, maliyet = s.toplam_maliyet, tarih = (DateTime)s.Onay_tarih, islem = s.IslemParca, islem_turu = s.cihaz_adi, islem_adres = s.tamirci_id == null?s.adet.ToString() + "Adet" : "Dış servis", cesit = "karar", masraf_tipi = "servis kararı", islem_tarihi = s.Onay_tarih }; return(odeme_tahsilat.Union(servis).Union(internet_fatura).Union(hesaplar).OrderByDescending(x => x.tarih).ToList()); }
/// <summary>Produces the set union of the first sequence and the specified items by using the default equality comparer. /// /// This method is an overload for Union that uses the params argument to provide /// a better syntax when used with a known set of items. /// </summary> public static IEnumerable <T> Union <T>(this IEnumerable <T> first, params T[] secondItems) { return(first.Union((IEnumerable <T>)secondItems)); }