public override void _Backward(INode fromNode, IGraphData errorSignal, IContext context, IReadOnlyList <INode> parents) { Debug.Assert(_source._children.Contains(fromNode)); _signalTable[fromNode] = errorSignal; if (_signalTable.All(s => s.Value != null) && parents?.Any() == true) { var firstSignal = _signalTable[_source._children.First()]; var otherSignals = _signalTable .Where(s => s.Value != firstSignal && s.Value.Columns == firstSignal.Columns && s.Value.Rows == firstSignal.Rows) .ToList() ; if (otherSignals.Any()) { var matrix = firstSignal.GetMatrix(); foreach (var item in otherSignals) { matrix.AddInPlace(item.Value.GetMatrix()); } firstSignal = firstSignal.ReplaceWith(matrix); } foreach (var parent in parents) { context.AddBackward(firstSignal, parent, _source); } _source._onBackpropagation?.Invoke(_signalTable); } }
public IBusControl CreateServiceBus(MassTransitOptions options, IReadOnlyList<Action<IReceiveEndpointConfigurator>> commandSubscriptions, IReadOnlyList<Action<IReceiveEndpointConfigurator>> eventSubscriptions) { return Bus.Factory.CreateUsingInMemory(cfg => { cfg.UseJsonSerializer(); cfg.UseConcurrencyLimit(options.ConcurrencyLimit); if (commandSubscriptions.Any()) { cfg.ReceiveEndpoint(options.CommandQueueNameStrategy.GetQueueName(), endpoint => { endpoint.UseRetry(options.CommandErrorPolicy); foreach (var subscription in commandSubscriptions) subscription(endpoint); }); } if (eventSubscriptions.Any()) { cfg.ReceiveEndpoint(options.EventQueueNameStrategy.GetQueueName(), endpoint => { endpoint.UseRetry(options.EventErrorPolicy); foreach (var subscription in eventSubscriptions) subscription(endpoint); }); } }); }
public override async Task <IEnumerable <Models.Geoposition> > CalculateRoute(Models.Geoposition from, Models.Geoposition to) { Geopoint nativeFrom = CoordinateConverter.ConvertToNative(from); Geopoint nativeTo = CoordinateConverter.ConvertToNative(to); MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteAsync( nativeFrom, nativeTo, MapRouteOptimization.Time, MapRouteRestrictions.None); List <Models.Geoposition> result = new List <Models.Geoposition>(); IReadOnlyList <BasicGeoposition> routePositions = routeResult?.Route?.Path?.Positions; if (routePositions?.Any() == true) { foreach (BasicGeoposition position in routePositions) { result.Add(new Models.Geoposition { Latitude = position.Latitude, Longitude = position.Longitude }); } } return(result); }
public void Load(IReadOnlyList <string> args) { try { if (args?.Any() != true) { return; } string exportPath = Path.Combine("F:", "Projects", "Progamming", "utinyTest", "Ripped"); PrepareExportDirectory(exportPath); var exportSttings = new ExportSettings { ExportScripts = false, GUIDByContent = true, ExportDir = exportPath, GameDir = args.First(), DumpInfo = true, ScriptByName = false, ShaderByName = true, ShaderExportMode = ShaderExportMode.Asm, CondenseShaderSubprograms = true, }; GameStructureExporter.ExportGameStructure(exportSttings); Logger.Log(LogType.Info, LogCategory.General, "Finished"); } catch (Exception ex) { Logger.Log(LogType.Error, LogCategory.General, ex.ToString()); } }
public Observation(IReadOnlyList<int> currentQuoteCount, DateTime date) { if (currentQuoteCount == null) throw new ArgumentNullException("quoteCount"); if (!currentQuoteCount.Any()) throw new ArgumentException("Collection must containt at least one item."); this.CurrentQuoteCount = currentQuoteCount; this.Date = date; }
/// <summary> /// Sends a backpropagation signal further up the graph /// </summary> /// <param name="errorSignal">The backpropagating error</param> /// <param name="context">Graph context</param> /// <param name="parents">Parents of the current node</param> protected void _SendErrorTo(IGraphData errorSignal, IContext context, IReadOnlyList <INode> parents) { if (parents?.Any() == true) { foreach (var parent in parents) { context.AddBackward(errorSignal, parent, _source); } } }
public override void OnExtractionSuccess(string filePath, IReadOnlyList<Directory> directories, string relativePath, TextWriter log) { base.OnExtractionSuccess(filePath, directories, relativePath, log); try { using (var writer = OpenWriter(filePath)) { try { // Write any errors if (directories.Any(d => d.HasError)) { foreach (var directory in directories) { if (!directory.HasError) continue; foreach (var error in directory.Errors) writer.Write("[ERROR: {0}] {1}\n", directory.Name, error); } writer.Write('\n'); } // Write tag values for each directory foreach (var directory in directories) { var directoryName = directory.Name; foreach (var tag in directory.Tags) { var tagName = tag.TagName; var description = tag.Description; if (directory is FileMetadataDirectory && tag.TagType == FileMetadataDirectory.TagFileModifiedDate) description = "<omitted for regression testing as checkout dependent>"; writer.Write("[{0} - 0x{1:x4}] {2} = {3}\n", directoryName, tag.TagType, tagName, description); } if (directory.TagCount != 0) writer.Write('\n'); } } finally { writer.Write("Generated using metadata-extractor\n"); writer.Write("https://drewnoakes.com/code/exif/\n"); } } } catch (Exception e) { log.Write("Exception after extraction: {0}\n", e.Message); } }
public static IReadOnlyList<string> GetStringContents(string textBeforeCollapse, string textAfterCollapse, IReadOnlyList<string> collapsedContent) { var contents = new List<string> { textBeforeCollapse + (collapsedContent.Any() ? collapsedContent[0] : string.Empty) }; contents.AddRange(from text in collapsedContent.Skip(1).Take(collapsedContent.Count - 1) select text); contents[contents.Count - 1] += textAfterCollapse; return contents; }
public void CalculateWeights(IReadOnlyList <BuildingDto> buildings, string originalSearchQuery, IReadOnlyList <string> separateSearchTerms) { if (!(buildings?.Any() ?? false)) { return; } foreach (var building in buildings) { var fullyMatchedProperties = CalculateFullMatch(building, originalSearchQuery); CalculatePartialMatches(building, separateSearchTerms, fullyMatchedProperties); } }
/// <summary> /// Default Constructor /// </summary> /// <param name="arguments">Arguments</param> public Parameters(IReadOnlyList<string> arguments) { if (null == arguments) { throw new ArgumentNullException("arguments"); } if (!arguments.Any() || arguments.Count() > 4) { throw new ArgumentException("Invalid parameter count."); } this.arguments = arguments; }
public void CalculateWeights(IReadOnlyList <GroupDto> groups, string originalSearchQuery, IReadOnlyList <string> separateSearchTerms) { if (!(groups?.Any() ?? false)) { return; } foreach (var groupDto in groups) { var fullyMatchedProperties = CalculateFullMatch(groupDto, originalSearchQuery); CalculatePartialMatches(groupDto, separateSearchTerms, fullyMatchedProperties); } }
/// <summary> /// Composes the given projection lambdas into a single projection which only references the /// necessary selected colums. Thus, if you have something like /// <code> /// query.Select(c => new { CompanyName = c.Company.Name, c.Name }) /// .Where(t => t.CompanyName != null >> t.CompanyName.Length > 0) /// .Select(t => t.Name); /// </code> /// we might naively generate a projection like c => new { CompanyName = c.Company.Name, c.Name }.Name. /// This will fail when executed, because we will not have selected any columns from Company. /// </summary> public static LambdaExpression CreateProjection(IReadOnlyList<LambdaExpression> projections) { Throw.If(projections.Count == 0, "projections: at least one projection is required"); Throw.If(projections.Any(e => e == null || e.Parameters.Count != 1), "projections: all expressions must be projections"); // first, create a composition of the lambdas with all parameters inlined var composedProjection = ComposeWithInlining(projections, indexToMerge: projections.Count - 1); // next, replace constructs like // x = new { a = p.Foo.Bar, b = 2 * p.Name.Length }.b with x = 2 * p.Name.Length var simplifiedProjection = (LambdaExpression)Visitor.Visit(composedProjection); return simplifiedProjection; }
public static void Save(string fileName, IReadOnlyList<Bookmark> bookmarks) { if (!bookmarks.Any()) { File.Delete(fileName); return; } var bookmarksFile = new BookmarksFile { Bookmarks = bookmarks.OrderBy(x => x.Time).ToList() }; using (var stream = new FileStream(fileName, FileMode.Create)) { Serializer.Serialize(stream, bookmarksFile); } }
private async Task <IReadOnlyList <VSInternalDiagnosticReport> > RemapDocumentDiagnosticsAsync( IReadOnlyList <VSInternalDiagnosticReport> unmappedDiagnosticReports, Uri razorDocumentUri, CancellationToken cancellationToken) { if (unmappedDiagnosticReports?.Any() != true) { return(unmappedDiagnosticReports); } var mappedDiagnosticReports = new List <VSInternalDiagnosticReport>(unmappedDiagnosticReports.Count); foreach (var diagnosticReport in unmappedDiagnosticReports) { // Check if there are any diagnostics in this report if (diagnosticReport?.Diagnostics?.Any() != true) { _logger.LogInformation("Diagnostic report contained no diagnostics."); mappedDiagnosticReports.Add(diagnosticReport); continue; } _logger.LogInformation($"Requesting processing of {diagnosticReport.Diagnostics.Length} diagnostics."); var processedDiagnostics = await _diagnosticsProvider.TranslateAsync( RazorLanguageKind.CSharp, razorDocumentUri, diagnosticReport.Diagnostics, cancellationToken ).ConfigureAwait(false); if (!_documentManager.TryGetDocument(razorDocumentUri, out var documentSnapshot) || documentSnapshot.Version != processedDiagnostics.HostDocumentVersion) { _logger.LogInformation($"Document version mismatch, discarding {diagnosticReport.Diagnostics.Length} diagnostics."); // We choose to discard diagnostics in this case & report nothing changed. diagnosticReport.Diagnostics = null; mappedDiagnosticReports.Add(diagnosticReport); continue; } _logger.LogInformation($"Returning {processedDiagnostics.Diagnostics.Length} diagnostics."); diagnosticReport.Diagnostics = processedDiagnostics.Diagnostics; mappedDiagnosticReports.Add(diagnosticReport); } return(mappedDiagnosticReports.ToArray()); }
public void CalculateWeights(IReadOnlyList <MediumDto> mediums, IReadOnlyList <GroupDto> groups, string originalSearchTerms, IReadOnlyList <string> separateSearchTerms) { if (!(mediums?.Any() ?? false)) { return; } foreach (var mediumDto in mediums) { var fullyMatchedProperties = CalculateFullMatch(mediumDto, originalSearchTerms); CalculatePartialMatches(mediumDto, separateSearchTerms, fullyMatchedProperties); CalculateTypeWeight(mediumDto, separateSearchTerms); mediumDto.Weight += groups.FirstOrDefault(x => x.Id == mediumDto.GroupId)?.TransitoryWeight ?? 0; } }
public void CalculateWeights(IReadOnlyList <LockDto> locks, IReadOnlyList <BuildingDto> buildings, string originalSearchTerms, IReadOnlyList <string> separateSearchTerms) { if (!(locks?.Any() ?? false)) { return; } foreach (var lockDto in locks) { var fullyMatchedProperties = CalculateFullMatch(lockDto, originalSearchTerms); CalculateTypeWeight(lockDto, separateSearchTerms); CalculatePartialMatches(lockDto, separateSearchTerms, fullyMatchedProperties); lockDto.Weight += buildings.SingleOrDefault(x => x.Id == lockDto.BuildingId)?.TransitoryWeight ?? 0; } }
protected virtual Uri PickNewServer(Uri lastServer, IReadOnlyList<Uri> serverPool) { if (!serverPool.Any()) { throw new NoServersAvailableException(); } if (serverPool.Count == 1) { return serverPool[0]; } if (lastServer != null) { serverPool = serverPool.Except(new[] { lastServer }).ToList(); } if (!serverPool.Any()) { if (lastServer == null) { throw new NoServersAvailableException(); } return lastServer; } if (serverPool.Count == 1) { return serverPool[0]; } _server++; int index = _server; return serverPool[index % serverPool.Count]; }
private static IReadOnlyList<Issue> FilterByKompetenz(IReadOnlyList<Issue> issues, IReadOnlyList<string> kompetenzen) { if (!kompetenzen.Any()) { return issues; } issues = issues .Where(i => i.Kompetenzen .Select(x => x.ToLowerInvariant()) .Intersect( kompetenzen.Select(x => x.ToLowerInvariant())) .Any()) .ToList(); return issues; }
private static void InvokeCallbackCommand( OpenFileInteraction openFile, IReadOnlyList<IFile> files ) { Contract.Requires( openFile != null ); Contract.Requires( files != null ); if ( files.Any() ) { // set file and execute accept openFile.Files.ReplaceAll( files ); openFile.ExecuteDefaultCommand(); } else { // execute cancel openFile.ExecuteCancelCommand(); } }
private static bool IsTransformRequired( string propertyName, DisplayMetadata modelMetadata, IReadOnlyList<object> propertyAttributes) { if (!string.IsNullOrEmpty(modelMetadata.SimpleDisplayProperty)) { return false; } if (propertyAttributes.Any(a => a is DisplayAttribute)) { return false; } return !string.IsNullOrEmpty(propertyName); }
private IReadOnlyDictionary<int, string> CharacterEntered(IReadOnlyList<string> lines, string text, TextPosition startingTextPosition) { var currentTextLine = new StringBuilder(); if (lines.Any()) { if (startingTextPosition.Column >= lines[startingTextPosition.Line].Length) { currentTextLine.Append(lines[startingTextPosition.Line]).Append(text); } else { currentTextLine.Append(lines[startingTextPosition.Line]).Insert(startingTextPosition.Column, text); } } else { currentTextLine.Append(text); } return new Dictionary<int, string> { [startingTextPosition.Line] = currentTextLine.ToString() }; }
public virtual void OnExtractionSuccess(string filePath, IReadOnlyList<Directory> directories, string relativePath, TextWriter log) { if (!directories.Any(d => d.HasError)) return; log.WriteLine(filePath); foreach (var directory in directories) { if (!directory.HasError) continue; foreach (var error in directory.Errors) { log.Write("\t[{0}] {1}\n", directory.Name, error); _errorCount++; } } }
public static async Task <ContentSearchResult> GetRandomContentsAsync(IPictureparkService client, string searchString, int limit, IReadOnlyList <ContentType> contentTypes = null) { var request = new ContentSearchRequest { SearchString = searchString, Limit = limit }; if (contentTypes?.Any() == true) { request.Filter = new TermsFilter { Field = nameof(ContentDetail.ContentType).ToLowerCamelCase(), Terms = contentTypes.Select(ct => ct.ToString()).ToArray() }; } return(await client.Content.SearchAsync(request)); }
/// <summary> /// Called when backpropagating /// </summary> /// <param name="fromNode">The node that sent the backpropagation signal</param> /// <param name="errorSignal">The backpropagating error</param> /// <param name="context">Graph context</param> /// <param name="parents">Parents of the current node</param> public void Backward(INode fromNode, IGraphData errorSignal, IContext context, IReadOnlyList <INode> parents) { if (errorSignal == null) { if (parents?.Any() == true) { foreach (var parent in parents) { context.AddBackward(errorSignal, parent, _source); } } } else { _Backward(fromNode, errorSignal, context, parents); } }
public override async Task <IEnumerable <Position> > CalculateRoute(RouteModel route) { Geopoint nativeFrom = CoordinateConverter.ConvertToNative(route.From); Geopoint nativeTo = CoordinateConverter.ConvertToNative(route.To); // add route starts List <Geopoint> routeWaypoints = new List <Geopoint>() { nativeFrom }; // add route waypoints if any if (route.WayPoints != null && route.WayPoints.Any()) { foreach (var point in route.WayPoints) { routeWaypoints.Add(CoordinateConverter.ConvertToNative(point)); } } // add route ends routeWaypoints.Add(nativeTo); MapRouteFinderResult routeResult = await MapRouteFinder.GetDrivingRouteFromWaypointsAsync( routeWaypoints, MapRouteOptimization.Time, MapRouteRestrictions.None); List <Position> result = new List <Position>(); IReadOnlyList <BasicGeoposition> routePositions = routeResult?.Route?.Path?.Positions; route.Distance = routeResult?.Route?.LengthInMeters ?? 0; route.Duration = routeResult?.Route?.EstimatedDuration.TotalMinutes ?? 0; if (routePositions?.Any() == true) { foreach (BasicGeoposition position in routePositions) { result.Add(new Position(position.Latitude, position.Longitude)); } } return(result); }
public LiquidRenderer(string tag, IReadOnlyList<Category> categories, IEnumerable<Issue> issues) { if (categories == null || !categories.Any()) categories = Defaults.Categories; var issuesVariable = categories.ToDictionary( cat => cat.Id, cat => issues.Where(issue => issue.Labels.Any(label => label.MatchesAny(cat.Labels))) .Select(issue => new IssueDrop(issue, cat.Labels))); var categoriesVariable = categories.Select(category => new CategoryDrop(category.Id, category.Title, issuesVariable.ContainsKey(category.Id) && issuesVariable[category.Id].Any())); _variables = new Hash { {"tag", tag}, {"categories", categoriesVariable}, {"issues", issuesVariable} }; }
public static IEnumerable <T> SortDynamically <T>(this IEnumerable <T> items, IReadOnlyList <ISortOrderField> sortArgs) { if (items == null || !items.Any()) { return(new List <T>()); } if (sortArgs?.Any() == false) { return(items); } //Map the Sort by property string names to actual Property Descriptors //for dynamic processing... var propCollection = TypeDescriptor.GetProperties(typeof(T)); var sortGetters = sortArgs?.Select(s => new { SortArg = s, Getter = propCollection.Find(s.FieldName, true) }); IOrderedEnumerable <T> orderedItems = null; foreach (var sort in sortGetters) { if (orderedItems == null) { orderedItems = sort.SortArg.IsAscending() ? items.OrderBy(c => sort.Getter.GetValue(c)) : items.OrderByDescending(c => sort.Getter.GetValue(c)); } else { orderedItems = sort.SortArg.IsAscending() ? orderedItems.ThenBy(c => sort.Getter.GetValue(c)) : orderedItems.ThenByDescending(c => sort.Getter.GetValue(c)); } } //NOTE: To Finish the sorting, we materialize the Results! return(orderedItems?.ToList() ?? items); }
public IReadOnlyList <GroupDto> Search(string originalSearchQuery, IReadOnlyList <string> searchTerms) { if (!(searchTerms?.Any() ?? false)) { return(new List <GroupDto>()); } var groupEntities = _groupRepository.GetGroupsMatchingTerms(searchTerms); if (!groupEntities.Any()) { return(new List <GroupDto>()); } var groupDtos = groupEntities.Select(ToGroupDto).ToList(); _groupWeightCalculator.CalculateWeights(groupDtos, originalSearchQuery, searchTerms); return(groupDtos); }
public override void ApplyState() { base.ApplyState(); shader = Source.shader; texture = Source.texture; drawSize = Source.DrawSize; points = Source.ResampledWaveform?.GetPoints(); channels = Source.ResampledWaveform?.GetChannels() ?? 0; lowColour = Source.lowColour ?? DrawColourInfo.Colour; midColour = Source.midColour ?? DrawColourInfo.Colour; highColour = Source.highColour ?? DrawColourInfo.Colour; if (points?.Any() == true) { highMax = points.Max(p => p.HighIntensity); midMax = points.Max(p => p.MidIntensity); lowMax = points.Max(p => p.LowIntensity); } }
public IReadOnlyList <BuildingDto> Search(string originalSearchQuery, IReadOnlyList <string> searchTerms) { if (!(searchTerms?.Any() ?? false)) { return(new List <BuildingDto>()); } var buildingEntities = _buildingRepository.GetBuildingsMatchingTerms(searchTerms); if (!buildingEntities.Any()) { return(new List <BuildingDto>()); } var buildingDtos = buildingEntities.Select(ToBuildingDto).ToList(); _buildingWeightCalculator.CalculateWeights(buildingDtos, originalSearchQuery, searchTerms); return(buildingDtos); }
public IBusControl CreateServiceBus(MassTransitOptions options, IReadOnlyList<Action<IReceiveEndpointConfigurator>> commandSubscriptions, IReadOnlyList<Action<IReceiveEndpointConfigurator>> eventSubscriptions) { var bus = Bus.Factory.CreateUsingRabbitMq(cfg => { var host = cfg.Host(_connectionDescriptor.Host, h => { h.Username(_connectionDescriptor.UserName); h.Password(_connectionDescriptor.Password); }); cfg.UseJsonSerializer(); cfg.UseConcurrencyLimit(options.ConcurrencyLimit); if (commandSubscriptions.Any()) { cfg.ReceiveEndpoint(host, options.CommandQueueNameStrategy.GetQueueName(), endpoint => { endpoint.UseRetry(options.CommandErrorPolicy); _rabbitMqOptions.CommandQueuePolicy.ApplyPolicy(endpoint); foreach (var subscription in commandSubscriptions) subscription(endpoint); }); } if (eventSubscriptions.Any()) { cfg.ReceiveEndpoint(host, options.EventQueueNameStrategy.GetQueueName(), endpoint => { endpoint.UseRetry(options.EventErrorPolicy); _rabbitMqOptions.EventQueuePolicy.ApplyPolicy(endpoint); foreach (var subscription in eventSubscriptions) subscription(endpoint); }); } }); return bus; }
public async Task <bool> DeleteNotes(IReadOnlyList <long> noteIds) { if (noteIds?.Any() == false) { throw new ArgumentNullException(nameof(noteIds)); } var notes = await _context .Notes .Where(n => noteIds !.Contains(n.Id)) .ToListAsync(); if (notes?.Any() == false) { return(false); } _context.Notes.RemoveRange(notes); return(await _context.SaveChangesAsync() > 0); }
/// <summary> /// The viewmodel for the song metadata editor. /// </summary> /// <param name="songs">The metadata for the songs to edit.</param> /// <param name="multipleSongSaveWarning"> /// A warning that is displayed when an attempt is made to save the metadata for more than /// one song. /// </param> public TagEditorViewModel(IReadOnlyList<LocalSong> songs, Func<Task<bool>> multipleSongSaveWarning) { if (songs == null) throw new ArgumentNullException("songs"); if (!songs.Any()) throw new ArgumentException("Tag editor requires at least 1 song"); this.songs = songs; this.Save = ReactiveCommand.CreateAsyncTask(async _ => { bool shouldSave = true; if (songs.Count > 1) { shouldSave = await multipleSongSaveWarning(); } if (shouldSave) { await this.SaveTags(); } }); this.isSaving = this.Save.IsExecuting .ToProperty(this, x => x.IsSaving); this.DismissFailure = ReactiveCommand.Create(); this.saveFailed = this.Save.ThrownExceptions.Select(_ => true) .Merge(this.DismissFailure.Select(_ => false)) .ToProperty(this, x => x.SaveFailed); this.Cancel = ReactiveCommand.Create(); this.Finished = this.Save.Merge(this.Cancel.ToUnit()) .FirstAsync() .PublishLast() .PermaRef(); }
public IReadOnlyList <LockDto> Search(string originalSearchQuery, IReadOnlyList <string> searchTerms, IReadOnlyList <BuildingDto> buildings) { if (string.IsNullOrWhiteSpace(originalSearchQuery) || !(searchTerms?.Any() ?? false)) { return(new List <LockDto>()); } var maybeLockTypes = TryGetLockTypesOnSearchTerms(searchTerms); var lockEntities = _lockRepository.GetLocksMatchingTerms(searchTerms, maybeLockTypes); if (!lockEntities.Any()) { return(new List <LockDto>()); } var lockDtos = lockEntities.Select(ToLockDto).ToList(); _lockWeightCalculator.CalculateWeights(lockDtos, buildings, originalSearchQuery, searchTerms); return(lockDtos); }
public IReadOnlyList <MediumDto> Search(string originalSearchQuery, IReadOnlyList <string> searchTerms, IReadOnlyList <GroupDto> groups) { if (!(searchTerms?.Any() ?? false)) { return(new List <MediumDto>()); } var maybeMediumTypes = TryGetMediumTypesOnSearchTerms(searchTerms); var mediumEntities = _mediumRepository.GetMediumsMatchingTerms(searchTerms, maybeMediumTypes); if (!mediumEntities.Any()) { return(new List <MediumDto>()); } var mediumDtos = mediumEntities.Select(ToMediumDto).ToList(); _mediumWeightCalculator.CalculateWeights(mediumDtos, groups, originalSearchQuery, searchTerms); return(mediumDtos); }
public async void ContinueFileOpenPicker(IReadOnlyList<StorageFile> files) { if (files == null || !files.Any()) return; IsLoading = true; using (var stream = (FileRandomAccessStream)await files[0].OpenAsync(FileAccessMode.Read)) { var newImageBytes = new byte[stream.Size]; using (var dataReader = new DataReader(stream)) { await dataReader.LoadAsync((uint)stream.Size); dataReader.ReadBytes(newImageBytes); } var contentHelper = new ContentClientHelper(QuickbloxClient); var blobUploadInfo = await contentHelper.UploadImage(newImageBytes, false); if (blobUploadInfo != null) { SendAttachment(blobUploadInfo); } } IsLoading = false; }
private static Uri AsRelativeUri(this string @this, IReadOnlyList<string> queryParameters) => queryParameters.Any() ? AsRelativeUri(@this + (@this.Contains("?") ? "&" : "?") + string.Join("&", queryParameters)) : AsRelativeUri(@this);
private bool IsTypeExcludedFromValidation(IReadOnlyList<IExcludeTypeValidationFilter> filters, Type type) { // This can be set to null in ModelBinding scenarios which does not flow through this path. if (filters == null) { return false; } return filters.Any(filter => filter.IsTypeExcluded(type)); }
/// <summary> /// Returns a string representation of the settings. /// </summary> /// <returns>A string representation of the settings.</returns> public override string ToString() { if (_isFrozen) { return(_frozenStringRepresentation); } var sb = new StringBuilder(); if (_applicationName != null) { sb.AppendFormat("ApplicationName={0};", _applicationName); } if (_autoEncryptionOptions != null) { sb.AppendFormat("AutoEncryptionOptions={0};", _autoEncryptionOptions); } if (_compressors?.Any() ?? false) { sb.AppendFormat("Compressors=[{0}];", string.Join(",", _compressors)); } sb.AppendFormat("ConnectionMode={0};", _connectionMode); sb.AppendFormat("ConnectTimeout={0};", _connectTimeout); sb.AppendFormat("Credentials={{{0}}};", _credentials); sb.AppendFormat("GuidRepresentation={0};", _guidRepresentation); sb.AppendFormat("HeartbeatInterval={0};", _heartbeatInterval); sb.AppendFormat("HeartbeatTimeout={0};", _heartbeatTimeout); sb.AppendFormat("IPv6={0};", _ipv6); sb.AppendFormat("MaxConnectionIdleTime={0};", _maxConnectionIdleTime); sb.AppendFormat("MaxConnectionLifeTime={0};", _maxConnectionLifeTime); sb.AppendFormat("MaxConnectionPoolSize={0};", _maxConnectionPoolSize); sb.AppendFormat("MinConnectionPoolSize={0};", _minConnectionPoolSize); if (_readEncoding != null) { sb.Append("ReadEncoding=UTF8Encoding;"); } sb.AppendFormat("ReadConcern={0};", _readConcern); sb.AppendFormat("ReadPreference={0};", _readPreference); sb.AppendFormat("ReplicaSetName={0};", _replicaSetName); sb.AppendFormat("RetryReads={0}", _retryReads); sb.AppendFormat("RetryWrites={0}", _retryWrites); sb.AppendFormat("LocalThreshold={0};", _localThreshold); if (_scheme != ConnectionStringScheme.MongoDB) { sb.AppendFormat("Scheme={0};", _scheme); } if (_sdamLogFilename != null) { sb.AppendFormat("SDAMLogFileName={0};", _sdamLogFilename); } sb.AppendFormat("Servers={0};", string.Join(",", _servers.Select(s => s.ToString()).ToArray())); sb.AppendFormat("ServerSelectionTimeout={0};", _serverSelectionTimeout); sb.AppendFormat("SocketTimeout={0};", _socketTimeout); if (_sslSettings != null) { sb.AppendFormat("SslSettings={0};", _sslSettings); } sb.AppendFormat("Tls={0};", _useTls); sb.AppendFormat("TlsInsecure={0};", _allowInsecureTls); sb.AppendFormat("WaitQueueSize={0};", _waitQueueSize); sb.AppendFormat("WaitQueueTimeout={0}", _waitQueueTimeout); sb.AppendFormat("WriteConcern={0};", _writeConcern); if (_writeEncoding != null) { sb.Append("WriteEncoding=UTF8Encoding;"); } return(sb.ToString()); }
public async Task<IReadOnlyList<TenantResource>> FindTenants(IReadOnlyList<string> tenantNames, IReadOnlyList<string> tenantTags) { if (!tenantNames.Any() && !tenantTags.Any()) { return new List<TenantResource>(0); } if (!repository.SupportsTenants()) { throw new CommandException( "Your Octopus server does not support tenants, which was introduced in Octopus 3.4. Please upgrade your Octopus server, enable the multi-tenancy feature or remove the --tenant and --tenanttag arguments."); } var tenantsByName = FindTenantsByName(tenantNames).ConfigureAwait(false); var tenantsByTags = FindTenantsByTags(tenantTags).ConfigureAwait(false); var distinctTenants = (await tenantsByTags) .Concat(await tenantsByName) .GroupBy(t => t.Id) .Select(g => g.First()) .ToList(); return distinctTenants; }
private bool CanSaveCurrentSearch() => _currentSearchTags?.Any() == true;
public void MainMethodCode() { // Opening a Non-Versioned SQL Server instance. DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. Instance = @"testMachine\testInstance", // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. Database = "LocalGovernment", // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. User = "******", Password = "******", Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) using (RelationshipClass relationshipClass = geodatabase.OpenDataset <RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections")) using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.luCodeViolation")) using (Table inspectionTable = geodatabase.OpenDataset <Table>("LocalGovernment.GDB.luCodeInspection")) { List <Row> jeffersonAveViolations = new List <Row>(); QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '///%Jefferson///%'" }; // If you need to *cache* the rows retrieved from the cursor for processing later, it is important that you don't use recycling in // the Search() method (i.e., useRecyclingCursor must be set to *false*). Also, the returned rows/features cached in the list // should be disposed when no longer in use so that unmanaged resources are not held on to longer than necessary. using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { jeffersonAveViolations.Add(rowCursor.Current); } } IReadOnlyList <Row> relatedOriginRows = null; IReadOnlyList <Row> relatedDestinationRows = null; try { QueryFilter filter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" }; Selection selection = inspectionTable.Select(filter, SelectionType.ObjectID, SelectionOption.Normal); relatedOriginRows = relationshipClass.GetRowsRelatedToDestinationRows(selection.GetObjectIDs()); // Find out if any of 1st Notice inspections were from Jefferson Avenue. FeatureClassDefinition featureClassDefinition = violationsFeatureClass.GetDefinition(); int locationDescriptionIndex = featureClassDefinition.FindField("LOCDESC"); bool containsJeffersonAve = relatedOriginRows.Any(row => Convert.ToString(row[locationDescriptionIndex]).Contains("Jefferson")); List <long> jeffersonAveViolationObjectIds = jeffersonAveViolations.Select(row => row.GetObjectID()).ToList(); relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(jeffersonAveViolationObjectIds); //Find out if any Jefferson Ave Violations have 1st Notice Inspections TableDefinition tableDefinition = inspectionTable.GetDefinition(); int actionFieldIndex = tableDefinition.FindField("ACTION"); bool hasFirstNoticeInspections = relatedDestinationRows.Any(row => Convert.ToString(row[actionFieldIndex]).Contains("1st Notice")); } finally { Dispose(jeffersonAveViolations); Dispose(relatedOriginRows); Dispose(relatedDestinationRows); } } }
public bool Has <T>() => Chunks?.Any(x => x.GetType() == typeof(T)) ?? false;
/// <summary> /// Returns a string representation of the settings. /// </summary> /// <returns>A string representation of the settings.</returns> public override string ToString() { if (_isFrozen) { return(_frozenStringRepresentation); } var parts = new List <string>(); if (_applicationName != null) { parts.Add(string.Format("ApplicationName={0}", _applicationName)); } if (_compressors?.Any() ?? false) { parts.Add($"Compressors={string.Join(",", _compressors)}"); } parts.Add(string.Format("ConnectionMode={0}", _connectionMode)); parts.Add(string.Format("ConnectTimeout={0}", _connectTimeout)); parts.Add(string.Format("Credentials={{{0}}}", _credentials)); parts.Add(string.Format("GuidRepresentation={0}", _guidRepresentation)); parts.Add(string.Format("HeartbeatInterval={0}", _heartbeatInterval)); parts.Add(string.Format("HeartbeatTimeout={0}", _heartbeatTimeout)); parts.Add(string.Format("IPv6={0}", _ipv6)); parts.Add(string.Format("MaxConnectionIdleTime={0}", _maxConnectionIdleTime)); parts.Add(string.Format("MaxConnectionLifeTime={0}", _maxConnectionLifeTime)); parts.Add(string.Format("MaxConnectionPoolSize={0}", _maxConnectionPoolSize)); parts.Add(string.Format("MinConnectionPoolSize={0}", _minConnectionPoolSize)); parts.Add(string.Format("OperationTimeout={0}", _operationTimeout)); parts.Add(string.Format("ReadConcern={0}", _readConcern)); if (_readEncoding != null) { parts.Add("ReadEncoding=UTF8Encoding"); } parts.Add(string.Format("ReadPreference={0}", _readPreference)); parts.Add(string.Format("ReplicaSetName={0}", _replicaSetName)); parts.Add(string.Format("RetryReads={0}", _retryReads)); parts.Add(string.Format("RetryWrites={0}", _retryWrites)); parts.Add(string.Format("LocalThreshold={0}", _localThreshold)); if (_scheme != ConnectionStringScheme.MongoDB) { parts.Add(string.Format("Scheme={0}", _scheme)); } if (_sdamLogFilename != null) { parts.Add($"SDAMLogFilename={_sdamLogFilename}"); } parts.Add(string.Format("Servers={0}", string.Join(",", _servers.Select(s => s.ToString()).ToArray()))); parts.Add(string.Format("ServerSelectionTimeout={0}", _serverSelectionTimeout)); parts.Add(string.Format("SocketTimeout={0}", _socketTimeout)); if (_sslSettings != null) { parts.Add(string.Format("SslSettings={0}", _sslSettings)); } parts.Add(string.Format("Tls={0}", _useTls)); parts.Add(string.Format("TlsInsecure={0}", _allowInsecureTls)); parts.Add(string.Format("WaitQueueSize={0}", _waitQueueSize)); parts.Add(string.Format("WaitQueueTimeout={0}", _waitQueueTimeout)); parts.Add(string.Format("WriteConcern={0}", _writeConcern)); if (_writeEncoding != null) { parts.Add("WriteEncoding=UTF8Encoding"); } return(string.Join(",", parts.ToArray())); }
/// <summary> /// Returns the canonical URL based on the settings in this MongoUrlBuilder. /// </summary> /// <returns>The canonical URL.</returns> public override string ToString() { StringBuilder url = new StringBuilder(); if (_scheme == ConnectionStringScheme.MongoDB) { url.Append("mongodb://"); } else { url.Append("mongodb+srv://"); } if (!string.IsNullOrEmpty(_username)) { url.Append(Uri.EscapeDataString(_username)); if (_password != null) { url.AppendFormat(":{0}", Uri.EscapeDataString(_password)); } url.Append("@"); } else if (_password != null) { // this would be weird and we really shouldn't be here... url.AppendFormat(":{0}@", _password); } if (_servers != null) { bool firstServer = true; foreach (MongoServerAddress server in _servers) { if (!firstServer) { url.Append(","); } if (server.Port == 27017 || _scheme == ConnectionStringScheme.MongoDBPlusSrv) { url.Append(server.Host); } else { url.AppendFormat("{0}:{1}", server.Host, server.Port); } firstServer = false; } } if (_databaseName != null) { url.Append("/"); url.Append(_databaseName); } var query = new StringBuilder(); if (_authenticationMechanism != null) { query.AppendFormat("authMechanism={0};", _authenticationMechanism); } if (_authenticationMechanismProperties.Any()) { query.AppendFormat( "authMechanismProperties={0};", string.Join(",", _authenticationMechanismProperties .Select(x => string.Format("{0}:{1}", x.Key, x.Value)).ToArray())); } if (_authenticationSource != null) { query.AppendFormat("authSource={0};", _authenticationSource); } if (_applicationName != null) { query.AppendFormat("appname={0};", _applicationName); } if (_ipv6) { query.AppendFormat("ipv6=true;"); } if (_scheme == ConnectionStringScheme.MongoDBPlusSrv) { if (!_useSsl) { query.AppendFormat("ssl=false;"); } } else { if (_useSsl) { query.AppendFormat("ssl=true;"); } } if (!_verifySslCertificate) { query.AppendFormat("sslVerifyCertificate=false;"); } if (_compressors?.Any() ?? false) { query.AppendFormat("compressors={0};", string.Join(",", _compressors.Select(x => x.Type.ToString().ToLowerInvariant()))); foreach (var compressor in _compressors) { ParseAndAppendCompressorOptions(query, compressor); } } if (_connectionMode != ConnectionMode.Automatic) { query.AppendFormat("connect={0};", MongoUtils.ToCamelCase(_connectionMode.ToString())); } if (!string.IsNullOrEmpty(_replicaSetName)) { query.AppendFormat("replicaSet={0};", _replicaSetName); } if (_readConcernLevel != null) { query.AppendFormat("readConcernLevel={0};", MongoUtils.ToCamelCase(_readConcernLevel.Value.ToString())); } if (_readPreference != null) { query.AppendFormat("readPreference={0};", MongoUtils.ToCamelCase(_readPreference.ReadPreferenceMode.ToString())); if (_readPreference.TagSets != null) { foreach (var tagSet in _readPreference.TagSets) { query.AppendFormat("readPreferenceTags={0};", string.Join(",", tagSet.Tags.Select(t => string.Format("{0}:{1}", t.Name, t.Value)).ToArray())); } } if (_readPreference.MaxStaleness.HasValue) { query.AppendFormat("maxStaleness={0};", FormatTimeSpan(_readPreference.MaxStaleness.Value)); } } if (_fsync != null) { query.AppendFormat("fsync={0};", JsonConvert.ToString(_fsync.Value)); } if (_journal != null) { query.AppendFormat("journal={0};", JsonConvert.ToString(_journal.Value)); } if (_w != null) { query.AppendFormat("w={0};", _w); } if (_wTimeout != null) { query.AppendFormat("wtimeout={0};", FormatTimeSpan(_wTimeout.Value)); } if (_connectTimeout != MongoDefaults.ConnectTimeout) { query.AppendFormat("connectTimeout={0};", FormatTimeSpan(_connectTimeout)); } if (_heartbeatInterval != ServerSettings.DefaultHeartbeatInterval) { query.AppendFormat("heartbeatInterval={0};", FormatTimeSpan(_heartbeatInterval)); } if (_heartbeatTimeout != ServerSettings.DefaultHeartbeatTimeout) { query.AppendFormat("heartbeatTimeout={0};", FormatTimeSpan(_heartbeatTimeout)); } if (_maxConnectionIdleTime != MongoDefaults.MaxConnectionIdleTime) { query.AppendFormat("maxIdleTime={0};", FormatTimeSpan(_maxConnectionIdleTime)); } if (_maxConnectionLifeTime != MongoDefaults.MaxConnectionLifeTime) { query.AppendFormat("maxLifeTime={0};", FormatTimeSpan(_maxConnectionLifeTime)); } if (_maxConnectionPoolSize != MongoDefaults.MaxConnectionPoolSize) { query.AppendFormat("maxPoolSize={0};", _maxConnectionPoolSize); } if (_minConnectionPoolSize != MongoDefaults.MinConnectionPoolSize) { query.AppendFormat("minPoolSize={0};", _minConnectionPoolSize); } if (_localThreshold != MongoDefaults.LocalThreshold) { query.AppendFormat("localThreshold={0};", FormatTimeSpan(_localThreshold)); } if (_serverSelectionTimeout != MongoDefaults.ServerSelectionTimeout) { query.AppendFormat("serverSelectionTimeout={0};", FormatTimeSpan(_serverSelectionTimeout)); } if (_socketTimeout != MongoDefaults.SocketTimeout) { query.AppendFormat("socketTimeout={0};", FormatTimeSpan(_socketTimeout)); } if (_waitQueueMultiple != 0.0 && _waitQueueMultiple != MongoDefaults.WaitQueueMultiple) { query.AppendFormat("waitQueueMultiple={0};", _waitQueueMultiple); } if (_waitQueueSize != 0 && _waitQueueSize != MongoDefaults.WaitQueueSize) { query.AppendFormat("waitQueueSize={0};", _waitQueueSize); } if (_waitQueueTimeout != MongoDefaults.WaitQueueTimeout) { query.AppendFormat("waitQueueTimeout={0};", FormatTimeSpan(WaitQueueTimeout)); } if (_guidRepresentation != MongoDefaults.GuidRepresentation) { query.AppendFormat("uuidRepresentation={0};", (_guidRepresentation == GuidRepresentation.CSharpLegacy) ? "csharpLegacy" : MongoUtils.ToCamelCase(_guidRepresentation.ToString())); } if (!_retryReads.GetValueOrDefault(true)) { query.AppendFormat("retryReads=false;"); } if (_retryWrites.HasValue) { query.AppendFormat("retryWrites={0};", JsonConvert.ToString(_retryWrites.Value)); } if (query.Length != 0) { query.Length = query.Length - 1; // remove trailing ";" if (_databaseName == null) { url.Append("/"); } url.Append("?"); url.Append(query.ToString()); } return(url.ToString()); }
private IEnumerable<Func<IReadOnlyList<IRelationalCommand>>> GetMigrationCommands( IReadOnlyList<HistoryRow> appliedMigrationEntries, string targetMigration = null) { var appliedMigrations = new Dictionary<string, TypeInfo>(); var unappliedMigrations = new Dictionary<string, TypeInfo>(); foreach (var migration in _migrationsAssembly.Migrations) { if (appliedMigrationEntries.Any( e => string.Equals(e.MigrationId, migration.Key, StringComparison.OrdinalIgnoreCase))) { appliedMigrations.Add(migration.Key, migration.Value); } else { unappliedMigrations.Add(migration.Key, migration.Value); } } IReadOnlyList<Migration> migrationsToApply; IReadOnlyList<Migration> migrationsToRevert; if (string.IsNullOrEmpty(targetMigration)) { migrationsToApply = unappliedMigrations .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider)) .ToList(); migrationsToRevert = new Migration[0]; } else if (targetMigration == Migration.InitialDatabase) { migrationsToApply = new Migration[0]; migrationsToRevert = appliedMigrations .OrderByDescending(m => m.Key) .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider)) .ToList(); } else { targetMigration = _migrationsAssembly.GetMigrationId(targetMigration); migrationsToApply = unappliedMigrations .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) <= 0) .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider)) .ToList(); migrationsToRevert = appliedMigrations .Where(m => string.Compare(m.Key, targetMigration, StringComparison.OrdinalIgnoreCase) > 0) .OrderByDescending(m => m.Key) .Select(p => _migrationsAssembly.CreateMigration(p.Value, _activeProvider)) .ToList(); } for (var i = 0; i < migrationsToRevert.Count; i++) { var migration = migrationsToRevert[i]; yield return () => { _logger.LogInformation(RelationalStrings.RevertingMigration(migration.GetId())); return GenerateDownSql( migration, i != migrationsToRevert.Count - 1 ? migrationsToRevert[i + 1] : null); }; } foreach (var migration in migrationsToApply) { yield return () => { _logger.LogInformation(RelationalStrings.ApplyingMigration(migration.GetId())); return GenerateUpSql(migration); }; } }
// The assembly info must be in the last minus 1 position because: // - assemblyInfo should be in the end to override attributes // - assemblyInfo cannot be in the last position, because last file contains the main private static IEnumerable<string> GetSourceFiles(IReadOnlyList<string> sourceFiles, string assemblyInfo) { if (!sourceFiles.Any()) { yield return assemblyInfo; yield break; } foreach (var s in sourceFiles.Take(sourceFiles.Count() - 1)) yield return s; yield return assemblyInfo; yield return sourceFiles.Last(); }
public static ICompleteEventStreamMutator Create(IReadOnlyList<IEventMigration> eventMigrationFactories) { return eventMigrationFactories.Any() ? new RealMutator(eventMigrationFactories) : (ICompleteEventStreamMutator)new OnlySerializeVersionsMutator(); }
protected ResultListViewModel() { OpenResult = new Command <T>(async(x) => await OnOpenResultAsync(x).ConfigureAwait(false)); CopyToClipboardCommand = new Command(CopyAllToClipboard, () => displayResults?.Any() ?? false); }
public static Type CreateType(string typeName, IReadOnlyList<IMemberDefinition> nodes, bool serializable = false, bool @sealed = false, Type parent = null, IEnumerable<Type> interfaces = null) { Type type; if (_typeCache.TryGetValue(typeName, out type)) return type; var typeAttributes = ClassTypeAttributes; if (@sealed) typeAttributes |= TypeAttributes.Sealed; if (serializable) typeAttributes |= TypeAttributes.Serializable; var typeBuilder = _HorizonModule.DefineType(typeName, typeAttributes); List<IMemberDefinition> members; if (parent == null) { members = nodes.ToList(); } else { typeBuilder.SetParent(parent); var properties = Info.Extended.Properties(parent); var fields = Info.Extended.Fields(parent); var names = properties.Select(x => x.Name).Union(fields.Select(x => x.Name)).ToList(); members = nodes.Where(x => !names.Contains(x.Name)).ToList(); if (parent.IsAbstract) { //We need to implement these ourselves var abstractProperties = properties.Where(x => (x.PropertyInfo.CanRead && x.PropertyInfo.GetGetMethod().IsAbstract) || (x.PropertyInfo.CanWrite && x.PropertyInfo.GetSetMethod().IsAbstract)) .Select(x => MemberDefinition.Property(x, isVirtual: true)); members.AddRange(abstractProperties); var abstractMethods = Info.Extended.Methods(parent) .Where(x => x.MethodInfo.IsAbstract) .Where(x => !nodes.Any(n => n.Name == x.Name)) .Select(x => MemberDefinition.EmptyMethod(x, isVirtual: true)); members.AddRange(abstractMethods); } } var notifyChanges = false; MethodBuilder raisePropertyChanged = null; if (interfaces != null) { var interfaceSet = new HashSet<Type>(); foreach (var @interface in interfaces.Where(interfaceSet.Add).SelectMany(x => x.GetInterfaces())) interfaceSet.Add(@interface); foreach (var @interface in interfaceSet) { typeBuilder.AddInterfaceImplementation(@interface); var properties = Info.Extended.Properties(@interface).Select(x => MemberDefinition.Property(x.Name, x.MemberType)); members = members.Union(properties).ToList(); var events = Info.Extended.Events(@interface); if (!notifyChanges && (notifyChanges = typeof(INotifyPropertyChanged).IsAssignableFrom(@interface))) { foreach (var @event in events) { var tuple = GenerateEvent(typeBuilder, @event); if (@event.Name != "PropertyChanged") continue; var eventBuilder = tuple.Item1; var eventBackingField = tuple.Item2; raisePropertyChanged = BuildOnPropertyChanged(typeBuilder, eventBuilder, eventBackingField); } } else { members.AddRange(events.Select(x => new EventMemberDefinition(x.Name, x.EventHandlerType))); } var emptyMethods = Info.Extended.Methods(@interface).Select(method => MemberDefinition.EmptyMethod(method)); members.AddRange(emptyMethods); } } if (raisePropertyChanged != null) { foreach (var propertyDefinition in members.OfType<PropertyMemberDefinition>()) propertyDefinition.RaisePropertyChanged = raisePropertyChanged; } foreach (var member in members) member.Build(typeBuilder); if (parent != null) { if (raisePropertyChanged != null) OverrideParentPropertiesForPropertyChanged(typeBuilder, parent, raisePropertyChanged); } // Generate our type and cache it. _typeCache[typeName] = type = typeBuilder.CreateType(); return type; }
private double SimulateOpponentWithPrediction(double lowerTimeBound, double timePerLeaf, POGame oppGame, Controller opponent, IReadOnlyList <Prediction> predicitionMap, ref Dictionary <POGame, List <MctsNode> > newSimulations) { double predictionScore = 0; if (!(predicitionMap?.Any() ?? false)) { return(predictionScore); } int denominator = predicitionMap.Count; var scorings = predicitionMap.GroupBy(p => p.Deck.Scoring) .Select(c => new MctsNode.ScoreExt(((double)c.Count() / denominator), c.Key)) .OrderByDescending(s => s.Value).ToList(); // the simulation time for one prediction double timePerPrediction = timePerLeaf / predicitionMap.Count; // use prediction for each game for (int i = 0; i < predicitionMap.Count; i++) { Prediction prediction = predicitionMap[i]; SetasideZone setasideZone; setasideZone = new SetasideZone(opponent); // create deck zone List <Card> deckCards = prediction.Deck.Cards; DeckZone deckZone; deckZone = new DeckZone(opponent); createZone(opponent, deckCards, deckZone, ref setasideZone); deckZone.Shuffle(); // create hand zone List <Card> handCards = prediction.Hand.Cards; HandZone handZone; handZone = new HandZone(opponent); createZone(opponent, handCards, handZone, ref setasideZone); var oppLeafNodes = new List <MctsNode>(); // forward game POGame forwardGame = oppGame.getCopy(); // upper time bound for simulation the opponent using the current prediction double oppSimulationTime = lowerTimeBound + (i + 1) * timePerPrediction / 2; // simulate opponent's moves while (forwardGame != null && forwardGame.State == SabberStoneCore.Enums.State.RUNNING && forwardGame.CurrentPlayer.Id == opponent.Id) { // simulate var oppRoot = new MctsNode(opponent.Id, scorings, forwardGame, null, null); MctsNode bestOppNode = Simulate(oppSimulationTime, oppRoot, ref oppLeafNodes); // get solution List <PlayerTask> solutions = bestOppNode.GetSolution(); for (int j = 0; j < solutions.Count && (forwardGame != null); j++) { PlayerTask oppTask = solutions[j]; Dictionary <PlayerTask, POGame> dir = forwardGame.Simulate(new List <PlayerTask> { oppTask }); forwardGame = dir[oppTask]; if (forwardGame != null && forwardGame.CurrentPlayer.Choice != null) { break; } } } // upper time bound for simulation the player using the forwarded game double simulationTime = oppSimulationTime + timePerPrediction / 2; double score = 0; var leafs = new List <MctsNode>(); // simulate player using forwarded opponent game while (forwardGame != null && forwardGame.State == SabberStoneCore.Enums.State.RUNNING && forwardGame.CurrentPlayer.Id == _playerId) { // simulate var root = new MctsNode(_playerId, new List <MctsNode.ScoreExt> { new MctsNode.ScoreExt(1.0, _scoring) }, forwardGame, null, null); MctsNode bestNode = Simulate(simulationTime, root, ref leafs); // get solution List <PlayerTask> solutions = bestNode.GetSolution(); for (int j = 0; j < solutions.Count && (forwardGame != null); j++) { PlayerTask task = solutions[j]; Dictionary <PlayerTask, POGame> dir = forwardGame.Simulate(new List <PlayerTask> { task }); forwardGame = dir[task]; if (forwardGame != null && forwardGame.CurrentPlayer.Choice != null) { break; } } // TODO: maybe penalty forwardGame == null score = bestNode.TotalScore; } predictionScore += score; if (forwardGame != null) { newSimulations.Add(forwardGame, leafs); } } return(predictionScore); }
public static void Run(string[] args) { IReadOnlyList <string> input = Array.Empty <string>(); IReadOnlyList <string> resources = null; IReadOnlyList <string> additionalFormats = null; string output = null; string manifest = null; bool allConfigurations = false; // Preview options bool autosize = false; double imgWidth = 640; double imgHeight = 480; string configuration = null; bool recursive = false; bool silent = false; bool verbose = false; var cliOptions = ArgumentSyntax.Parse(args, options => { options.ApplicationName = "cdcli component"; options.DefineOption("o|output", ref output, "Output file (the format will be inferred from the extension). Cannot be used for directory inputs or in combination with specific output format options."); var manifestOption = options.DefineOption("manifest", ref manifest, false, "Writes a manifest file listing the compiled components."); if (manifestOption.IsSpecified && manifest == null) { manifest = "manifest.xml"; } options.DefineOption("autosize", ref autosize, "Automatically sizes the output image to fit the rendered preview."); options.DefineOption("w|width", ref imgWidth, double.Parse, "Width of output images to generate (default=640)."); options.DefineOption("h|height", ref imgHeight, double.Parse, "Height of output images to generate (default=480)."); options.DefineOption("r|recursive", ref recursive, "Recursively searches sub-directories of the input directory."); options.DefineOption("s|silent", ref silent, "Does not output anything to the console on successful operation."); options.DefineOption("v|verbose", ref verbose, "Outputs extra information to the console."); options.DefineOption("c|configuration", ref configuration, "Name of component configuration to use."); options.DefineOption("all-configurations", ref allConfigurations, "Produce an output for every component configuration (supported output formats only)."); options.DefineOptionList("resources", ref resources, "Resources to use in generating the output. Either a directory, or a space-separated list of [key] [filename] pairs."); options.DefineOptionList("format", ref additionalFormats, "Output formats to write."); options.DefineParameterList("input", ref input, "Components to compile."); }); var loggerFactory = new LoggerFactory(); if (!silent) { loggerFactory.AddProvider(new BasicConsoleLogger(LogLevel.Information)); } var logger = loggerFactory.CreateLogger(typeof(ComponentApp)); if (!input.Any()) { logger.LogError("At least one input file must be specified."); Environment.Exit(1); } var generators = new Dictionary <IOutputGenerator, string>(); var outputGenerators = new OutputGeneratorRepository(); bool outputIsDirectory = Directory.Exists(output); if (output != null && !outputIsDirectory) { if (outputGenerators.TryGetGeneratorByFileExtension(Path.GetExtension(output), out var generator)) { // Use the generator implied by the file extension generators.Add(generator, output); } else if (additionalFormats?.Any() != true) { logger.LogError("Unable to infer format from output file extension." + Environment.NewLine + "Specify a known file extension or specify explicitly using --format"); Environment.Exit(1); } else { logger.LogInformation("Unable to infer format from output file extension. Using formats only."); } } if (additionalFormats?.Any() == true) { foreach (var format in additionalFormats) { if (outputGenerators.TryGetGeneratorByFormat(format, out var generator)) { generators.Add(generator, outputIsDirectory ? output : null); } else { logger.LogError($"Unknown format: {format}"); Environment.Exit(1); } } } var previewOptions = new PreviewGenerationOptions { Center = true, Crop = autosize, Width = imgWidth, Height = imgHeight, Configuration = configuration, Properties = new Dictionary <string, string>(), }; DirectoryComponentDescriptionLookup componentDescriptionLookup; if (input.Count == 1 && Directory.Exists(input.Single())) { componentDescriptionLookup = new DirectoryComponentDescriptionLookup(input.Single(), true); } else { componentDescriptionLookup = new DirectoryComponentDescriptionLookup(input.ToArray()); } var resourceProvider = ResourceProviderFactory.Create(loggerFactory.CreateLogger(typeof(ResourceProviderFactory)), resources); var outputRunner = new OutputRunner(loggerFactory.CreateLogger <OutputRunner>(), resourceProvider); var compileRunner = new ComponentDescriptionRunner(loggerFactory.CreateLogger <ComponentDescriptionRunner>(), outputRunner); var configurationDefinitionRunner = new ConfigurationDefinitionRunner(loggerFactory.CreateLogger <ConfigurationDefinitionRunner>(), componentDescriptionLookup, outputRunner); var results = new List <IManifestEntry>(); var inputs = new List <string>(); foreach (var i in input) { if (File.Exists(i)) { inputs.Add(i); } else if (Directory.Exists(i)) { foreach (var generator in generators) { if (generator.Value != null && !Directory.Exists(generator.Value)) { logger.LogError("Outputs must be directories when the input is a directory."); Environment.Exit(1); } } foreach (var file in Directory.GetFiles(i, "*.xml", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)) { inputs.Add(file); } foreach (var file in Directory.GetFiles(i, "*.yaml", recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly)) { inputs.Add(file); } } else { logger.LogError($"Input is not a valid file or directory: {i}"); Environment.Exit(1); } } foreach (var file in inputs.OrderBy(x => x)) { IManifestEntry result; switch (Path.GetExtension(file)) { case ".xml": result = compileRunner.CompileOne(file, previewOptions, allConfigurations, generators); break; case ".yaml": result = configurationDefinitionRunner.CompileOne(file, previewOptions, generators); break; default: throw new NotSupportedException($"File type '{Path.GetExtension(file)}' not supported."); } results.Add(result); } if (manifest != null) { using (var manifestFs = File.Open(manifest, FileMode.Create)) { logger.LogInformation($"Writing manifest to {manifest}"); ManifestWriter.WriteManifest(results, manifestFs); } } }
/// <summary> /// Maps from a list of one type TK to a list of a another type T using a mapper function designated while calling the method. /// </summary> /// <typeparam name="TIn">A type that we map from.</typeparam> /// <typeparam name="TOut">A type that we map to.</typeparam> /// <param name="items">The inventory item objects or models to be mapped.</param> /// <param name="mapper">The function used for mapping.</param> /// <returns></returns> public IReadOnlyList <TIn> Map <TIn, TOut>(IReadOnlyList <TOut> items, Func <TOut, TIn> mapper) { // If the input collection is empty, return a new empty list of the target type. // Otherwise, preform the individual mapping. return(items?.Any() == true?items.Select(mapper).ToList() : new List <TIn>()); }
private void WriteLocations(Location location, IReadOnlyList<Location> additionalLocations) { if (HasPath(location)) { _writer.WriteArrayStart("locations"); _writer.WriteObjectStart(); // location _writer.WriteKey("resultFile"); WritePhysicalLocation(location); _writer.WriteObjectEnd(); // location _writer.WriteArrayEnd(); // locations } // See https://github.com/dotnet/roslyn/issues/11228 for discussion around // whether this is the correct treatment of Diagnostic.AdditionalLocations // as SARIF relatedLocations. if (additionalLocations != null && additionalLocations.Count > 0 && additionalLocations.Any(l => HasPath(l))) { _writer.WriteArrayStart("relatedLocations"); foreach (var additionalLocation in additionalLocations) { if (HasPath(additionalLocation)) { _writer.WriteObjectStart(); // annotatedCodeLocation _writer.WriteKey("physicalLocation"); WritePhysicalLocation(additionalLocation); _writer.WriteObjectEnd(); // annotatedCodeLocation } } _writer.WriteArrayEnd(); // relatedLocations } }
private void LoadNavigationProperties( object entity, IReadOnlyList<INavigation> navigationPath, int currentNavigationIndex, IReadOnlyList<object> relatedEntities) { if (navigationPath[currentNavigationIndex].PointsToPrincipal() && relatedEntities.Any()) { _clrPropertySetterSource .GetAccessor(navigationPath[currentNavigationIndex]) .SetClrValue(entity, relatedEntities[0]); var inverseNavigation = navigationPath[currentNavigationIndex].FindInverse(); if (inverseNavigation != null) { if (inverseNavigation.IsCollection()) { _clrCollectionAccessorSource .GetAccessor(inverseNavigation) .AddRange(relatedEntities[0], new[] { entity }); } else { _clrPropertySetterSource .GetAccessor(inverseNavigation) .SetClrValue(relatedEntities[0], entity); } } } else { if (navigationPath[currentNavigationIndex].IsCollection()) { _clrCollectionAccessorSource .GetAccessor(navigationPath[currentNavigationIndex]) .AddRange(entity, relatedEntities); var inverseNavigation = navigationPath[currentNavigationIndex].FindInverse(); if (inverseNavigation != null) { var clrPropertySetter = _clrPropertySetterSource .GetAccessor(inverseNavigation); foreach (var relatedEntity in relatedEntities) { clrPropertySetter.SetClrValue(relatedEntity, entity); } } } else if (relatedEntities.Any()) { _clrPropertySetterSource .GetAccessor(navigationPath[currentNavigationIndex]) .SetClrValue(entity, relatedEntities[0]); var inverseNavigation = navigationPath[currentNavigationIndex].FindInverse(); if (inverseNavigation != null) { _clrPropertySetterSource .GetAccessor(inverseNavigation) .SetClrValue(relatedEntities[0], entity); } } } }
private static bool ContainsCitiesFile(IReadOnlyList<StorageFile> files) { return files.Any(f => f.Name == SETTING_KEY); }
/// <summary> /// Creates graph from the given items. /// Contains implementation of INSERT(hnsw, q, M, Mmax, efConstruction, mL) algorithm. /// Article: Section 4. Algorithm 1. /// </summary> /// <param name="items">The items to insert.</param> /// <param name="generator">The random number generator to distribute nodes across layers.</param> internal void Build(IReadOnlyList <TItem> items, Random generator) { if (!items?.Any() ?? false) { return; } var core = new Core(this.distance, this.Parameters, items); core.AllocateNodes(generator); var entryPoint = core.Nodes[0]; var searcher = new Searcher(core); Func <int, int, TDistance> nodeDistance = core.GetDistance; var neighboursIdsBuffer = new List <int>(core.Algorithm.GetM(0) + 1); for (int nodeId = 1; nodeId < core.Nodes.Count; ++nodeId) { using (new ScopeLatencyTracker(GraphBuildEventSource.Instance?.GraphInsertNodeLatencyReporter)) { /* * W ← ∅ // list for the currently found nearest elements * ep ← get enter point for hnsw * L ← level of ep // top layer for hnsw * l ← ⌊-ln(unif(0..1))∙mL⌋ // new element’s level * for lc ← L … l+1 * W ← SEARCH-LAYER(q, ep, ef=1, lc) * ep ← get the nearest element from W to q * for lc ← min(L, l) … 0 * W ← SEARCH-LAYER(q, ep, efConstruction, lc) * neighbors ← SELECT-NEIGHBORS(q, W, M, lc) // alg. 3 or alg. 4 * for each e ∈ neighbors // shrink connections if needed * eConn ← neighbourhood(e) at layer lc * if │eConn│ > Mmax // shrink connections of e if lc = 0 then Mmax = Mmax0 * eNewConn ← SELECT-NEIGHBORS(e, eConn, Mmax, lc) // alg. 3 or alg. 4 * set neighbourhood(e) at layer lc to eNewConn * ep ← W * if l > L * set enter point for hnsw to q */ // zoom in and find the best peer on the same level as newNode var bestPeer = entryPoint; var currentNode = core.Nodes[nodeId]; var currentNodeTravelingCosts = new TravelingCosts <int, TDistance>(nodeDistance, nodeId); for (int layer = bestPeer.MaxLayer; layer > currentNode.MaxLayer; --layer) { searcher.RunKnnAtLayer(bestPeer.Id, currentNodeTravelingCosts, neighboursIdsBuffer, layer, 1); bestPeer = core.Nodes[neighboursIdsBuffer[0]]; neighboursIdsBuffer.Clear(); } // connecting new node to the small world for (int layer = Math.Min(currentNode.MaxLayer, entryPoint.MaxLayer); layer >= 0; --layer) { searcher.RunKnnAtLayer(bestPeer.Id, currentNodeTravelingCosts, neighboursIdsBuffer, layer, this.Parameters.ConstructionPruning); var bestNeighboursIds = core.Algorithm.SelectBestForConnecting(neighboursIdsBuffer, currentNodeTravelingCosts, layer); for (int i = 0; i < bestNeighboursIds.Count; ++i) { int newNeighbourId = bestNeighboursIds[i]; core.Algorithm.Connect(currentNode, core.Nodes[newNeighbourId], layer); core.Algorithm.Connect(core.Nodes[newNeighbourId], currentNode, layer); // if distance from newNode to newNeighbour is better than to bestPeer => update bestPeer if (DistanceUtils.Lt(currentNodeTravelingCosts.From(newNeighbourId), currentNodeTravelingCosts.From(bestPeer.Id))) { bestPeer = core.Nodes[newNeighbourId]; } } neighboursIdsBuffer.Clear(); } // zoom out to the highest level if (currentNode.MaxLayer > entryPoint.MaxLayer) { entryPoint = currentNode; } // report distance cache hit rate GraphBuildEventSource.Instance?.CoreGetDistanceCacheHitRateReporter?.Invoke(core.DistanceCacheHitRate); } } // construction is done this.core = core; this.entryPoint = entryPoint; }
private void AugmentCompletionsBasedOnLinesBefore(IReadOnlyList<RobotsTxtLineSyntax> before, IList<Completion> completions) { // first line if (!before.Any()) { completions.Add(ToCompletion("User-agent")); } // right after User-agent else if (before.All(l => l.NameToken.Value.Equals("User-agent", StringComparison.InvariantCultureIgnoreCase))) { completions.Add(ToCompletion("User-agent")); completions.Add(ToCompletion("Allow")); completions.Add(ToCompletion("Disallow")); completions.Add(ToCompletion("Sitemap")); completions.Add(ToCompletion("Host")); completions.Add(ToCompletion("Crawl-delay")); } // any other case else { completions.Add(ToCompletion("Allow")); completions.Add(ToCompletion("Disallow")); completions.Add(ToCompletion("Sitemap")); if (!before.Any(l => l.NameToken.Value.Equals("Host", StringComparison.InvariantCultureIgnoreCase))) completions.Add(ToCompletion("Host")); if (!before.Any(l => l.NameToken.Value.Equals("Crawl-delay", StringComparison.InvariantCultureIgnoreCase))) completions.Add(ToCompletion("Crawl-delay")); } }
private void SetupWallSideActuators(IEnumerable<GrabableItemData> items, IReadOnlyList<ActuatorItemData> actuators) { if (actuators.Any()) { CurrentGrabableItems = items; var factory = parser.TryMatchFactory(actuators, items.Any()); if (factory != null) { CurrentTile.SubItems.Add(factory.CreateItem(builder, CurrentTile, actuators)); } else { if(actuators.All(x => x.ActuatorType != 5 && x.ActuatorType != 6)) { foreach (var i in actuators) { Point? absolutePosition = null; if (i.ActionLocation is RemoteTarget) absolutePosition = ((RemoteTarget) i.ActionLocation).Position.Position.ToAbsolutePosition(builder.CurrentMap); CurrentTile.SubItems.Add(new Actuator(builder.GetWallPosition(i.TilePosition, CurrentTile), $"{absolutePosition} {i.DumpString()}")); } } else { } } } }
public async void ContinueFileOpenPicker(IReadOnlyList<StorageFile> files) { if (files != null && files.Any()) { var stream = (FileRandomAccessStream)await files[0].OpenAsync(FileAccessMode.Read); using (var streamForImage = stream.CloneStream()) { newImageBytes = new byte[stream.Size]; using (var dataReader = new DataReader(stream)) { await dataReader.LoadAsync((uint)stream.Size); dataReader.ReadBytes(newImageBytes); } UserImage = ImageHelper.CreateBitmapImage(streamForImage, 100); } } }