public static Point GetInsidePoint(IReadOnlyList<Point> points, Box boundingBox) { var y = (boundingBox.MinY + boundingBox.MaxY) / 2; var xIntersections = new List<double>(); var point1 = points.Last(); foreach (var point2 in points) { if ((y > point1.Y) != (y > point2.Y)) { xIntersections.Add((y - point2.Y) * (point1.X - point2.X) / (point1.Y - point2.Y) + point2.X); } point1 = point2; } xIntersections.Sort(); Debugger.BreakWhen(xIntersections.Count == 0 || xIntersections.Count % 2 != 0); var x = (boundingBox.MinX + boundingBox.MaxX) / 2; var maxDelta = double.NegativeInfinity; for (var i = 0; i < xIntersections.Count - 1; i += 2) { var delta = Math.Abs(xIntersections[i] - xIntersections[i + 1]); if (delta > maxDelta) { x = (xIntersections[i] + xIntersections[i + 1]) / 2; maxDelta = delta; } } var point = new Point(x, y); #if DEBUG Debugger.BreakWhen(!PointInPolygonTest.Contains(points, point)); #endif return point; }
/// <summary> /// Initializes a new instance of the <see cref="ConnectionSendingMessagesFailedEvent" /> struct. /// </summary> /// <param name="connectionId">The connection identifier.</param> /// <param name="requestIds">The request ids.</param> /// <param name="exception">The exception.</param> /// <param name="operationId">The operation identifier.</param> public ConnectionSendingMessagesFailedEvent(ConnectionId connectionId, IReadOnlyList<int> requestIds, Exception exception, long? operationId) { _connectionId = connectionId; _requestIds = requestIds; _exception = exception; _operationId = operationId; }
public NamespaceViewModel(IReadOnlyList<DocumentedNamespace> namespaces) { if (namespaces.Count == 0) { throw new ArgumentException("No namespaces in list."); } Data = namespaces[0]; Name = Data.Name; var namespaceWithSummary = namespaces.FirstOrDefault(x => x.Summary != null); if (namespaceWithSummary != null) { Summary = namespaceWithSummary.Summary; } Classes = new List<DocumentedType>(); Interfaces = new List<DocumentedType>(); foreach (var @namespace in namespaces) { var classes = @namespace.Types.Where(x => x.Definition.IsClass && !IsExtensionMethodClass(x)).ToArray(); Classes.AddRange(classes); var interfaces = @namespace.Types.Where(x => x.Definition.IsInterface).ToArray(); Interfaces.AddRange(interfaces); } // For child namespaces, just get them from the first one // since they're going to be the same anyway. Namespaces = new List<DocumentedNamespace>(); foreach (var childNamespace in Data.Tree.Children) { Namespaces.Add(childNamespace.Namespace); } }
internal static ColliderShape Compose(IReadOnlyList<IAssetColliderShapeDesc> descs) { ColliderShape res = null; if (descs.Count == 1) //single shape case { res = CreateShape(descs[0]); if (res == null) return null; res.IsPartOfAsset = true; } else if (descs.Count > 1) //need a compound shape in this case { var compound = new CompoundColliderShape(); foreach (var desc in descs) { var subShape = CreateShape(desc); if(subShape == null) continue; compound.AddChildShape(subShape); } res = compound; res.IsPartOfAsset = true; } return res; }
public IncludeExpressionVisitor( [NotNull] ISelectExpressionFactory selectExpressionFactory, [NotNull] IMaterializerFactory materializerFactory, [NotNull] ICommandBuilderFactory commandBuilderFactory, [NotNull] IRelationalAnnotationProvider relationalAnnotationProvider, [NotNull] ISqlQueryGeneratorFactory sqlQueryGeneratorFactory, [NotNull] IQuerySource querySource, [NotNull] IReadOnlyList<INavigation> navigationPath, [NotNull] RelationalQueryCompilationContext queryCompilationContext, [NotNull] IReadOnlyList<int> queryIndexes, bool querySourceRequiresTracking) { Check.NotNull(selectExpressionFactory, nameof(selectExpressionFactory)); Check.NotNull(materializerFactory, nameof(materializerFactory)); Check.NotNull(commandBuilderFactory, nameof(commandBuilderFactory)); Check.NotNull(relationalAnnotationProvider, nameof(relationalAnnotationProvider)); Check.NotNull(sqlQueryGeneratorFactory, nameof(sqlQueryGeneratorFactory)); Check.NotNull(querySource, nameof(querySource)); Check.NotNull(navigationPath, nameof(navigationPath)); Check.NotNull(queryCompilationContext, nameof(queryCompilationContext)); Check.NotNull(queryIndexes, nameof(queryIndexes)); _selectExpressionFactory = selectExpressionFactory; _materializerFactory = materializerFactory; _commandBuilderFactory = commandBuilderFactory; _relationalAnnotationProvider = relationalAnnotationProvider; _sqlQueryGeneratorFactory = sqlQueryGeneratorFactory; _querySource = querySource; _navigationPath = navigationPath; _queryCompilationContext = queryCompilationContext; _queryIndexes = queryIndexes; _querySourceRequiresTracking = querySourceRequiresTracking; }
public VariablePathResolvingStatus TryResolve(IEnumerable<KeyValuePair<string, string>> variables, out IAbsoluteFilePath resolvedPath, out IReadOnlyList<string> unresolvedVariables) { Argument.IsNotNull(nameof(variables), variables); string path; if (!TryResolve(variables, out path, out unresolvedVariables)) { resolvedPath = null; return VariablePathResolvingStatus.UnresolvedVariable; } if (!path.IsValidAbsoluteFilePath()) { resolvedPath = null; return VariablePathResolvingStatus.CannotConvertToAbsolutePath; } resolvedPath = path.ToAbsoluteFilePath(); return VariablePathResolvingStatus.Success; }
public override IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { ImmutableArray<IDocument> commitDocuments = GetCommitDocuments(inputs, context); // Outputting commits as new documents if (string.IsNullOrEmpty(_commitsMetadataKey)) { return commitDocuments; } var test = commitDocuments.Select(x => x.Get<IReadOnlyDictionary<string, string>>(GitKeys.Entries)); // Outputting commit information for each document string repositoryLocation = GetRepositoryLocation(context); return inputs.AsParallel().Select(input => { if (string.IsNullOrEmpty(input.Source)) { return input; } string relativePath = PathHelper.GetRelativePath(repositoryLocation, input.Source); if (string.IsNullOrEmpty(relativePath)) { return input; } ImmutableArray<IDocument> inputCommitDocuments = commitDocuments .Where(x => x.Get<IReadOnlyDictionary<string, string>>(GitKeys.Entries).ContainsKey(relativePath)) .ToImmutableArray(); return context.GetDocument(input, new MetadataItems { new MetadataItem(_commitsMetadataKey, inputCommitDocuments) }); }); }
internal static string BuildMetricFilter(DateTime? startTime, DateTime? endTime, string timeGrain, IReadOnlyList<string> metricNames) { var dateTimeFormat = "yyyy-MM-ddTHH:mm:ssZ"; var filter = ""; if (metricNames != null && metricNames.Count > 0) { if (metricNames.Count == 1) { filter = "name.value eq '" + metricNames[0] + "'"; } else { filter = "(name.value eq '" + string.Join("' or name.value eq '", metricNames) + "')"; } } if (startTime.HasValue) { filter += string.Format("and startTime eq {0}", startTime.Value.ToString(dateTimeFormat)); } if (endTime.HasValue) { filter += string.Format("and endTime eq {0}", endTime.Value.ToString(dateTimeFormat)); } if (!string.IsNullOrWhiteSpace(timeGrain)) { filter += string.Format("and timeGrain eq duration'{0}'", timeGrain); } return filter; }
public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { return inputs .AsParallel() .Select(input => { try { object data = _data(input, context); if (data != null) { string result = JsonConvert.SerializeObject(data, _indenting ? Formatting.Indented : Formatting.None); if (string.IsNullOrEmpty(_destinationKey)) { return context.GetDocument(input, result); } return context.GetDocument(input, new MetadataItems { {_destinationKey, result} }); } } catch (Exception ex) { Trace.Error("Error serializing JSON for {0}: {1}", input.Source, ex.ToString()); } return input; }) .Where(x => x != null); }
public SqlForeignKeyConstraintExpression(string constraintName, IReadOnlyList<string> columnNames, SqlReferencesColumnExpression referencesColumnExpression) : base(typeof(void)) { this.ConstraintName = constraintName; this.ColumnNames = columnNames; this.ReferencesColumnExpression = referencesColumnExpression; }
/// <summary> /// ツイートを投稿する /// </summary> /// <param name="t">ツイート本文</param> /// <param name="selectedPictures">選択された画像ファイルの List</param> public async void PostTweetAsync(string t, IReadOnlyList<StorageFile> selectedPictures) { var mediaIds = await this.UploadPictures(selectedPictures); var replayToStatusId = this._replyToStatus?.Id; await this._tokens.Statuses.UpdateAsync(status => t, in_reply_to_status_id => replayToStatusId, media_ids => mediaIds); this._replyToStatus = null; }
public FairPartitionResolver(IReadOnlyList<string> collectionLinks) { Guard.NotNull("collectionLinks", collectionLinks); this.collectionLinks = collectionLinks; this.random = new ThreadLocal<Random>(CreateNewRandom); }
public Task<PermissionSet> GetPermissions(IReadOnlyList<SignatureEvidence> authentication, LedgerPath path, bool recursiveOnly, string recordName) { HashSet<string> identities = new HashSet<string>(authentication.Select(evidence => keyEncoder.GetPubKeyHash(evidence.PublicKey)), StringComparer.Ordinal); LedgerPath pathRecordName; // If the path is root and the record name is a tird-party asset owned by the current identity, // arbitrary modification of the balance is allowed if (LedgerPath.TryParse(recordName, out pathRecordName) && thirdPartyAssetPath.IsStrictParentOf(pathRecordName) && path.Segments.Count == 0 && identities.Contains(pathRecordName.Segments[thirdPartyAssetPath.Segments.Count])) { return Task.FromResult(new PermissionSet(accountNegative: Access.Permit)); } // Account /asset/p2pkh/[addr]/ if (thirdPartyAssetPath.IsStrictParentOf(path) && path.Segments.Count == thirdPartyAssetPath.Segments.Count + 1 && keyEncoder.IsP2pkh(path.Segments[path.Segments.Count - 1])) { Access ownAccount = identities.Contains(path.Segments[path.Segments.Count - 1]) && recordName != DynamicPermissionLayout.AclResourceName ? Access.Permit : Access.Unset; return Task.FromResult(new PermissionSet( accountModify: Access.Permit, accountCreate: Access.Permit, accountSpend: ownAccount, dataModify: ownAccount)); } else { return Task.FromResult(new PermissionSet()); } }
private SimpleDiagnostic( DiagnosticDescriptor descriptor, DiagnosticSeverity severity, int warningLevel, Location location, IEnumerable<Location> additionalLocations, object[] messageArgs, ImmutableDictionary<string, string> properties, bool isSuppressed) { if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) || (warningLevel != 0 && severity == DiagnosticSeverity.Error)) { throw new ArgumentException(nameof(warningLevel)); } if (descriptor == null) { throw new ArgumentNullException(nameof(descriptor)); } _descriptor = descriptor; _severity = severity; _warningLevel = warningLevel; _location = location ?? Location.None; _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList<Location>(); _messageArgs = messageArgs ?? Array.Empty<object>(); _properties = properties ?? ImmutableDictionary<string, string>.Empty; _isSuppressed = isSuppressed; }
private SolutionState( BranchId branchId, int workspaceVersion, SolutionServices solutionServices, SolutionId id, string filePath, IEnumerable<ProjectId> projectIds, ImmutableDictionary<ProjectId, ProjectState> idToProjectStateMap, ImmutableDictionary<ProjectId, CompilationTracker> projectIdToTrackerMap, ImmutableDictionary<string, ImmutableArray<DocumentId>> linkedFilesMap, ProjectDependencyGraph dependencyGraph, VersionStamp version, Lazy<VersionStamp> lazyLatestProjectVersion) { _branchId = branchId; _workspaceVersion = workspaceVersion; _id = id; _filePath = filePath; _solutionServices = solutionServices; _projectIds = projectIds.ToImmutableReadOnlyListOrEmpty(); _projectIdToProjectStateMap = idToProjectStateMap; _projectIdToTrackerMap = projectIdToTrackerMap; _linkedFilesMap = linkedFilesMap; _dependencyGraph = dependencyGraph; _version = version; _lazyLatestProjectVersion = lazyLatestProjectVersion; CheckInvariants(); }
public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { foreach (IDocument input in inputs) { string path = _path(input); if (path != null) { path = Path.Combine(context.InputFolder, path); string fileRoot = Path.GetDirectoryName(path); if (fileRoot != null && Directory.Exists(fileRoot)) { foreach (string file in Directory.EnumerateFiles(fileRoot, Path.GetFileName(path), _searchOption).Where(x => _where == null || _where(x))) { string content = File.ReadAllText(file); context.Trace.Verbose("Read file {0}", file); yield return input.Clone(content, new Dictionary<string, object> { {MetadataKeys.SourceFileRoot, fileRoot}, {MetadataKeys.SourceFileBase, Path.GetFileNameWithoutExtension(file)}, {MetadataKeys.SourceFileExt, Path.GetExtension(file)}, {MetadataKeys.SourceFileName, Path.GetFileName(file)}, {MetadataKeys.SourceFileDir, Path.GetDirectoryName(file)}, {MetadataKeys.SourceFilePath, file}, {MetadataKeys.RelativeFilePath, Path.Combine(PathHelper.GetRelativePath(context.InputFolder, file))} }); } } } } }
public virtual RawSqlCommand Build(string sql, IReadOnlyList<object> parameters) { Check.NotEmpty(sql, nameof(sql)); Check.NotNull(parameters, nameof(parameters)); var relationalCommandBuilder = _relationalCommandBuilderFactory.Create(); var substitutions = new string[parameters.Count]; var parameterNameGenerator = _parameterNameGeneratorFactory.Create(); var parameterValues = new Dictionary<string, object>(); for (var i = 0; i < substitutions.Length; i++) { var parameterName = parameterNameGenerator.GenerateNext(); substitutions[i] = _sqlGenerationHelper.GenerateParameterName(parameterName); relationalCommandBuilder.AddParameter( parameterName, substitutions[i]); parameterValues.Add(parameterName, parameters[i]); } // ReSharper disable once CoVariantArrayConversion sql = string.Format(sql, substitutions); return new RawSqlCommand( relationalCommandBuilder.Append(sql).Build(), parameterValues); }
private static void PrintDayStats(IReadOnlyList<DateTime> dates) { var totalMinutesIn = new TimeSpan(0, 0, 0, 0); var totalMinutesOut = new TimeSpan(0, 0, 0, 0); DateTime lastDate = dates[0]; var isIn = false; for (int i = 1; i < dates.Count; i++) { var instance = dates[i]; isIn = !isIn; if (isIn) { totalMinutesIn = totalMinutesIn.Add(instance.Subtract(lastDate)); } else { totalMinutesOut = totalMinutesOut.Add(instance.Subtract(lastDate)); } lastDate = instance; } Console.WriteLine("Total minutes in: {0}, out: {1}, extra: {2}", totalMinutesIn, totalMinutesOut, totalMinutesIn.Subtract(Day)); _overtime = _overtime.Add(totalMinutesIn.Subtract(Day)); }
static SAMER08F() { int[] squareCounts = new int[_limit + 1]; squareCounts[0] = 0; squareCounts[1] = 1; squareCounts[2] = 5; for (int n = 3; n <= _limit; ++n) { // Add the parent square as a whole. squareCounts[n] += 1; // Add the squares that touch only one of the parent square's four corners. // For example, growing from the top left for n = 3 there's square n = 1, and square n = 2, and this repeats for each corner. squareCounts[n] += 4 * (n - 1); // Add the squares that touch the parent square's edge but don't touch one of the parent square's four corners. // For example, for n = 4 there's two unused edge squares on each side, from the first there's two (n = 1, n = 2) second there's one (n = 1). // In general, for each side there's n - 2 squares to start from, the first gives n - 2 squares, the second n - 3 squares, etc, to one. squareCounts[n] += 4 * SumFromOneUntil(n - 2); // Add the counts from interior square (touching no edges or corners) of dimension n - 2. squareCounts[n] += squareCounts[n - 2]; } _squareCounts = squareCounts; }
public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { List<IDocument> results = new List<IDocument>(); IEnumerable<IDocument> documents = inputs; foreach (Tuple<DocumentConfig, IModule[]> condition in _conditions) { // Split the documents into ones that satisfy the predicate and ones that don't List<IDocument> handled = new List<IDocument>(); List<IDocument> unhandled = new List<IDocument>(); foreach (IDocument document in documents) { if (condition.Item1 == null || condition.Item1.Invoke<bool>(document, context)) { handled.Add(document); } else { unhandled.Add(document); } } // Run the modules on the documents that satisfy the predicate results.AddRange(context.Execute(condition.Item2, handled)); // Continue with the documents that don't satisfy the predicate documents = unhandled; } // Add back any documents that never matched a predicate results.AddRange(documents); return results; }
public WebSocketRfc6455(Stream clientStream, WebSocketListenerOptions options, IPEndPoint local, IPEndPoint remote, WebSocketHttpRequest httpRequest, IReadOnlyList<IWebSocketMessageExtensionContext> extensions) { if (clientStream == null) throw new ArgumentNullException("clientStream"); if (options == null) throw new ArgumentNullException("options"); if (local == null) throw new ArgumentNullException("local"); if (remote == null) throw new ArgumentNullException("remote"); if (extensions == null) throw new ArgumentNullException("extensions"); if (httpRequest == null) throw new ArgumentNullException("httpRequest"); _remoteEndpoint = remote; _localEndpoint = local; _httpRequest = httpRequest; Connection = new WebSocketConnectionRfc6455(clientStream, options); _extensions = extensions; }
private static List<SectionTime> Calculate(IReadOnlyList<IAnimationSection> animationSections, DateTime startTime) { return animationSections .Scan(new SectionTime(null, startTime), (acc, section) => new SectionTime(section, acc.EndTime + section.Duration)) .Skip(1) .ToList(); }
public IEnumerable<IDocument> Execute(IReadOnlyList<IDocument> inputs, IExecutionContext context) { if (_modules != null) { Dictionary<string, object> metadata = new Dictionary<string, object>(); // Execute the modules for each input document if (_forEachDocument) { return inputs.Select(input => { foreach (IDocument result in context.Execute(_modules, new[] { input })) { foreach (KeyValuePair<string, object> kvp in result) { metadata[kvp.Key] = kvp.Value; } } return input.Clone(metadata); }); } // Execute the modules once and apply to each input document foreach (IDocument result in context.Execute(_modules)) { foreach (KeyValuePair<string, object> kvp in result) { metadata[kvp.Key] = kvp.Value; } } return inputs.Select(input => input.Clone(metadata)); } return inputs.Select(x => x.Clone(new [] { new KeyValuePair<string, object>(_key, _metadata.GetValue(x, context)) })); }
public static void Save(IReadOnlyList<Contribution> contributions) { Guard.AgainstNullArgument(nameof(contributions), contributions); using (var writer = new StreamWriter("contributions.txt", false)) { writer.Write("Login/Group"); foreach (var group in contributions.Select(contribution => contribution.Group).Distinct()) { writer.Write("\t" + @group); } writer.WriteLine(); foreach (var login in contributions.Select(contribution => contribution.Login).Distinct()) { writer.Write(login); foreach (var group in contributions.Select(contribution => contribution.Group).Distinct()) { var contribution = contributions.SingleOrDefault( candidate => candidate.Group == @group && candidate.Login == login); writer.Write( "\t" + (contribution?.Score.ToString(CultureInfo.InvariantCulture) ?? "0")); } writer.WriteLine(); } } }
// constructors /// <summary> /// Initializes a new instance of the <see cref="BulkWriteOperationResult" /> class. /// </summary> /// <param name="requestCount">The request count.</param> /// <param name="processedRequests">The processed requests.</param> protected BulkWriteOperationResult( int requestCount, IReadOnlyList<WriteRequest> processedRequests) { _requestCount = requestCount; _processedRequests = processedRequests; }
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); }); } }); }
/// <summary> /// Instantiates a new SteinerTabViewModel. /// </summary> /// <param name="tree">The (not null) SkillTree instance to operate on.</param> /// <param name="dialogCoordinator">The <see cref="IDialogCoordinator"/> used to display dialogs.</param> /// <param name="dialogContext">The context used for <paramref name="dialogCoordinator"/>.</param> /// <param name="runCallback">The action that is called when RunCommand is executed.</param> public SteinerTabViewModel(SkillTree tree, IDialogCoordinator dialogCoordinator, object dialogContext, Action<GeneratorTabViewModel> runCallback) : base(tree, dialogCoordinator, dialogContext, 1, runCallback) { DisplayName = L10n.Message("Tagged Nodes"); SubSettings = new[] {ExcludeCrossed}; }
public static void AddImplements(this TypeBuilder builder, IReadOnlyList<TypeStructure> imp) { foreach (var v in imp) { builder.AddInterfaceImplementation(v.GainType()); } }
public async Task<IList<Mutation>> Validate(ParsedMutation mutation, IReadOnlyList<SignatureEvidence> authentication, IReadOnlyDictionary<AccountKey, AccountStatus> accounts) { await ValidateAccountMutations(mutation.AccountMutations, accounts, authentication); await ValidateDataMutations(mutation.DataRecords, authentication); return new Mutation[0]; }
public RSessionEvaluation(IReadOnlyList<IRContext> contexts, IRExpressionEvaluator evaluator, CancellationToken ct) { Contexts = contexts; _evaluator = evaluator; _tcs = new TaskCompletionSource<object>(); _ct = ct; ct.Register(() => _tcs.TrySetCanceled()); }
public BasketViewModel(IReadOnlyList <BasketLineItem> basketLineItems) { this.BasketLineItems = basketLineItems; }
private TableFormula createTableFormulaFrom(TableFormulaParameter <IDistributedParameter> parameter, IReadOnlyList <ParameterDistributionMetaData> allDistributionsWithAgeStrictBiggerThanOriginData) { if (allDistributionsWithAgeStrictBiggerThanOriginData.Count == 0) { return(null); } var tableFormula = _formulaFactory.CreateDistributedTableFormula(); updateTableFormulaFrom(tableFormula, parameter.Parameter); tableFormula.Percentile = parameter.Percentile; if (parameter.PercentileIsInvalid) { throw new PKSimException(PKSimConstants.Error.CannotCreateAgingSimulationWithInvalidPercentile(_fullPathDisplayResolver.FullPathFor(parameter.Parameter), parameter.Percentile)); } //0 because of the offset with age tableFormula.AddPoint(0, parameter.Value, DistributionMetaData.From(parameter.Parameter)); foreach (var scaledDistribution in scaleDistributions(parameter, allDistributionsWithAgeStrictBiggerThanOriginData)) { var age = ageWithOffsetInMin(scaledDistribution.Age, parameter.OriginData.Age.Value); var value = valueFrom(scaledDistribution, parameter.Percentile); tableFormula.AddPoint(age, value, DistributionMetaData.From(scaledDistribution)); } return(tableFormula); }
public bool TryGetProjectRestoreInfo(string name, out DependencyGraphSpec projectRestoreInfo, out IReadOnlyList <IAssetsLogMessage> additionalMessages) { if (string.IsNullOrEmpty(name)) { throw new ArgumentException(CommonResources.Argument_Cannot_Be_Null_Or_Empty, nameof(name)); } projectRestoreInfo = null; additionalMessages = null; CacheEntry cacheEntry; if (TryGetCacheEntry(name, out cacheEntry)) { projectRestoreInfo = cacheEntry.ProjectRestoreInfo; additionalMessages = cacheEntry.AdditionalMessages; } return(projectRestoreInfo != null); }
public bool AddProjectRestoreInfo(ProjectNames projectNames, DependencyGraphSpec projectRestoreInfo, IReadOnlyList <IAssetsLogMessage> additionalMessages) { if (projectNames == null) { throw new ArgumentNullException(nameof(projectNames)); } if (projectNames.FullName == null) { throw new ArgumentNullException(nameof(projectNames.FullName)); } _readerWriterLock.EnterWriteLock(); try { if (!_projectNamesCache.ContainsKey(projectNames.FullName)) { UpdateProjectNamesCache(projectNames); } AddOrUpdateCacheEntry( projectNames.FullName, addEntryFactory: k => new CacheEntry { ProjectRestoreInfo = projectRestoreInfo, AdditionalMessages = additionalMessages }, updateEntryFactory: (k, e) => { e.ProjectRestoreInfo = projectRestoreInfo; e.AdditionalMessages = additionalMessages; return(e); }); } finally { _readerWriterLock.ExitWriteLock(); } FireCacheUpdatedEvent(projectNames.FullName); return(true); }
public new async Task SendMailAsync(MailMessage message) { if (_disposed) { throw new ObjectDisposedException("SmtpClientEx"); } if (DeliveryMethod == SmtpDeliveryMethod.Network) { if (string.IsNullOrEmpty(_host)) { if (_dnsClient == null) { _dnsClient = new DnsClient(); } IReadOnlyList <string> mxServers = await _dnsClient.ResolveMXAsync(message.To[0].Host); if (mxServers.Count > 0) { _host = mxServers[0]; } else { _host = message.To[0].Host; } _port = 25; Credentials = null; } if (_proxy == null) { if (_enableSslWrapper) { EndPoint remoteEP = EndPointExtension.GetEndPoint(_host, _port); if ((_tunnelProxy != null) && !_tunnelProxy.RemoteEndPoint.Equals(remoteEP)) { _tunnelProxy.Dispose(); _tunnelProxy = null; } if ((_tunnelProxy == null) || _tunnelProxy.IsBroken) { IPEndPoint ep = await remoteEP.GetIPEndPointAsync(); Socket socket = new Socket(ep.AddressFamily, SocketType.Stream, ProtocolType.Tcp); await socket.ConnectAsync(ep); _tunnelProxy = new TunnelProxy(socket, remoteEP, _enableSslWrapper, _ignoreCertificateErrors); } base.Host = _tunnelProxy.TunnelEndPoint.Address.ToString(); base.Port = _tunnelProxy.TunnelEndPoint.Port; } else { base.Host = _host; base.Port = _port; } await base.SendMailAsync(message); } else { EndPoint remoteEP = EndPointExtension.GetEndPoint(_host, _port); if ((_tunnelProxy != null) && !_tunnelProxy.RemoteEndPoint.Equals(remoteEP)) { _tunnelProxy.Dispose(); _tunnelProxy = null; } if ((_tunnelProxy == null) || _tunnelProxy.IsBroken) { _tunnelProxy = await _proxy.CreateTunnelProxyAsync(remoteEP, _enableSslWrapper, _ignoreCertificateErrors); } base.Host = _tunnelProxy.TunnelEndPoint.Address.ToString(); base.Port = _tunnelProxy.TunnelEndPoint.Port; await base.SendMailAsync(message); } } else { await base.SendMailAsync(message); } }
public SyntaxTreeDeclarationInfo(VersionStamp version, IReadOnlyList<DeclaredSymbolInfo> declaredSymbolInfos) : base(version) { DeclaredSymbolInfos = declaredSymbolInfos; }
private Func <OriginData, (double mean, double deviation)> distributionSamplesFor(IReadOnlyList <ParameterDistributionMetaData> distributions) { var knownSamples = from distribution in distributions select new { Mean = new Sample(distribution.Age, distribution.Mean), Std = new Sample(distribution.Age, distribution.Deviation), }; knownSamples = knownSamples.ToList(); return((originData) => { double mean = _interpolation.Interpolate(knownSamples.Select(item => item.Mean), originData.Age.Value); double deviation = _interpolation.Interpolate(knownSamples.Select(item => item.Std), originData.Age.Value); return (mean, deviation); }); }
private IReadOnlyList <ParameterDistributionMetaData> scaleDistributions(TableFormulaParameter <IDistributedParameter> parameter, IReadOnlyList <ParameterDistributionMetaData> distributionsToScale) { //Retrieve the mean height parameter for the given origin data var originData = parameter.OriginData; var individualParameter = parameter.Parameter; bool needHeightScaling = needScaling(originData, individualParameter); if (!needHeightScaling) { return(distributionsToScale); } var(meanHeight, currentHeight, currentPercentile, heightDistributionSamples) = heightDistributionsFor(originData); //same height, not need to scale if (ValueComparer.AreValuesEqual(meanHeight, currentHeight)) { return(distributionsToScale); } //is used in order to retrieve the percentile double alpha = individualParameter.ParentContainer.Parameter(CoreConstants.Parameters.ALLOMETRIC_SCALE_FACTOR).Value; var currentOriginData = originData.Clone(); var scaledParameterDistributionMetaData = new List <ParameterDistributionMetaData>(); foreach (var originDistributionMetaData in distributionsToScale) { var distributionMetaData = ParameterDistributionMetaData.From(originDistributionMetaData); currentOriginData.Age = originDistributionMetaData.Age; var(mean, deviation) = heightDistributionSamples(currentOriginData); double heightAtPercentile = valueFrom(DistributionTypes.Normal, mean, deviation, currentPercentile); double hrelForAge = heightAtPercentile / mean; scaleDistributionMetaData(distributionMetaData, hrelForAge, alpha); scaledParameterDistributionMetaData.Add(distributionMetaData); } return(scaledParameterDistributionMetaData); }
private IReadOnlyList <ParameterDistributionMetaData> allDistributionsWithAgeStrictBiggerThanOriginData( IReadOnlyList <ParameterDistributionMetaData> distributionsForMale, IReadOnlyList <ParameterDistributionMetaData> distributionsForFemale, OriginData originData) { return(allDistributionsFor(distributionsForMale, distributionsForFemale, originData, x => x.Age > originData.Age)); }
private TableFormula createTableFormulaFrom(IDistributedParameter individualParameter, IReadOnlyList <ParameterDistributionMetaData> allDistributionsWithAgeStrictBiggerThanOriginData) { var parameter = new TableFormulaParameter <IDistributedParameter> { OriginData = _baseOriginData, Parameter = individualParameter, Value = individualParameter.Value, Percentile = individualParameter.Percentile }; return(createTableFormulaFrom(parameter, allDistributionsWithAgeStrictBiggerThanOriginData)); }
/// <inheritdoc /> public bool IsProcessorCompatible(IReadOnlyList <ITfsProcessingConfig> otherProcessors) { return(true); }
private TableFormula createMoleculeOntogenyTableFormula(IParameter ontogenyFactor, OriginData originData, IReadOnlyList <Sample> allOntogenies) { //null is ok here. It's the default value for formula in ParameterStartValue if (allOntogenies.Count == 0) { return(null); } var tableFormula = _formulaFactory.CreateTableFormula(); updateTableFormulaFrom(tableFormula, ontogenyFactor); //0 because of the offset with age tableFormula.AddPoint(0, ontogenyFactor.Value); foreach (var ontogenyForAge in allOntogenies) { var age = ageWithOffsetInMin(ontogenyForAge.X, originData.Age.Value); tableFormula.AddPoint(age, ontogenyForAge.Y); } tableFormula.UseDerivedValues = false; return(tableFormula); }
public PagedResult(IReadOnlyList <TEntity> items, string?paginationToken) { Items = items; PaginationToken = paginationToken; }
public async Task ReadAsync() { this.RaiseProgressUpdate(0, null); int totalFileCount = await FileUtil.GetFilesCountInAllDirectoriesAsync(this.RootFolder); int progressStep = totalFileCount / 1000; int filesAlreadyProcessed = 0; int filesAlreadyProcessedTillLastProgressUpdate = progressStep + 1; // set so that we get status update as soon as we start updating the DB async Task directorySearch(StorageFolder rootFolder) { // recursively search through all folders IReadOnlyList <StorageFolder> folders = await rootFolder.GetFoldersAsync(Windows.Storage.Search.CommonFolderQuery.DefaultQuery); foreach (StorageFolder folder in folders) { await directorySearch(folder); } using (MusicLibraryContext dbContext = new MusicLibraryContext()) { // get all files in directory foreach (StorageFile file in await rootFolder.GetFilesAsync()) { filesAlreadyProcessed++; filesAlreadyProcessedTillLastProgressUpdate++; // continue for sound files only if (allowedExtensions.Contains(file.FileType.ToUpperInvariant())) { Song song; Mp3Stream tagStream = new Id3.Mp3Stream(await file.OpenStreamForReadAsync()); bool anySongTags; Id3Tag[] songTags = null; try { songTags = tagStream.GetAllTags(); anySongTags = songTags.Length > 0; } catch (Exception e) { anySongTags = false; } if (anySongTags) { Id3Tag songTag = songTags[0]; // search for an existing artist by name Artist artist = Artist.CreateOrFind(dbContext, songTag.Artists.Value); // search for an existing album by name and artist Album album = Album.CreateOrFind(dbContext, songTag.Album, artist.ArtistId); // search for an existing song by path song = Song.CreateOrFind(dbContext, file.Path); // set reference to the album song.Album = album; // load other simpler properties if (songTag.Year.IsAssigned) { song.Year = songTag.Year.AsDateTime.Value.Year; } if (songTag.Track.IsAssigned) { song.Track = songTag.Track.AsInt.Value; } song.Title = songTag.Title; song.Genre = songTag.Genre; song.Comment = string.Join(", ", songTag.Comments); // insert/update to DB dbContext.SaveChanges(); // save image to localappdata if (songTag.Pictures.Any()) { await SongImageUtil.SaveImageAsync(song.SongId, songTag.Pictures.First().PictureData, songTag.Pictures.First().MimeType); } } else { song = Song.CreateOrFind(dbContext, file.Path); song.Title = Path.GetFileNameWithoutExtension(file.Path); // insert/update to DB dbContext.SaveChanges(); } // update progress if (filesAlreadyProcessedTillLastProgressUpdate > progressStep) { filesAlreadyProcessedTillLastProgressUpdate = 0; this.RaiseProgressUpdate((float)filesAlreadyProcessed / totalFileCount, song); } } } } }; if (totalFileCount > 0) { await directorySearch(this.RootFolder); } }
internal KeyVaultPrivateEndpointConnectionListResult(IReadOnlyList <KeyVaultPrivateEndpointConnectionData> value, string nextLink) { Value = value; NextLink = nextLink; }
public CompositeCallCredentials(CallCredentials[] credentials) { GrpcPreconditions.CheckArgument(credentials.Length >= 2, "Composite credentials object can only be created from 2 or more credentials."); this.credentials = new List <CallCredentials>(credentials).AsReadOnly(); }
/// <summary> /// Initializes an instance of <see cref="CommandInput"/>. /// </summary> public CommandInput(string commandName, IReadOnlyList <CommandOptionInput> options) : this(commandName, EmptyDirectives, options) { }
/// <summary> /// Initializes an instance of <see cref="CommandInput"/>. /// </summary> public CommandInput(IReadOnlyList <CommandOptionInput> options) : this(null, options) { }
private async void UpdateSearch(string enteredText, string locationText, bool restrictToExtent = false) { // Clear any existing markers. MyMapView.GraphicsOverlays.Clear(); // Return gracefully if the textbox is empty or the geocoder isn't ready. if (String.IsNullOrWhiteSpace(enteredText) || _geocoder == null) { return; } // Create the geocode parameters. GeocodeParameters parameters = new GeocodeParameters(); // Get the MapPoint for the current search location. MapPoint searchLocation = await GetSearchMapPoint(locationText); // Update the geocode parameters if the map point is not null. if (searchLocation != null) { parameters.PreferredSearchLocation = searchLocation; } // Update the search area if desired. if (restrictToExtent) { // Get the current map extent. Geometry extent = MyMapView.VisibleArea; // Update the search parameters. parameters.SearchArea = extent; } // Show the progress bar. MyProgressBar.IsVisible = true; // Get the location information. IReadOnlyList<GeocodeResult> locations = await _geocoder.GeocodeAsync(enteredText, parameters); // Stop gracefully and show a message if the geocoder does not return a result. if (locations.Count < 1) { MyProgressBar.IsVisible = false; // 1. Hide the progress bar. ShowStatusMessage("No results found"); // 2. Show a message. return; // 3. Stop. } // Create the GraphicsOverlay so that results can be drawn on the map. GraphicsOverlay resultOverlay = new GraphicsOverlay(); // Add each address to the map. foreach (GeocodeResult location in locations) { // Get the Graphic to display. Graphic point = await GraphicForPoint(location.DisplayLocation); // Add the specific result data to the point. point.Attributes["Match_Title"] = location.Label; // Get the address for the point. IReadOnlyList<GeocodeResult> addresses = await _geocoder.ReverseGeocodeAsync(location.DisplayLocation); // Add the first suitable address if possible. if (addresses.Any()) { point.Attributes["Match_Address"] = addresses.First().Label; } // Add the Graphic to the GraphicsOverlay. resultOverlay.Graphics.Add(point); } // Hide the progress bar. MyProgressBar.IsVisible = false; // Add the GraphicsOverlay to the MapView. MyMapView.GraphicsOverlays.Add(resultOverlay); // Update the map viewpoint. await MyMapView.SetViewpointGeometryAsync(resultOverlay.Extent, 50); }
/// <summary> /// Initializes an instance of <see cref="CommandInput"/>. /// </summary> public CommandInput(string commandName, IReadOnlyList <string> directives, IReadOnlyList <CommandOptionInput> options) { CommandName = commandName; // can be null Directives = directives.GuardNotNull(nameof(directives)); Options = options.GuardNotNull(nameof(options)); }
// Забираем у всего сервера роль игры, выпиливаем всех из скрытого канала public static async Task <bool> Wipe(bool fullWipe = false) { try { Stopwatch timer = new Stopwatch(); timer.Start(); await Print("Wipe(): ПРОЦЕДУРА ЗАПУЩЕНА..."); if (Logovo != null) { await Print("Wipe(): Запущено удаление канала логова..."); await RemoveLogovo(); await Print($"Wipe(): Выполнено за {timer.Elapsed.TotalSeconds} сек."); timer.Restart(); } IReadOnlyList <DiscordMember> members = null; if (fullWipe) { await Print("Wipe(): Получаю список пользователей сервера..."); members = await Config.Guild.GetAllMembersAsync(); await Print($"Wipe(): Выполнено за {timer.Elapsed.TotalSeconds} сек."); timer.Restart(); await Print("Wipe(): Открываю доступ в главный канал..."); await DisableMod(); await Print($"Wipe(): Выполнено за {timer.Elapsed.TotalSeconds} сек."); timer.Restart(); } else { await Print("Wipe(): Получаю список игроков..."); members = Game.Players.Keys.ToList(); await Print($"Wipe(): Выполнено за {timer.Elapsed.TotalSeconds} сек."); timer.Restart(); } await Print("Wipe(): Удаляю роли у всех пользователей с ролью мафии..."); foreach (DiscordMember member in members) { if (member.Roles.ToList().Contains(Config.RoleMain)) { await member.RevokeRoleAsync(Config.RoleMain); await Task.Delay(2000); } } await Print($"Wipe(): Выполнено за {timer.Elapsed.TotalSeconds} сек."); timer.Reset(); await Print("Wipe(): ПРОЦЕДУРА ЗАВЕРШЕНА!"); return(true); } catch (Exception) { return(false); } }
protected override decimal?ComputeByIndexImpl(IReadOnlyList <decimal> mappedInputs, int index) { var bb = _bb[index]; return((bb.UpperBand - bb.LowerBand) / bb.MiddleBand * 100); }
public Task SendToAllExcept(string message, IReadOnlyList<string> excludedIds) { return Clients.AllExcept(excludedIds).Send(message); }
/// <summary> /// Constructor for the <see cref="CsClass"/> /// </summary> /// <param name="isLoaded">Flag that determines if the model was loaded.</param> /// <param name="hasErrors">Flag that determine if errors were found creating the model.</param> /// <param name="loadedFromSource">Flag that determines if the model was loaded from source code or from an existing library.</param> /// <param name="language">The target language the model was generated from.</param> /// <param name="members">The members assigned to this container.</param> /// <param name="baseClass">The class model that is base class of this class.</param> /// <param name="sourceDocument">The source document that was used to build this model. This is optional parameter and can be null.</param> /// <param name="modelStore">Optional the lookup storage for models created during the compile or lookup of the model.</param> /// <param name="modelErrors">Optional the error that occured while creating the model.</param> /// <param name="attributes">List of the attributes assigned to this model.</param> /// <param name="isGeneric">Flag that determines if the container is a generic definition.</param> /// <param name="hasStrongTypesInGenerics">Flag that determines if the generics use strong type definitions.</param> /// <param name="genericParameters">Generic parameters assigned to the container.</param> /// <param name="genericTypes">Target types for the generic parameters assigned to the container.</param> /// <param name="sourceFiles">List of the fully qualified paths to the source code files this model is defined in.</param> /// <param name="hasDocumentation">Flag that determines if the model has XML documentation assigned to it.</param> /// <param name="documentation">The xml documentation assigned to the model.</param> /// <param name="lookupPath">The fully qualified model lookup path for this model.</param> /// <param name="name">The name of the model.</param> /// <param name="ns">The namespace the container belongs to.</param> /// <param name="parentPath">The fully qualified lookup path for the parent model to this one.</param> /// <param name="security">The security scope assigned to this model.</param> /// <param name="inheritedInterfaces">The interfaces that are inherited by this container.</param> /// <param name="isStatic">Flag that determines if the model is static.</param> /// <param name="isAbstract">Flag that determines if the model is abstract.</param> /// <param name="isSealed">Flag that determines if the model is sealed.</param> protected CsClass(bool isLoaded, bool hasErrors, bool loadedFromSource, SourceCodeType language, IReadOnlyList<CsAttribute> attributes, bool isGeneric, bool hasStrongTypesInGenerics, IReadOnlyList<CsGenericParameter> genericParameters, IReadOnlyList<CsType> genericTypes, IReadOnlyList<string> sourceFiles, bool hasDocumentation, string documentation, string lookupPath, string name, string ns, string parentPath, CsSecurity security, IReadOnlyList<CsInterface> inheritedInterfaces, IReadOnlyList<CsMember> members, bool isStatic, bool isAbstract, bool isSealed, CsClass baseClass, string sourceDocument = null, ModelStore<ICsModel> modelStore = null, IReadOnlyList<ModelLoadException> modelErrors = null) : base(isLoaded, hasErrors, loadedFromSource, language, CsModelType.Class, attributes, isGeneric, hasStrongTypesInGenerics, genericParameters, genericTypes, sourceFiles, hasDocumentation, documentation, lookupPath, name, ns, parentPath, CsContainerType.Class, security, inheritedInterfaces, members, sourceDocument, modelStore, modelErrors) { _isStatic = isStatic; _isAbstract = isAbstract; _isSealed = isSealed; _baseClass = baseClass; }
public Task GroupExceptSendMethod(string groupName, string message, IReadOnlyList<string> excludedIds) { return Clients.GroupExcept(groupName, excludedIds).SendAsync("Send", message); }
/// <summary> /// Renderes the given historic coverages as PNG image. /// </summary> /// <param name="historicCoverages">The historic coverages.</param> /// <returns>The image in PNG format.</returns> public static byte[] RenderHistoryChart(IReadOnlyList <HistoricCoverage> historicCoverages) { using (Image <Rgba32> image = new Image <Rgba32>(1450, 150)) using (MemoryStream output = new MemoryStream()) { var grayPen = Pens.Dash(Color.LightGray, 1); var redPen = Pens.Solid(Color.ParseHex("cc0000"), 2); var bluePen = Pens.Solid(Color.ParseHex("1c2298"), 2); var redBrush = Brushes.Solid(Color.ParseHex("cc0000")); var blueBrush = Brushes.Solid(Color.ParseHex("1c2298")); int numberOfLines = historicCoverages.Count; if (numberOfLines == 1) { numberOfLines = 2; } float totalWidth = 1445 - 50; float width = totalWidth / (numberOfLines - 1); float totalHeight = 115 - 15; image.Mutate(ctx => { ctx.Fill(Color.White); ctx.DrawLines(grayPen, new PointF(50, 115), new PointF(1445, 115)); ctx.DrawLines(grayPen, new PointF(50, 90), new PointF(1445, 90)); ctx.DrawLines(grayPen, new PointF(50, 65), new PointF(1445, 65)); ctx.DrawLines(grayPen, new PointF(50, 40), new PointF(1445, 40)); ctx.DrawLines(grayPen, new PointF(50, 15), new PointF(1445, 15)); for (int i = 0; i < numberOfLines; i++) { ctx.DrawLines(grayPen, new PointF(50 + (i * width), 15), new PointF(50 + (i * width), 115)); } for (int i = 1; i < historicCoverages.Count; i++) { float x1 = 50 + ((i - 1) * width); float y1 = 15 + (((100 - (float)historicCoverages[i - 1].CoverageQuota.GetValueOrDefault()) * totalHeight) / 100); float x2 = 50 + (i * width); float y2 = 15 + (((100 - (float)historicCoverages[i].CoverageQuota.GetValueOrDefault()) * totalHeight) / 100); ctx.DrawLines(redPen, new PointF(x1, y1), new PointF(x2, y2)); } if (historicCoverages.Any(h => h.BranchCoverageQuota.HasValue)) { for (int i = 1; i < historicCoverages.Count; i++) { float x1 = 50 + ((i - 1) * width); float y1 = 15 + (((100 - (float)historicCoverages[i - 1].BranchCoverageQuota.GetValueOrDefault()) * totalHeight) / 100); float x2 = 50 + (i * width); float y2 = 15 + (((100 - (float)historicCoverages[i].BranchCoverageQuota.GetValueOrDefault()) * totalHeight) / 100); ctx.DrawLines(bluePen, new PointF(x1, y1), new PointF(x2, y2)); } } for (int i = 0; i < historicCoverages.Count; i++) { float x1 = 50 + (i * width); float y1 = 15 + (((100 - (float)historicCoverages[i].CoverageQuota.GetValueOrDefault()) * totalHeight) / 100); ctx.Fill(redBrush, new EllipsePolygon(x1, y1, 3)); } if (historicCoverages.Any(h => h.BranchCoverageQuota.HasValue)) { for (int i = 0; i < historicCoverages.Count; i++) { float x1 = 50 + (i * width); float y1 = 15 + (((100 - (float)historicCoverages[i].BranchCoverageQuota.GetValueOrDefault()) * totalHeight) / 100); ctx.Fill(blueBrush, new EllipsePolygon(x1, y1, 3)); } } try { var font = SystemFonts.CreateFont("Arial", 11, FontStyle.Regular); var textGraphicsOptions = new TextGraphicsOptions(); textGraphicsOptions.TextOptions.HorizontalAlignment = HorizontalAlignment.Right; ctx.DrawText(textGraphicsOptions, "100", font, Color.Gray, new PointF(38, 5)); ctx.DrawText(textGraphicsOptions, "75", font, Color.Gray, new PointF(38, 30)); ctx.DrawText(textGraphicsOptions, "50", font, Color.Gray, new PointF(38, 55)); ctx.DrawText(textGraphicsOptions, "25", font, Color.Gray, new PointF(38, 80)); ctx.DrawText(textGraphicsOptions, "0", font, Color.Gray, new PointF(38, 105)); } catch (SixLabors.Fonts.Exceptions.FontFamilyNotFoundException) { // Font 'Arial' may not be present on Linux } }); image.Save(output, new PngEncoder()); return(output.ToArray()); } }
public Task SendToMultipleUsers(IReadOnlyList<string> userIds, string message) { return Clients.Users(userIds).Send(message); }
public Task SendToMultipleGroups(string message, IReadOnlyList<string> groupNames) { return Clients.Groups(groupNames).SendAsync("Send", message); }
public static byte[] Slice(this IReadOnlyList<byte> lst, int begin, int len) { byte[] res = new byte[len]; for(int i=0; i<len; i++) res[i] = lst[begin + i]; return res; }
public Task SendToMultipleClients(string message, IReadOnlyList<string> connectionIds) { return Clients.Clients(connectionIds).SendAsync("Send", message); }