public HashSet<CartItem> Get(CartItemBasedDiscountApplication application, CartModel cart) { var cartItems = new HashSet<CartItem>(); cartItems.AddRange(_getCartItemsBySKUList.GetCartItems(cart, application.SKUs)); cartItems.AddRange(_getCartItemsByCategoryIdList.GetCartItems(cart, application.CategoryIds)); return cartItems; }
private RenameLocationSet(ISymbol symbol, Solution solution, OptionSet optionSet, SearchResult originalSymbolResult, List<SearchResult> overloadsResult, IEnumerable<RenameLocation> stringsResult, IEnumerable<RenameLocation> commentsResult) { _symbol = symbol; _solution = solution; _optionSet = optionSet; _originalSymbolResult = originalSymbolResult; _overloadsResult = overloadsResult; _stringsResult = stringsResult; _commentsResult = commentsResult; var mergedLocations = new HashSet<RenameLocation>(); var mergedReferencedSymbols = new List<ISymbol>(); var mergedImplicitLocations = new List<ReferenceLocation>(); if (optionSet.GetOption(RenameOptions.RenameInStrings)) { mergedLocations.AddRange(stringsResult); } if (optionSet.GetOption(RenameOptions.RenameInComments)) { mergedLocations.AddRange(commentsResult); } var overloadsToMerge = (optionSet.GetOption(RenameOptions.RenameOverloads) ? overloadsResult : null) ?? SpecializedCollections.EmptyEnumerable<SearchResult>(); foreach (var result in overloadsToMerge.Concat(originalSymbolResult)) { mergedLocations.AddRange(result.Locations); mergedImplicitLocations.AddRange(result.ImplicitLocations); mergedReferencedSymbols.AddRange(result.ReferencedSymbols); } _mergedResult = new SearchResult(mergedLocations, mergedImplicitLocations, mergedReferencedSymbols); }
protected override void ProcessAssembly(AssemblyDefinition assemblyDef) { if (_frameworkProfile == null) { _frameworkProfile = assemblyDef.GuessAssemblyProfile(); } if (_frameworkProfile != null) { _assemblyResolver.AddSearchDirectory(_frameworkProfile.ReferencesDirectory); } var typesDependenciesCollector = new CollectTypesDependenciesProcessor(_frameworkProfile); typesDependenciesCollector.Process(assemblyDef); var goodAssemblyNames = assemblyDef.Modules.SelectMany(asmDef => asmDef.AssemblyReferences); if(_removeNonRetargetable) { goodAssemblyNames = goodAssemblyNames.Where(asmRef => asmRef.IsRetargetable); } if (_frameworkProfile != null) { goodAssemblyNames = goodAssemblyNames.Concat(_frameworkProfile.GetFrameworkAssemblies()); } var goodModules = new HashSet<ModuleDefinition>(CecilEqualityComparer.Default); goodModules.AddRange(assemblyDef.Modules); goodModules.AddRange(goodAssemblyNames.Select(_assemblyResolver.TryResolve).Where(asmDef => asmDef != null).SelectMany(asmDef => asmDef.Modules)); var allTypesDependencies = typesDependenciesCollector.AllTypesDependencies; var typeDependenciesToRemove = new Queue<TypeReferenceAndDependencies>(allTypesDependencies.Where( kv => { var typeRef = kv.Key; var typeDef = typeRef.TryResolve(); return typeDef == null || !goodModules.Contains(typeDef.Module); }).Select(kv => (TypeReferenceAndDependencies)kv)); var removedDependencies = new HashSet<TypeDependency>(); while (typeDependenciesToRemove.Any()) { var typeDependencies = typeDependenciesToRemove.Dequeue(); var typeRef = typeDependencies.Type; var dependencies = typeDependencies.DependingMembers; Trace.WriteLine(string.Format("Removing dependencies on type {0}:", typeRef), "RemoveExternalTypesUsage"); Trace.Indent(); foreach (var dependency in dependencies) { if (!removedDependencies.Contains(dependency)) { dependency.Break(); removedDependencies.Add(dependency); var baseClassDependency = dependency as BaseClassDependency; if (baseClassDependency != null) { var removedClass = baseClassDependency.DerivedClass; if (allTypesDependencies.ContainsKey(removedClass)) { var removedClassDependencies = allTypesDependencies[removedClass]; typeDependenciesToRemove.Enqueue(new TypeReferenceAndDependencies(removedClass, removedClassDependencies)); } } } } Trace.Unindent(); } base.ProcessAssembly(assemblyDef); }
private static IEnumerable<string> Edits(string word) { var set = new HashSet<string>(); var splits = Splits(set, word); set.AddRange(Deletes(splits)); set.AddRange(Transposes(splits)); set.AddRange(Replaces(splits)); set.AddRange(Inserts(splits)); return set; }
public void Grant(params string[] permissions) { if (permissions == null || permissions.Length == 0) throw new ArgumentNullException(nameof(permissions)); var grantingStack = GetGrantingStack(true); if (grantingStack.Count > 0) { var oldSet = grantingStack.Peek(); if (oldSet == null) { grantingStack.Push(null); } else { var newSet = new HashSet<string>(oldSet); newSet.AddRange(permissions); grantingStack.Push(newSet); } } else { grantingStack.Push(new HashSet<string>(permissions)); } }
public void UpdateLayout() { HashSet<UIElement> arrangedElements = new HashSet<UIElement>(); while (measureQueue.Count > 0 || arrangeQueue.Count > 0) { while (measureQueue.Count > 0) { UIElement element = GetTopElement(measureQueue); element.Measure(element.VisualParent == null || element.PreviousAvailableSize.IsEmpty ? Size.Infinity : element.PreviousAvailableSize); } arrangedElements.AddRange(arrangeQueue.SelectMany(element => GetElementPath(element))); while (arrangeQueue.Count > 0) { UIElement element = GetTopElement(arrangeQueue); element.Arrange(element.VisualParent == null || element.PreviousFinalRect.IsEmpty ? new Rect(element.DesiredSize) : element.PreviousFinalRect); } while (arrangedElements.Count > 0 && measureQueue.Count == 0 && arrangeQueue.Count == 0) // LayoutUpdated can invalidate other elements { UIElement element = arrangedElements.First(); arrangedElements.Remove(element); element.RaiseLayoutUpdated(); } } }
/// <summary> /// Gets the application assemblies. /// </summary> /// <param name="assemblyFilter">(Optional) A filter for the assemblies.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A promise of an enumeration of application assemblies. /// </returns> public virtual async Task<IEnumerable<Assembly>> GetAppAssembliesAsync(Func<AssemblyName, bool> assemblyFilter = null, CancellationToken cancellationToken = default(CancellationToken)) { // TODO The assemblies from the current domain do not consider the not loaded // but required referenced assemblies. Therefore load all the references recursively. // This could be optimized somehow. var assemblies = this.GetLoadedAssemblies(); assemblyFilter = assemblyFilter ?? this.AssemblyFilter; var loadedAssemblyRefs = new HashSet<string>(assemblies.Select(a => a.GetName().FullName)); var assembliesToCheck = assemblies.Where(a => assemblyFilter(a.GetName())).ToList(); while (assembliesToCheck.Count > 0) { var assemblyRefsToLoad = new HashSet<AssemblyName>(); foreach (var assembly in assembliesToCheck) { var referencesToLoad = this.GetReferencedAssemblies(assembly).Where(a => !loadedAssemblyRefs.Contains(a.FullName) && assemblyFilter(a)); assemblyRefsToLoad.AddRange(referencesToLoad); } loadedAssemblyRefs.AddRange(assemblyRefsToLoad.Select(an => an.FullName)); assembliesToCheck = assemblyRefsToLoad.Select(this.AssemblyLoader.LoadAssembly).ToList(); assemblies.AddRange(assembliesToCheck); } await this.AddAdditionalAssembliesAsync(assemblies, assemblyFilter, cancellationToken).PreserveThreadContext(); return assemblies; }
public async Task<Document> AddImportsAsync(Document document, IEnumerable<TextSpan> spans, OptionSet options, CancellationToken cancellationToken) { options = options ?? document.Project.Solution.Workspace.Options; var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var root = await model.SyntaxTree.GetRootAsync(cancellationToken).ConfigureAwait(false); // Create a simple interval tree for simplification spans. var spansTree = new SimpleIntervalTree<TextSpan>(TextSpanIntervalIntrospector.Instance, spans); Func<SyntaxNodeOrToken, bool> isInSpan = (nodeOrToken) => spansTree.GetOverlappingIntervals(nodeOrToken.FullSpan.Start, nodeOrToken.FullSpan.Length).Any(); var nodesWithExplicitNamespaces = root.DescendantNodesAndSelf().Where(n => isInSpan(n) && GetExplicitNamespaceSymbol(n, model) != null).ToList(); var namespacesToAdd = new HashSet<INamespaceSymbol>(); namespacesToAdd.AddRange(nodesWithExplicitNamespaces.Select(n => GetExplicitNamespaceSymbol(n, model))); // annotate these nodes so they get simplified later var newRoot = root.ReplaceNodes(nodesWithExplicitNamespaces, (o, r) => r.WithAdditionalAnnotations(Simplifier.Annotation)); var newDoc = document.WithSyntaxRoot(newRoot); var newModel = await newDoc.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); newRoot = await this.AddNamespaceImportsAsync(newDoc, newModel, options, namespacesToAdd, cancellationToken).ConfigureAwait(false); return document.WithSyntaxRoot(newRoot); }
void UpdateCompilerComboBox() { if (listView.SelectedItems.Count > 0) { // Fetch list of available compiler versions HashSet<CompilerVersion> availableVersionsSet = new HashSet<CompilerVersion>(); HashSet<CompilerVersion> currentVersions = new HashSet<CompilerVersion>(); foreach (Entry entry in listView.SelectedItems) { if (entry.CompilerVersion != null) currentVersions.Add(entry.CompilerVersion); availableVersionsSet.AddRange(entry.Project.GetAvailableCompilerVersions()); } List<CompilerVersion> availableVersions = availableVersionsSet.OrderBy(n => n.MSBuildVersion).ThenBy(n => n.DisplayName).ToList(); if (currentVersions.Count != 1) { availableVersions.Insert(0, new UnchangedCompilerVersion()); } // Assign available versions to newVersionComboBox // Unless the user has already chosen a version, automatically set the selection to the // current version of the chosen projects, or to 'do not change' if there are different // current versions. newCompilerSelectionChangingByCode = true; newVersionComboBox.ItemsSource = availableVersions; CompilerVersion oldSelectedVersion = newVersionComboBox.SelectedValue as CompilerVersion; if (!newCompilerSelectionSetByUser || oldSelectedVersion == null) { newCompilerSelectionSetByUser = false; if (currentVersions.Count == 1) newVersionComboBox.SelectedValue = currentVersions.Single(); else newVersionComboBox.SelectedValue = new UnchangedCompilerVersion(); } newCompilerSelectionChangingByCode = false; UpdateTargetFrameworkComboBox(); } }
static void FindDerivedClasses(HashSet<IClass> resultList, IClass baseClass, IEnumerable<IProjectContent> projectContents, bool directDerivationOnly) { baseClass = baseClass.GetCompoundClass(); string baseClassName = baseClass.Name; string baseClassFullName = baseClass.FullyQualifiedName; LoggingService.Debug("FindDerivedClasses for " + baseClassFullName); List<IClass> list = new List<IClass>(); foreach (IProjectContent pc in projectContents) { if (pc != baseClass.ProjectContent && !pc.ReferencedContents.Contains(baseClass.ProjectContent)) { // only project contents referencing the content of the base class // can derive from the class continue; } AddDerivedClasses(pc, baseClass, baseClassName, baseClassFullName, pc.Classes, list); } if (directDerivationOnly) { resultList.AddRange(list); } else { foreach (IClass c in list) { if (resultList.Add(c)) { FindDerivedClasses(resultList, c, projectContents, directDerivationOnly); } } } }
public ActorId[] Get(ActorId id) { lock (creatorToOther) { var actors = new HashSet<ActorId>(); List<ActorId> a; foreach (var alias in DnsAlias.Get(id)) { if (creatorToOther.TryGetValue(alias, out a)) actors.AddRange(a); if (otherToCreator.TryGetValue(alias, out a)) actors.AddRange(a); } return actors.ToArray(); } }
public HashSet<string> GetAllAvailableLocalTextKeys() { var result = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (var assembly in ExtensibilityHelper.SelfAssemblies) { foreach (NavigationItemAttribute attr in assembly.GetCustomAttributes(typeof(NavigationItemAttribute), false)) result.Add("Navigation." + (attr.Category.IsEmptyOrNull() ? "" : attr.Category + "/") + attr.Title); foreach (var type in assembly.GetTypes()) { var attr = type.GetCustomAttribute<FormScriptAttribute>(); if (attr != null) { foreach (var member in type.GetMembers(BindingFlags.Instance | BindingFlags.Public)) { var category = member.GetCustomAttribute<CategoryAttribute>(); if (category != null && !category.Category.IsEmptyOrNull()) result.Add("Forms." + attr.Key + ".Categories." + category.Category); } } } } var repository = Dependency.Resolve<ILocalTextRegistry>() as LocalTextRegistry; if (repository != null) result.AddRange(repository.GetAllTextKeys(false)); return result; }
static ClientTypesGenerator() { lookupEditorBaseOptions = new HashSet<string>(StringComparer.OrdinalIgnoreCase); lookupEditorBaseOptions.AddRange(typeof(LookupEditorBaseAttribute) .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly) .Select(x => x.Name)); }
/// <summary> /// Initializes a new instance of the <see cref="ExchangeInfoProvider"/>. /// </summary> /// <param name="entityRegistry">The storage of trade objects.</param> public ExchangeInfoProvider(IEntityRegistry entityRegistry) { if (entityRegistry == null) throw new ArgumentNullException(nameof(entityRegistry)); ExchangeBoard.EnumerateExchanges().ForEach(exchange => _exchanges.Add(exchange.Name, exchange)); ExchangeBoard.EnumerateExchangeBoards().ForEach(board => _boards.Add(board.Code, board)); _entityRegistry = entityRegistry; var boardCodes = new HashSet<string>(); var boardList = _entityRegistry.ExchangeBoards as ExchangeBoardList; boardCodes.AddRange(boardList != null ? boardList.GetIds() : _entityRegistry.ExchangeBoards.Select(b => b.Code)); var boards = Boards.Where(b => !boardCodes.Contains(b.Code)).ToArray(); if (boards.Length > 0) { boards .Select(b => b.Exchange) .Distinct() .ForEach(Save); boards .ForEach(Save); } _entityRegistry.Exchanges.ForEach(e => _exchanges[e.Name] = e); _entityRegistry.ExchangeBoards.ForEach(b => _boards[b.Code] = b); }
public void AddRange_should_add_provided_values_to_target_Set() { var target = new HashSet<int>(); var source = new[] {1, 2, 3, 4, 5}; target.AddRange(source); CollectionAssert.AreEquivalent(source, target); }
public VirtualRepository(IPackageRepository repo) { _packages = new HashSet<IPackage>(PackageEqualityComparer.IdAndVersion); if (repo != null) { _packages.AddRange(repo.GetPackages()); } }
/// <summary> /// Retrieves all of the document's siblings /// </summary> /// <param name="extended">The extended <see cref="XmlDocument"/></param> /// <returns>An <see cref="IEnumerable{T}"/> containing all the document's sibling <see cref="XmlNode"/>s</returns> public static IEnumerable<XmlNode> GetAllSiblings(this XmlDocument extended) { HashSet<XmlNode> siblings; siblings = new HashSet<XmlNode>(); siblings.Add(extended.FirstChild); siblings.AddRange(extended.FirstChild.GetAllSiblings()); return siblings; }
/// <summary> /// Gets the runtime elements from the application assemblies. /// </summary> /// <param name="cancellationToken">The cancellation token.</param> /// <returns> /// A promise of an enumeration of runtime elements. /// </returns> public async Task<IEnumerable<object>> GetRuntimeElementsAsync(CancellationToken cancellationToken = default(CancellationToken)) { var assemblies = await this.appRuntime.GetAppAssembliesAsync(cancellationToken: cancellationToken).PreserveThreadContext(); var eligibleAssemblyPairs = (from kv in from a in assemblies select new KeyValuePair<Assembly, IList<ModelAssemblyAttribute>>( a, a.GetCustomAttributes<ModelAssemblyAttribute>().ToList()) where kv.Value.Count > 0 select kv).ToList(); var types = new HashSet<Type>(); foreach (var kv in eligibleAssemblyPairs) { var assembly = kv.Key; // first of all add all explicitely given types. var attrs = kv.Value; foreach (var attr in attrs.Where(attr => attr.ModelTypes != null && attr.ModelTypes.Length > 0)) { types.AddRange(attr.ModelTypes); } // then add the types indicated by their namespace. var allTypesAttribute = attrs.FirstOrDefault(a => a.ModelTypes == null && a.ModelNamespaces == null); if (allTypesAttribute != null) { // if no model types or namespaces are indicated, simply add all // exported types from the assembly with no further processing types.AddRange(assembly.GetLoadableExportedTypes()); } else { // add only the types from the provided namespaces var allTypes = assembly.GetLoadableExportedTypes().ToList(); var namespaces = new HashSet<string>(attrs.Where(a => a.ModelNamespaces != null && a.ModelNamespaces.Length > 0).SelectMany(a => a.ModelNamespaces)); var namespacePatterns = namespaces.Select(n => n + ".").ToList(); types.AddRange(allTypes.Where(t => namespaces.Contains(t.Namespace) || namespacePatterns.Any(p => t.Namespace.StartsWith(p)))); } } return types; }
public void Run() { ITypeWeaver bulkWeaving = null; var compositesQueue = new Queue<ITypeWeaver>(); AspectsAttributeWeaver aspectRepository = null; AspectArgsMapperWeaver aspectArgsMapperWeaver = null; var aspectDefinitionsTypeSet = new HashSet<Type>(); var composites = typeFactory.Types.Select(type => new { Type = type, Attributes = type.GetCustomAttributesArray<CompositeAttribute>() }) .Where(composite => composite.Attributes.Length > 0); var compositeWeavingSettings = composites.ToList(composite => { var compositeType = composite.Type; var mixinsMap = new MixinsMap(compositeType); var aspectMappedMembers = new AspectMemberMapper(compositeType, mixinsMap); var aspectsMap = new AspectsMap(aspectMappedMembers); var aspectDefinitionsTypes = aspectsMap.SelectMany(aspectMap => { return aspectMap.Aspects.Select(aspectDefinition => { return aspectDefinition.Aspect.AspectType; }); }); aspectDefinitionsTypeSet.AddRange(aspectDefinitionsTypes); return new CompositeWeavingSettingsImpl { Registry = registry, MixinsMap = mixinsMap, AspectsMap = aspectsMap, CompositeType = compositeType, AspectMemebrsCollection = aspectMappedMembers }; }); aspectArgsMapperWeaver = new AspectArgsMapperWeaver(); aspectRepository = new AspectsAttributeWeaver(aspectDefinitionsTypeSet); compositesQueue.Enqueue(aspectArgsMapperWeaver); compositesQueue.Enqueue(aspectRepository); compositeWeavingSettings.ForEach(compositeSettings => { IBuilder<ITypeWeaver> builder = null; compositeSettings.AspectRepository = aspectRepository; compositeSettings.AspectArgsMapper = aspectArgsMapperWeaver; builder = new CompositeTypeWeaverBuilder(compositeSettings); compositesQueue.Enqueue(builder.Build()); }); bulkWeaving = new BulkWeaving(compositesQueue); bulkWeaving.Weave(); }
/// <summary> /// Tokenize the specified string value. /// </summary> /// <returns> /// Returns string list which will contain only the unique word tokens in lower case which have >= 2 length from initial value. /// The resulting tokens also will be sorted. /// </returns> /// <param name="value">String value.</param> public static List<string> Tokenize(this string value) { if (value == null) return null; var tokens = stringTokenizer.Split(value); HashSet<string> uniqueTokens = new HashSet<string>(); uniqueTokens.AddRange(tokens.Where(t => t.Length >= 2).Select(t => t.ToLower())); var sorted = uniqueTokens.ToList(); sorted.Sort(); return sorted; }
public ICollection<Number640> Evaluate1(IDictionary<PeerAddress, IDictionary<Number640, Number160>> rawKeys) { var result = new HashSet<Number640>(); if (rawKeys != null) { foreach (var dictionary in rawKeys.Values) { result.AddRange(dictionary.Keys); } } return result; }
//Validate that the we are using valid colors and set appropriate defaults if not. private void CheckForInvalidColorData() { HashSet<Color> validColors = new HashSet<Color>(); validColors.AddRange(TargetNodes.SelectMany(x => ColorModule.getValidColorsForElementNode(x, true))); if (validColors.Any() && (!validColors.Contains(_data.StaticColor) || !_data.ColorGradient.GetColorsInGradient().IsSubsetOf(validColors))) //Discrete colors specified { _data.ColorGradient = new ColorGradient(validColors.DefaultIfEmpty(Color.White).First()); _data.StaticColor = validColors.First(); } }
/// <summary> /// Gets the historical data for specified symbol in format like KC, CC etc; /// </summary> public IEnumerable<Quote> GetWeeklyData(string symbol) { var quotes = new HashSet<Quote>(); var contractSpecification = ContractSpecification.Data.First(d => d.Symbol == symbol); var yearlyCodes = GetExpirationMonths(contractSpecification); foreach (var code in yearlyCodes) { OnDownload(code); quotes.AddRange(_robot.GetHistoricalData(code, Period.Weekly, BarChartProxy.FrameSize.Largest)); } return new List<Quote>(quotes).OrderBy(d => d.DateTime); }
private IEnumerable<string> GetReferencedAssemblyPaths(IList<FilePathAbsolute> projects) { var list = new HashSet<string>(projects.AsStrings()); foreach (var binDir in projects.Select(p => p.ParentDirectoryPath)) { var files = Directory.EnumerateFiles(binDir.Path, "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".dll") || s.EndsWith(".pdb")) .Where(p => !projects.Contains(p.ToFilePathAbs())); list.AddRange(files); } return list; }
public static HashSet<Color> GetDiscreteColors(object component) { var validColors = new HashSet<Color>(); if (component is IEffect) { var effect = (IEffect)component; validColors.AddRange(effect.TargetNodes.SelectMany(x => ColorModule.getValidColorsForElementNode(x, true))); } else if (component is Array) { foreach (var item in (Array)component) { if (item is IEffect) { var effect = (IEffect)item; validColors.AddRange(effect.TargetNodes.SelectMany(x => ColorModule.getValidColorsForElementNode(x, true))); } } } return validColors; }
/// <summary> /// Retrieves all the siblings of the specified <see cref="XmlNode"/> /// </summary> /// <param name="extended">The extended <see cref="XmlNode"/></param> /// <returns>An <see cref="IEnumerable{T}"/> containing all of the <see cref="XmlNode"/> siblings</returns> public static IEnumerable<XmlNode> GetAllSiblings(this XmlNode extended) { HashSet<XmlNode> siblings; siblings = new HashSet<XmlNode>(); if(extended.ChildNodes != null) { foreach (XmlNode node in extended.ChildNodes) { siblings.Add(node); siblings.AddRange(node.ChildNodes); } } return siblings; }
public override void ExecuteCommand() { WithMasterConnection((connection, db) => { // Get the list of backups var backups = db.Query<Db>( "SELECT name, state FROM sys.databases WHERE name LIKE 'WarehouseBackup_%'", new { state = Util.OnlineState }) .Select(d => new OnlineDatabaseBackup(Util.GetDatabaseServerName(ConnectionString), d.Name, d.State)) .OrderByDescending(b => b.Timestamp) .ToList(); // Any currently copying are safe var keepers = new HashSet<string>(); keepers.AddRange(backups.Where(b => b.State == Util.CopyingState).Select(b => b.DatabaseName)); // The last online database is safe keepers.AddRange(backups .Where(b => b.State == Util.OnlineState && b.Timestamp != null) .OrderByDescending(d => d.Timestamp.Value) .Select(b => b.DatabaseName) .Take(1)); // Figure out how many we're keeping Log.Info("Keeping the following Backups: {0}", String.Join(", ", keepers)); // Done! Delete the non-keepers foreach (var backup in backups.Where(b => !keepers.Contains(b.DatabaseName))) { if (!WhatIf) { db.Execute("DROP DATABASE " + backup.DatabaseName); } Log.Info("Deleted {0}", backup.DatabaseName); } }); }
public static int Answer() { int max = 28123; var range = Enumerable.Range(1, max).ToList(); var abundantNumbers = range.Where(i => i.IsAbundant()).ToList(); var abundantSums = new HashSet<int>(); abundantSums.AddRange(from a in abundantNumbers from b in abundantNumbers select a + b); return range .Where(i => !abundantSums.Contains(i)) .Sum(); }
public HgBundle BuildBundle(HgRepository hgRepository, HgRevset hgRevset) { log.Debug("bundling changelog"); var paths = new HashSet<string>(); var changelog = BuildChangesetBundleGroup(hgRepository, hgRevset, hc => paths.AddRange(hc.Files)); log.Debug("bundling manifests"); var manifest = BuildManifestBundleGroup(hgRepository, hgRevset); // // List of all files that ever were tracked log.Debug("bundling filelogs"); var files = BuildBundleFiles(hgRepository, hgRevset, paths); var hgBundle = new HgBundle(changelog, manifest, files); return hgBundle; }
/// <summary> /// Tokenize the specified string values. /// </summary> /// <returns> /// Returns string list which will contain only the unique word tokens in lower case from each of the initial string values. /// The resulting tokens also will be sorted. /// </returns> /// <param name="values">Values.</param> public static List<string> Tokenize(this IEnumerable<string> values) { if (values == null) return null; HashSet<string> uniqueTokens = new HashSet<string>(); foreach (var value in values) { if (value != null) { var tokens = Tokenize(value); uniqueTokens.AddRange(tokens); } } var sorted = uniqueTokens.ToList(); sorted.Sort(); return sorted; }
private static async Task <RestoreSummary> PerformNuGetV2RestoreAsync(Common.ILogger log, DependencyGraphSpec dgFile, bool noCache, bool disableParallel, bool interactive) { string globalPackageFolder = null; string repositoryPath = null; string firstPackagesConfigPath = null; IList <PackageSource> packageSources = null; var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer()); ISettings settings = null; foreach (PackageSpec packageSpec in dgFile.Projects.Where(i => i.RestoreMetadata.ProjectStyle == ProjectStyle.PackagesConfig)) { var pcRestoreMetadata = (PackagesConfigProjectRestoreMetadata)packageSpec.RestoreMetadata; globalPackageFolder = globalPackageFolder ?? pcRestoreMetadata.PackagesPath; repositoryPath = repositoryPath ?? pcRestoreMetadata.RepositoryPath; if (packageSources == null) { packageSources = new List <PackageSource>(); if (!noCache) { if (!string.IsNullOrEmpty(globalPackageFolder) && Directory.Exists(globalPackageFolder)) { packageSources.Add(new FeedTypePackageSource(globalPackageFolder, FeedType.FileSystemV3)); } } packageSources.AddRange(pcRestoreMetadata.Sources); } settings = settings ?? Settings.LoadSettingsGivenConfigPaths(pcRestoreMetadata.ConfigFilePaths); var packagesConfigPath = Path.Combine(Path.GetDirectoryName(pcRestoreMetadata.ProjectPath), NuGetConstants.PackageReferenceFile); firstPackagesConfigPath = firstPackagesConfigPath ?? packagesConfigPath; installedPackageReferences.AddRange(GetInstalledPackageReferences(packagesConfigPath, allowDuplicatePackageIds: true, log)); } if (string.IsNullOrEmpty(repositoryPath)) { throw new InvalidOperationException(Strings.RestoreNoSolutionFound); } PackageSourceProvider packageSourceProvider = new PackageSourceProvider(settings); var sourceRepositoryProvider = new CachingSourceProvider(packageSourceProvider); var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, settings, repositoryPath); var effectivePackageSaveMode = CalculateEffectivePackageSaveMode(settings); var packageSaveMode = effectivePackageSaveMode == Packaging.PackageSaveMode.None ? Packaging.PackageSaveMode.Defaultv2 : effectivePackageSaveMode; var missingPackageReferences = installedPackageReferences.Where(reference => !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray(); if (missingPackageReferences.Length == 0) { return(new RestoreSummary(true)); } var packageRestoreData = missingPackageReferences.Select(reference => new PackageRestoreData( reference, new[] { firstPackagesConfigPath }, isMissing: true)); var repositories = sourceRepositoryProvider.GetRepositories().ToArray(); var installCount = 0; var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>(); var collectorLogger = new RestoreCollectorLogger(log); var packageRestoreContext = new PackageRestoreContext( nuGetPackageManager, packageRestoreData, CancellationToken.None, packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); }, packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); }, sourceRepositories: repositories, maxNumberOfParallelTasks: disableParallel ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism, logger: collectorLogger); // TODO: Check require consent? // NOTE: This feature is currently not working at all. See https://github.com/NuGet/Home/issues/4327 // CheckRequireConsent(); var clientPolicyContext = ClientPolicyContext.GetClientPolicy(settings, collectorLogger); var projectContext = new ConsoleProjectContext(collectorLogger) { PackageExtractionContext = new PackageExtractionContext( packageSaveMode, PackageExtractionBehavior.XmlDocFileSaveMode, clientPolicyContext, collectorLogger) }; if (effectivePackageSaveMode != Packaging.PackageSaveMode.None) { projectContext.PackageExtractionContext.PackageSaveMode = packageSaveMode; } using (var cacheContext = new SourceCacheContext()) { cacheContext.NoCache = noCache; var downloadContext = new PackageDownloadContext(cacheContext, repositoryPath, directDownload: false) { ClientPolicyContext = clientPolicyContext }; DefaultCredentialServiceUtility.SetupDefaultCredentialService(log, !interactive); var result = await PackageRestoreManager.RestoreMissingPackagesAsync( packageRestoreContext, projectContext, downloadContext); return(new RestoreSummary( result.Restored, "packages.config projects", settings.GetConfigFilePaths().ToArray(), packageSources.Select(x => x.Source).ToArray(), installCount, collectorLogger.Errors.Concat(ProcessFailedEventsIntoRestoreLogs(failedEvents)).ToArray() )); } }
public ManualConfig AddHardwareCounters(params HardwareCounter[] newHardwareCounters) { hardwareCounters.AddRange(newHardwareCounters); return(this); }
private async Task <PrepareResult> PrepareResourceAsync( string label, Resource res, bool custom, bool remote, ResourceArgs args, ResourceOptions options) { /* IMPORTANT! We should never await prior to this line, otherwise the Resource will be partly uninitialized. */ // Before we can proceed, all our dependencies must be finished. var type = res.GetResourceType(); var name = res.GetResourceName(); LogExcessive($"Gathering explicit dependencies: t={type}, name={name}, custom={custom}, remote={remote}"); var explicitDirectDependencies = new HashSet <Resource>( await GatherExplicitDependenciesAsync(options.DependsOn).ConfigureAwait(false)); LogExcessive($"Gathered explicit dependencies: t={type}, name={name}, custom={custom}, remote={remote}"); // Serialize out all our props to their final values. In doing so, we'll also collect all // the Resources pointed to by any Dependency objects we encounter, adding them to 'propertyDependencies'. LogExcessive($"Serializing properties: t={type}, name={name}, custom={custom}, remote={remote}"); var dictionary = await args.ToDictionaryAsync().ConfigureAwait(false); var(serializedProps, propertyToDirectDependencies) = await SerializeResourcePropertiesAsync( label, dictionary, await this.MonitorSupportsResourceReferences().ConfigureAwait(false)).ConfigureAwait(false); LogExcessive($"Serialized properties: t={type}, name={name}, custom={custom}, remote={remote}"); // Wait for the parent to complete. // If no parent was provided, parent to the root resource. LogExcessive($"Getting parent urn: t={type}, name={name}, custom={custom}, remote={remote}"); var parentURN = options.Parent != null ? await options.Parent.Urn.GetValueAsync().ConfigureAwait(false) : await GetRootResourceAsync(type).ConfigureAwait(false); LogExcessive($"Got parent urn: t={type}, name={name}, custom={custom}, remote={remote}"); string?providerRef = null; if (custom) { var customOpts = options as CustomResourceOptions; providerRef = await ProviderResource.RegisterAsync(customOpts?.Provider).ConfigureAwait(false); } var providerRefs = new Dictionary <string, string>(); if (remote) { var componentOpts = options as ComponentResourceOptions; if (componentOpts != null) { // If only the Provider opt is set, move it to the Providers list for further processing. if (componentOpts.Provider != null && componentOpts.Providers.Count == 0) { componentOpts.Providers.Add(componentOpts.Provider); componentOpts.Provider = null; } foreach (var provider in componentOpts.Providers) { var pref = await ProviderResource.RegisterAsync(provider).ConfigureAwait(false); if (pref != null) { providerRefs.Add(provider.Package, pref); } } } } // Collect the URNs for explicit/implicit dependencies for the engine so that it can understand // the dependency graph and optimize operations accordingly. // The list of all dependencies (implicit or explicit). var allDirectDependencies = new HashSet <Resource>(explicitDirectDependencies); var allDirectDependencyURNs = await GetAllTransitivelyReferencedCustomResourceURNsAsync(explicitDirectDependencies).ConfigureAwait(false); var propertyToDirectDependencyURNs = new Dictionary <string, HashSet <string> >(); foreach (var(propertyName, directDependencies) in propertyToDirectDependencies) { allDirectDependencies.AddRange(directDependencies); var urns = await GetAllTransitivelyReferencedCustomResourceURNsAsync(directDependencies).ConfigureAwait(false); allDirectDependencyURNs.AddRange(urns); propertyToDirectDependencyURNs[propertyName] = urns; } // Wait for all aliases. Note that we use 'res._aliases' instead of 'options.aliases' as // the former has been processed in the Resource constructor prior to calling // 'registerResource' - both adding new inherited aliases and simplifying aliases down // to URNs. var aliases = new List <string>(); var uniqueAliases = new HashSet <string>(); foreach (var alias in res._aliases) { var aliasVal = await alias.ToOutput().GetValueAsync().ConfigureAwait(false); if (uniqueAliases.Add(aliasVal)) { aliases.Add(aliasVal); } } return(new PrepareResult( serializedProps, parentURN ?? "", providerRef ?? "", providerRefs, allDirectDependencyURNs, propertyToDirectDependencyURNs, aliases)); void LogExcessive(string message) { if (_excessiveDebugOutput) { Log.Debug(message); } } }
public IEnumerable <string> GetAllScenes() { var excludeMap = new HashSet <string>(); // Exclude scenes: if (this.ExcludeScenePaths != null) { var excludeDirectories = this.ExcludeScenePaths.Select(x => x.Trim('/')).Where(x => !string.IsNullOrEmpty(x) && Directory.Exists(x)).ToArray(); var excludeScenesFiles = this.ExcludeScenePaths.Where(x => File.Exists(x)); if (excludeDirectories.Length > 0) { excludeMap.AddRange(AssetDatabase.FindAssets("t:SceneAsset", excludeDirectories).Select(x => AssetDatabase.GUIDToAssetPath(x))); } excludeMap.AddRange(excludeScenesFiles); } // Add scenes: if (this.ScenePaths != null) { var addDirectories = this.ScenePaths.Select(x => x.Trim('/')).Where(x => !string.IsNullOrEmpty(x) && Directory.Exists(x)).ToArray(); var addSceneFiles = this.ScenePaths.Where(x => File.Exists(x)); if (addDirectories.Length > 0) { var scenes = AssetDatabase.FindAssets("t:SceneAsset", addDirectories) .Select(x => AssetDatabase.GUIDToAssetPath(x)); foreach (var scene in scenes) { if (excludeMap.Add(scene)) { yield return(scene); } } } foreach (var scene in addSceneFiles) { if (excludeMap.Add(scene)) { yield return(scene); } } } if (this.IncludeScenesFromBuildOptions) { foreach (var scene in EditorBuildSettings.scenes) { if (scene.enabled && !string.IsNullOrEmpty(scene.path) && excludeMap.Add(scene.path) && File.Exists(scene.path)) { yield return(scene.path); } } } if (this.IncludeOpenScenes) { var setupScenes = EditorSceneManager.GetSceneManagerSetup(); foreach (var scene in setupScenes) { if (!string.IsNullOrEmpty(scene.path) && excludeMap.Add(scene.path)) { yield return(scene.path); } } } }
void UpdateSurfaceSelection() { surfaceOutlines.Clear(); var selection = ChiselSurfaceSelectionManager.Selection; var hovered = ChiselSurfaceSelectionManager.Hovered; if (selection.Count == 0 && hovered.Count == 0) { surfaceOutlines.Clear(); surfaceOutlineRenderer.Clear(); } else { var allSurfaces = new HashSet <SurfaceReference>(selection); allSurfaces.AddRange(hovered); foreach (var outline in surfaceOutlines.Keys) { var surface = outline.surface; if (!allSurfaces.Contains(surface) || !surface.TreeBrush.Valid || surface.TreeBrush.BrushMesh == BrushMeshInstance.InvalidInstance) { removedSurfaces.Add(outline); } else { allSurfaces.Remove(surface); } } if (removedSurfaces.Count > 0) { foreach (var outline in removedSurfaces) { surfaceOutlines.Remove(outline); } } removedSurfaces.Clear(); foreach (var surface in allSurfaces) { var transform = CSGNodeHierarchyManager.FindModelTransformOfTransform(surface.node.hierarchyItem.Transform); var outline = new SurfaceOutline(transform, surface); foundSurfaceOutlines.Add(outline); } foreach (var outline in foundSurfaceOutlines) { if (!outline.surface.TreeBrush.Valid || outline.surface.TreeBrush.BrushMesh == BrushMeshInstance.InvalidInstance) { continue; } var wireframe = CSGWireframe.CreateWireframe(outline.surface.TreeBrush, outline.surface.surfaceID); surfaceOutlines[outline] = wireframe; } } foundSurfaceOutlines.Clear(); updateSurfaceWireframe = true; }
[InlineData(".*d\\.txt$")] // no files public void TestAddDirectoryToDropWithFilters(string filter) { // TestOutputDirectory // |- foo <directory> <- 'uploading' this directory // |- a.txt // |- b.txt // |- bar <directory> // |- c.txt string remoteDirectoryPath = "remoteDirectory"; string fakeDirectoryId = "123:1:12345"; var directoryPath = Path.Combine(TestOutputDirectory, "foo"); var files = new List <(string fileName, string remoteFileName)> { (Path.Combine(directoryPath, "a.txt"), $"{remoteDirectoryPath}/a.txt"), (Path.Combine(directoryPath, "b.txt"), $"{remoteDirectoryPath}/b.txt"), (Path.Combine(directoryPath, "bar", "c.txt"), $"{remoteDirectoryPath}/bar/c.txt"), }; var dropPaths = new List <string>(); var expectedDropPaths = new HashSet <string>(); var regex = new Regex(filter, RegexOptions.IgnoreCase | RegexOptions.Compiled); expectedDropPaths.AddRange(files.Where(a => regex.IsMatch(a.fileName)).Select(a => a.remoteFileName)); if (!Directory.Exists(directoryPath)) { Directory.CreateDirectory(directoryPath); } var dropClient = new MockDropClient(addFileFunc: (item) => { dropPaths.Add(item.RelativeDropPath); return(Task.FromResult(AddFileResult.UploadedAndAssociated)); }); var ipcProvider = IpcFactory.GetProvider(); // this lambda mocks BuildXL server receiving 'GetSealedDirectoryContent' API call and returning a response var ipcExecutor = new LambdaIpcOperationExecutor(op => { var cmd = ReceiveGetSealedDirectoryContentCommandAndCheckItMatchesDirectoryId(op.Payload, fakeDirectoryId); // Now 'fake' the response - here we only care about the 'FileName' field. // In real life it's not the case, but this is a test and our custom addFileFunc // in dropClient simply collects the drop file names. var result = files.Select(a => CreateFakeSealedDirectoryFile(a.fileName)).ToList(); return(IpcResult.Success(cmd.RenderResult(result))); }); WithIpcServer( ipcProvider, ipcExecutor, new ServerConfig(), (moniker, mockServer) => { var bxlApiClient = new Client(ipcProvider.GetClient(ipcProvider.RenderConnectionString(moniker), new ClientConfig())); WithSetup( dropClient, (daemon, etwListener) => { var addArtifactsCommand = Program.ParseArgs($"addartifacts --ipcServerMoniker {moniker.Id} --directory {directoryPath} --directoryId {fakeDirectoryId} --directoryDropPath {remoteDirectoryPath} --directoryFilter {filter}", new UnixParser()); var ipcResult = addArtifactsCommand.Command.ServerAction(addArtifactsCommand, daemon).GetAwaiter().GetResult(); XAssert.IsTrue(ipcResult.Succeeded, ipcResult.Payload); XAssert.AreSetsEqual(expectedDropPaths, dropPaths, expectedResult: true); }, bxlApiClient); return(Task.CompletedTask); }).GetAwaiter().GetResult(); }
public static BonusPath TryCreate(BotMain bot, BonusIDType bonusID, Func <TerritoryStanding, bool> weOwn) { var bonus = bot.Map.Bonuses[bonusID]; var allUnownedTerrsInBonus = bonus.Territories.Where(o => !weOwn(bot.Standing.Territories[o])).ToHashSet(true); if (allUnownedTerrsInBonus.Count == 0) { return(new BonusPath(bonusID, 0, new HashSet <TerritoryIDType>())); //Already own the bonus. We'll only get here with one-territory bonuses during distribution } var terrsToTake = allUnownedTerrsInBonus.ToHashSet(true); var ownedTerritoriesTraverse = bot.Standing.Territories.Values.Where(o => weOwn(o)).Select(o => o.ID).ToHashSet(true); HashSet <TerritoryIDType> finalTerritoriesCaptured = null; var turns = 1; while (true) { var takeThisTurn = terrsToTake.Where(o => bot.Map.Territories[o].ConnectedTo.Keys.Any(z => ownedTerritoriesTraverse.Contains(z))).ToHashSet(true); if (takeThisTurn.Count == 0) { //We can't take it without leaving the bonus. AILog.Log("BonusPath", " Could not find a way to take bonus " + bot.BonusString(bonus) + " without leaving it"); return(null); } if (takeThisTurn.Count == terrsToTake.Count) { //We captured the bonus finalTerritoriesCaptured = takeThisTurn; break; } //Keep expanding! turns++; ownedTerritoriesTraverse.AddRange(takeThisTurn); terrsToTake.RemoveAll(takeThisTurn); } var terrsWeOwnInOrAroundBonus = bonus.Territories.Concat(bonus.Territories.SelectMany(o => bot.Map.Territories[o].ConnectedTo.Keys)).Where(o => weOwn(bot.Standing.Territories[o])).ToHashSet(false); var traverse = allUnownedTerrsInBonus.Concat(terrsWeOwnInOrAroundBonus).ToHashSet(false); var criticalPath = new HashSet <TerritoryIDType>(); foreach (var final in finalTerritoriesCaptured) { var path = FindPath.TryFindShortestPathReversed(bot, o => weOwn(bot.Standing.Territories[o]), final, o => traverse.Contains(o)); if (path != null) { //AILog.Log("BonusPath", " Critical path to " + bot.TerrString(final) + " goes " + path.Select(o => bot.TerrString(o)).JoinStrings(" -> ")); criticalPath.AddRange(path); } else { AILog.Log("BonusPath", " Could not find a path to " + bot.TerrString(final)); } } //AILog.Log("BonusPath", "With infinite armies, we can take bonus " + bot.BonusString(bonus) + " in " + TurnsToTake + " turns. " + /*" Final territories=" + finalTerritoriesCaptured.Select(o => bot.TerrString(o)).JoinStrings(", ") +*/ " Critical path=" + TerritoriesOnCriticalPath.Select(o => bot.TerrString(o)).JoinStrings(", ")); return(new BonusPath(bonusID, turns, criticalPath)); }
/// <summary> /// Отправить сообщение. /// </summary> /// <param name="message">Сообщение.</param> protected override void OnSendInMessage(Message message) { switch (message.Type) { case MessageTypes.Reset: { _requestsType.Clear(); _secIds.Clear(); _candleParsers.Clear(); _newsIds.Clear(); _lookupResult.Clear(); _currSystemType = null; if (_lookupFeed != null) { SafeDisconnectFeed(ref _lookupFeed); } if (_level1Feed != null) { SafeDisconnectFeed(ref _level1Feed); } if (_level2Feed != null) { SafeDisconnectFeed(ref _level2Feed); } if (_derivativeFeed != null) { SafeDisconnectFeed(ref _derivativeFeed); } SendOutMessage(new ResetMessage()); break; } case MessageTypes.Connect: { _isDownloadSecurityFromSite = IsDownloadSecurityFromSite; _lookupFeed = CreateFeed(LookupAddress, "LookupFeed"); _level1Feed = CreateFeed(Level1Address, "Level1Feed"); _level2Feed = CreateFeed(Level2Address, "Level2Feed"); _derivativeFeed = CreateFeed(DerivativeAddress, "DerivativeFeed"); _level1Feed.SetLevel1FieldSet(new[] { Level1ColumnRegistry.Symbol, Level1ColumnRegistry.ExchangeId, Level1ColumnRegistry.LastTradeMarket, Level1ColumnRegistry.BidMarket, Level1ColumnRegistry.AskMarket } .Concat(Level1Columns) .Select(c => c.Name) .ToArray()); break; } case MessageTypes.Disconnect: { SafeDisconnectFeed(ref _lookupFeed); SafeDisconnectFeed(ref _level1Feed); SafeDisconnectFeed(ref _level2Feed); SafeDisconnectFeed(ref _derivativeFeed); //_isCommonLookupDone = null; SendOutMessage(new DisconnectMessage()); break; } case MessageTypes.MarketData: { var mdMsg = (MarketDataMessage)message; var from = mdMsg.From.ToLocalTime(TimeHelper.Est); var to = mdMsg.To.ToLocalTime(TimeHelper.Est); switch (mdMsg.DataType) { case MarketDataTypes.Level1: { if (mdMsg.To == DateTimeOffset.MaxValue) { if (mdMsg.IsSubscribe) { _level1Feed.SubscribeSymbol(mdMsg.SecurityId.SecurityCode); } else { _level1Feed.UnSubscribeSymbol(mdMsg.SecurityId.SecurityCode); } } else { if (mdMsg.IsSubscribe) { _requestsType.Add(mdMsg.TransactionId, MessageTypes.Execution); _secIds.Add(mdMsg.TransactionId, mdMsg.SecurityId); if (mdMsg.Count != 0) { _lookupFeed.RequestTicks(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, mdMsg.Count); } else { _lookupFeed.RequestTicks(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, from, to); } } } break; } case MarketDataTypes.MarketDepth: { if (mdMsg.IsSubscribe) { _level2Feed.SubscribeSymbol(mdMsg.SecurityId.SecurityCode); } else { _level2Feed.UnSubscribeSymbol(mdMsg.SecurityId.SecurityCode); } break; } //case MarketDataTypes.Trades: //{ // if (mdMsg.To == DateTime.MaxValue) // { // if (mdMsg.IsSubscribe) // _level1Feed.SubscribeSymbol(mdMsg.SecurityId.SecurityCode); // else // _level1Feed.UnSubscribeSymbol(mdMsg.SecurityId.SecurityCode); // } // else // { // if (mdMsg.IsSubscribe) // { // _requestsType.Add(mdMsg.TransactionId, MessageTypes.Execution); // _lookupFeed.RequestTrades(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, mdMsg.From, mdMsg.To); // } // } // break; //} case MarketDataTypes.News: { if (mdMsg.IsSubscribe) { if (mdMsg.NewsId.IsEmpty()) { if (mdMsg.From.IsDefault()) { _level1Feed.SubscribeNews(); } else { _requestsType.Add(mdMsg.TransactionId, MessageTypes.News); _lookupFeed.RequestNewsHeadlines(mdMsg.TransactionId, from); } } else { var newsId = mdMsg.NewsId; _newsIds.Add(mdMsg.TransactionId, newsId); _requestsType.Add(mdMsg.TransactionId, ExtendedMessageTypes.NewsStory); _lookupFeed.RequestNewsStory(mdMsg.TransactionId, newsId); } } else { _level1Feed.UnSubscribeNews(); } break; } case MarketDataTypes.CandleTimeFrame: case MarketDataTypes.CandleTick: case MarketDataTypes.CandleVolume: case MarketDataTypes.CandleRange: case MarketDataTypes.CandlePnF: case MarketDataTypes.CandleRenko: { if (mdMsg.IsSubscribe) { // streaming if (from == DateTimeOffset.MaxValue && mdMsg.Count == 0) { string strArg, intervalType; GetCandleParams(mdMsg.DataType, mdMsg.Arg, out strArg, out intervalType); _requestsType.Add(mdMsg.TransactionId, mdMsg.DataType.ToCandleMessageType()); _secIds.Add(mdMsg.TransactionId, mdMsg.SecurityId); _candleParsers.Add(mdMsg.TransactionId, Tuple.Create(_candleStreamingParser, mdMsg.Arg)); _derivativeFeed.SubscribeCandles(mdMsg.SecurityId.SecurityCode, intervalType, strArg, from, mdMsg.TransactionId); break; } if (mdMsg.Arg is TimeSpan) { var tf = (TimeSpan)mdMsg.Arg; if (tf.Ticks == TimeHelper.TicksPerMonth) { _requestsType.Add(mdMsg.TransactionId, ExtendedMessageTypes.HistoryExtraDayCandle); _secIds.Add(mdMsg.TransactionId, mdMsg.SecurityId); _candleParsers.Add(mdMsg.TransactionId, Tuple.Create(_candleParser, mdMsg.Arg)); var count = mdMsg.Count; if (count == 0) { count = ExchangeBoard.Associated.GetTimeFrameCount(new Range <DateTimeOffset>(mdMsg.From, mdMsg.To), tf); } _lookupFeed.RequestMonthlyCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, count); } else if (tf == TimeSpan.FromDays(7)) { _requestsType.Add(mdMsg.TransactionId, ExtendedMessageTypes.HistoryExtraDayCandle); _secIds.Add(mdMsg.TransactionId, mdMsg.SecurityId); _candleParsers.Add(mdMsg.TransactionId, Tuple.Create(_candleParser, mdMsg.Arg)); var count = mdMsg.Count; if (count == 0) { count = ExchangeBoard.Associated.GetTimeFrameCount(new Range <DateTimeOffset>(mdMsg.From, mdMsg.To), tf); } _lookupFeed.RequestWeeklyCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, count); } else if (tf == TimeSpan.FromDays(1)) { _requestsType.Add(mdMsg.TransactionId, ExtendedMessageTypes.HistoryExtraDayCandle); _secIds.Add(mdMsg.TransactionId, mdMsg.SecurityId); _candleParsers.Add(mdMsg.TransactionId, Tuple.Create(_candleParser, mdMsg.Arg)); if (mdMsg.Count != 0) { _lookupFeed.RequestDailyCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, mdMsg.Count); } else { _lookupFeed.RequestDailyCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, from, to); } } else if (tf < TimeSpan.FromDays(1)) { string strArg, intervalType; GetCandleParams(mdMsg.DataType, mdMsg.Arg, out strArg, out intervalType); _requestsType.Add(mdMsg.TransactionId, mdMsg.DataType.ToCandleMessageType()); _secIds.Add(mdMsg.TransactionId, mdMsg.SecurityId); _candleParsers.Add(mdMsg.TransactionId, Tuple.Create(_candleIntradayParser, mdMsg.Arg)); //var interval = tf.TotalSeconds.To<int>(); if (mdMsg.Count != 0) { _lookupFeed.RequestCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, intervalType, strArg, mdMsg.Count); } else { _lookupFeed.RequestCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, intervalType, strArg, from, to); } } else { throw new InvalidOperationException(LocalizedStrings.Str2139Params.Put(tf)); } } else { string strArg, intervalType; GetCandleParams(mdMsg.DataType, mdMsg.Arg, out strArg, out intervalType); if (mdMsg.Count != 0) { _lookupFeed.RequestCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, intervalType, strArg, mdMsg.Count); } else { _lookupFeed.RequestCandles(mdMsg.TransactionId, mdMsg.SecurityId.SecurityCode, intervalType, strArg, from, to); } } } else { _derivativeFeed.UnSubscribeCandles(mdMsg.SecurityId.SecurityCode, mdMsg.OriginalTransactionId); } break; } default: { SendOutMarketDataNotSupported(mdMsg.TransactionId); return; } } var reply = (MarketDataMessage)message.Clone(); reply.OriginalTransactionId = mdMsg.TransactionId; SendOutMessage(reply); break; } case MessageTypes.SecurityLookup: { var lookupMsg = (SecurityLookupMessage)message; var securityTypes = new HashSet <SecurityTypes>(); if (lookupMsg.SecurityTypes != null) { securityTypes.AddRange(lookupMsg.SecurityTypes); } else if (lookupMsg.SecurityType != null) { securityTypes.Add(lookupMsg.SecurityType.Value); } if (_isDownloadSecurityFromSite) { _isDownloadSecurityFromSite = false; using (var zip = new ZipArchive( SecuritiesFile.IsEmpty() ? IQFeedHelper.DownloadSymbols().To <Stream>() : File.OpenRead(SecuritiesFile))) { var entry = zip.GetEntry("mktsymbols_v2.txt"); using (var reader = entry.Open()) { reader .ReadLines() .Skip(1) .Select(line => line.Split('\t')) .ForEach(parts => { if (parts.Length == 9) { // mika 2014.09.16 // below line has incorrect tabulation // CS.17.CB CREDIT SUISSE NEW YORK 1.375% 05/26/17 NYSE NYSE BONDS var list = parts.ToList(); list.RemoveAt(2); parts = list.ToArray(); } var secType = parts[4].ToSecurityType(); if (secType == null) { this.AddWarningLog(LocalizedStrings.Str2140Params.Put(parts[4])); } if (secType != null && !securityTypes.Contains(secType.Value)) { return; } var secCode = parts[0]; var secName = parts[0]; var boardCode = parts[2]; SendOutMessage(new BoardMessage { Code = boardCode, ExchangeCode = boardCode }); SendOutMessage(new SecurityMessage { SecurityId = new SecurityId { SecurityCode = secCode, BoardCode = boardCode }, Name = secName, SecurityType = secType, OriginalTransactionId = lookupMsg.TransactionId }); }); } } break; } var requestedTypes = _securityTypes .Where(t => t.Value != null && securityTypes.Contains(t.Value.Value)) .Select(i => i.Key.To <string>()) .ToArray(); _requestsType.Add(lookupMsg.TransactionId, MessageTypes.Security); _lookupResult.Add(lookupMsg.TransactionId, lookupMsg); var code = lookupMsg.SecurityId.SecurityCode; if (code.IsEmpty()) { code = "*"; } _lookupFeed.RequestSecurities(lookupMsg.TransactionId, IQFeedSearchField.Symbol, code, IQFeedFilterType.SecurityType, requestedTypes); break; } } }
private static void EvaluateContentPlacementClassifier(Args arguments) { Contract.Requires(arguments.InputDirectory != null, "You must specify an input directory"); Contract.Requires(Directory.Exists(arguments.InputDirectory), "The input directory must exist"); var configurationFile = $"{Path.Combine(arguments.InputDirectory, "classifier.json")}"; s_logger.Info($"Evaluating classifier from [{configurationFile}]"); // approx memory consumption and check load time var initialMemory = GC.GetTotalMemory(true); var load = Stopwatch.StartNew(); var classifier = new ContentPlacementClassifier(configurationFile); load.Stop(); var consumedMemory = GC.GetTotalMemory(false) - initialMemory; s_logger.Info($"Classifier loaded in {load.ElapsedMilliseconds}ms, approxBytes={consumedMemory}"); var numInstances = 0; var random = new Random(Environment.TickCount); // read some queue names var qNames = new List <string>(); var instances = new Dictionary <ContentPlacementInstance, List <string> >(); var uniqueMachines = new HashSet <string>(); foreach (var qq in Directory.EnumerateFiles(Path.Combine(arguments.InputDirectory, "QueueMap"))) { qNames.Add(Path.GetFileNameWithoutExtension(qq)); ++numInstances; } // now test for some instances. Just some random instances, one per queue var ns = 0; var na = 0; var classify = Stopwatch.StartNew(); foreach (var queueName in qNames) { var instance = new ContentPlacementInstance() { QueueName = queueName, Artifact = new RandomForestInstance() { Attributes = new Dictionary <string, double>() { ["SizeBytes"] = random.Next(0, 1000000000), ["AvgInputPips"] = random.Next(0, 100000), ["AvgOutputPips"] = random.Next(0, 100000), ["AvgPositionForInputPips"] = random.NextDouble(), ["AvgPositionForOutputPips"] = random.NextDouble(), ["AvgDepsForInputPips"] = random.Next(0, 10000), ["AvgDepsForOutputPips"] = random.Next(0, 10000), ["AvgInputsForInputPips"] = random.Next(0, 100000), ["AvgInputsForOutputPips"] = random.Next(0, 100000), ["AvgOutputsForInputPips"] = random.Next(0, 100000), ["AvgOutputsForOutputPips"] = random.Next(0, 100000), ["AvgPriorityForInputPips"] = random.Next(0, 100), ["AvgPriorityForOutputPips"] = random.Next(0, 100), ["AvgWeightForInputPips"] = random.Next(0, 100), ["AvgWeightForOutputPips"] = random.Next(0, 100), ["AvgTagCountForInputPips"] = random.Next(0, 100), ["AvgTagCountForOutputPips"] = random.Next(0, 100), ["AvgSemaphoreCountForInputPips"] = random.Next(0, 100), ["AvgSemaphoreCountForOutputPips"] = random.Next(0, 100) } } }; var result = classifier.Classify(instance); if (result.Succeeded) { instances.Add(instance, result.Value); } switch (result.ReturnCode) { case ContentPlacementClassifierResult.ResultCode.ArtifactNotShared: ns++; break; case ContentPlacementClassifierResult.ResultCode.NoAlternativesForQueue: na++; break; default: break; } } classify.Stop(); s_logger.Info($"Classifier ({numInstances} instances, {ns} not shared, {na} without alternatives) done in {classify.ElapsedMilliseconds}ms (perInstanceAvg={(1.0 * classify.ElapsedMilliseconds) / (1.0 * numInstances)}ms)"); foreach (var kvp in instances) { var instance = kvp.Key; var predictedClasses = kvp.Value; var unique = new HashSet <string>(predictedClasses).Count; var real = predictedClasses.Count; if (unique != real) { Console.ForegroundColor = ConsoleColor.Yellow; } s_logger.Info($"queue={instance.QueueName}, count={real}, uniqueCount={unique}, alternatives=[{string.Join(",", predictedClasses)}]"); Console.ResetColor(); uniqueMachines.AddRange(predictedClasses); } foreach (var qq in classifier.AlternativesPerQueue()) { uniqueMachines.AddRange(qq.Value); } s_logger.Info($"totalMachinesAvailable={uniqueMachines.Count}, avg={(1.0 * uniqueMachines.Count) /(1.0 * classifier.AlternativesPerQueue().Count)} per queue"); }
public static float ApparelScoreRaw(Pawn pawn, Apparel ap) { float num = 0.1f + ap.def.apparel.scoreOffset; float num2 = ap.GetStatValue(StatDefOf.ArmorRating_Sharp) + ap.GetStatValue(StatDefOf.ArmorRating_Blunt) + ap.GetStatValue(StatDefOf.ArmorRating_Heat); num += num2; if (ap.def.useHitPoints) { float x = (float)ap.HitPoints / (float)ap.MaxHitPoints; num *= HitPointsPercentScoreFactorCurve.Evaluate(x); } num += ap.GetSpecialApparelScoreOffset(); float num3 = 1f; //if (neededWarmth == NeededWarmth.Warm) //{ // float statValue = ap.GetStatValue(StatDefOf.Insulation_Cold); // num3 *= InsulationColdScoreFactorCurve_NeedWarm.Evaluate(statValue); //} num *= num3; if (ap.WornByCorpse && (pawn == null || ThoughtUtility.CanGetThought(pawn, ThoughtDefOf.DeadMansApparel, checkIfNullified: true))) { num -= 0.5f; if (num > 0f) { num *= 0.1f; } } if (ap.Stuff == ThingDefOf.Human.race.leatherDef) { if (pawn == null || ThoughtUtility.CanGetThought(pawn, ThoughtDefOf.HumanLeatherApparelSad, checkIfNullified: true)) { num -= 0.5f; if (num > 0f) { num *= 0.1f; } } if (pawn != null && ThoughtUtility.CanGetThought(pawn, ThoughtDefOf.HumanLeatherApparelHappy, checkIfNullified: true)) { num += 0.12f; } } if (pawn != null && !ap.def.apparel.CorrectGenderForWearing(pawn.gender)) { num *= 0.01f; } if (pawn != null && pawn.royalty != null && pawn.royalty.AllTitlesInEffectForReading.Count > 0) { tmpAllowedApparels.Clear(); tmpRequiredApparels.Clear(); tmpBodyPartGroupsWithRequirement.Clear(); QualityCategory qualityCategory = QualityCategory.Awful; foreach (RoyalTitle item in pawn.royalty.AllTitlesInEffectForReading) { if (item.def.requiredApparel != null) { for (int i = 0; i < item.def.requiredApparel.Count; i++) { tmpAllowedApparels.AddRange(item.def.requiredApparel[i].AllAllowedApparelForPawn(pawn, ignoreGender: false, includeWorn: true)); tmpRequiredApparels.AddRange(item.def.requiredApparel[i].AllRequiredApparelForPawn(pawn, ignoreGender: false, includeWorn: true)); tmpBodyPartGroupsWithRequirement.AddRange(item.def.requiredApparel[i].bodyPartGroupsMatchAny); } } if ((int)item.def.requiredMinimumApparelQuality > (int)qualityCategory) { qualityCategory = item.def.requiredMinimumApparelQuality; } } bool num4 = ap.def.apparel.bodyPartGroups.Any((BodyPartGroupDef bp) => tmpBodyPartGroupsWithRequirement.Contains(bp)); if (ap.TryGetQuality(out QualityCategory qc) && (int)qc < (int)qualityCategory) { num *= 0.25f; } if (num4) { foreach (ThingDef tmpRequiredApparel in tmpRequiredApparels) { tmpAllowedApparels.Remove(tmpRequiredApparel); } if (tmpAllowedApparels.Contains(ap.def)) { num *= 10f; } if (tmpRequiredApparels.Contains(ap.def)) { num *= 25f; } } } return(num); }
public virtual int DeleteHistoryEntries() { var count = 0; var idsToDelete = new HashSet <int>(); if (_commonSettings.Value.MaxScheduleHistoryAgeInDays > 0) { var earliestDate = DateTime.UtcNow.AddDays(-1 * _commonSettings.Value.MaxScheduleHistoryAgeInDays); var ids = _taskHistoryRepository.TableUntracked .Where(x => x.StartedOnUtc <= earliestDate && !x.IsRunning) .Select(x => x.Id) .ToList(); idsToDelete.AddRange(ids); } // We have to group by task otherwise we would only keep entries from very frequently executed tasks. if (_commonSettings.Value.MaxNumberOfScheduleHistoryEntries > 0) { var query = from th in _taskHistoryRepository.TableUntracked where !th.IsRunning group th by th.ScheduleTaskId into grp select grp .OrderByDescending(x => x.StartedOnUtc) .ThenByDescending(x => x.Id) .Skip(_commonSettings.Value.MaxNumberOfScheduleHistoryEntries) .Select(x => x.Id); var ids = query.SelectMany(x => x).ToList(); idsToDelete.AddRange(ids); } try { if (idsToDelete.Any()) { using (var scope = new DbContextScope(_taskHistoryRepository.Context, autoCommit: false)) { var pageIndex = 0; IPagedList <int> pagedIds = null; do { pagedIds = new PagedList <int>(idsToDelete, pageIndex++, 100); var entries = _taskHistoryRepository.Table .Where(x => pagedIds.Contains(x.Id)) .ToList(); entries.Each(x => DeleteHistoryEntry(x)); count += scope.Commit(); }while (pagedIds.HasNextPage); } } } catch (Exception ex) { Logger.Error(ex); } return(count); }
public CakeScript Generate(FileChange fileChange) { if (fileChange == null) { throw new ArgumentNullException(nameof(fileChange)); } // Make the script path absolute. var scriptPath = new FilePath(fileChange.FileName).MakeAbsolute(_environment); // Prepare the file changes _log.Verbose("Handling file change..."); HandleFileChange(scriptPath, fileChange); // Analyze the script file. _log.Verbose("Analyzing build script..."); var result = _analyzer.Analyze(scriptPath, new ScriptAnalyzerSettings { Mode = ScriptAnalyzerMode.Everything, }); // Install addins. foreach (var addin in result.Addins) { try { _log.Verbose("Installing addins..."); var addinReferences = _processor.InstallAddins(new[] { addin }, _addinRoot); foreach (var addinReference in addinReferences) { result.References.Add(addinReference.FullPath); } } catch (Exception e) { // Log and continue if it fails _log.Error(e); } } // Load all references. _log.Verbose("Adding references..."); var references = new HashSet <FilePath>( _scriptConventions .GetDefaultAssemblies(_environment.ApplicationRoot) .Union(_referenceAssemblyResolver.GetReferenceAssemblies()) .Select(a => FilePath.FromString(a.Location))); references.AddRange(result.References.Select(r => new FilePath(r))); // Find aliases _log.Verbose("Finding aliases..."); var aliases = new List <CakeScriptAlias>(); foreach (var reference in references) { if (_fileSystem.Exist(reference)) { aliases.AddRange(_aliasFinder.FindAliases(reference)); } } // Import all namespaces. _log.Verbose("Importing namespaces..."); var namespaces = new HashSet <string>(result.Namespaces, StringComparer.Ordinal); namespaces.AddRange(_scriptConventions.GetDefaultNamespaces()); namespaces.AddRange(aliases.SelectMany(alias => alias.Namespaces)); // Create the response. // ReSharper disable once UseObjectOrCollectionInitializer _log.Verbose("Creating response..."); var response = new CakeScript(); response.Host.TypeName = _hostObject.TypeName; response.Host.AssemblyPath = _hostObject.AssemblyPath; response.Source = string.Join("\n", result.Defines) + string.Join("\n", result.UsingAliases) + string.Join("\n", result.UsingStaticDirectives) + GenerateSource(aliases) + string.Join("\n", result.Lines); response.Usings.AddRange(namespaces); response.References.AddRange(references.Select(r => r.FullPath)); // Return the response. return(response); }
public async Task <IActionResult> AddSector(OrganisationViewModel model) { //Ensure user has completed the registration process var checkResult = await CheckUserRegisteredOkAsync(); if (checkResult != null) { return(checkResult); } //Make sure we can load employers from session var m = UnstashModel <OrganisationViewModel>(); if (m == null) { return(View("CustomError", WebService.ErrorViewModelFactory.Create(1112))); } model.Employers = m.Employers; model.ManualEmployers = m.ManualEmployers; //Exclude the organisation details var excludes = new HashSet <string>(); excludes.AddRange( nameof(model.OrganisationName), nameof(model.CompanyNumber), nameof(model.CharityNumber), nameof(model.MutualNumber), nameof(model.OtherName), nameof(model.OtherValue)); //Exclude the address details excludes.AddRange( nameof(model.Address1), nameof(model.Address2), nameof(model.Address3), nameof(model.City), nameof(model.County), nameof(model.Country), nameof(model.Postcode), nameof(model.PoBox)); //Exclude the contact details excludes.AddRange( nameof(model.ContactFirstName), nameof(model.ContactLastName), nameof(model.ContactJobTitle), nameof(model.ContactEmailAddress), nameof(model.ContactPhoneNumber)); //Exclude the SIC codes when public sector if (model.SectorType != SectorTypes.Private) { excludes.Add(nameof(model.SicCodeIds)); } //Exclude the SIC Codes excludes.Add(nameof(model.DUNSNumber)); //Check model is valid ModelState.Exclude(excludes.ToArray()); var codes = new SortedSet <int>(); if (!string.IsNullOrWhiteSpace(model.SicCodeIds)) { var separators = ";,: \n\r" + Environment.NewLine; if (!model.SicCodeIds.ContainsAll(Text.NumberChars + separators)) { ModelState.AddModelError("", "You have entered an invalid SIC code"); } else { foreach (var codeStr in model.SicCodeIds.SplitI(separators)) { var code = codeStr.ToInt32(); if (code == 0) { ModelState.AddModelError("", codeStr + " is not a recognised SIC code"); break; } if (codes.Contains(code)) { ModelState.AddModelError("", "Duplicate SIC code detected"); break; } var sic = SharedBusinessLogic.DataRepository.Get <SicCode>(code); if (sic == null || code == 1) { ModelState.AddModelError("", code + " is not a recognised SIC code"); break; } codes.Add(code); } } } if (!ModelState.IsValid) { this.CleanModelErrors <OrganisationViewModel>(); return(View("AddSector", model)); } model.SicSource = VirtualUser.EmailAddress; model.ConfirmReturnAction = nameof(AddSector); StashModel(model); return(RedirectToAction(nameof(ConfirmOrganisation))); }
private void AssignBestDrawPos(WorldFeature newFeature, List <int> tilesForTextDrawPosCalculation) { WorldGrid worldGrid = Find.WorldGrid; tmpEdgeTiles.Clear(); tmpTilesForTextDrawPosCalculationSet.Clear(); tmpTilesForTextDrawPosCalculationSet.AddRange(tilesForTextDrawPosCalculation); Vector3 zero = Vector3.zero; for (int i = 0; i < tilesForTextDrawPosCalculation.Count; i++) { int num = tilesForTextDrawPosCalculation[i]; zero += worldGrid.GetTileCenter(num); bool flag = worldGrid.IsOnEdge(num); if (!flag) { worldGrid.GetTileNeighbors(num, tmpNeighbors); for (int j = 0; j < tmpNeighbors.Count; j++) { if (!tmpTilesForTextDrawPosCalculationSet.Contains(tmpNeighbors[j])) { flag = true; break; } } } if (flag) { tmpEdgeTiles.Add(num); } } zero /= (float)tilesForTextDrawPosCalculation.Count; if (!tmpEdgeTiles.Any()) { tmpEdgeTiles.Add(tilesForTextDrawPosCalculation.RandomElement()); } int bestTileDist = 0; tmpTraversedTiles.Clear(); Find.WorldFloodFiller.FloodFill(-1, (int x) => tmpTilesForTextDrawPosCalculationSet.Contains(x), delegate(int tile, int traversalDist) { tmpTraversedTiles.Add(new Pair <int, int>(tile, traversalDist)); bestTileDist = traversalDist; return(false); }, int.MaxValue, tmpEdgeTiles); int num2 = -1; float num3 = -1f; for (int k = 0; k < tmpTraversedTiles.Count; k++) { if (tmpTraversedTiles[k].Second == bestTileDist) { float sqrMagnitude = (worldGrid.GetTileCenter(tmpTraversedTiles[k].First) - zero).sqrMagnitude; if (num2 == -1 || sqrMagnitude < num3) { num2 = tmpTraversedTiles[k].First; num3 = sqrMagnitude; } } } float maxDrawSizeInTiles = (float)bestTileDist * 2f * 1.2f; newFeature.drawCenter = worldGrid.GetTileCenter(num2); newFeature.maxDrawSizeInTiles = maxDrawSizeInTiles; }
/// <summary> /// Join faces that equally satisfy the predicate, to ease for the triangulator. /// If two faces share the same result on the predicate, they are joined /// </summary> public void SimplifyFaces(Func <Face, bool> predicate) { // Curiously, this code unmodified works with single edges // First, we are going to pass through all the edges to check which can be removed var edgesToRemove = new HashSet <Edge>(ReferenceEqualityComparer.Default); var facesToRemove = new HashSet <Face>(ReferenceEqualityComparer.Default); foreach (var edge in edges) { // If the edge's twin is already inserted, ignore it if (edgesToRemove.Contains(edge.Twin)) { continue; } // Else, add it if necessary if (predicate(edge.Face) == predicate(edge.Twin.Face)) { edgesToRemove.Add(edge); } } // Now, proceed to remove the edges foreach (var edge in edgesToRemove) { // Fix the links var ep = edge.Previous; var en = edge.Next; var etp = edge.Twin.Previous; var etn = edge.Twin.Next; if (ep != edge.Twin) { ep.Next = etn; etn.Previous = ep; } if (en != edge.Twin) { en.Previous = etp; etp.Next = en; } // Now, fix if necessary the contour lists // If they are on same face, necessarily they separate a single contour in two if (edge.Face == edge.Twin.Face) { var edgeSet = new HashSet <Edge>(ReferenceEqualityComparer.Default); if (en != edge.Twin) { edgeSet.AddRange(en.CyclicalSequence); } if (ep != edge.Twin) { edgeSet.AddRange(ep.CyclicalSequence); } edgeSet.Add(edge); edgeSet.Add(edge.Twin); // Remove the original contour edge.Face.Contours.RemoveAll(edgeSet.Contains); // And add the new contours // Account for "wedge" edges, if both contours are the same if (ep != edge.Twin) { edge.Face.Contours.Add(ep); } if (en != edge.Twin) { edge.Face.Contours.Add(en); } } // If they are on different faces, we need to join both faces' contours somewhat else { var e = ep != edge.Twin ? ep : en; // There is a single contour now var edgeSet = new HashSet <Edge>(ReferenceEqualityComparer.Default); edgeSet.AddRange(e.CyclicalSequence); edgeSet.Add(edge); edgeSet.Add(edge.Twin); // Remove the references to the possible new contour edge.Face.Contours.RemoveAll(edgeSet.Contains); edge.Twin.Face.Contours.RemoveAll(edgeSet.Contains); // Just make sure we don't trash the outer face by accident var keepFace = edge.Face; var removeFace = edge.Twin.Face; if (removeFace.IsOuterFace) { Swap(ref keepFace, ref removeFace); } // Now, join the contours, reassigning the face, and add the new joined one foreach (var contour in removeFace.Contours) { keepFace.Contours.Add(contour); AssignFace(keepFace, contour); } keepFace.Contours.Add(e); AssignFace(keepFace, e); // And trash one of the faces facesToRemove.Add(removeFace); } } // Now, we remove the faces and the edges edges.RemoveAll(e => edgesToRemove.Contains(e) || edgesToRemove.Contains(e.Twin)); faces.RemoveAll(facesToRemove.Contains); }
protected override async Task FixAllAsync( Document document, ImmutableArray <Diagnostic> diagnostics, SyntaxEditor editor, CodeActionOptionsProvider fallbackOptions, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var nodesFromDiagnostics = new List <( LocalDeclarationStatementSyntax declaration, AnonymousFunctionExpressionSyntax function, List <ExpressionSyntax> references)>(diagnostics.Length); var nodesToTrack = new HashSet <SyntaxNode>(); foreach (var diagnostic in diagnostics) { var localDeclaration = (LocalDeclarationStatementSyntax)diagnostic.AdditionalLocations[0].FindNode(cancellationToken); var anonymousFunction = (AnonymousFunctionExpressionSyntax)diagnostic.AdditionalLocations[1].FindNode(cancellationToken); var references = new List <ExpressionSyntax>(diagnostic.AdditionalLocations.Count - 2); for (var i = 2; i < diagnostic.AdditionalLocations.Count; i++) { references.Add((ExpressionSyntax)diagnostic.AdditionalLocations[i].FindNode(getInnermostNodeForTie: true, cancellationToken)); } nodesFromDiagnostics.Add((localDeclaration, anonymousFunction, references)); nodesToTrack.Add(localDeclaration); nodesToTrack.Add(anonymousFunction); nodesToTrack.AddRange(references); } var root = editor.OriginalRoot; var currentRoot = root.TrackNodes(nodesToTrack); var languageVersion = semanticModel.SyntaxTree.Options.LanguageVersion(); bool makeStaticIfPossible; if (languageVersion >= LanguageVersion.CSharp8) { var options = (CSharpCodeGenerationOptions)await document.GetCodeGenerationOptionsAsync(fallbackOptions, cancellationToken).ConfigureAwait(false); makeStaticIfPossible = options.PreferStaticLocalFunction.Value; } else { makeStaticIfPossible = false; } // Process declarations in reverse order so that we see the effects of nested // declarations befor processing the outer decls. foreach (var(localDeclaration, anonymousFunction, references) in nodesFromDiagnostics.OrderByDescending(nodes => nodes.function.SpanStart)) { var delegateType = (INamedTypeSymbol)semanticModel.GetTypeInfo(anonymousFunction, cancellationToken).ConvertedType; var parameterList = GenerateParameterList(anonymousFunction, delegateType.DelegateInvokeMethod); var makeStatic = MakeStatic(semanticModel, makeStaticIfPossible, localDeclaration, cancellationToken); var currentLocalDeclaration = currentRoot.GetCurrentNode(localDeclaration); var currentAnonymousFunction = currentRoot.GetCurrentNode(anonymousFunction); currentRoot = ReplaceAnonymousWithLocalFunction( document.Project.Solution.Workspace.Services, currentRoot, currentLocalDeclaration, currentAnonymousFunction, delegateType.DelegateInvokeMethod, parameterList, makeStatic); // these invocations might actually be inside the local function! so we have to do this separately currentRoot = ReplaceReferences( document, currentRoot, delegateType, parameterList, references.Select(node => currentRoot.GetCurrentNode(node)).ToImmutableArray()); } editor.ReplaceNode(root, currentRoot); }
public async Task <InvoiceEntity> CreateInvoiceAsync(string storeId, InvoiceEntity invoice, string[] additionalSearchTerms = null) { var textSearch = new HashSet <string>(); invoice = Clone(invoice); invoice.Networks = _btcPayNetworkProvider; invoice.Id = Encoders.Base58.EncodeData(RandomUtils.GetBytes(16)); #pragma warning disable CS0618 invoice.Payments = new List <PaymentEntity>(); #pragma warning restore CS0618 invoice.StoreId = storeId; using (var context = _applicationDbContextFactory.CreateContext()) { var invoiceData = new Data.InvoiceData() { StoreDataId = storeId, Id = invoice.Id, Created = invoice.InvoiceTime, Blob = ToBytes(invoice, null), OrderId = invoice.Metadata.OrderId, #pragma warning disable CS0618 // Type or member is obsolete Status = invoice.StatusString, #pragma warning restore CS0618 // Type or member is obsolete ItemCode = invoice.Metadata.ItemCode, CustomerEmail = invoice.RefundMail, Archived = false }; await context.Invoices.AddAsync(invoiceData); foreach (var paymentMethod in invoice.GetPaymentMethods()) { if (paymentMethod.Network == null) { throw new InvalidOperationException("CryptoCode unsupported"); } var details = paymentMethod.GetPaymentMethodDetails(); if (!details.Activated) { continue; } var paymentDestination = details.GetPaymentDestination(); string address = GetDestination(paymentMethod); await context.AddressInvoices.AddAsync(new AddressInvoiceData() { InvoiceDataId = invoice.Id, CreatedTime = DateTimeOffset.UtcNow, }.Set(address, paymentMethod.GetId())); await context.HistoricalAddressInvoices.AddAsync(new HistoricalAddressInvoiceData() { InvoiceDataId = invoice.Id, Assigned = DateTimeOffset.UtcNow }.SetAddress(paymentDestination, paymentMethod.GetId().ToString())); textSearch.Add(paymentDestination); textSearch.Add(paymentMethod.Calculate().TotalDue.ToString()); } await context.PendingInvoices.AddAsync(new PendingInvoiceData() { Id = invoice.Id }); textSearch.Add(invoice.Id); textSearch.Add(invoice.InvoiceTime.ToString(CultureInfo.InvariantCulture)); if (!invoice.IsUnsetTopUp()) { textSearch.Add(invoice.Price.ToString(CultureInfo.InvariantCulture)); } textSearch.Add(invoice.Metadata.OrderId); textSearch.Add(invoice.StoreId); textSearch.Add(invoice.Metadata.BuyerEmail); if (additionalSearchTerms != null) { textSearch.AddRange(additionalSearchTerms); } AddToTextSearch(context, invoiceData, textSearch.ToArray()); await context.SaveChangesAsync().ConfigureAwait(false); } return(invoice); }
static void Execute(ILSpyTreeNode[] nodes) { if (!CanExecute(nodes)) { return; } var asmNodes = nodes.Select(a => (AssemblyTreeNode)a).ToArray(); var modNodes = new HashSet <AssemblyTreeNode>(asmNodes); modNodes.AddRange(asmNodes.SelectMany(a => !a.IsAssembly ? new AssemblyTreeNode[0] : a.Children.Cast <AssemblyTreeNode>())); if (!SaveModule.Saver.AskUserToSaveIfModified(modNodes)) { return; } var keepNodes = new List <AssemblyTreeNode>(); var freeNodes = new List <AssemblyTreeNode>(); var onlyInRedoHistory = new List <AssemblyTreeNode>(); foreach (var info in UndoCommandManager.Instance.GetUndoRedoInfo(asmNodes)) { if (!info.IsInUndo && !info.IsInRedo) { // This asm is safe to remove freeNodes.Add(info.Node); } else if (!info.IsInUndo && info.IsInRedo) { // If we add a RemoveAssemblyCommand, the redo history will be cleared, so this // assembly will be cleared from the history and don't need to be kept. onlyInRedoHistory.Add(info.Node); } else { // The asm is in the undo history, and maybe in the redo history. We must keep it. keepNodes.Add(info.Node); } } if (keepNodes.Count > 0 || onlyInRedoHistory.Count > 0) { // We can't free the asm since older commands might reference it so we must record // it in the history. The user can click Clear History to free everything. foreach (var node in keepNodes) { var mod = node.DnSpyFile.ModuleDef as ModuleDefMD; if (mod != null) { mod.MetaData.PEImage.UnsafeDisableMemoryMappedIO(); } } UndoCommandManager.Instance.Add(new RemoveAssemblyCommand(keepNodes.ToArray())); // Redo history was cleared FreeAssemblies(onlyInRedoHistory); } FreeAssemblies(freeNodes); if (freeNodes.Count > 0 || onlyInRedoHistory.Count > 0) { UndoCommandManager.Instance.CallGc(); } }
public static bool TryParseNode(Genero4glParser parser, out InputBlock node, IModuleResult containingModule, List <Func <PrepareStatement, bool> > prepStatementBinders, Func <ReturnStatement, ParserResult> returnStatementBinder = null, Action <IAnalysisResult, int, int> limitedScopeVariableAdder = null, List <TokenKind> validExitKeywords = null, IEnumerable <ContextStatementFactory> contextStatementFactories = null, HashSet <TokenKind> endKeywords = null) { node = null; bool result = false; if (parser.PeekToken(TokenKind.InputKeyword)) { result = true; node = new InputBlock(); parser.NextToken(); node.StartIndex = parser.Token.Span.Start; node.VariableList = new List <FglNameExpression>(); node.FieldList = new List <FglNameExpression>(); node.Attributes = new List <InputAttribute>(); if (parser.PeekToken(TokenKind.ByKeyword)) { parser.NextToken(); if (parser.PeekToken(TokenKind.NameKeyword)) { parser.NextToken(); // Implicit field mapping node.IsImplicitMapping = true; } else { parser.ReportSyntaxError("Expected \"name\" token in input statement."); } } else if (parser.PeekToken(TokenKind.ArrayKeyword)) { parser.NextToken(); node.IsArray = true; FglNameExpression arrName; if (FglNameExpression.TryParseNode(parser, out arrName)) { node.ArrayName = arrName; } else { parser.ReportSyntaxError("Invalid array name found in input statement."); } } node.DecoratorEnd = parser.Token.Span.End; FglNameExpression nameExpr; if (!node.IsArray) { // read the variable list while (FglNameExpression.TryParseNode(parser, out nameExpr)) { node.VariableList.Add(nameExpr); if (!parser.PeekToken(TokenKind.Comma)) { break; } parser.NextToken(); } } if (parser.PeekToken(TokenKind.WithoutKeyword)) { parser.NextToken(); if (parser.PeekToken(TokenKind.DefaultsKeyword)) { parser.NextToken(); } else { parser.ReportSyntaxError("Expected \"defaults\" token in input statement."); } } if (!node.IsImplicitMapping || node.IsArray) { if (parser.PeekToken(TokenKind.FromKeyword)) { parser.NextToken(); // read the field list while (FglNameExpression.TryParseNode(parser, out nameExpr)) { node.FieldList.Add(nameExpr); if (node.IsArray || !parser.PeekToken(TokenKind.Comma)) { break; } parser.NextToken(); } } else { parser.ReportSyntaxError("Expected \"from\" token in input statement."); } } if (parser.PeekToken(TokenKind.AttributesKeyword) || parser.PeekToken(TokenKind.AttributeKeyword)) { parser.NextToken(); if (parser.PeekToken(TokenKind.LeftParenthesis)) { parser.NextToken(); // get the list of display or control attributes InputAttribute attrib; while (InputAttribute.TryParseNode(parser, out attrib, node.IsArray)) { node.Attributes.Add(attrib); if (!parser.PeekToken(TokenKind.Comma)) { break; } parser.NextToken(); } if (parser.PeekToken(TokenKind.RightParenthesis)) { parser.NextToken(); } else { parser.ReportSyntaxError("Expecting right-paren in input attributes section."); } } else { parser.ReportSyntaxError("Expecting left-paren in input attributes section."); } } if (parser.PeekToken(TokenKind.HelpKeyword)) { parser.NextToken(); // get the help number ExpressionNode optionNumber; if (FglExpressionNode.TryGetExpressionNode(parser, out optionNumber)) { node.HelpNumber = optionNumber; } else { parser.ReportSyntaxError("Invalid help-number found in input statement."); } } List <TokenKind> validExits = new List <TokenKind>(); if (validExitKeywords != null) { validExits.AddRange(validExits); } validExits.Add(TokenKind.InputKeyword); HashSet <TokenKind> newEndKeywords = new HashSet <TokenKind>(); if (endKeywords != null) { newEndKeywords.AddRange(endKeywords); } newEndKeywords.Add(TokenKind.InputKeyword); bool hasControlBlocks = false; InputControlBlock icb; prepStatementBinders.Insert(0, node.BindPrepareCursorFromIdentifier); while (InputControlBlock.TryParseNode(parser, out icb, containingModule, hasControlBlocks, node.IsArray, prepStatementBinders, returnStatementBinder, limitedScopeVariableAdder, validExits, contextStatementFactories, newEndKeywords) && icb != null) { if (icb.StartIndex < 0) { continue; } node.Children.Add(icb.StartIndex, icb); hasControlBlocks = true; if (parser.PeekToken(TokenKind.EndOfFile) || (parser.PeekToken(TokenKind.EndKeyword) && parser.PeekToken(TokenKind.InputKeyword, 2))) { break; } } prepStatementBinders.RemoveAt(0); if (hasControlBlocks || (parser.PeekToken(TokenKind.EndKeyword) && parser.PeekToken(TokenKind.InputKeyword, 2))) { if (!(parser.PeekToken(TokenKind.EndKeyword) && parser.PeekToken(TokenKind.InputKeyword, 2))) { parser.ReportSyntaxError("A input block must be terminated with \"end input\"."); } else { parser.NextToken(); // advance to the 'end' token parser.NextToken(); // advance to the 'input' token node.EndIndex = parser.Token.Span.End; } } } return(result); }
public void AlignNodes(VseGraphView vseGraphView, bool follow, List <ISelectable> selection) { HashSet <INodeModel> topMostModels = new HashSet <INodeModel>(); topMostModels.Clear(); var selectedNodeModels = selection.OfType <Node>().Select(e => e.model); var nodeModelsFromSelectedEdges = selection.OfType <Edge>().SelectMany(e => e.model.GetPortModels().Select(p => p.NodeModel)); var affectedNodeModels = selectedNodeModels.Concat(nodeModelsFromSelectedEdges); foreach (INodeModel stackedNode in affectedNodeModels.Where(n => n.IsStacked)) { InitModelPositionFromUI(stackedNode); } bool anyEdge = false; foreach (Edge edge in selection.OfType <Edge>()) { if (!edge.GraphElementModel.GraphModel.Stencil.CreateDependencyFromEdge(edge.model, out LinkedNodesDependency dependency, out INodeModel parent)) { continue; } anyEdge = true; GraphElement element = vseGraphView.UIController.ModelsToNodeMapping[dependency.DependentNode]; AlignDependency(element, dependency, Vector2.zero, parent); topMostModels.Add(dependency.DependentNode); } if (anyEdge && !follow) { return; } if (!topMostModels.Any()) { foreach (GraphElement element in selection.OfType <GraphElement>()) { if (element is IHasGraphElementModel hasModel && hasModel.GraphElementModel is INodeModel nodeModel) { topMostModels.Add(nodeModel); } } } if (!anyEdge && !follow) { // Align each top-most node then move dependencies by the same delta foreach (INodeModel model in topMostModels) { if (!m_DependenciesByNode.TryGetValue(model.Guid, out Dictionary <GUID, IDependency> dependencies)) { continue; } foreach (KeyValuePair <GUID, IDependency> dependency in dependencies) { INodeModel dependentNode = dependency.Value.DependentNode; GraphElement element = vseGraphView.UIController.ModelsToNodeMapping[dependentNode]; Vector2 startPos = dependentNode.Position; AlignDependency(element, dependency.Value, Vector2.zero, model); Vector2 endPos = dependentNode.Position; Vector2 delta = endPos - startPos; OffsetNodeDependencies(dependentNode, delta); } } } else { // Align recursively m_ModelsToMove.AddRange(topMostModels); ProcessMovedNodes(Vector2.zero, AlignDependency); } m_ModelsToMove.Clear(); m_TempMovedModels.Clear(); }
private void MigrateConfig0_9(IUnitOfWork uow, BotConfig botConfig) { Config0_9 oldConfig; const string configPath = "data/config.json"; try { oldConfig = JsonConvert.DeserializeObject <Config0_9>(File.ReadAllText(configPath)); } catch (FileNotFoundException) { _log.Warn("config.json not found"); return; } catch (Exception) { _log.Error("Unknown error while deserializing file config.json, pls check its integrity, aborting migration"); throw new MigrationException(); } //Basic botConfig.ForwardMessages = oldConfig.ForwardMessages; botConfig.ForwardToAllOwners = oldConfig.ForwardToAllOwners; botConfig.BufferSize = (ulong)oldConfig.BufferSize; botConfig.RemindMessageFormat = oldConfig.RemindMessageFormat; botConfig.CurrencySign = oldConfig.CurrencySign; botConfig.CurrencyName = oldConfig.CurrencyName; botConfig.DMHelpString = oldConfig.DMHelpString; botConfig.HelpString = oldConfig.HelpString; //messages botConfig.RotatingStatuses = oldConfig.IsRotatingStatus; var messages = new List <PlayingStatus>(); oldConfig.RotatingStatuses.ForEach(i => messages.Add(new PlayingStatus { Status = i })); botConfig.RotatingStatusMessages = messages; //Prefix botConfig.ModulePrefixes.Clear(); botConfig.ModulePrefixes.AddRange(new HashSet <ModulePrefix> { new ModulePrefix() { ModuleName = "Administration", Prefix = oldConfig.CommandPrefixes.Administration }, new ModulePrefix() { ModuleName = "Searches", Prefix = oldConfig.CommandPrefixes.Searches }, new ModulePrefix() { ModuleName = "NSFW", Prefix = oldConfig.CommandPrefixes.NSFW }, new ModulePrefix() { ModuleName = "Conversations", Prefix = oldConfig.CommandPrefixes.Conversations }, new ModulePrefix() { ModuleName = "ClashOfClans", Prefix = oldConfig.CommandPrefixes.ClashOfClans }, new ModulePrefix() { ModuleName = "Help", Prefix = oldConfig.CommandPrefixes.Help }, new ModulePrefix() { ModuleName = "Music", Prefix = oldConfig.CommandPrefixes.Music }, new ModulePrefix() { ModuleName = "Trello", Prefix = oldConfig.CommandPrefixes.Trello }, new ModulePrefix() { ModuleName = "Games", Prefix = oldConfig.CommandPrefixes.Games }, new ModulePrefix() { ModuleName = "Gambling", Prefix = oldConfig.CommandPrefixes.Gambling }, new ModulePrefix() { ModuleName = "Permissions", Prefix = oldConfig.CommandPrefixes.Permissions }, new ModulePrefix() { ModuleName = "Programming", Prefix = oldConfig.CommandPrefixes.Programming }, new ModulePrefix() { ModuleName = "Pokemon", Prefix = oldConfig.CommandPrefixes.Pokemon }, new ModulePrefix() { ModuleName = "Utility", Prefix = oldConfig.CommandPrefixes.Utility } }); //Blacklist var blacklist = new HashSet <BlacklistItem>(oldConfig.ServerBlacklist.Select(server => new BlacklistItem() { ItemId = server, Type = BlacklistItem.BlacklistType.Server })); blacklist.AddRange(oldConfig.ChannelBlacklist.Select(channel => new BlacklistItem() { ItemId = channel, Type = BlacklistItem.BlacklistType.Channel })); blacklist.AddRange(oldConfig.UserBlacklist.Select(user => new BlacklistItem() { ItemId = user, Type = BlacklistItem.BlacklistType.User })); botConfig.Blacklist = blacklist; //Eightball botConfig.EightBallResponses = new HashSet <EightBallResponse>(oldConfig._8BallResponses.Select(response => new EightBallResponse() { Text = response })); //customreactions uow.CustomReactions.AddRange(oldConfig.CustomReactions.SelectMany(cr => { return(cr.Value.Select(res => new CustomReaction() { GuildId = null, IsRegex = false, OwnerOnly = false, Response = res, Trigger = cr.Key.ToLowerInvariant(), })); }).ToArray()); try { File.Move(configPath, "./data/DELETE_ME_config.json"); } catch { } }
private async Task <PluginPackage> GetLatestTemplatePackage(string packageId, string frameworkVersion, IAbsoluteDirectoryPath pluginRepositoryPath) { var nugetFramework = NuGetFramework.ParseFolder(frameworkVersion); ISettings settings = Settings.LoadSpecificSettings(root: null, this.appEnvironment.NuGetConfigFilePath.ToString()); var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(settings), Repository.Provider.GetCoreV3()); var packageMetaDataList = new List <PluginPackage>(); using (var cacheContext = new SourceCacheContext()) { IEnumerable <SourceRepository> repositories = sourceRepositoryProvider.GetRepositories(); var availablePackages = new HashSet <SourcePackageDependencyInfo>(PackageIdentityComparer.Default); foreach (SourceRepository sourceRepository in repositories) { DependencyInfoResource dependencyInfoResource = await sourceRepository.GetResourceAsync <DependencyInfoResource>().ConfigureAwait(false); IEnumerable <SourcePackageDependencyInfo> dependencyInfo = await dependencyInfoResource.ResolvePackages( packageId, nugetFramework, cacheContext, NullLogger.Instance, CancellationToken.None).ConfigureAwait(false); if (dependencyInfo == null) { continue; } availablePackages.AddRange(dependencyInfo); } var resolverContext = new PackageResolverContext( DependencyBehavior.Highest, new[] { packageId }, Enumerable.Empty <string>(), Enumerable.Empty <PackageReference>(), Enumerable.Empty <PackageIdentity>(), availablePackages, sourceRepositoryProvider.GetRepositories().Select(s => s.PackageSource), NullLogger.Instance); var resolver = new PackageResolver(); try { SourcePackageDependencyInfo packageToInstall = resolver .Resolve(resolverContext, CancellationToken.None).Select(p => availablePackages.Single(x => PackageIdentityComparer.Default.Equals(x, p))) .FirstOrDefault(); var packagePathResolver = new PackagePathResolver(SettingsUtility.GetGlobalPackagesFolder(settings)); var packageExtractionContext = new PackageExtractionContext( PackageSaveMode.Defaultv3, XmlDocFileSaveMode.None, ClientPolicyContext.GetClientPolicy(settings, NullLogger.Instance), NullLogger.Instance); var frameworkReducer = new FrameworkReducer(); string installedPath = packagePathResolver.GetInstalledPath(packageToInstall); PackageReaderBase packageReader; if (installedPath == null && packageToInstall != null) { DownloadResource downloadResource = await packageToInstall.Source .GetResourceAsync <DownloadResource>(CancellationToken.None).ConfigureAwait(false); DownloadResourceResult downloadResult = await downloadResource.GetDownloadResourceResultAsync( packageToInstall, new PackageDownloadContext(cacheContext), SettingsUtility.GetGlobalPackagesFolder(settings), NullLogger.Instance, CancellationToken.None).ConfigureAwait(false); await PackageExtractor.ExtractPackageAsync( downloadResult.PackageSource, downloadResult.PackageStream, packagePathResolver, packageExtractionContext, CancellationToken.None).ConfigureAwait(false); packageReader = downloadResult.PackageReader; } else { packageReader = new PackageFolderReader(installedPath); } PackageIdentity identity = await packageReader.GetIdentityAsync(CancellationToken.None).ConfigureAwait(false); var packageMetaData = new PluginPackage { Name = identity.Id, Version = identity.Version.OriginalVersion, RepositoryPath = pluginRepositoryPath, }; foreach (FrameworkSpecificGroup contentItem in await packageReader.GetContentItemsAsync(CancellationToken.None).ConfigureAwait(false)) { packageMetaData.Plugins.AddRange(contentItem.Items); } var packageFileExtractor = new PackageFileExtractor( packageMetaData.Plugins, XmlDocFileSaveMode.None); await packageReader.CopyFilesAsync( packageMetaData.PluginPath.ToString(), packageMetaData.Plugins, packageFileExtractor.ExtractPackageFile, NullLogger.Instance, CancellationToken.None).ConfigureAwait(false); foreach (IAbsoluteFilePath file in packageMetaData.PluginPath.GetChildDirectoryWithName("content").ChildrenFilesPath) { File.Copy(file.ToString(), Path.Join(packageMetaData.PluginPath.ToString(), file.FileName), overwrite: true); } packageMetaData.Plugins.Clear(); foreach (IAbsoluteFilePath file in packageMetaData.PluginPath.ChildrenFilesPath) { packageMetaData.Plugins.Add(file.GetRelativePathFrom(packageMetaData.PluginPath).ToString()); } Directory.Delete(packageMetaData.PluginPath.GetChildDirectoryWithName("content").ToString(), recursive: true); packageMetaDataList.Add(packageMetaData); } catch (NuGetResolverConstraintException exception) { string foo = exception.Message; } } return(packageMetaDataList.FirstOrDefault()); }
public async Task <ActionResult> Submit(CommentCommand dto) { var match = Regex.Match(dto.NickName + dto.Content, CommonHelper.BanRegex); if (match.Success) { LogManager.Info($"提交内容:{dto.NickName}/{dto.Content},敏感词:{match.Value}"); return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!")); } Post post = await PostService.GetByIdAsync(dto.PostId) ?? throw new NotFoundException("评论失败,文章未找到"); if (post.DisableComment) { return(ResultData(null, false, "本文已禁用评论功能,不允许任何人回复!")); } dto.Content = dto.Content.Trim().Replace("<p><br></p>", string.Empty); if (dto.Content.RemoveHtmlTag().Trim().Equals(HttpContext.Session.Get <string>("comment" + dto.PostId))) { return(ResultData(null, false, "您刚才已经在这篇文章发表过一次评论了,换一篇文章吧,或者换一下评论内容吧!")); } var comment = dto.Mapper <Comment>(); if (Regex.Match(dto.NickName + dto.Content, CommonHelper.ModRegex).Length <= 0) { comment.Status = Status.Published; } comment.CommentDate = DateTime.Now; var user = HttpContext.Session.Get <UserInfoDto>(SessionKey.UserInfo); if (user != null) { comment.NickName = user.NickName; comment.QQorWechat = user.QQorWechat; comment.Email = user.Email; if (user.IsAdmin) { comment.Status = Status.Published; comment.IsMaster = true; } } comment.Content = dto.Content.HtmlSantinizerStandard().ClearImgAttributes(); comment.Browser = dto.Browser ?? Request.Headers[HeaderNames.UserAgent]; comment.IP = ClientIP; comment.Location = comment.IP.GetIPLocation(); comment = CommentService.AddEntitySaved(comment); if (comment == null) { return(ResultData(null, false, "评论失败")); } HttpContext.Session.Set("comment" + comment.PostId, comment.Content.RemoveHtmlTag().Trim()); var emails = new HashSet <string>(); var email = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱 emails.Add(email); var content = new Template(await System.IO.File.ReadAllTextAsync(HostEnvironment.WebRootPath + "/template/notify.html")) .Set("title", post.Title) .Set("time", DateTime.Now.ToTimeZoneF(HttpContext.Session.Get <string>(SessionKey.TimeZone))) .Set("nickname", comment.NickName) .Set("content", comment.Content); if (comment.Status == Status.Published) { if (!comment.IsMaster) { await MessageService.AddEntitySavedAsync(new InternalMessage() { Title = $"来自【{comment.NickName}】的新文章评论", Content = comment.Content, Link = Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment" }); } #if !DEBUG if (comment.ParentId == 0) { emails.Add(post.Email); emails.Add(post.ModifierEmail); //新评论,只通知博主和楼主 foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论:", content.Set("link", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment").Render(false), s)); } } else { //通知博主和上层所有关联的评论访客 var pid = CommentService.GetParentCommentIdByChildId(comment.Id); emails.AddRange(CommentService.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).ToArray()); emails.AddRange(post.Email, post.ModifierEmail); emails.Remove(comment.Email); string link = Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment"; foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{Request.Host}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Set("link", link).Render(false), s)); } } #endif return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中")); } foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(Request.Host + "|博客文章新评论(待审核):", content.Set("link", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment").Render(false) + "<p style='color:red;'>(待审核)</p>", s)); } return(ResultData(null, true, "评论成功,待站长审核通过以后将显示")); }
/// <inheritdoc /> public async Task <IProjectTree> BuildTreeAsync( IProjectTree dependenciesTree, DependenciesSnapshot snapshot, CancellationToken cancellationToken = default) { // Keep a reference to the original tree to return in case we are cancelled. IProjectTree originalTree = dependenciesTree; bool hasSingleTarget = snapshot.DependenciesByTargetFramework.Count(x => !x.Key.Equals(TargetFramework.Any)) == 1; var currentTopLevelNodes = new HashSet <IProjectTree>(); if (hasSingleTarget) { await BuildSingleTargetTreeAsync(); } else { await BuildMultiTargetTreeAsync(); } if (cancellationToken.IsCancellationRequested) { return(originalTree); } dependenciesTree = CleanupOldNodes(dependenciesTree, currentTopLevelNodes); ProjectImageMoniker rootIcon = _viewModelFactory.GetDependenciesRootIcon(snapshot.HasReachableVisibleUnresolvedDependency).ToProjectSystemType(); return(dependenciesTree.SetProperties(icon: rootIcon, expandedIcon: rootIcon)); async Task BuildSingleTargetTreeAsync() { foreach ((ITargetFramework _, TargetedDependenciesSnapshot targetedSnapshot) in snapshot.DependenciesByTargetFramework) { if (cancellationToken.IsCancellationRequested) { return; } dependenciesTree = await BuildSubTreesAsync( rootNode : dependenciesTree, snapshot.ActiveTargetFramework, targetedSnapshot, RememberNewNodes); } } async Task BuildMultiTargetTreeAsync() { foreach ((ITargetFramework targetFramework, TargetedDependenciesSnapshot targetedSnapshot) in snapshot.DependenciesByTargetFramework) { if (cancellationToken.IsCancellationRequested) { return; } if (targetFramework.Equals(TargetFramework.Any)) { dependenciesTree = await BuildSubTreesAsync( rootNode : dependenciesTree, snapshot.ActiveTargetFramework, targetedSnapshot, RememberNewNodes); } else { IProjectTree? node = dependenciesTree.FindChildWithCaption(targetFramework.FriendlyName); bool shouldAddTargetNode = node == null; IDependencyViewModel targetViewModel = _viewModelFactory.CreateTargetViewModel(targetedSnapshot); node = CreateOrUpdateNode( node, targetViewModel, browseObjectProperties: null, isProjectItem: false, additionalFlags: ProjectTreeFlags.Create(ProjectTreeFlags.Common.BubbleUp)); node = await BuildSubTreesAsync( rootNode : node, snapshot.ActiveTargetFramework, targetedSnapshot, CleanupOldNodes); dependenciesTree = shouldAddTargetNode ? dependenciesTree.Add(node).Parent ! : node.Parent !; Assumes.NotNull(dependenciesTree); currentTopLevelNodes.Add(node); } } } IProjectTree RememberNewNodes(IProjectTree rootNode, IEnumerable <IProjectTree> currentNodes) { if (currentNodes != null) { currentTopLevelNodes.AddRange(currentNodes); } return(rootNode); } }
private static bool TryFindBestBillIngredients(Bill bill, Pawn pawn, Thing billGiver, List <ThingCount> chosen) { chosen.Clear(); newRelevantThings.Clear(); if (bill.recipe.ingredients.Count == 0) { return(true); } IntVec3 rootCell = GetBillGiverRootCell(billGiver, pawn); Region rootReg = rootCell.GetRegion(pawn.Map); if (rootReg == null) { return(false); } MakeIngredientsListInProcessingOrder(ingredientsOrdered, bill); relevantThings.Clear(); processedThings.Clear(); bool foundAll = false; Predicate <Thing> baseValidator = (Thing t) => t.Spawned && !t.IsForbidden(pawn) && (float)(t.Position - billGiver.Position).LengthHorizontalSquared < bill.ingredientSearchRadius * bill.ingredientSearchRadius && bill.IsFixedOrAllowedIngredient(t) && bill.recipe.ingredients.Any((IngredientCount ingNeed) => ingNeed.filter.Allows(t)) && pawn.CanReserve(t); bool billGiverIsPawn = billGiver is Pawn; if (billGiverIsPawn) { AddEveryMedicineToRelevantThings(pawn, billGiver, relevantThings, baseValidator, pawn.Map); if (TryFindBestBillIngredientsInSet(relevantThings, bill, chosen)) { relevantThings.Clear(); ingredientsOrdered.Clear(); return(true); } } TraverseParms traverseParams = TraverseParms.For(pawn); RegionEntryPredicate entryCondition = (Region from, Region r) => r.Allows(traverseParams, isDestination: false); int adjacentRegionsAvailable = rootReg.Neighbors.Count((Region region) => entryCondition(rootReg, region)); int regionsProcessed = 0; processedThings.AddRange(relevantThings); RegionProcessor regionProcessor = delegate(Region r) { List <Thing> list = r.ListerThings.ThingsMatching(ThingRequest.ForGroup(ThingRequestGroup.HaulableEver)); for (int i = 0; i < list.Count; i++) { Thing thing = list[i]; if (!processedThings.Contains(thing) && ReachabilityWithinRegion.ThingFromRegionListerReachable(thing, r, PathEndMode.ClosestTouch, pawn) && baseValidator(thing) && (!thing.def.IsMedicine || !billGiverIsPawn)) { newRelevantThings.Add(thing); processedThings.Add(thing); } } regionsProcessed++; if (newRelevantThings.Count > 0 && regionsProcessed > adjacentRegionsAvailable) { Comparison <Thing> comparison = delegate(Thing t1, Thing t2) { float num = (float)(t1.Position - rootCell).LengthHorizontalSquared; float value = (float)(t2.Position - rootCell).LengthHorizontalSquared; return(num.CompareTo(value)); }; newRelevantThings.Sort(comparison); relevantThings.AddRange(newRelevantThings); newRelevantThings.Clear(); if (TryFindBestBillIngredientsInSet(relevantThings, bill, chosen)) { foundAll = true; return(true); } } return(false); }; RegionTraverser.BreadthFirstTraverse(rootReg, entryCondition, regionProcessor, 99999); relevantThings.Clear(); newRelevantThings.Clear(); processedThings.Clear(); ingredientsOrdered.Clear(); return(foundAll); }
public ActionResult Put(CommentInputDto dto) { if (Regex.Match(dto.Content, CommonHelper.BanRegex).Length > 0) { return(ResultData(null, false, "您提交的内容包含敏感词,被禁止发表,请检查您的内容后尝试重新提交!")); } Post post = PostService.GetById(dto.PostId); if (post is null) { return(ResultData(null, false, "评论失败,文章不存在!")); } if (post.DisableComment) { return(ResultData(null, false, "本文已禁用评论功能,不允许任何人回复!")); } dto.Content = dto.Content.Trim().Replace("<p><br></p>", string.Empty); if (dto.Content.RemoveHtmlTag().Trim().Equals(HttpContext.Session.Get <string>("comment" + dto.PostId))) { return(ResultData(null, false, "您刚才已经在这篇文章发表过一次评论了,换一篇文章吧,或者换一下评论内容吧!")); } var comment = dto.Mapper <Comment>(); if (Regex.Match(dto.Content, CommonHelper.ModRegex).Length <= 0) { comment.Status = Status.Pended; } comment.CommentDate = DateTime.Now; var user = HttpContext.Session.Get <UserInfoOutputDto>(SessionKey.UserInfo); if (user != null) { comment.NickName = user.NickName; comment.QQorWechat = user.QQorWechat; comment.Email = user.Email; if (user.IsAdmin) { comment.Status = Status.Pended; comment.IsMaster = true; } } comment.Content = dto.Content.HtmlSantinizerStandard().ClearImgAttributes(); comment.Browser = dto.Browser ?? Request.Headers[HeaderNames.UserAgent]; comment.IP = ClientIP; comment.Location = comment.IP.GetIPLocation().Split("|").Where(s => !int.TryParse(s, out _)).ToHashSet().Join("|"); comment = CommentService.AddEntitySaved(comment); if (comment == null) { return(ResultData(null, false, "评论失败")); } HttpContext.Session.Set("comment" + comment.PostId, comment.Content.RemoveHtmlTag().Trim()); var emails = new HashSet <string>(); var email = CommonHelper.SystemSettings["ReceiveEmail"]; //站长邮箱 emails.Add(email); var content = System.IO.File.ReadAllText(HostEnvironment.WebRootPath + "/template/notify.html") .Replace("{{title}}", post.Title) .Replace("{{time}}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")) .Replace("{{nickname}}", comment.NickName) .Replace("{{content}}", comment.Content); if (comment.Status == Status.Pended) { if (!comment.IsMaster) { MessageService.AddEntitySaved(new InternalMessage() { Title = $"来自【{comment.NickName}】的新文章评论", Content = comment.Content, Link = Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment" }); } #if !DEBUG if (comment.ParentId == 0) { emails.Add(post.Email); emails.Add(post.ModifierEmail); //新评论,只通知博主和楼主 foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客文章新评论:", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment"), s)); } } else { //通知博主和上层所有关联的评论访客 var pid = CommentService.GetParentCommentIdByChildId(comment.Id); emails.AddRange(CommentService.GetSelfAndAllChildrenCommentsByParentId(pid).Select(c => c.Email).ToArray()); emails.AddRange(post.Email, post.ModifierEmail); emails.Remove(comment.Email); string link = Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment"; foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail($"{CommonHelper.SystemSettings["Domain"]}{CommonHelper.SystemSettings["Title"]}文章评论回复:", content.Replace("{{link}}", link), s)); } } #endif return(ResultData(null, true, "评论发表成功,服务器正在后台处理中,这会有一定的延迟,稍后将显示到评论列表中")); } foreach (var s in emails) { BackgroundJob.Enqueue(() => CommonHelper.SendMail(CommonHelper.SystemSettings["Domain"] + "|博客文章新评论(待审核):", content.Replace("{{link}}", Url.Action("Details", "Post", new { id = comment.PostId, cid = comment.Id }, Request.Scheme) + "#comment") + "<p style='color:red;'>(待审核)</p>", s)); } return(ResultData(null, true, "评论成功,待站长审核通过以后将显示")); }
/// <summary> /// Runs the script using the specified script host. /// </summary> /// <param name="host">The script host.</param> /// <param name="scriptPath">The script.</param> /// <param name="arguments">The arguments.</param> public void Run(IScriptHost host, FilePath scriptPath, IDictionary <string, string> arguments) { if (host == null) { throw new ArgumentNullException(nameof(host)); } if (scriptPath == null) { throw new ArgumentNullException(nameof(scriptPath)); } if (arguments == null) { throw new ArgumentNullException(nameof(arguments)); } // Make the script path absolute. scriptPath = scriptPath.MakeAbsolute(_environment); // Prepare the environment. _environment.WorkingDirectory = scriptPath.GetDirectory(); // Analyze the script file. _log.Verbose("Analyzing build script..."); var result = _analyzer.Analyze(scriptPath.GetFilename()); // Log all errors and throw if (!result.Succeeded) { foreach (var error in result.Errors) { var format = $"{error.File.MakeAbsolute(_environment).FullPath}:{error.Line}: {{0}}"; _log.Error(format, error.Message); } throw new CakeException("Errors occurred while analyzing script."); } // Install tools. _log.Verbose("Processing build script..."); var toolsPath = GetToolPath(scriptPath.GetDirectory()); _processor.InstallTools(result.Tools, toolsPath); // Install addins. var addinRoot = GetAddinPath(scriptPath.GetDirectory()); var addinReferences = _processor.InstallAddins(result.Addins, addinRoot); foreach (var addinReference in addinReferences) { result.References.Add(addinReference.FullPath); } // Create and prepare the session. var session = _engine.CreateSession(host); // Load all references. var applicationRoot = _environment.ApplicationRoot; var assemblies = new HashSet <Assembly>(); assemblies.AddRange(_conventions.GetDefaultAssemblies(applicationRoot)); foreach (var reference in result.References) { var referencePath = new FilePath(reference); if (host.Context.FileSystem.Exist(referencePath)) { var assembly = _assemblyLoader.Load(referencePath, true); assemblies.Add(assembly); } else { // Add a reference to the session. session.AddReference(referencePath); } } var aliases = new List <ScriptAlias>(); // Got any assemblies? if (assemblies.Count > 0) { // Find all script aliases. var foundAliases = _aliasFinder.FindAliases(assemblies); if (foundAliases.Count > 0) { aliases.AddRange(foundAliases); } // Add assembly references to the session. foreach (var assembly in assemblies) { session.AddReference(assembly); } } // Import all namespaces. var namespaces = new HashSet <string>(result.Namespaces, StringComparer.Ordinal); namespaces.AddRange(_conventions.GetDefaultNamespaces()); namespaces.AddRange(aliases.SelectMany(alias => alias.Namespaces)); foreach (var @namespace in namespaces.OrderBy(ns => ns)) { session.ImportNamespace(@namespace); } var defines = new HashSet <string>(result.Defines, StringComparer.Ordinal); defines.AddRange(_conventions.GetDefaultDefines()); // Execute the script. var script = new Script(result.Namespaces, result.Lines, aliases, result.UsingAliases, result.UsingStaticDirectives, defines); session.Execute(script); }
public async Task <IActionResult> AddContact(OrganisationViewModel model) { //Ensure user has completed the registration process var checkResult = await CheckUserRegisteredOkAsync(); if (checkResult != null) { return(checkResult); } //Make sure we can load employers from session var m = UnstashModel <OrganisationViewModel>(); if (m == null) { return(View("CustomError", WebService.ErrorViewModelFactory.Create(1112))); } model.Employers = m.Employers; model.ManualEmployers = m.ManualEmployers; //Exclude the organisation details var excludes = new HashSet <string>(); excludes.AddRange( nameof(model.OrganisationName), nameof(model.CompanyNumber), nameof(model.CharityNumber), nameof(model.MutualNumber), nameof(model.OtherName), nameof(model.OtherValue)); //Exclude the address details excludes.AddRange( nameof(model.Address1), nameof(model.Address2), nameof(model.Address3), nameof(model.City), nameof(model.County), nameof(model.Country), nameof(model.Postcode), nameof(model.PoBox)); //Exclude the search excludes.AddRange(nameof(model.SearchText)); //Exclude the SIC Codes excludes.Add(nameof(model.SicCodeIds)); //Exclude the SIC Codes excludes.Add(nameof(model.DUNSNumber)); //Check model is valid ModelState.Exclude(excludes.ToArray()); if (!ModelState.IsValid) { this.CleanModelErrors <OrganisationViewModel>(); return(View("AddContact", model)); } //Whenever doing a manual address change redirect to confirm page if (model.ManualAddress) { if (string.IsNullOrWhiteSpace(model.ConfirmReturnAction)) { model.ConfirmReturnAction = nameof(AddContact); } StashModel(model); return(RedirectToAction(nameof(ConfirmOrganisation))); } StashModel(model); return(RedirectToAction("AddSector")); }
private async Task <RestoreSummary> PerformNuGetV2RestoreAsync(PackageRestoreInputs packageRestoreInputs) { ReadSettings(packageRestoreInputs); var packagesFolderPath = GetPackagesFolder(packageRestoreInputs); var sourceRepositoryProvider = new CommandLineSourceRepositoryProvider(SourceProvider); var nuGetPackageManager = new NuGetPackageManager(sourceRepositoryProvider, Settings, packagesFolderPath); var installedPackageReferences = new HashSet <Packaging.PackageReference>(new PackageReferenceComparer()); if (packageRestoreInputs.RestoringWithSolutionFile) { installedPackageReferences.AddRange(packageRestoreInputs .PackagesConfigFiles .SelectMany(file => GetInstalledPackageReferences(file, allowDuplicatePackageIds: true))); } else if (packageRestoreInputs.PackagesConfigFiles.Count > 0) { // By default the PackageReferenceFile does not throw // if the file does not exist at the specified path. // So we'll need to verify that the file exists. Debug.Assert(packageRestoreInputs.PackagesConfigFiles.Count == 1, "Only one packages.config file is allowed to be specified " + "at a time when not performing solution restore."); var packageReferenceFile = packageRestoreInputs.PackagesConfigFiles[0]; if (!File.Exists(packageReferenceFile)) { var message = string.Format( CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("RestoreCommandFileNotFound"), packageReferenceFile); throw new InvalidOperationException(message); } installedPackageReferences.AddRange( GetInstalledPackageReferences(packageReferenceFile, allowDuplicatePackageIds: true)); } // EffectivePackageSaveMode is None when -PackageSaveMode is not provided by the user. None is treated as // Defaultv3 for V3 restore and should be treated as Defaultv2 for V2 restore. This is the case in the // actual V2 restore flow and should match in this preliminary missing packages check. var packageSaveMode = EffectivePackageSaveMode == Packaging.PackageSaveMode.None ? Packaging.PackageSaveMode.Defaultv2 : EffectivePackageSaveMode; var missingPackageReferences = installedPackageReferences.Where(reference => !nuGetPackageManager.PackageExistsInPackagesFolder(reference.PackageIdentity, packageSaveMode)).ToArray(); if (missingPackageReferences.Length == 0) { var message = string.Format( CultureInfo.CurrentCulture, LocalizedResourceManager.GetString("InstallCommandNothingToInstall"), "packages.config"); Console.LogMinimal(message); return(new RestoreSummary(true)); } var packageRestoreData = missingPackageReferences.Select(reference => new PackageRestoreData( reference, new[] { packageRestoreInputs.RestoringWithSolutionFile ? packageRestoreInputs.DirectoryOfSolutionFile : packageRestoreInputs.PackagesConfigFiles[0] }, isMissing: true)); var packageSources = GetPackageSources(Settings); var repositories = packageSources .Select(sourceRepositoryProvider.CreateRepository) .ToArray(); var installCount = 0; var failedEvents = new ConcurrentQueue <PackageRestoreFailedEventArgs>(); var packageRestoreContext = new PackageRestoreContext( nuGetPackageManager, packageRestoreData, CancellationToken.None, packageRestoredEvent: (sender, args) => { Interlocked.Add(ref installCount, args.Restored ? 1 : 0); }, packageRestoreFailedEvent: (sender, args) => { failedEvents.Enqueue(args); }, sourceRepositories: repositories, maxNumberOfParallelTasks: DisableParallelProcessing ? 1 : PackageManagementConstants.DefaultMaxDegreeOfParallelism); CheckRequireConsent(); var collectorLogger = new CollectorLogger(Console); var projectContext = new ConsoleProjectContext(collectorLogger) { PackageExtractionContext = new PackageExtractionContext(collectorLogger) }; if (EffectivePackageSaveMode != Packaging.PackageSaveMode.None) { projectContext.PackageExtractionContext.PackageSaveMode = EffectivePackageSaveMode; } using (var cacheContext = new SourceCacheContext()) { cacheContext.NoCache = NoCache; cacheContext.DirectDownload = DirectDownload; var downloadContext = new PackageDownloadContext(cacheContext, packagesFolderPath, DirectDownload); var result = await PackageRestoreManager.RestoreMissingPackagesAsync( packageRestoreContext, projectContext, downloadContext); if (downloadContext.DirectDownload) { GetDownloadResultUtility.CleanUpDirectDownloads(downloadContext); } return(new RestoreSummary( result.Restored, "packages.config projects", Settings.Priority.Select(x => Path.Combine(x.Root, x.FileName)), packageSources.Select(x => x.Source), installCount, collectorLogger.Errors.Concat(failedEvents.Select(e => e.Exception.Message)))); } }
public async Task <IActionResult> AddAddress(OrganisationViewModel model) { //Ensure user has completed the registration process var checkResult = await CheckUserRegisteredOkAsync(); if (checkResult != null) { return(checkResult); } //Make sure we can load employers from session var m = UnstashModel <OrganisationViewModel>(); if (m == null) { return(View("CustomError", WebService.ErrorViewModelFactory.Create(1112))); } model.Employers = m.Employers; model.ManualEmployers = m.ManualEmployers; //Exclude the contact details var excludes = new HashSet <string>(); excludes.AddRange( nameof(model.ContactFirstName), nameof(model.ContactLastName), nameof(model.ContactJobTitle), nameof(model.ContactEmailAddress), nameof(model.ContactPhoneNumber)); //Exclude the organisation details excludes.AddRange( nameof(model.OrganisationName), nameof(model.CompanyNumber), nameof(model.CharityNumber), nameof(model.MutualNumber), nameof(model.OtherName), nameof(model.OtherValue)); //Exclude the search excludes.AddRange(nameof(model.SearchText)); //Exclude the SIC Codes excludes.Add(nameof(model.SicCodeIds)); //Exclude the SIC Codes excludes.Add(nameof(model.DUNSNumber)); //Check model is valid ModelState.Exclude(excludes.ToArray()); if (!ModelState.IsValid) { this.CleanModelErrors <OrganisationViewModel>(); return(View(nameof(AddAddress), model)); } var sector = model.SectorType; var authorised = false; EmployerRecord employer = null; if (!model.ManualRegistration) { employer = model.GetManualEmployer(); if (employer != null) { authorised = model.ManualAuthorised; } else { employer = model.GetSelectedEmployer(); authorised = model.SelectedAuthorised; } } //Set the address source to the user or original source if unchanged if (employer != null && model.GetAddressModel().Equals(employer.GetAddressModel())) { model.AddressSource = employer.AddressSource; } else { model.AddressSource = VirtualUser.EmailAddress; } if (model.WrongAddress) { model.ManualAddress = true; } //When doing manual address only and user is already authorised redirect to confirm page if (model.ManualAddress && sector == SectorTypes.Public && authorised && !employer.HasAnyAddress()) { //We don't need contact info if there is no address only when there is an address model.ConfirmReturnAction = nameof(AddAddress); StashModel(model); return(RedirectToAction(nameof(ConfirmOrganisation))); } //When manual registration StashModel(model); return(RedirectToAction("AddContact")); }