public ulong Size(int mbSize) { var size = (int)(((ulong)mbSize << 20) / (ulong)ClusterSize); EnsureArg.IsGte(mbSize, 1, nameof(mbSize)); if (_table == null) { _table = new List <TTCluster>(size); _elements = (ulong)size; } else if (_table.Count != size) { _elements = (ulong)size; _table.Clear(); _table.Capacity = size; _table.TrimExcess(); } _generation = 1; PopulateTable(); _fullnessElements = Math.Min(size, 250); return((ulong)(size * ClusterSize)); }
protected PagedList(IQueryable <TItem> queryable, int pageNumber, int pageSize) { EnsureArg.IsNotNull(queryable, nameof(queryable)); EnsureArg.IsGte(pageNumber, 1, optsFn: options => options.WithMessage(_PAGE_NUMBER_BELOW_1)); EnsureArg.IsGte(pageSize, 1, optsFn: options => options.WithMessage(_PAGE_SIZE_LESS_THAN_1)); TotalItemCount = queryable.Count(); PageSize = pageSize; PageCount = TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)PageSize) : 0; PageNumber = pageNumber > PageCount ? PageCount : pageNumber; HasPreviousPage = PageNumber > 1; HasNextPage = PageNumber < PageCount; IsFirstPage = PageNumber == 1; IsLastPage = PageNumber == PageCount; FirstItemOnPage = (PageNumber - 1) * PageSize + 1; var assumedLastItemOnPage = FirstItemOnPage + PageSize - 1; LastItemOnPage = assumedLastItemOnPage > TotalItemCount ? TotalItemCount : assumedLastItemOnPage; Items = queryable.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToArray(); }
public ThreadStats(int replies, int images, int posters, int page) { Replies = EnsureArg.IsGte(replies, 0, nameof(replies)); Images = EnsureArg.IsGte(images, 0, nameof(images)); Posters = EnsureArg.IsGte(posters, 0, nameof(posters)); Page = EnsureArg.IsGte(page, 0, nameof(page)); }
/// <summary> /// Gets all calendar events within a month that have not been deleted. /// </summary> /// <param name="year">The year.</param> /// <param name="month">The month (indexed by 1).</param> /// <returns>The calendar events within the time period.</returns> public IEnumerable <CalendarEventDO> GetCalendarEvents(int year, int month) { // Guards EnsureArg.IsGte(month, 1, nameof(month)); EnsureArg.IsLte(month, 12, nameof(month)); var daysInMonth = DateTime.DaysInMonth(year, month); var monthStartDate = new DateTime(year, month, 1); var monthEndDate = new DateTime(year, month, daysInMonth); using (var repo = this.repositoryFactory.Create()) { var records = repo.CalendarEvents .Where( e => e.IsDeleted == false && ( /* Event starts within the month */ (e.StartDate.Date >= monthStartDate.Date && e.StartDate.Date <= monthEndDate.Date) || /* Event ends within the month */ (e.EndDate.Date >= monthStartDate.Date && e.EndDate.Date <= monthEndDate.Date) || /* Event spans the entire month */ (e.StartDate.Date <monthStartDate.Date && e.EndDate.Date> monthEndDate.Date))); foreach (var record in records) { yield return(this.calendarEventMapper.Map(record)); } } }
/// <summary> /// Find the K nearest neighbors. /// O(K logN) /// </summary> /// <param name="startingLocation"></param> /// <param name="maxDistance"></param> /// <param name="maxResults"></param> /// <returns></returns> public async Task <IEnumerable <LocationWithDistanceFromStartingPoint> > GetNearestLocations(StartingLocation startingLocation, int maxDistance, int maxResults) { EnsureArg.IsNotNull(startingLocation, nameof(startingLocation)); EnsureArg.IsGte(maxDistance, 0, nameof(maxDistance)); EnsureArg.IsGt(maxResults, 0, nameof(maxResults)); var startLoc = new Location(startingLocation.Latitude, startingLocation.Longitude); var nearestNeighbors = _locationsKdTree.GetNearestRadialNeighbors( startingLocation.Latitude, startingLocation.Longitude, maxDistance); var res = nearestNeighbors .Select(t => { var loc = new Location(t.Item2, t.Item1[0], t.Item1[1]); return(new LocationWithDistanceFromStartingPoint(loc, loc.CalculateDistance(startLoc))); }) .Where(l => l.DistanceFromStartingPoint <= maxDistance) .OrderBy(l => l.DistanceFromStartingPoint) .Take(maxResults) .ToList(); return(await Task.FromResult(res)); }
public SchemaUpgradedNotification(int version, bool isFullSchemaSnapshot) { EnsureArg.IsGte(version, 1); Version = version; IsFullSchemaSnapshot = isFullSchemaSnapshot; }
public Result <decimal> GetPriceForMonth(Guid companyId, Month month, int violations) { EnsureArg.IsNotEmpty(companyId); EnsureArg.IsGte(violations, 0); var companyOrNothing = companyRepository.GetById(companyId); if (companyOrNothing.HasNoValue) { return(Result.Fail <decimal>("Company does not exist")); } var company = companyOrNothing.Value; var subscriptionOrNothing = company.SubscriptionFor(month); return(subscriptionOrNothing.ToResult("No subscription for given month!") .OnSuccess(subscription => { var employeesCost = company.NumberOfEmployees * subscription.Subscription.Price; var exceedingNumberOfViolations = company.GetExceedingNumberOfViolations(violations); var violationsCost = exceedingNumberOfViolations * violationCost; return employeesCost + violationsCost; })); }
/// <summary> /// Initializes a new instance of the <see cref="ErrorRecord{TErrorCode}"/> class. /// </summary> /// <param name="id">The identifier.</param> /// <param name="ordinalPosition">The ordinal position.</param> /// <param name="errorMessages">The error messages.</param> public ErrorRecord(long id, int ordinalPosition, ErrorMessages <TErrorCode> errorMessages) { EnsureArg.IsGte(ordinalPosition, 0, nameof(ordinalPosition)); EnsureArg.IsNotNull(errorMessages, nameof(errorMessages)); SetValues(id, ordinalPosition, errorMessages); }
/// <inheritdoc /> public async Task ExecuteScriptAndCompleteSchemaVersionAsync(string script, int version, CancellationToken cancellationToken) { EnsureArg.IsNotNull(script, nameof(script)); EnsureArg.IsGte(version, 1); using SqlConnection connection = await _sqlConnectionFactory.GetSqlConnectionAsync(cancellationToken : cancellationToken).ConfigureAwait(false); await connection.TryOpenAsync(cancellationToken).ConfigureAwait(false); var serverConnection = new ServerConnection(connection); try { var server = new Server(serverConnection); server.ConnectionContext.ExecuteNonQuery(script); await UpsertSchemaVersionAsync(connection, version, SchemaVersionStatus.Completed.ToString(), cancellationToken).ConfigureAwait(false); } catch (Exception e) when(e is SqlException || e is ExecutionFailureException) { await UpsertSchemaVersionAsync(connection, version, SchemaVersionStatus.Failed.ToString(), cancellationToken).ConfigureAwait(false); throw; } }
public static void AppendRandomPixelData(int rows, int columns, int frames, params DicomFile[] dicomFiles) { EnsureArg.IsGte(rows, 0, nameof(rows)); EnsureArg.IsGte(columns, 0, nameof(columns)); EnsureArg.IsNotNull(dicomFiles, nameof(dicomFiles)); var pixelDataSize = rows * columns; const ushort bitsAllocated = 8; dicomFiles.Each(x => { x.Dataset.AddOrUpdate(DicomTag.Rows, (ushort)rows); x.Dataset.AddOrUpdate(DicomTag.Columns, (ushort)columns); x.Dataset.AddOrUpdate(DicomTag.BitsAllocated, bitsAllocated); var pixelData = DicomPixelData.Create(x.Dataset, true); pixelData.SamplesPerPixel = 1; pixelData.PixelRepresentation = PixelRepresentation.Unsigned; pixelData.BitsStored = bitsAllocated; pixelData.HighBit = bitsAllocated - 1; for (var i = 0; i < frames; i++) { pixelData.AddFrame(CreateRandomPixelData(pixelDataSize)); } }); }
/// <summary> /// Deletes an existing calendar event (logical delete, not physical, by applying deletion flag). /// </summary> /// <param name="calendarEventId">The calendar event ID.</param> /// <exception cref="RecordNotFoundException">Exception thrown when calendar event for ID does not exist in the database.</exception> public void DeleteCalendarEvent(long calendarEventId) { // Guards EnsureArg.IsGte(calendarEventId, 1, nameof(calendarEventId)); using (var repo = this.repositoryFactory.Create()) { var record = repo.CalendarEvents .Where(e => e.Id == calendarEventId) .SingleOrDefault(); if (record == null) { this.logger.LogError($"Calendar event with ID '{calendarEventId}' could not be found."); throw new RecordNotFoundException(); } record.IsDeleted = true; repo.UpdateCalendarEvent(record); repo.SaveChanges(); } this.logger.LogInformation($"Calendar event with ID '{calendarEventId}' has been marked as deleted."); }
protected PagedList(IEnumerable <TItem> enumerable, int pageNumber, int pageSize) { EnsureArg.IsGte(pageNumber, 1, optsFn: options => options.WithMessage(_PAGE_NUMBER_BELOW_1)); EnsureArg.IsGte(pageSize, 1, optsFn: options => options.WithMessage(_PAGE_SIZE_LESS_THAN_1)); var items = enumerable?.ToArray() ?? new TItem[0]; TotalItemCount = items.Length; PageSize = pageSize; PageCount = TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)PageSize) : 0; PageNumber = pageNumber > PageCount ? PageCount : pageNumber; HasPreviousPage = PageNumber > 1; HasNextPage = PageNumber < PageCount; IsFirstPage = PageNumber == 1; IsLastPage = PageNumber == PageCount; FirstItemOnPage = (PageNumber - 1) * PageSize + 1; var assumedLastItemOnPage = FirstItemOnPage + PageSize - 1; LastItemOnPage = assumedLastItemOnPage > TotalItemCount ? TotalItemCount : assumedLastItemOnPage; Items = items.Skip((pageNumber - 1) * pageSize).Take(pageSize).ToArray(); }
public MultipartResult(int statusCode, IEnumerable <MultipartItem> multipartItems) { EnsureArg.IsGte(statusCode, 100, nameof(statusCode)); EnsureArg.IsNotNull(multipartItems, nameof(multipartItems)); _statusCode = statusCode; _multipartItems = multipartItems; }
public void IsGte_When_value_is_lt_than_limit_It_throws_ArgumentException() { var spec = When_value_is_lt_than_limit(); AssertIsGteScenario(spec.Value, spec.Limit, () => Ensure.That(spec.Value, ParamName).IsGte(spec.Limit), () => EnsureArg.IsGte(spec.Value, spec.Limit, ParamName)); }
public void IsGte_When_value_is_gt_than_limit_It_should_not_throw() { var spec = When_value_is_gt_than_limit(); ShouldNotThrow( () => Ensure.That(spec.Value, ParamName).IsGte(spec.Limit), () => EnsureArg.IsGte(spec.Value, spec.Limit, ParamName)); }
/// <summary> /// Read quorum needed for the result. /// Defaults to 1. /// </summary> /// <param name="value"></param> /// <returns></returns> public virtual FindParametersConfigurator ReadQuorum(int value) { EnsureArg.IsGte(value, 1, nameof(value)); Parameters.ReadQuorum = value; return(this); }
public async Task <IReadOnlyList <GetExtendedQueryTagEntry> > GetTagsAsync(int limit, int offset, CancellationToken cancellationToken = default) { EnsureArg.IsGte(limit, 1, nameof(limit)); EnsureArg.IsGte(offset, 0, nameof(offset)); var response = await _dicomWebClient.GetExtendedQueryTagsAsync(limit, offset, cancellationToken); return((await response.GetValueAsync()).ToList()); }
public ReadOnlyLimitStream(Stream stream, long limit) { EnsureArg.IsNotNull(stream, nameof(stream)); EnsureArg.IsGte(limit, 0); _stream = stream; _bytesLeft = limit; _limit = limit; }
/// <summary> /// Initializes a new instance of the <see cref="BatchCreationArguments"/> class with the specified values. /// </summary> /// <param name="maxWatermark">The optional inclusive maximum watermark.</param> /// <param name="batchSize">The number of DICOM instances processed by a single activity.</param> /// <param name="maxParallelBatches">The maximum number of concurrent batches processed at a given time.</param> /// <exception cref="ArgumentOutOfRangeException"> /// <para><paramref name="batchSize"/> is less than <c>1</c>.</para> /// <para>-or-</para> /// <para><paramref name="maxParallelBatches"/> is less than <c>1</c>.</para> /// </exception> public BatchCreationArguments(long?maxWatermark, int batchSize, int maxParallelBatches) { EnsureArg.IsGte(batchSize, 1, nameof(batchSize)); EnsureArg.IsGte(maxParallelBatches, 1, nameof(maxParallelBatches)); BatchSize = batchSize; MaxParallelBatches = maxParallelBatches; MaxWatermark = maxWatermark; }
public CancelExportRequestHandler(IFhirOperationDataStore fhirOperationDataStore, int retryCount, Func <int, TimeSpan> sleepDurationProvider) { EnsureArg.IsNotNull(fhirOperationDataStore, nameof(fhirOperationDataStore)); EnsureArg.IsGte(retryCount, 0, nameof(retryCount)); EnsureArg.IsNotNull(sleepDurationProvider, nameof(sleepDurationProvider)); _fhirOperationDataStore = fhirOperationDataStore; _retryPolicy = Policy.Handle <JobConflictException>() .WaitAndRetryAsync(retryCount, sleepDurationProvider); }
public async Task <IReadOnlyList <ExtendedQueryTagError> > GetTagErrorsAsync(string tagPath, int limit, int offset, CancellationToken cancellationToken = default) { EnsureArg.IsNotNull(tagPath, nameof(tagPath)); EnsureArg.IsGte(limit, 1, nameof(limit)); EnsureArg.IsGte(offset, 0, nameof(offset)); var response = await _dicomWebClient.GetExtendedQueryTagErrorsAsync(tagPath, limit, offset, cancellationToken); return((await response.GetValueAsync()).ToList()); }
public ExtendedQueryTagStoreEntry(int key, string path, string vr, string privateCreator, QueryTagLevel level, ExtendedQueryTagStatus status, QueryStatus queryStatus, int errorCount) { Key = key; Path = EnsureArg.IsNotNullOrWhiteSpace(path); VR = EnsureArg.IsNotNullOrWhiteSpace(vr); PrivateCreator = privateCreator; Level = EnsureArg.EnumIsDefined(level); Status = EnsureArg.EnumIsDefined(status); QueryStatus = EnsureArg.EnumIsDefined(queryStatus); ErrorCount = EnsureArg.IsGte(errorCount, 0, nameof(errorCount)); }
public void IsGte_When_value_is_gt_than_limit_It_returns_passed_value() { var spec = When_value_is_gt_than_limit(); var returnedValue = Ensure.That(spec.Value, ParamName).IsGte(spec.Limit); AssertReturnedAsExpected(returnedValue, spec.Value); Action a = () => EnsureArg.IsGte(spec.Value, spec.Limit, ParamName); a.ShouldNotThrow(); }
/// <summary> /// Initializes a new instance of the <see cref="ReindexBatchArguments"/> class with the specified values. /// </summary> /// <param name="queryTags">The tag entries.</param> /// <param name="watermarkRange">The inclusive watermark range.</param> /// <param name="threadCount">The number of threads available for each batch.</param> /// <exception cref="ArgumentNullException"><paramref name="queryTags"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="threadCount"/> is less than <c>1</c>. /// </exception> public ReindexBatchArguments( IReadOnlyCollection <ExtendedQueryTagStoreEntry> queryTags, WatermarkRange watermarkRange, int threadCount) { EnsureArg.IsNotNull(queryTags, nameof(queryTags)); EnsureArg.IsGte(threadCount, 1, nameof(threadCount)); QueryTags = queryTags; ThreadCount = threadCount; WatermarkRange = watermarkRange; }
/// <summary> /// Initializes a new instance of the <see cref="ErrorRecord{TErrorCode}"/> class. /// </summary> /// <param name="ordinalPosition">The ordinal position.</param> /// <param name="errorMessage">The error message.</param> public ErrorRecord(int ordinalPosition, ErrorMessage <TErrorCode> errorMessage) { EnsureArg.IsGte(ordinalPosition, 0, nameof(ordinalPosition)); EnsureArg.IsNotNull(errorMessage, nameof(errorMessage)); var errorMessages = new ErrorMessages <TErrorCode>() { errorMessage }; SetValues(null, ordinalPosition, errorMessages); }
public async Task <IReadOnlyList <T> > GetPagedResponseAsync(int pageNumber, int pageSize) { EnsureArg.IsGte(pageNumber, 1, nameof(pageNumber)); EnsureArg.IsGte(pageSize, 1, nameof(pageSize)); return(await _dbContext .Set <T>() .Skip((pageNumber - 1) * pageSize) .Take(pageSize) .AsNoTracking() .ToListAsync()); }
public CancelReindexRequestHandler(IFhirOperationDataStore fhirOperationDataStore, IAuthorizationService <DataActions> authorizationService, int retryCount, Func <int, TimeSpan> sleepDurationProvider) { EnsureArg.IsNotNull(fhirOperationDataStore, nameof(fhirOperationDataStore)); EnsureArg.IsNotNull(authorizationService, nameof(authorizationService)); EnsureArg.IsGte(retryCount, 0, nameof(retryCount)); EnsureArg.IsNotNull(sleepDurationProvider, nameof(sleepDurationProvider)); _fhirOperationDataStore = fhirOperationDataStore; _authorizationService = authorizationService; _retryPolicy = Policy.Handle <JobConflictException>() .WaitAndRetryAsync(retryCount, sleepDurationProvider); }
/// <summary> /// Initializes a new instance of the <see cref="ErrorRecord{TErrorCode}"/> class. /// </summary> /// <param name="ordinalPosition">The ordinal position.</param> /// <param name="errorCode">The error code.</param> /// <param name="message">The message.</param> public ErrorRecord(int ordinalPosition, TErrorCode errorCode, string message) { EnsureArg.IsGte(ordinalPosition, 0, nameof(ordinalPosition)); EnsureArg.IsNotNull <TErrorCode>(errorCode, nameof(errorCode)); EnsureArg.IsNotEmptyOrWhiteSpace(message, nameof(message)); var errorMessages = new ErrorMessages <TErrorCode> { new ErrorMessage <TErrorCode>(errorCode, message) }; SetValues(null, ordinalPosition, errorMessages); }
public async Task <DicomWebResponse <IEnumerable <GetExtendedQueryTagEntry> > > GetExtendedQueryTagsAsync(int limit, int offset, CancellationToken cancellationToken) { EnsureArg.IsGte(limit, 1, nameof(limit)); EnsureArg.IsGte(offset, 0, nameof(offset)); var uri = new Uri($"/{_apiVersion}{DicomWebConstants.BaseExtendedQueryTagUri}?{DicomWebConstants.LimitParameter}={limit}&{DicomWebConstants.OffsetParameter}={offset}", UriKind.Relative); using var request = new HttpRequestMessage(HttpMethod.Get, uri); HttpResponseMessage response = await HttpClient.SendAsync(request, cancellationToken).ConfigureAwait(false); await EnsureSuccessStatusCodeAsync(response).ConfigureAwait(false); return(new DicomWebResponse <IEnumerable <GetExtendedQueryTagEntry> >(response, ValueFactory <IEnumerable <GetExtendedQueryTagEntry> >)); }
/// <inheritdoc /> public async Task DeleteSchemaVersionAsync(int version, string status, CancellationToken cancellationToken) { EnsureArg.IsNotNull(status, nameof(status)); EnsureArg.IsGte(version, 1); using SqlConnection connection = await _sqlConnectionFactory.GetSqlConnectionAsync(cancellationToken : cancellationToken).ConfigureAwait(false); await connection.TryOpenAsync(cancellationToken).ConfigureAwait(false); using var deleteCommand = new SqlCommand("DELETE FROM dbo.SchemaVersion WHERE Version = @version AND Status = @status", connection); deleteCommand.Parameters.AddWithValue("@version", version); deleteCommand.Parameters.AddWithValue("@status", status); await deleteCommand.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false); }