language
stringclasses
1 value
repo
stringclasses
133 values
path
stringlengths
13
229
class_span
dict
source
stringlengths
14
2.92M
target
stringlengths
1
153
csharp
AvaloniaUI__Avalonia
src/Windows/Avalonia.Win32.Automation/Interop/ISelectionProvider.cs
{ "start": 440, "end": 802 }
internal partial interface ____ { #if NET8_0_OR_GREATER [return: MarshalUsing(typeof(SafeArrayMarshaller<IRawElementProviderSimple>))] #endif IRawElementProviderSimple[] GetSelection(); [return: MarshalAs(UnmanagedType.Bool)] bool CanSelectMultiple(); [return: MarshalAs(UnmanagedType.Bool)] bool IsSelectionRequired(); }
ISelectionProvider
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Themes/TheTheme/Drivers/ToggleThemeNavbarDisplayDriver.cs
{ "start": 205, "end": 797 }
public sealed class ____ : DisplayDriver<Navbar> { private readonly ISiteThemeService _siteThemeService; public ToggleThemeNavbarDisplayDriver(ISiteThemeService siteThemeService) { _siteThemeService = siteThemeService; } public override IDisplayResult Display(Navbar model, BuildDisplayContext context) { return View("ToggleTheme", model) .RenderWhen(async () => await _siteThemeService.GetSiteThemeNameAsync() == "TheTheme") .Location(OrchardCoreConstants.DisplayType.Detail, "Content:10"); } }
ToggleThemeNavbarDisplayDriver
csharp
louthy__language-ext
LanguageExt.Core/DataTypes/Record/RecordType.cs
{ "start": 743, "end": 934 }
record ____ /// </summary> public static Func<A, A, bool> EqualityTyped => RecordTypeEqualityTyped<A>.EqualityTyped; /// <summary> /// General typed comparison function for
types
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler.Tests/TestCases/Pretty/DeconstructionTests.cs
{ "start": 1726, "end": 1911 }
private class ____<T, T2> { public int Dummy { get; set; } public void Deconstruct(out T a, out T2 b) { a = default(T); b = default(T2); } }
DeconstructionSource
csharp
EventStore__EventStore
src/KurrentDB.Projections.Core.Tests/Services/core_projection/when_receiving_committed_events_the_projection_without_when.cs
{ "start": 1571, "end": 3070 }
public class ____<TLogFormat, TStreamId> : specification_with_query_without_when<TLogFormat, TStreamId> { protected override void When() { //projection subscribes here _eventId = Guid.NewGuid(); _consumer.HandledMessages.Clear(); _bus.Publish( EventReaderSubscriptionMessage.CommittedEventReceived.Sample( new ResolvedEvent( "account-01", 1, "account-01", 1, false, new TFPos(120, 110), _eventId, "handle_this_type", false, "data1", "metadata"), _subscriptionId, 0)); _bus.Publish( EventReaderSubscriptionMessage.CommittedEventReceived.Sample( new ResolvedEvent( "account-02", 2, "account-02", 2, false, new TFPos(140, 130), _eventId, "handle_this_type", false, "data2", "metadata"), _subscriptionId, 1)); } [Test] public void update_state_snapshots_are_written_to_the_correct_stream() { var writeEvents = _writeEventHandler.HandledMessages.Where(v => v.Events.Any(e => e.EventType == "Result")).ToList(); Assert.AreEqual(2, writeEvents.Count); Assert.AreEqual("$projections-projection-result", writeEvents[0].EventStreamId); Assert.AreEqual("$projections-projection-result", writeEvents[1].EventStreamId); Assert.AreEqual("data1", Encoding.UTF8.GetString(writeEvents[0].Events[0].Data)); Assert.AreEqual("data2", Encoding.UTF8.GetString(writeEvents[1].Events[0].Data)); } } [TestFixture(typeof(LogFormat.V2), typeof(string))] [TestFixture(typeof(LogFormat.V3), typeof(uint))]
when_receiving_committed_events_the_projection_without_when
csharp
exceptionless__Exceptionless
tests/Exceptionless.Tests/Search/EventStackFilterQueryVisitorTests.cs
{ "start": 6779, "end": 7737 }
public class ____ : IXunitSerializable { public string Source { get; set; } = String.Empty; public string Stack { get; set; } = String.Empty; public string InvertedStack { get; set; } = String.Empty; public string Event { get; set; } = String.Empty; public override string ToString() { return $"Source: \"{Source}\" Stack: \"{Stack}\" InvertedStack: \"{InvertedStack}\" Event: \"{Event}\""; } public void Deserialize(IXunitSerializationInfo info) { var value = JsonConvert.DeserializeObject<FilterScenario>(info.GetValue<string>("objValue")) ?? throw new InvalidOperationException(); Source = value.Source; Stack = value.Stack; InvertedStack = value.InvertedStack; Event = value.Event; } public void Serialize(IXunitSerializationInfo info) { string? json = JsonConvert.SerializeObject(this); info.AddValue("objValue", json); } }
FilterScenario
csharp
jellyfin__jellyfin
MediaBrowser.XbmcMetadata/Providers/SeriesNfoSeasonProvider.cs
{ "start": 455, "end": 3846 }
public class ____ : BaseNfoProvider<Season> { private readonly ILogger<SeriesNfoSeasonProvider> _logger; private readonly IConfigurationManager _config; private readonly IProviderManager _providerManager; private readonly IUserManager _userManager; private readonly IUserDataManager _userDataManager; private readonly IDirectoryService _directoryService; private readonly ILibraryManager _libraryManager; /// <summary> /// Initializes a new instance of the <see cref="SeriesNfoSeasonProvider"/> class. /// </summary> /// <param name="logger">Instance of the <see cref="ILogger{SeasonFromSeriesNfoProvider}"/> interface.</param> /// <param name="fileSystem">Instance of the <see cref="IFileSystem"/> interface.</param> /// <param name="config">Instance of the <see cref="IConfigurationManager"/> interface.</param> /// <param name="providerManager">Instance of the <see cref="IProviderManager"/> interface.</param> /// <param name="userManager">Instance of the <see cref="IUserManager"/> interface.</param> /// <param name="userDataManager">Instance of the <see cref="IUserDataManager"/> interface.</param> /// <param name="directoryService">Instance of the <see cref="IDirectoryService"/> interface.</param> /// <param name="libraryManager">Instance of the <see cref="ILibraryManager"/> interface.</param> public SeriesNfoSeasonProvider( ILogger<SeriesNfoSeasonProvider> logger, IFileSystem fileSystem, IConfigurationManager config, IProviderManager providerManager, IUserManager userManager, IUserDataManager userDataManager, IDirectoryService directoryService, ILibraryManager libraryManager) : base(fileSystem) { _logger = logger; _config = config; _providerManager = providerManager; _userManager = userManager; _userDataManager = userDataManager; _directoryService = directoryService; _libraryManager = libraryManager; } /// <inheritdoc /> protected override void Fetch(MetadataResult<Season> result, string path, CancellationToken cancellationToken) { new SeriesNfoSeasonParser(_logger, _config, _providerManager, _userManager, _userDataManager, _directoryService).Fetch(result, path, cancellationToken); } /// <inheritdoc /> protected override FileSystemMetadata? GetXmlFile(ItemInfo info, IDirectoryService directoryService) { var seasonPath = info.Path; if (seasonPath is not null) { var path = Path.Combine(seasonPath, "tvshow.nfo"); if (Path.Exists(path)) { return directoryService.GetFile(path); } } var seriesPath = _libraryManager.GetItemById(info.ParentId)?.Path; if (seriesPath is not null) { var path = Path.Combine(seriesPath, "tvshow.nfo"); if (Path.Exists(path)) { return directoryService.GetFile(path); } } return null; } } }
SeriesNfoSeasonProvider
csharp
nuke-build__nuke
source/Nuke.Common/Attributes/LatestMyGetVersionAttribute.cs
{ "start": 354, "end": 1051 }
public class ____ : ValueInjectionAttributeBase { private readonly string _feed; private readonly string _package; public LatestMyGetVersionAttribute(string feed, string package) { _feed = feed; _package = package; } public override object GetValue(MemberInfo member, object instance) { var content = HttpTasks.HttpDownloadString($"https://www.myget.org/RSS/{_feed}"); return XmlTasks.XmlPeekFromString(content, ".//title") // TODO: regex? .First(x => x.Contains($"/{_package} ")) .Split('(').Last() .Split(')').First() .TrimStart("version "); } }
LatestMyGetVersionAttribute
csharp
dotnet__aspnetcore
src/DataProtection/samples/KeyManagementSimulator/Program.cs
{ "start": 10058, "end": 10193 }
interface ____, which would usually be prohibited, so we decode exactly those types to /// instances known in advance. /// </summary>
types
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/test/HttpNotFoundObjectResultTest.cs
{ "start": 432, "end": 2597 }
public class ____ { [Fact] public void HttpNotFoundObjectResult_InitializesStatusCode() { // Arrange & act var notFound = new NotFoundObjectResult(null); // Assert Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode); } [Fact] public void HttpNotFoundObjectResult_InitializesStatusCodeAndResponseContent() { // Arrange & act var notFound = new NotFoundObjectResult("Test Content"); // Assert Assert.Equal(StatusCodes.Status404NotFound, notFound.StatusCode); Assert.Equal("Test Content", notFound.Value); } [Fact] public async Task HttpNotFoundObjectResult_ExecuteSuccessful() { // Arrange var httpContext = GetHttpContext(); var actionContext = new ActionContext() { HttpContext = httpContext, }; var result = new NotFoundObjectResult("Test Content"); // Act await result.ExecuteResultAsync(actionContext); // Assert Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode); } private static HttpContext GetHttpContext() { var httpContext = new DefaultHttpContext(); httpContext.Request.PathBase = new PathString(""); httpContext.Response.Body = new MemoryStream(); httpContext.RequestServices = CreateServices(); return httpContext; } private static IServiceProvider CreateServices() { var options = Options.Create(new MvcOptions()); options.Value.OutputFormatters.Add(new StringOutputFormatter()); options.Value.OutputFormatters.Add(SystemTextJsonOutputFormatter.CreateFormatter(new JsonOptions())); var services = new ServiceCollection(); services.AddSingleton<IActionResultExecutor<ObjectResult>>(new ObjectResultExecutor( new DefaultOutputFormatterSelector(options, NullLoggerFactory.Instance), new TestHttpResponseStreamWriterFactory(), NullLoggerFactory.Instance, options)); return services.BuildServiceProvider(); } }
HttpNotFoundObjectResultTest
csharp
npgsql__npgsql
test/Npgsql.Tests/Types/LTreeTests.cs
{ "start": 130, "end": 2690 }
public class ____(MultiplexingMode multiplexingMode) : MultiplexingTestBase(multiplexingMode) { [Test] public Task LQuery() => AssertType("Top.Science.*", "Top.Science.*", "lquery", NpgsqlDbType.LQuery, isDefaultForWriting: false); [Test] public Task LTree() => AssertType("Top.Science.Astronomy", "Top.Science.Astronomy", "ltree", NpgsqlDbType.LTree, isDefaultForWriting: false); [Test] public Task LTxtQuery() => AssertType("Science & Astronomy", "Science & Astronomy", "ltxtquery", NpgsqlDbType.LTxtQuery, isDefaultForWriting: false); [Test] public async Task LTree_not_supported_by_default_on_NpgsqlSlimSourceBuilder() { var errorMessage = string.Format( NpgsqlStrings.LTreeNotEnabled, nameof(NpgsqlSlimDataSourceBuilder.EnableLTree), nameof(NpgsqlSlimDataSourceBuilder)); var dataSourceBuilder = new NpgsqlSlimDataSourceBuilder(ConnectionString); await using var dataSource = dataSourceBuilder.Build(); var exception = await AssertTypeUnsupportedRead<NpgsqlRange<int>>("Top.Science.Astronomy", "ltree", dataSource); Assert.That(exception.InnerException!.Message, Is.EqualTo(errorMessage)); exception = await AssertTypeUnsupportedWrite<string>("Top.Science.Astronomy", "ltree", dataSource); Assert.That(exception.InnerException!.Message, Is.EqualTo(errorMessage)); } [Test] public async Task NpgsqlSlimSourceBuilder_EnableLTree() { var dataSourceBuilder = new NpgsqlSlimDataSourceBuilder(ConnectionString); dataSourceBuilder.EnableLTree(); await using var dataSource = dataSourceBuilder.Build(); await AssertType(dataSource, "Top.Science.Astronomy", "Top.Science.Astronomy", "ltree", NpgsqlDbType.LTree, isDefaultForWriting: false, skipArrayCheck: true); } [Test] public async Task NpgsqlSlimSourceBuilder_EnableArrays() { var dataSourceBuilder = new NpgsqlSlimDataSourceBuilder(ConnectionString); dataSourceBuilder.EnableLTree(); dataSourceBuilder.EnableArrays(); await using var dataSource = dataSourceBuilder.Build(); await AssertType(dataSource, "Top.Science.Astronomy", "Top.Science.Astronomy", "ltree", NpgsqlDbType.LTree, isDefaultForWriting: false); } [OneTimeSetUp] public async Task SetUp() { await using var conn = await OpenConnectionAsync(); TestUtil.MinimumPgVersion(conn, "13.0"); await TestUtil.EnsureExtensionAsync(conn, "ltree"); } }
LTreeTests
csharp
dotnet__aspnetcore
src/SiteExtensions/Sdk/HostingStartup/Program.cs
{ "start": 138, "end": 197 }
public class ____ { public static void Main() { } }
Program
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Users.Abstractions/Handlers/UserUpdateContext.cs
{ "start": 114, "end": 295 }
public class ____ : UserContextBase { /// <inheritdocs /> public UserUpdateContext(IUser user) : base(user) { } public bool Cancel { get; set; } }
UserUpdateContext
csharp
unoplatform__uno
src/Uno.UI.RuntimeTests/Tests/HotReload/Frame/HRApp/Tests/RemoteControlExtensions.cs
{ "start": 225, "end": 3764 }
internal static class ____ { public static async Task UpdateServerFile<T>(string originalText, string replacementText, CancellationToken ct) where T : FrameworkElement, new() { if (RemoteControlClient.Instance is null) { return; } await RemoteControlClient.Instance.WaitForConnection(); var message = new T().CreateUpdateFileMessage( originalText: originalText, replacementText: replacementText); if (message is null) { return; } await RemoteControlClient.Instance.SendMessage(message); var reloadWaiter = TypeMappings.WaitForResume(); if (!reloadWaiter.IsCompleted) { // Reloads are paused (ie task hasn't completed), so don't wait for any update // This is to handle testing the pause/resume feature of HR return; } await TestingUpdateHandler.WaitForVisualTreeUpdate().WaitAsync(ct); } /// <summary> /// Updates a specific file using an app relative path. /// </summary> public static async Task UpdateServerFile(string filePathInProject, string originalText, string replacementText, CancellationToken ct) { if (RemoteControlClient.Instance is null) { return; } await RemoteControlClient.Instance.WaitForConnection(); var message = new UpdateFile { FilePath = Path.Combine(GetProjectPath(), filePathInProject.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar)), OldText = originalText, NewText = replacementText }; if (message is null) { return; } await RemoteControlClient.Instance.SendMessage(message); var reloadWaiter = TypeMappings.WaitForResume(); if (!reloadWaiter.IsCompleted) { // Reloads are paused (ie task hasn't completed), so don't wait for any update // This is to handle testing the pause/resume feature of HR return; } await TestingUpdateHandler.WaitForVisualTreeUpdate().WaitAsync(ct); } /// <summary> /// Updates a project file's contents, asserts the change then revert. /// </summary> public static async Task UpdateProjectFileAndRevert( string filePathInProject, string originalText, string replacementText, Func<Task> callback, CancellationToken ct) { if (RemoteControlClient.Instance is null) { return; } await RemoteControlClient.Instance.WaitForConnection(); try { await UpdateServerFile(filePathInProject, originalText, replacementText, ct); await callback(); } finally { await UpdateServerFile(filePathInProject, replacementText, originalText, CancellationToken.None); } } public static async Task UpdateServerFileAndRevert<T>( string originalText, string replacementText, Func<Task> callback, CancellationToken ct) where T : FrameworkElement, new() { if (RemoteControlClient.Instance is null) { return; } await RemoteControlClient.Instance.WaitForConnection(); try { await UpdateServerFile<T>(originalText, replacementText, ct); await callback(); } finally { await UpdateServerFile<T>(replacementText, originalText, CancellationToken.None); } } /// <summary> /// Gets the project path from the remotecontrol attributes /// </summary> private static string GetProjectPath() { if (Application.Current.GetType().Assembly.GetCustomAttributes(typeof(ProjectConfigurationAttribute), false) is ProjectConfigurationAttribute[] configs) { var config = configs.First(); return Path.GetDirectoryName(config.ProjectPath)!; } else { throw new InvalidOperationException("Missing ProjectConfigurationAttribute"); } } }
HotReloadHelper
csharp
moq__moq4
src/Moq.Tests/ExpressionSplitFixture.cs
{ "start": 11830, "end": 12032 }
public interface ____ { IC C { get; set; } IC GetC(); IC GetC(bool arg1, bool arg2); IC this[bool arg1, bool arg2] { get; set; } }
IB
csharp
abpframework__abp
modules/cms-kit/src/Volo.CmsKit.Common.Application.Contracts/Volo/CmsKit/Contents/BlogPostCommonDto.cs
{ "start": 122, "end": 490 }
public class ____ : ExtensibleAuditedEntityDto<Guid> { public Guid BlogId { get; set; } public string Title { get; set; } public string Slug { get; set; } public string ShortDescription { get; set; } public string Content { get; set; } public Guid? CoverImageMediaId { get; set; } public CmsUserDto Author { get; set; } }
BlogPostCommonDto
csharp
npgsql__efcore.pg
src/EFCore.PG/Storage/Internal/Mapping/NpgsqlRangeTypeMapping.cs
{ "start": 2020, "end": 2845 }
class ____ a built-in range type which has a /// <see cref="NpgsqlDbType" /> defined. /// </summary> /// <param name="rangeStoreType">The database type to map</param> /// <param name="rangeClrType">The CLR type to map.</param> /// <param name="rangeNpgsqlDbType">The <see cref="NpgsqlDbType" /> of the built-in range.</param> /// <param name="subtypeMapping">The type mapping for the range subtype.</param> public static NpgsqlRangeTypeMapping CreatBuiltInRangeMapping( string rangeStoreType, Type rangeClrType, NpgsqlDbType rangeNpgsqlDbType, RelationalTypeMapping subtypeMapping) => new(rangeStoreType, rangeClrType, rangeNpgsqlDbType, subtypeMapping); /// <summary> /// Constructs an instance of the <see cref="NpgsqlRangeTypeMapping" />
for
csharp
abpframework__abp
modules/openiddict/src/Volo.Abp.OpenIddict.Domain/Volo/Abp/OpenIddict/Authorizations/OpenIddictAuthorization.cs
{ "start": 118, "end": 1572 }
public class ____ : AggregateRoot<Guid> { public OpenIddictAuthorization() { } public OpenIddictAuthorization(Guid id) : base(id) { } /// <summary> /// Gets or sets the application associated with the current authorization. /// </summary> public virtual Guid? ApplicationId { get; set; } /// <summary> /// Gets or sets the UTC creation date of the current authorization. /// </summary> [DisableDateTimeNormalization] public virtual DateTime? CreationDate { get; set; } /// <summary> /// Gets or sets the additional properties serialized as a JSON object, /// or <c>null</c> if no bag was associated with the current authorization. /// </summary> public virtual string Properties { get; set; } /// <summary> /// Gets or sets the scopes associated with the current /// authorization, serialized as a JSON array. /// </summary> public virtual string Scopes { get; set; } /// <summary> /// Gets or sets the status of the current authorization. /// </summary> public virtual string Status { get; set; } /// <summary> /// Gets or sets the subject associated with the current authorization. /// </summary> public virtual string Subject { get; set; } /// <summary> /// Gets or sets the type of the current authorization. /// </summary> public virtual string Type { get; set; } }
OpenIddictAuthorization
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.Widgets.AccessiBe/Domain/TriggerVerticalPosition.cs
{ "start": 137, "end": 382 }
public enum ____ { /// <summary> /// Align bottom /// </summary> Bottom, /// <summary> /// Align center /// </summary> Center, /// <summary> /// Align top /// </summary> Top }
TriggerVerticalPosition
csharp
ServiceStack__ServiceStack
ServiceStack.Text/src/ServiceStack.Text/CharMemoryExtensions.cs
{ "start": 85, "end": 15361 }
public static class ____ { [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullOrEmpty(this ReadOnlyMemory<char> value) => value.IsEmpty; [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsWhiteSpace(this ReadOnlyMemory<char> value) { var span = value.Span; for (int i = 0; i < span.Length; i++) { if (!char.IsWhiteSpace(span[i])) return false; } return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsNullOrWhiteSpace(this ReadOnlyMemory<char> value) => value.IsEmpty || value.IsWhiteSpace(); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlyMemory<char> Advance(this ReadOnlyMemory<char> text, int to) => text.Slice(to, text.Length - to); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlyMemory<char> AdvancePastWhitespace(this ReadOnlyMemory<char> literal) { var span = literal.Span; var i = 0; while (i < span.Length && char.IsWhiteSpace(span[i])) i++; return i == 0 ? literal : literal.Slice(i < literal.Length ? i : literal.Length); } public static ReadOnlyMemory<char> AdvancePastChar(this ReadOnlyMemory<char> literal, char delim) { var i = 0; var c = (char) 0; var span = literal.Span; while (i < span.Length && (c = span[i]) != delim) i++; if (c == delim) return literal.Slice(i + 1); return i == 0 ? literal : literal.Slice(i < literal.Length ? i : literal.Length); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool ParseBoolean(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseBoolean(value.Span); public static bool TryParseBoolean(this ReadOnlyMemory<char> value, out bool result) => MemoryProvider.Instance.TryParseBoolean(value.Span, out result); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryParseDecimal(this ReadOnlyMemory<char> value, out decimal result) => MemoryProvider.Instance.TryParseDecimal(value.Span, out result); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryParseFloat(this ReadOnlyMemory<char> value, out float result) => MemoryProvider.Instance.TryParseFloat(value.Span, out result); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool TryParseDouble(this ReadOnlyMemory<char> value, out double result) => MemoryProvider.Instance.TryParseDouble(value.Span, out result); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static decimal ParseDecimal(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseDecimal(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static float ParseFloat(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseFloat(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static double ParseDouble(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseDouble(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static sbyte ParseSByte(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseSByte(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static byte ParseByte(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseByte(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static short ParseInt16(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseInt16(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ushort ParseUInt16(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseUInt16(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int ParseInt32(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseInt32(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static uint ParseUInt32(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseUInt32(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static long ParseInt64(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseInt64(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ulong ParseUInt64(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseUInt64(value.Span); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Guid ParseGuid(this ReadOnlyMemory<char> value) => MemoryProvider.Instance.ParseGuid(value.Span); public static ReadOnlyMemory<char> LeftPart(this ReadOnlyMemory<char> strVal, char needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.IndexOf(needle); return pos == -1 ? strVal : strVal.Slice(0, pos); } public static ReadOnlyMemory<char> LeftPart(this ReadOnlyMemory<char> strVal, string needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.IndexOf(needle); return pos == -1 ? strVal : strVal.Slice(0, pos); } public static ReadOnlyMemory<char> RightPart(this ReadOnlyMemory<char> strVal, char needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.IndexOf(needle); return pos == -1 ? strVal : strVal.Slice(pos + 1); } public static ReadOnlyMemory<char> RightPart(this ReadOnlyMemory<char> strVal, string needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.IndexOf(needle); return pos == -1 ? strVal : strVal.Slice(pos + needle.Length); } public static ReadOnlyMemory<char> LastLeftPart(this ReadOnlyMemory<char> strVal, char needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.LastIndexOf(needle); return pos == -1 ? strVal : strVal.Slice(0, pos); } public static ReadOnlyMemory<char> LastLeftPart(this ReadOnlyMemory<char> strVal, string needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.LastIndexOf(needle); return pos == -1 ? strVal : strVal.Slice(0, pos); } public static ReadOnlyMemory<char> LastRightPart(this ReadOnlyMemory<char> strVal, char needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.LastIndexOf(needle); return pos == -1 ? strVal : strVal.Slice(pos + 1); } public static ReadOnlyMemory<char> LastRightPart(this ReadOnlyMemory<char> strVal, string needle) { if (strVal.IsEmpty) return strVal; var pos = strVal.LastIndexOf(needle); return pos == -1 ? strVal : strVal.Slice(pos + needle.Length); } public static bool TryReadLine(this ReadOnlyMemory<char> text, out ReadOnlyMemory<char> line, ref int startIndex) { if (startIndex >= text.Length) { line = TypeConstants.NullStringMemory; return false; } text = text.Slice(startIndex); var nextLinePos = text.Span.IndexOfAny('\r', '\n'); if (nextLinePos == -1) { var nextLine = text.Slice(0, text.Length); startIndex += text.Length; line = nextLine; return true; } else { var nextLine = text.Slice(0, nextLinePos); startIndex += nextLinePos + 1; var span = text.Span; if (span[nextLinePos] == '\r' && span.Length > nextLinePos + 1 && span[nextLinePos + 1] == '\n') startIndex += 1; line = nextLine; return true; } } public static bool TryReadPart(this ReadOnlyMemory<char> text, ReadOnlyMemory<char> needle, out ReadOnlyMemory<char> part, ref int startIndex) { if (startIndex >= text.Length) { part = TypeConstants.NullStringMemory; return false; } text = text.Slice(startIndex); var nextPartPos = text.Span.IndexOf(needle.Span); if (nextPartPos == -1) { var nextPart = text.Slice(0, text.Length); startIndex += text.Length; part = nextPart; return true; } else { var nextPart = text.Slice(0, nextPartPos); startIndex += nextPartPos + needle.Length; part = nextPart; return true; } } public static void SplitOnFirst(this ReadOnlyMemory<char> strVal, char needle, out ReadOnlyMemory<char> first, out ReadOnlyMemory<char> last) { first = default; last = default; if (strVal.IsEmpty) return; var pos = strVal.Span.IndexOf(needle); if (pos == -1) { first = strVal; } else { first = strVal.Slice(0, pos); last = strVal.Slice(pos + 1); } } public static void SplitOnFirst(this ReadOnlyMemory<char> strVal, ReadOnlyMemory<char> needle, out ReadOnlyMemory<char> first, out ReadOnlyMemory<char> last) { first = default; last = default; if (strVal.IsEmpty) return; var pos = strVal.Span.IndexOf(needle.Span); if (pos == -1) { first = strVal; } else { first = strVal.Slice(0, pos); last = strVal.Slice(pos + needle.Length); } } public static void SplitOnLast(this ReadOnlyMemory<char> strVal, char needle, out ReadOnlyMemory<char> first, out ReadOnlyMemory<char> last) { first = default; last = default; if (strVal.IsEmpty) return; var pos = strVal.Span.LastIndexOf(needle); if (pos == -1) { first = strVal; } else { first = strVal.Slice(0, pos); last = strVal.Slice(pos + 1); } } public static void SplitOnLast(this ReadOnlyMemory<char> strVal, ReadOnlyMemory<char> needle, out ReadOnlyMemory<char> first, out ReadOnlyMemory<char> last) { first = default; last = default; if (strVal.IsEmpty) return; var pos = strVal.Span.LastIndexOf(needle.Span); if (pos == -1) { first = strVal; } else { first = strVal.Slice(0, pos); last = strVal.Slice(pos + needle.Length); } } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlyMemory<char> value, char needle) => value.Span.IndexOf(needle); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlyMemory<char> value, string needle) => value.Span.IndexOf(needle.AsSpan()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlyMemory<char> value, char needle, int start) { var pos = value.Slice(start).Span.IndexOf(needle); return pos == -1 ? -1 : start + pos; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int IndexOf(this ReadOnlyMemory<char> value, string needle, int start) { var pos = value.Slice(start).Span.IndexOf(needle.AsSpan()); return pos == -1 ? -1 : start + pos; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this ReadOnlyMemory<char> value, char needle) => value.Span.LastIndexOf(needle); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this ReadOnlyMemory<char> value, string needle) => value.Span.LastIndexOf(needle.AsSpan()); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this ReadOnlyMemory<char> value, char needle, int start) { var pos = value.Slice(start).Span.LastIndexOf(needle); return pos == -1 ? -1 : start + pos; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int LastIndexOf(this ReadOnlyMemory<char> value, string needle, int start) { var pos = value.Slice(start).Span.LastIndexOf(needle.AsSpan()); return pos == -1 ? -1 : start + pos; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith(this ReadOnlyMemory<char> value, string other) => value.Span.StartsWith(other.AsSpan(), StringComparison.OrdinalIgnoreCase); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool StartsWith(this ReadOnlyMemory<char> value, string other, StringComparison comparison) => value.Span.StartsWith(other.AsSpan(), comparison); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith(this ReadOnlyMemory<char> value, string other) => value.Span.EndsWith(other.AsSpan(), StringComparison.OrdinalIgnoreCase); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EndsWith(this ReadOnlyMemory<char> value, string other, StringComparison comparison) => value.Span.EndsWith(other.AsSpan(), comparison); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsOrdinal(this ReadOnlyMemory<char> value, string other) => value.Span.Equals(other.AsSpan(), StringComparison.Ordinal); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool EqualsOrdinal(this ReadOnlyMemory<char> value, ReadOnlyMemory<char> other) => value.Span.Equals(other.Span, StringComparison.Ordinal); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static ReadOnlyMemory<char> SafeSlice(this ReadOnlyMemory<char> value, int startIndex) => SafeSlice(value, startIndex, value.Length); public static ReadOnlyMemory<char> SafeSlice(this ReadOnlyMemory<char> value, int startIndex, int length) { if (value.IsEmpty) return TypeConstants.NullStringMemory; if (startIndex < 0) startIndex = 0; if (value.Length >= startIndex + length) return value.Slice(startIndex, length); return value.Length > startIndex ? value.Slice(startIndex) : TypeConstants.NullStringMemory; } public static string SubstringWithEllipsis(this ReadOnlyMemory<char> value, int startIndex, int length) { if (value.IsEmpty) return string.Empty; var str = value.Slice(startIndex, length); return str.Length == length ? str + "..." : str.ToString(); } public static ReadOnlyMemory<byte> ToUtf8(this ReadOnlyMemory<char> chars) => MemoryProvider.Instance.ToUtf8(chars.Span); public static ReadOnlyMemory<char> FromUtf8(this ReadOnlyMemory<byte> bytes) => MemoryProvider.Instance.FromUtf8(bytes.Span); }
CharMemoryExtensions
csharp
ChilliCream__graphql-platform
src/HotChocolate/AzureFunctions/test/HotChocolate.AzureFunctions.IsolatedProcess.Tests/Helpers/MockIsolatedProcessHostBuilder.cs
{ "start": 1915, "end": 2485 }
internal class ____ : IHost { public MockIsolatedProcessHost(IServiceProvider serviceProvider) => Services = serviceProvider; public void Dispose() { } //DO NOTHING; public Task StartAsync(CancellationToken cancellationToken = default) => DoNothingAsync(); public Task StopAsync(CancellationToken cancellationToken = default) => DoNothingAsync(); // DO NOTHING; protected virtual Task<IHost> DoNothingAsync() => Task.FromResult((IHost)this); public IServiceProvider Services { get; } }
MockIsolatedProcessHost
csharp
grandnode__grandnode2
src/Business/Grand.Business.Checkout/Commands/Handlers/Orders/PartiallyRefundOfflineCommandHandler.cs
{ "start": 476, "end": 3639 }
public class ____ : IRequestHandler<PartiallyRefundOfflineCommand, bool> { private readonly LanguageSettings _languageSettings; private readonly IMediator _mediator; private readonly IMessageProviderService _messageProviderService; private readonly IOrderService _orderService; private readonly IPaymentTransactionService _paymentTransactionService; public PartiallyRefundOfflineCommandHandler( IOrderService orderService, IPaymentTransactionService paymentTransactionService, IMediator mediator, IMessageProviderService messageProviderService, LanguageSettings languageSettings) { _orderService = orderService; _paymentTransactionService = paymentTransactionService; _mediator = mediator; _messageProviderService = messageProviderService; _languageSettings = languageSettings; _orderService = orderService; } public async Task<bool> Handle(PartiallyRefundOfflineCommand command, CancellationToken cancellationToken) { var paymentTransaction = command.PaymentTransaction; ArgumentNullException.ThrowIfNull(paymentTransaction); var amountToRefund = command.AmountToRefund; var canPartiallyRefundOffline = await _mediator.Send( new CanPartiallyRefundOfflineQuery { PaymentTransaction = paymentTransaction, AmountToRefund = amountToRefund }, cancellationToken); if (!canPartiallyRefundOffline) throw new GrandException("You can't partially refund (offline) this order"); paymentTransaction.RefundedAmount += amountToRefund; paymentTransaction.TransactionStatus = paymentTransaction.RefundedAmount >= paymentTransaction.TransactionAmount ? TransactionStatus.Refunded : TransactionStatus.PartiallyRefunded; await _paymentTransactionService.UpdatePaymentTransaction(paymentTransaction); var order = await _orderService.GetOrderByGuid(paymentTransaction.OrderGuid); ArgumentNullException.ThrowIfNull(order); //total amount refunded var totalAmountRefunded = order.RefundedAmount + amountToRefund; //update order info order.RefundedAmount = totalAmountRefunded; order.PaymentStatusId = order.RefundedAmount >= order.OrderTotal ? PaymentStatus.Refunded : PaymentStatus.PartiallyRefunded; await _orderService.UpdateOrder(order); //check order status await _mediator.Send(new CheckOrderStatusCommand { Order = order }, cancellationToken); //notifications _ = await _messageProviderService.SendOrderRefundedStoreOwnerMessage(order, amountToRefund, _languageSettings.DefaultAdminLanguageId); _ = await _messageProviderService.SendOrderRefundedCustomerMessage(order, amountToRefund, order.CustomerLanguageId); //raise event await _mediator.Publish(new PaymentTransactionRefundedEvent(paymentTransaction, amountToRefund), cancellationToken); return true; } }
PartiallyRefundOfflineCommandHandler
csharp
smartstore__Smartstore
src/Smartstore.Web/Areas/Admin/Models/Settings/GeneralCommonSettingsModel.cs
{ "start": 8036, "end": 8518 }
public partial class ____ { [LocalizedDisplay("*CaptchaEnabled")] public bool Enabled { get; set; } [LocalizedDisplay("*ProviderSystemName")] public string ProviderSystemName { get; set; } [LocalizedDisplay("*CaptchaShowOnTargets")] public string[] ShowOn { get; set; } = []; public List<CaptchaProviderModel> AvailableProviders { get; set; } = new(); }
CaptchaSettingsModel
csharp
dotnetcore__WTM
demo/WalkingTec.Mvvm.ReactDemo/ViewModels/StudentVMs/StudentBatchVM.cs
{ "start": 630, "end": 905 }
public class ____ : BaseVM { [Display(Name = "性别")] public GenderEnum? Sex { get; set; } [Display(Name = "日期")] public DateRange EnRollDate { get; set; } protected override void InitVM() { } } }
Student_BatchEdit
csharp
dotnet__aspnetcore
src/Identity/Extensions.Core/src/IdentityServiceCollectionExtensions.cs
{ "start": 433, "end": 2524 }
public static class ____ { /// <summary> /// Adds and configures the identity system for the specified User type. Role services are not added /// by default but can be added with <see cref="IdentityBuilder.AddRoles{TRole}"/>. /// </summary> /// <typeparam name="TUser">The type representing a User in the system.</typeparam> /// <param name="services">The services available in the application.</param> /// <returns>An <see cref="IdentityBuilder"/> for creating and configuring the identity system.</returns> public static IdentityBuilder AddIdentityCore<TUser>(this IServiceCollection services) where TUser : class => services.AddIdentityCore<TUser>(o => { }); /// <summary> /// Adds and configures the identity system for the specified User type. Role services are not added by default /// but can be added with <see cref="IdentityBuilder.AddRoles{TRole}"/>. /// </summary> /// <typeparam name="TUser">The type representing a User in the system.</typeparam> /// <param name="services">The services available in the application.</param> /// <param name="setupAction">An action to configure the <see cref="IdentityOptions"/>.</param> /// <returns>An <see cref="IdentityBuilder"/> for creating and configuring the identity system.</returns> public static IdentityBuilder AddIdentityCore<TUser>(this IServiceCollection services, Action<IdentityOptions> setupAction) where TUser : class { // Services identity depends on services.AddOptions().AddLogging(); services.AddMetrics(); // Services used by identity services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>(); services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>(); services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>(); services.TryAddScoped<ILookupNormalizer, UpperInvariantLookupNormalizer>(); services.TryAddScoped<IUserConfirmation<TUser>, DefaultUserConfirmation<TUser>>(); // No
IdentityServiceCollectionExtensions
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Search/SearchTrackingOptions.cs
{ "start": 761, "end": 1345 }
public sealed class ____ { private string _searchTerms; /// <summary> /// Text or term associated with the query to track. You can specify only one term per query. /// </summary> public string SearchTerms { get => _searchTerms; set => _searchTerms = Ensure.IsNotNullOrEmpty(value, nameof(value)); } internal BsonDocument Render() => new() { { "searchTerms", _searchTerms, !string.IsNullOrEmpty(_searchTerms) } }; } }
SearchTrackingOptions
csharp
AvaloniaUI__Avalonia
src/Android/Avalonia.Android/Platform/Storage/AndroidStorageProvider.cs
{ "start": 421, "end": 11498 }
internal class ____ : IStorageProvider { public static ReadOnlySpan<byte> AndroidKey => "android"u8; private readonly Activity _activity; public AndroidStorageProvider(Activity activity) { _activity = activity; } public bool CanOpen => OperatingSystem.IsAndroidVersionAtLeast(19); public bool CanSave => OperatingSystem.IsAndroidVersionAtLeast(19); public bool CanPickFolder => OperatingSystem.IsAndroidVersionAtLeast(21); public Task<IStorageBookmarkFolder?> OpenFolderBookmarkAsync(string bookmark) { var uri = DecodeUriFromBookmark(bookmark); return Task.FromResult<IStorageBookmarkFolder?>(uri is null ? null : new AndroidStorageFolder(_activity, uri, false)); } public async Task<IStorageFile?> TryGetFileFromPathAsync(Uri filePath) { if (filePath is null) { throw new ArgumentNullException(nameof(filePath)); } if (filePath is not { IsAbsoluteUri: true, Scheme: "file" or "content" }) { throw new ArgumentException("File path is expected to be an absolute link with \"file\" or \"content\" scheme."); } var androidUri = AndroidUri.Parse(filePath.ToString()); if (androidUri?.Path is not {} androidUriPath) { return null; } await EnsureUriReadPermission(androidUri); var javaFile = new JavaFile(androidUriPath); if (javaFile.Exists() && javaFile.IsFile) { return null; } return new AndroidStorageFile(_activity, androidUri); } public async Task<IStorageFolder?> TryGetFolderFromPathAsync(Uri folderPath) { if (folderPath is null) { throw new ArgumentNullException(nameof(folderPath)); } if (folderPath is not { IsAbsoluteUri: true, Scheme: "file" or "content" }) { throw new ArgumentException("Folder path is expected to be an absolute link with \"file\" or \"content\" scheme."); } var androidUri = AndroidUri.Parse(folderPath.ToString()); if (androidUri?.Path is not {} androidUriPath) { return null; } await EnsureUriReadPermission(androidUri); var javaFile = new JavaFile(androidUriPath); if (javaFile.Exists() && javaFile.IsDirectory) { return null; } return new AndroidStorageFolder(_activity, androidUri, false); } public Task<IStorageFolder?> TryGetWellKnownFolderAsync(WellKnownFolder wellKnownFolder) { var dirCode = wellKnownFolder switch { WellKnownFolder.Desktop => null, WellKnownFolder.Documents => global::Android.OS.Environment.DirectoryDocuments, WellKnownFolder.Downloads => global::Android.OS.Environment.DirectoryDownloads, WellKnownFolder.Music => global::Android.OS.Environment.DirectoryMusic, WellKnownFolder.Pictures => global::Android.OS.Environment.DirectoryPictures, WellKnownFolder.Videos => global::Android.OS.Environment.DirectoryMovies, _ => throw new ArgumentOutOfRangeException(nameof(wellKnownFolder), wellKnownFolder, null) }; if (dirCode is null) { return Task.FromResult<IStorageFolder?>(null); } var dir = _activity.GetExternalFilesDir(dirCode); if (dir is null || !dir.Exists()) { return Task.FromResult<IStorageFolder?>(null); } var uri = AndroidUri.FromFile(dir); if (uri is null) { return Task.FromResult<IStorageFolder?>(null); } // To make TryGetWellKnownFolder API easier to use, we don't check for the permissions. // It will work with file picker activities, but it will fail on any direct access to the folder, like getting list of children. // We pass "needsExternalFilesPermission" parameter here, so folder itself can check for permissions on any FS access. return Task.FromResult<IStorageFolder?>(new WellKnownAndroidStorageFolder(_activity, dirCode, uri, true)); } public Task<IStorageBookmarkFile?> OpenFileBookmarkAsync(string bookmark) { var uri = DecodeUriFromBookmark(bookmark); return Task.FromResult<IStorageBookmarkFile?>(uri is null ? null : new AndroidStorageFile(_activity, uri)); } private static AndroidUri? DecodeUriFromBookmark(string bookmark) { return StorageBookmarkHelper.TryDecodeBookmark(AndroidKey, bookmark, out var bytes) switch { StorageBookmarkHelper.DecodeResult.Success => AndroidUri.Parse(Encoding.UTF8.GetString(bytes!)), // Attempt to decode 11.0 android bookmarks StorageBookmarkHelper.DecodeResult.InvalidFormat => AndroidUri.Parse(bookmark), _ => null }; } public async Task<IReadOnlyList<IStorageFile>> OpenFilePickerAsync(FilePickerOpenOptions options) { var mimeTypes = options.FileTypeFilter?.Where(t => t != FilePickerFileTypes.All) .SelectMany(f => f.MimeTypes ?? Array.Empty<string>()).Distinct().ToArray() ?? Array.Empty<string>(); var intent = new Intent(Intent.ActionOpenDocument) .AddCategory(Intent.CategoryOpenable) .PutExtra(Intent.ExtraAllowMultiple, options.AllowMultiple) .SetType(FilePickerFileTypes.All.MimeTypes![0]); if (mimeTypes.Length > 0) { intent = intent.PutExtra(Intent.ExtraMimeTypes, mimeTypes); } intent = TryAddExtraInitialUri(intent, options.SuggestedStartLocation); var pickerIntent = Intent.CreateChooser(intent, options.Title ?? "Select file"); var uris = await StartActivity(pickerIntent, false); return uris.Select(u => new AndroidStorageFile(_activity, u)).ToArray(); } public async Task<IStorageFile?> SaveFilePickerAsync(FilePickerSaveOptions options) { var mimeTypes = options.FileTypeChoices?.Where(t => t != FilePickerFileTypes.All) .SelectMany(f => f.MimeTypes ?? Array.Empty<string>()).Distinct().ToArray() ?? Array.Empty<string>(); var intent = new Intent(Intent.ActionCreateDocument) .AddCategory(Intent.CategoryOpenable) .SetType(FilePickerFileTypes.All.MimeTypes![0]); if (mimeTypes.Length > 0) { intent = intent.PutExtra(Intent.ExtraMimeTypes, mimeTypes); } if (options.SuggestedFileName is { } fileName) { if (options.DefaultExtension is { } ext) { fileName += ext.StartsWith('.') ? ext : "." + ext; } intent = intent.PutExtra(Intent.ExtraTitle, fileName); } intent = TryAddExtraInitialUri(intent, options.SuggestedStartLocation); var pickerIntent = Intent.CreateChooser(intent, options.Title ?? "Save file"); var uris = await StartActivity(pickerIntent, true); return uris.Select(u => new AndroidStorageFile(_activity, u)).FirstOrDefault(); } public async Task<SaveFilePickerResult> SaveFilePickerWithResultAsync(FilePickerSaveOptions options) { var file = await SaveFilePickerAsync(options).ConfigureAwait(false); return new SaveFilePickerResult(file); } public async Task<IReadOnlyList<IStorageFolder>> OpenFolderPickerAsync(FolderPickerOpenOptions options) { var intent = new Intent(Intent.ActionOpenDocumentTree) .PutExtra(Intent.ExtraAllowMultiple, options.AllowMultiple); intent = TryAddExtraInitialUri(intent, options.SuggestedStartLocation); var pickerIntent = Intent.CreateChooser(intent, options.Title ?? "Select folder"); var uris = await StartActivity(pickerIntent, false); return uris.Select(u => new AndroidStorageFolder(_activity, u, false)).ToArray(); } private async Task<List<AndroidUri>> StartActivity(Intent? pickerIntent, bool singleResult) { var resultList = new List<AndroidUri>(1); var tcs = new TaskCompletionSource<Intent?>(); var currentRequestCode = PlatformSupport.GetNextRequestCode(); if (!(_activity is IActivityResultHandler mainActivity)) { throw new InvalidOperationException("Main activity must implement IActivityResultHandler interface."); } mainActivity.ActivityResult += OnActivityResult; _activity.StartActivityForResult(pickerIntent, currentRequestCode); var result = await tcs.Task; if (result != null) { // ClipData first to avoid issue with multiple files selection. if (!singleResult && result.ClipData is { } clipData) { for (var i = 0; i < clipData.ItemCount; i++) { var uri = clipData.GetItemAt(i)?.Uri; if (uri != null) { resultList.Add(uri); } } } else if (result.Data is { } uri) { resultList.Add(uri); } } if (result?.HasExtra("error") == true) { throw new Exception(result.GetStringExtra("error")); } return resultList; void OnActivityResult(int requestCode, Result resultCode, Intent? data) { if (currentRequestCode != requestCode) { return; } mainActivity.ActivityResult -= OnActivityResult; _ = tcs.TrySetResult(resultCode == Result.Ok ? data : null); } } private static Intent TryAddExtraInitialUri(Intent intent, IStorageFolder? folder) { if (OperatingSystem.IsAndroidVersionAtLeast(26) && (folder as AndroidStorageItem)?.Uri is { } uri) { return intent.PutExtra(DocumentsContract.ExtraInitialUri, uri); } return intent; } private async Task EnsureUriReadPermission(AndroidUri androidUri) { bool hasPerms = false; Exception? innerEx = null; try { hasPerms = _activity.CheckUriPermission(androidUri, global::Android.OS.Process.MyPid(), global::Android.OS.Process.MyUid(), ActivityFlags.GrantReadUriPermission) == global::Android.Content.PM.Permission.Granted; // TODO: call RequestPermission or add proper permissions API, something like in Browser File API. hasPerms = hasPerms || await _activity.CheckPermission(Manifest.Permission.ReadExternalStorage); } catch (Exception ex) { innerEx = ex; } if (!hasPerms) { throw new InvalidOperationException("Application doesn't have READ_EXTERNAL_STORAGE permission. Make sure android manifest has this permission defined and user allowed it.", innerEx); } } }
AndroidStorageProvider
csharp
MonoGame__MonoGame
MonoGame.Framework.Content.Pipeline/Builder/IContentFIleCache.cs
{ "start": 337, "end": 1956 }
public interface ____ { /// <summary> /// Adds the specified file as a dependency related to the current content file. /// </summary> /// <param name="builder">A <see cref="ContentBuilder"/> the added depedency is related to.</param> /// <param name="dependencyPath">A relative or absolute path to the dependency file.</param> void AddDependency(ContentBuilder builder, string dependencyPath); /// <summary> /// Adds the specified file cache as a dependency related to the current content file. /// </summary> /// <param name="builder">A <see cref="ContentBuilder"/> the added depedency is related to.</param> /// <param name="fileCache">A dependent file cache.</param> void AddDependency(ContentBuilder builder, IContentFileCache fileCache); /// <summary> /// Adds the specified file as an output file related to the current content file. /// </summary> /// <param name="builder">A <see cref="ContentBuilder"/> the output file is related to.</param> /// <param name="outputPath">A relative or absolute path to the output file.</param> void AddOutputFile(ContentBuilder builder, string outputPath); /// <summary> /// /// </summary> /// <param name="builder">A <see cref="ContentBuilder"/> the added depedency is related to.</param> /// <param name="info">A <see cref="ContentInfo"/> for which to use to check the validity of the cached asset.</param> /// <returns><c>true</c> if the file cache is still valid, <c>false</c> otherwise.</returns> bool IsValid(ContentBuilder builder, ContentInfo info); }
IContentFileCache
csharp
dotnet__machinelearning
src/Microsoft.ML.Vision/ImageClassificationTrainer.cs
{ "start": 29317, "end": 38257 }
class ____ in the {_options.LabelColumnName} column. To build a multiclass classification model, the number of classes needs to be 2 or greater"; Contracts.CheckParam(labelCount > 1, nameof(labelCount), msg); _classCount = (int)labelCount; var imageSize = ImagePreprocessingSize[_options.Arch]; _session = LoadTensorFlowSessionFromMetaGraph(Host, _options.Arch).Session; _session.graph.as_default(); (_jpegData, _resizedImage) = AddJpegDecoding(imageSize.Item1, imageSize.Item2, 3); _jpegDataTensorName = _jpegData.name; _resizedImageTensorName = _resizedImage.name; // Add transfer learning layer. AddTransferLearningLayer(_options.LabelColumnName, _options.ScoreColumnName, _options.LearningRate, _useLRScheduling, _classCount); // Initialize the variables. new Runner(_session, operations: new IntPtr[] { tf.global_variables_initializer() }).Run(); // Add evaluation layer. (_evaluationStep, _) = AddEvaluationStep(_softMaxTensor, _labelTensor); _softmaxTensorName = _softMaxTensor.name; } private protected override SchemaShape.Column[] GetOutputColumnsCore(SchemaShape inputSchema) { bool success = inputSchema.TryFindColumn(_options.LabelColumnName, out _); Contracts.Assert(success); var metadata = new List<SchemaShape.Column>(); metadata.Add(new SchemaShape.Column(AnnotationUtils.Kinds.KeyValues, SchemaShape.Column.VectorKind.Vector, TextDataViewType.Instance, false)); return new[] { new SchemaShape.Column(_options.ScoreColumnName, SchemaShape.Column.VectorKind.Vector, NumberDataViewType.Single, false), new SchemaShape.Column(_options.PredictedLabelColumnName, SchemaShape.Column.VectorKind.Scalar, NumberDataViewType.UInt32, true, new SchemaShape(metadata.ToArray())) }; } private protected override MulticlassPredictionTransformer<ImageClassificationModelParameters> MakeTransformer( ImageClassificationModelParameters model, DataViewSchema trainSchema) => new MulticlassPredictionTransformer<ImageClassificationModelParameters>(Host, model, trainSchema, FeatureColumn.Name, LabelColumn.Name, _options.ScoreColumnName, _options.PredictedLabelColumnName); private protected override ImageClassificationModelParameters TrainModelCore(TrainContext trainContext) { // Workspace directory is cleaned after training run. However, the pipeline can be re-used by calling // fit() again after transform(), in which case we must ensure workspace directory exists. This scenario // is typical in the case of cross-validation. if (!Directory.Exists(_options.WorkspacePath)) { Directory.CreateDirectory(_options.WorkspacePath); } InitializeTrainingGraph(trainContext.TrainingSet.Data); CheckTrainingParameters(_options); var validationSet = trainContext.ValidationSet?.Data ?? _options.ValidationSet; var imageProcessor = new ImageProcessor(_session, _jpegDataTensorName, _resizedImageTensorName); string trainSetBottleneckCachedValuesFilePath = Path.Combine(_options.WorkspacePath, _options.TrainSetBottleneckCachedValuesFileName); string validationSetBottleneckCachedValuesFilePath = Path.Combine(_options.WorkspacePath, _options.ValidationSetBottleneckCachedValuesFileName); bool needValidationSet = _options.EarlyStoppingCriteria != null || _options.MetricsCallback != null; bool validationSetPresent = _options.ReuseValidationSetBottleneckCachedValues && File.Exists(validationSetBottleneckCachedValuesFilePath + "_features.bin") && File.Exists(validationSetBottleneckCachedValuesFilePath + "_labels.bin"); bool generateValidationSet = needValidationSet && !validationSetPresent; if (generateValidationSet && _options.ValidationSet != null) { CacheFeaturizedImagesToDisk(validationSet, _options.LabelColumnName, _options.FeatureColumnName, imageProcessor, _inputTensorName, _bottleneckTensor.name, validationSetBottleneckCachedValuesFilePath, ImageClassificationMetrics.Dataset.Validation, _options.MetricsCallback); generateValidationSet = false; validationSetPresent = true; } if (!_options.ReuseTrainSetBottleneckCachedValues || !(File.Exists(trainSetBottleneckCachedValuesFilePath + "_features.bin") && File.Exists(trainSetBottleneckCachedValuesFilePath + "_labels.bin"))) { CacheFeaturizedImagesToDisk(trainContext.TrainingSet.Data, _options.LabelColumnName, _options.FeatureColumnName, imageProcessor, _inputTensorName, _bottleneckTensor.name, trainSetBottleneckCachedValuesFilePath, ImageClassificationMetrics.Dataset.Train, _options.MetricsCallback, generateValidationSet ? _options.ValidationSetFraction : null); validationSetPresent = validationSetPresent || (generateValidationSet && _options.ValidationSetFraction.HasValue); generateValidationSet = needValidationSet && !validationSetPresent; } if (generateValidationSet && _options.ReuseTrainSetBottleneckCachedValues && !_options.ReuseValidationSetBottleneckCachedValues) { // Not sure if it makes sense to support this scenario. } Contracts.Assert(!generateValidationSet, "Validation set needed but cannot generate."); TrainAndEvaluateClassificationLayer(trainSetBottleneckCachedValuesFilePath, validationSetPresent && (_options.EarlyStoppingCriteria != null || _options.MetricsCallback != null) ? validationSetBottleneckCachedValuesFilePath : null); // Leave the ownership of _session so that it is not disposed/closed when this object goes out of scope // since it will be used by ImageClassificationModelParameters class (new owner that will take care of // disposing). var session = _session; _session = null; return new ImageClassificationModelParameters(Host, session, _classCount, _jpegDataTensorName, _resizedImageTensorName, _inputTensorName, _softmaxTensorName); } private void CheckTrainingParameters(Options options) { Host.CheckNonWhiteSpace(options.LabelColumnName, nameof(options.LabelColumnName)); if (_session.graph.OperationByName(_labelTensor.name.Split(':')[0]) == null) { throw Host.ExceptParam(nameof(_labelTensor.name), $"'{_labelTensor.name}' does not" + $"exist in the model"); } if (options.EarlyStoppingCriteria != null && options.ValidationSet == null && options.TestOnTrainSet == false) { throw Host.ExceptParam(nameof(options.EarlyStoppingCriteria), $"Early stopping enabled but unable to" + $"find a validation set and/or train set testing disabled. Please disable early stopping " + $"or either provide a validation set or enable train set training."); } } private (Tensor, Tensor) AddJpegDecoding(int height, int width, int depth) { // height, width, depth var inputDim = (height, width, depth); var jpegData = tf.placeholder(tf.@string, name: "DecodeJPGInput"); var decodedImage = tf.image.decode_jpeg(jpegData, channels: inputDim.Item3); // Convert from full range of uint8 to range [0,1] of float32. var decodedImageAsFloat = tf.image.convert_image_dtype(decodedImage, tf.float32); var decodedImage4d = tf.expand_dims(decodedImageAsFloat, 0); var resizeShape = tf.stack(new int[] { inputDim.Item1, inputDim.Item2 }); var resizeShapeAsInt = tf.cast(resizeShape, dtype: tf.int32); var resizedImage = tf.image.resize_bilinear(decodedImage4d, resizeShapeAsInt, false, name: "ResizeTensor"); return (jpegData, resizedImage); } private static Tensor EncodeByteAsString(VBuffer<byte> buffer) { return StringTensorFactory.CreateStringTensor(buffer.DenseValues().ToArray()); }
found
csharp
MassTransit__MassTransit
tests/MassTransit.Analyzers.Tests/MessageContractAnalyzerUnitTests.cs
{ "start": 26902, "end": 28023 }
class ____ : IConsumer<SubmitOrder> { public async Task Consume(ConsumeContext<SubmitOrder> context) { Uri address = null; await context.Send<OrderSubmitted>(address, new { Id = context.Message.Id, CustomerId = context.Message.CustomerId, }); } } } "; var expected = new DiagnosticResult { Id = "MCA0003", Message = "Anonymous type is missing properties that are in the message contract 'OrderSubmitted'. The following properties are missing: OrderItems.", Severity = DiagnosticSeverity.Info, Locations = new[] { new DiagnosticResultLocation("Test0.cs", 58, 57) } }; VerifyCSharpDiagnostic(test, expected); } [Test] public void WhenSendTypesAreStructurallyCompatibleAndMissingProperty_ShouldHaveDiagnostic() { var test = Usings + MessageContracts + @" namespace ConsoleApplication1 {
SubmitOrderConsumer
csharp
Xabaril__AspNetCore.Diagnostics.HealthChecks
src/HealthChecks.UI.PostgreSQL.Storage/HealthChecksUIBuilderExtensions.cs
{ "start": 179, "end": 979 }
public static class ____ { public static HealthChecksUIBuilder AddPostgreSqlStorage( this HealthChecksUIBuilder builder, string connectionString, Action<DbContextOptionsBuilder>? configureOptions = null, Action<NpgsqlDbContextOptionsBuilder>? configurePostgreOptions = null) { builder.Services.AddDbContext<HealthChecksDb>(optionsBuilder => { configureOptions?.Invoke(optionsBuilder); optionsBuilder.UseNpgsql(connectionString, npgsqlOptionsBuilder => { npgsqlOptionsBuilder.MigrationsAssembly("HealthChecks.UI.PostgreSQL.Storage"); configurePostgreOptions?.Invoke(npgsqlOptionsBuilder); }); }); return builder; } }
HealthChecksUIBuilderExtensions
csharp
dotnet__maui
src/Essentials/samples/Samples/View/BarometerPage.xaml.cs
{ "start": 116, "end": 229 }
public partial class ____ : BasePage { public BarometerPage() { InitializeComponent(); } } }
BarometerPage
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding101ManyToManyTestBase.cs
{ "start": 9265, "end": 9459 }
public class ____ { public int Id { get; set; } public List<Post> Posts { get; } = []; public List<PostTag> PostTags { get; } = []; }
Tag
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Transforms/SkipTakeFilter.cs
{ "start": 7129, "end": 7862 }
class ____ context.</summary> public static SkipTakeFilter Create(IHostEnvironment env, ModelLoadContext ctx, IDataView input) { Contracts.CheckValue(env, nameof(env)); var h = env.Register(RegistrationName); h.CheckValue(ctx, nameof(ctx)); ctx.CheckAtModel(GetVersionInfo()); // *** Binary format *** // long: skip // long: take long skip = ctx.Reader.ReadInt64(); h.CheckDecode(skip >= 0); long take = ctx.Reader.ReadInt64(); h.CheckDecode(take >= 0); return h.Apply("Loading Model", ch => new SkipTakeFilter(skip, take, h, input)); } ///<summary>Saves
from
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 298199, "end": 300158 }
public partial class ____ : global::System.IEquatable<ListApiKeyCommandQueryResult>, IListApiKeyCommandQueryResult { public ListApiKeyCommandQueryResult(global::ChilliCream.Nitro.CommandLine.Cloud.Client.IListApiKeyCommandQuery_WorkspaceById? workspaceById) { WorkspaceById = workspaceById; } public global::ChilliCream.Nitro.CommandLine.Cloud.Client.IListApiKeyCommandQuery_WorkspaceById? WorkspaceById { get; } public virtual global::System.Boolean Equals(ListApiKeyCommandQueryResult? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (((WorkspaceById is null && other.WorkspaceById is null) || WorkspaceById != null && WorkspaceById.Equals(other.WorkspaceById))); } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((ListApiKeyCommandQueryResult)obj); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; if (WorkspaceById != null) { hash ^= 397 * WorkspaceById.GetHashCode(); } return hash; } } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
ListApiKeyCommandQueryResult
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.AuditTrail/Drivers/AuditTrailOptionsDisplayDriver.cs
{ "start": 174, "end": 3124 }
public sealed class ____ : DisplayDriver<AuditTrailIndexOptions> { // Maintain the Options prefix for compatibility with binding. protected override void BuildPrefix(AuditTrailIndexOptions options, string htmlFieldPrefix) { Prefix = "Options"; } public override Task<IDisplayResult> DisplayAsync(AuditTrailIndexOptions model, BuildDisplayContext context) { return CombineAsync( View("AuditTrailAdminFilters_Thumbnail__Category", model).Location("Thumbnail", "Content:10"), View("AuditTrailAdminFilters_Thumbnail__Event", model).Location("Thumbnail", "Content:10"), View("AuditTrailAdminFilters_Thumbnail__Date", model).Location("Thumbnail", "Content:20"), View("AuditTrailAdminFilters_Thumbnail__UserName", model).Location("Thumbnail", "Content:30"), View("AuditTrailAdminFilters_Thumbnail__UserId", model).Location("Thumbnail", "Content:40"), View("AuditTrailAdminFilters_Thumbnail__CorrelationId", model).Location("Thumbnail", "Content:50") ); } public override Task<IDisplayResult> EditAsync(AuditTrailIndexOptions model, BuildEditorContext context) { // Map the filter result to a model so the ui can reflect current selections. model.FilterResult.MapTo(model); return CombineAsync( Initialize<AuditTrailIndexOptions>("AuditTrailAdminListSearch", m => BuildUserOptionsViewModel(m, model)).Location("Search:10"), Initialize<AuditTrailIndexOptions>("AuditTrailAdminListSummary", m => BuildUserOptionsViewModel(m, model)).Location("Summary:10"), Initialize<AuditTrailIndexOptions>("AuditTrailAdminListFilters", m => BuildUserOptionsViewModel(m, model)).Location("Actions:10.1") ); } public override Task<IDisplayResult> UpdateAsync(AuditTrailIndexOptions model, UpdateEditorContext context) { // Map the incoming values from a form post to the filter result. model.FilterResult.MapFrom(model); return EditAsync(model, context); } private static void BuildUserOptionsViewModel(AuditTrailIndexOptions m, AuditTrailIndexOptions model) { m.SearchText = model.SearchText; m.OriginalSearchText = model.OriginalSearchText; m.Category = model.Category; m.CorrelationId = model.CorrelationId; m.CorrelationIdFromRoute = model.CorrelationIdFromRoute; m.Categories = model.Categories; m.Event = model.Event; m.Events = model.Events; m.Sort = model.Sort; m.AuditTrailSorts = model.AuditTrailSorts; m.Date = model.Date; m.AuditTrailDates = model.AuditTrailDates; m.StartIndex = model.StartIndex; m.EndIndex = model.EndIndex; m.EventsCount = model.EventsCount; m.TotalItemCount = model.TotalItemCount; m.FilterResult = model.FilterResult; } }
AuditTrailOptionsDisplayDriver
csharp
microsoft__semantic-kernel
dotnet/samples/Demos/VectorStoreRAG/Options/WeaviateConfig.cs
{ "start": 192, "end": 362 }
internal sealed class ____ { public const string ConfigSectionName = "Weaviate"; [Required] public string Endpoint { get; set; } = string.Empty; }
WeaviateConfig
csharp
unoplatform__uno
src/Uno.Foundation/IStringable.cs
{ "start": 125, "end": 341 }
public partial interface ____ { /// <summary> /// Gets a string that represents the current object. /// </summary> /// <returns>A string that represents the current object.</returns> string ToString(); }
IStringable
csharp
dotnet__aspnetcore
src/SignalR/clients/csharp/Http.Connections.Client/src/Internal/ServerSentEventsTransport.cs
{ "start": 590, "end": 7353 }
partial class ____ : ITransport { private readonly HttpClient _httpClient; private readonly ILogger _logger; private readonly HttpConnectionOptions _httpConnectionOptions; // Volatile so that the SSE loop sees the updated value set from a different thread private volatile Exception? _error; private readonly CancellationTokenSource _transportCts = new CancellationTokenSource(); private readonly CancellationTokenSource _inputCts = new CancellationTokenSource(); private IDuplexPipe? _transport; private IDuplexPipe? _application; internal Task Running { get; private set; } = Task.CompletedTask; public PipeReader Input => _transport!.Input; public PipeWriter Output => _transport!.Output; public ServerSentEventsTransport(HttpClient httpClient, HttpConnectionOptions? httpConnectionOptions = null, ILoggerFactory? loggerFactory = null) { ArgumentNullThrowHelper.ThrowIfNull(httpClient); _httpClient = httpClient; _logger = (loggerFactory ?? NullLoggerFactory.Instance).CreateLogger(typeof(ServerSentEventsTransport)); _httpConnectionOptions = httpConnectionOptions ?? new(); } public async Task StartAsync(Uri url, TransferFormat transferFormat, CancellationToken cancellationToken = default) { if (transferFormat != TransferFormat.Text) { throw new ArgumentException($"The '{transferFormat}' transfer format is not supported by this transport.", nameof(transferFormat)); } Log.StartTransport(_logger, transferFormat); var request = new HttpRequestMessage(HttpMethod.Get, url); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream")); HttpResponseMessage? response = null; try { response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); response.EnsureSuccessStatusCode(); } catch { response?.Dispose(); Log.TransportStopping(_logger); throw; } // Create the pipe pair (Application's writer is connected to Transport's reader, and vice versa) var pair = DuplexPipe.CreateConnectionPair(_httpConnectionOptions.TransportPipeOptions, _httpConnectionOptions.AppPipeOptions); _transport = pair.Transport; _application = pair.Application; // Cancellation token will be triggered when the pipe is stopped on the client. // This is to avoid the client throwing from a 404 response caused by the // server stopping the connection while the send message request is in progress. // _application.Input.OnWriterCompleted((exception, state) => ((CancellationTokenSource)state).Cancel(), inputCts); Running = ProcessAsync(url, response); } private async Task ProcessAsync(Uri url, HttpResponseMessage response) { Debug.Assert(_application != null); // Start sending and polling (ask for binary if the server supports it) var receiving = ProcessEventStream(response, _transportCts.Token); var sending = SendUtils.SendMessages(url, _application, _httpClient, _logger, _inputCts.Token); // Wait for send or receive to complete var trigger = await Task.WhenAny(receiving, sending).ConfigureAwait(false); if (trigger == receiving) { // We're waiting for the application to finish and there are 2 things it could be doing // 1. Waiting for application data // 2. Waiting for an outgoing send (this should be instantaneous) _inputCts.Cancel(); // Cancel the application so that ReadAsync yields _application.Input.CancelPendingRead(); await sending.ConfigureAwait(false); } else { // Set the sending error so we communicate that to the application _error = sending.IsFaulted ? sending.Exception!.InnerException : null; _transportCts.Cancel(); // Cancel any pending flush so that we can quit _application.Output.CancelPendingFlush(); await receiving.ConfigureAwait(false); } } private async Task ProcessEventStream(HttpResponseMessage response, CancellationToken cancellationToken) { Debug.Assert(_application != null); Log.StartReceive(_logger); using (response) #pragma warning disable CA2016 // Forward the 'CancellationToken' parameter to methods using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false)) #pragma warning restore CA2016 // Forward the 'CancellationToken' parameter to methods { try { var parser = SseParser.Create(stream, (eventType, bytes) => bytes.ToArray()); await foreach (var item in parser.EnumerateAsync(cancellationToken).ConfigureAwait(false)) { Log.MessageToApplication(_logger, item.Data.Length); // When cancellationToken is canceled the next line will cancel pending flushes on the pipe unblocking the await. // Avoid passing the passed in context. var flushResult = await _application.Output.WriteAsync(item.Data, default).ConfigureAwait(false); // We canceled in the middle of applying back pressure // or if the consumer is done if (flushResult.IsCanceled || flushResult.IsCompleted) { Log.EventStreamEnded(_logger); break; } } } catch (OperationCanceledException) { Log.ReceiveCanceled(_logger); } catch (Exception ex) { _error = ex; } finally { _application.Output.Complete(_error); Log.ReceiveStopped(_logger); } } } public async Task StopAsync() { Log.TransportStopping(_logger); if (_application == null) { // We never started return; } _transport!.Output.Complete(); _transport!.Input.Complete(); _application.Input.CancelPendingRead(); try { await Running.ConfigureAwait(false); } catch (Exception ex) { Log.TransportStopped(_logger, ex); throw; } Log.TransportStopped(_logger, null); } }
ServerSentEventsTransport
csharp
dotnet__maui
src/Essentials/src/Browser/Browser.shared.cs
{ "start": 3602, "end": 3697 }
class ____ static extension methods for use with <see cref="IBrowser"/>. /// </summary>
contains
csharp
microsoft__FASTER
cs/src/core/Allocator/GenericScanIterator.cs
{ "start": 7913, "end": 8874 }
record ____, false if end of scan</returns> bool IPushScanIterator<Key>.BeginGetPrevInMemory(ref Key key, out RecordInfo recordInfo, out bool continueOnDisk) { recordInfo = default; currentKey = default; currentValue = default; currentPage = currentOffset = currentFrame = -1; continueOnDisk = false; while (true) { // "nextAddress" is reused as "previous address" for this operation. currentAddress = nextAddress; if (currentAddress < hlog.HeadAddress) { continueOnDisk = currentAddress >= hlog.BeginAddress; return false; } epoch?.Resume(); currentPage = currentAddress >> hlog.LogPageSizeBits; currentOffset = (currentAddress & hlog.PageSizeMask) / recordSize; // Read
found
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Execution/RepeatedSubfieldsIntegrationTests.cs
{ "start": 132, "end": 257 }
public class ____ { public string Name { get; set; } public Business Business { get; set; } }
Person
csharp
dotnet__aspnetcore
src/Middleware/OutputCaching/src/OutputCachePolicyBuilder.cs
{ "start": 412, "end": 12623 }
public sealed class ____ { private const DynamicallyAccessedMemberTypes ActivatorAccessibility = DynamicallyAccessedMemberTypes.PublicConstructors; private IOutputCachePolicy? _builtPolicy; private readonly List<IOutputCachePolicy> _policies = new(); private List<Func<OutputCacheContext, CancellationToken, ValueTask<bool>>>? _requirements; internal OutputCachePolicyBuilder() : this(false) { } internal OutputCachePolicyBuilder(bool excludeDefaultPolicy) { _builtPolicy = null; if (!excludeDefaultPolicy) { _policies.Add(DefaultPolicy.Instance); } } internal OutputCachePolicyBuilder AddPolicy(IOutputCachePolicy policy) { _builtPolicy = null; _policies.Add(policy); return this; } /// <summary> /// Adds a dynamically resolved policy. /// </summary> /// <param name="policyType">The type of policy to add</param> public OutputCachePolicyBuilder AddPolicy([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] Type policyType) { return AddPolicy(new TypedPolicy(policyType)); } /// <summary> /// Adds a dynamically resolved policy. /// </summary> /// <typeparam name="T">The policy type.</typeparam> public OutputCachePolicyBuilder AddPolicy<[DynamicallyAccessedMembers(ActivatorAccessibility)] T>() where T : IOutputCachePolicy { return AddPolicy(typeof(T)); } /// <summary> /// Adds a requirement to the current policy. /// </summary> /// <param name="predicate">The predicate applied to the policy.</param> public OutputCachePolicyBuilder With(Func<OutputCacheContext, CancellationToken, ValueTask<bool>> predicate) { ArgumentNullException.ThrowIfNull(predicate); _builtPolicy = null; _requirements ??= new(); _requirements.Add(predicate); return this; } /// <summary> /// Adds a requirement to the current policy. /// </summary> /// <param name="predicate">The predicate applied to the policy.</param> public OutputCachePolicyBuilder With(Func<OutputCacheContext, bool> predicate) { ArgumentNullException.ThrowIfNull(predicate); _builtPolicy = null; _requirements ??= new(); _requirements.Add((c, t) => ValueTask.FromResult(predicate(c))); return this; } /// <summary> /// Adds a policy to vary the cached responses by query strings. /// </summary> /// <param name="queryKey">The query key to vary the cached responses by.</param> /// <param name="queryKeys">The extra query keys to vary the cached responses by.</param> /// <remarks> /// By default all query keys vary the cache entries. However when specific query keys are specified only these are then taken into account. /// </remarks> public OutputCachePolicyBuilder SetVaryByQuery(string queryKey, params string[] queryKeys) { ArgumentNullException.ThrowIfNull(queryKey); return AddPolicy(new VaryByQueryPolicy(queryKey, queryKeys)); } /// <summary> /// Adds a policy to vary the cached responses by query strings. /// </summary> /// <param name="queryKeys">The query keys to vary the cached responses by.</param> /// <remarks> /// By default all query keys vary the cache entries. However when specific query keys are specified only these are then taken into account. /// </remarks> public OutputCachePolicyBuilder SetVaryByQuery(string[] queryKeys) { ArgumentNullException.ThrowIfNull(queryKeys); return AddPolicy(new VaryByQueryPolicy(queryKeys)); } /// <summary> /// Adds a policy to vary the cached responses by header. /// </summary> /// <param name="headerName">The header name to vary the cached responses by.</param> /// <param name="headerNames">Additional header names to vary the cached responses by.</param> public OutputCachePolicyBuilder SetVaryByHeader(string headerName, params string[] headerNames) { ArgumentNullException.ThrowIfNull(headerName); return AddPolicy(new VaryByHeaderPolicy(headerName, headerNames)); } /// <summary> /// Adds a policy to vary the cached responses by header. /// </summary> /// <param name="headerNames">The header names to vary the cached responses by.</param> public OutputCachePolicyBuilder SetVaryByHeader(string[] headerNames) { ArgumentNullException.ThrowIfNull(headerNames); return AddPolicy(new VaryByHeaderPolicy(headerNames)); } /// <summary> /// Adds a policy to vary the cached responses by route value. /// </summary> /// <param name="routeValueName">The route value name to vary the cached responses by.</param> /// <param name="routeValueNames">The extra route value names to vary the cached responses by.</param> public OutputCachePolicyBuilder SetVaryByRouteValue(string routeValueName, params string[] routeValueNames) { ArgumentNullException.ThrowIfNull(routeValueName); return AddPolicy(new VaryByRouteValuePolicy(routeValueName, routeValueNames)); } /// <summary> /// Adds a policy to vary the cached responses by route value. /// </summary> /// <param name="routeValueNames">The route value names to vary the cached responses by.</param> public OutputCachePolicyBuilder SetVaryByRouteValue(string[] routeValueNames) { ArgumentNullException.ThrowIfNull(routeValueNames); return AddPolicy(new VaryByRouteValuePolicy(routeValueNames)); } /// <summary> /// Adds a policy that varies the cache key using the specified value. /// </summary> /// <param name="keyPrefix">The value to vary the cache key by.</param> public OutputCachePolicyBuilder SetCacheKeyPrefix(string keyPrefix) { ArgumentNullException.ThrowIfNull(keyPrefix); ValueTask<string> varyByKeyFunc(HttpContext context, CancellationToken cancellationToken) { return ValueTask.FromResult(keyPrefix); } return AddPolicy(new SetCacheKeyPrefixPolicy(varyByKeyFunc)); } /// <summary> /// Adds a policy that varies the cache key using the specified value. /// </summary> /// <param name="keyPrefix">The value to vary the cache key by.</param> public OutputCachePolicyBuilder SetCacheKeyPrefix(Func<HttpContext, string> keyPrefix) { ArgumentNullException.ThrowIfNull(keyPrefix); ValueTask<string> varyByKeyFunc(HttpContext context, CancellationToken cancellationToken) { return ValueTask.FromResult(keyPrefix(context)); } return AddPolicy(new SetCacheKeyPrefixPolicy(varyByKeyFunc)); } /// <summary> /// Adds a policy that varies the cache key using the specified value. /// </summary> /// <param name="keyPrefix">The value to vary the cache key by.</param> public OutputCachePolicyBuilder SetCacheKeyPrefix(Func<HttpContext, CancellationToken, ValueTask<string>> keyPrefix) { ArgumentNullException.ThrowIfNull(keyPrefix); return AddPolicy(new SetCacheKeyPrefixPolicy(keyPrefix)); } /// <summary> /// Adds a policy to vary the cached responses by custom key/value. /// </summary> /// <param name="key">The key to vary the cached responses by.</param> /// <param name="value">The value to vary the cached responses by.</param> public OutputCachePolicyBuilder VaryByValue(string key, string value) { ArgumentNullException.ThrowIfNull(key); ArgumentNullException.ThrowIfNull(value); ValueTask<KeyValuePair<string, string>> varyByFunc(HttpContext context, CancellationToken cancellationToken) { return ValueTask.FromResult(new KeyValuePair<string, string>(key, value)); } return AddPolicy(new VaryByValuePolicy(varyByFunc)); } /// <summary> /// Adds a policy to vary the cached responses by custom key/value. /// </summary> /// <param name="varyBy">The key/value to vary the cached responses by.</param> public OutputCachePolicyBuilder VaryByValue(Func<HttpContext, KeyValuePair<string, string>> varyBy) { ArgumentNullException.ThrowIfNull(varyBy); ValueTask<KeyValuePair<string, string>> varyByFunc(HttpContext context, CancellationToken cancellationToken) { return ValueTask.FromResult(varyBy(context)); } return AddPolicy(new VaryByValuePolicy(varyByFunc)); } /// <summary> /// Adds a policy that vary the cached content based on the specified value. /// </summary> /// <param name="varyBy">The key/value to vary the cached responses by.</param> public OutputCachePolicyBuilder VaryByValue(Func<HttpContext, CancellationToken, ValueTask<KeyValuePair<string, string>>> varyBy) { ArgumentNullException.ThrowIfNull(varyBy); return AddPolicy(new VaryByValuePolicy(varyBy)); } /// <summary> /// Adds a policy to tag the cached response. /// </summary> /// <param name="tags">The tags to add to the cached reponse.</param> public OutputCachePolicyBuilder Tag(params string[] tags) { ArgumentNullException.ThrowIfNull(tags); return AddPolicy(new TagsPolicy(tags)); } /// <summary> /// Adds a policy to change the cached response expiration. /// </summary> /// <param name="expiration">The expiration of the cached reponse.</param> public OutputCachePolicyBuilder Expire(TimeSpan expiration) { return AddPolicy(new ExpirationPolicy(expiration)); } /// <summary> /// Adds a policy to change the request locking strategy. /// </summary> /// <param name="enabled">Whether the request should be locked.</param> /// <remarks>When the default policy is used, locking is enabled by default.</remarks> public OutputCachePolicyBuilder SetLocking(bool enabled) => AddPolicy(enabled ? LockingPolicy.Enabled : LockingPolicy.Disabled); /// <summary> /// Clears the policies and adds one preventing any caching logic to happen. /// </summary> /// <remarks> /// The cache key will never be computed. /// </remarks> public OutputCachePolicyBuilder NoCache() { _policies.Clear(); return AddPolicy(EnableCachePolicy.Disabled); } /// <summary> /// Enables caching for the current request if not already enabled. /// </summary> public OutputCachePolicyBuilder Cache() { // If no custom policy is added, the DefaultPolicy is already "enabled". if (_policies.Count != 1 || _policies[0] != DefaultPolicy.Instance) { AddPolicy(EnableCachePolicy.Enabled); } return this; } /// <summary> /// Adds a policy setting whether to vary by the Host header ot not. /// </summary> public OutputCachePolicyBuilder SetVaryByHost(bool enabled) { return AddPolicy(enabled ? VaryByHostPolicy.Enabled : VaryByHostPolicy.Disabled); } /// <summary> /// Creates the <see cref="IOutputCachePolicy"/>. /// </summary> /// <returns>The<see cref="IOutputCachePolicy"/> instance.</returns> internal IOutputCachePolicy Build() { if (_builtPolicy != null) { return _builtPolicy; } var policies = _policies.Count switch { 0 => EmptyPolicy.Instance, 1 => _policies[0], _ => new CompositePolicy(_policies.ToArray()), }; // If the policy was built with requirements, wrap it if (_requirements != null && _requirements.Any()) { policies = new PredicatePolicy(async c => { foreach (var r in _requirements) { if (!await r(c, c.HttpContext.RequestAborted)) { return false; } } return true; }, policies); } return _builtPolicy = policies; } }
OutputCachePolicyBuilder
csharp
smartstore__Smartstore
src/Smartstore/Data/Hooks/HookException.cs
{ "start": 39, "end": 332 }
public sealed class ____ : Exception { public HookException(string message) : base(message) { } public HookException(string message, Exception innerException) : base(message, innerException) { } } }
HookException
csharp
dotnet__maui
src/Controls/tests/CustomAttributes/Test.cs
{ "start": 5015, "end": 5451 }
public enum ____ { Source, Image, IsOpaque, IsLoading, Aspect, Aspect_AspectFill, Aspect_AspectFit, Aspect_Fill, Aspect_Center, BorderColor, CornerRadius, BorderWidth, BorderColor_WithBackground, CornerRadius_WithBackground, BorderWidth_WithBackground, Clicked, Command, Pressed, Padding, Padding_Add, // do not use, rather use Aspect_* instead AspectFill, AspectFit, Fill, }
ImageButton
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Automation/AutomationTextEditChangeType.cs
{ "start": 226, "end": 712 }
public enum ____ { // Skipping already declared field Microsoft.UI.Xaml.Automation.AutomationTextEditChangeType.None // Skipping already declared field Microsoft.UI.Xaml.Automation.AutomationTextEditChangeType.AutoCorrect // Skipping already declared field Microsoft.UI.Xaml.Automation.AutomationTextEditChangeType.Composition // Skipping already declared field Microsoft.UI.Xaml.Automation.AutomationTextEditChangeType.CompositionFinalized } #endif }
AutomationTextEditChangeType
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Services/Catalog/ManufacturerTemplateService.cs
{ "start": 145, "end": 3040 }
public partial class ____ : IManufacturerTemplateService { #region Fields protected readonly IRepository<ManufacturerTemplate> _manufacturerTemplateRepository; #endregion #region Ctor public ManufacturerTemplateService(IRepository<ManufacturerTemplate> manufacturerTemplateRepository) { _manufacturerTemplateRepository = manufacturerTemplateRepository; } #endregion #region Methods /// <summary> /// Delete manufacturer template /// </summary> /// <param name="manufacturerTemplate">Manufacturer template</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task DeleteManufacturerTemplateAsync(ManufacturerTemplate manufacturerTemplate) { await _manufacturerTemplateRepository.DeleteAsync(manufacturerTemplate); } /// <summary> /// Gets all manufacturer templates /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the manufacturer templates /// </returns> public virtual async Task<IList<ManufacturerTemplate>> GetAllManufacturerTemplatesAsync() { var templates = await _manufacturerTemplateRepository.GetAllAsync(query => { return from pt in query orderby pt.DisplayOrder, pt.Id select pt; }, cache => default); return templates; } /// <summary> /// Gets a manufacturer template /// </summary> /// <param name="manufacturerTemplateId">Manufacturer template identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the manufacturer template /// </returns> public virtual async Task<ManufacturerTemplate> GetManufacturerTemplateByIdAsync(int manufacturerTemplateId) { return await _manufacturerTemplateRepository.GetByIdAsync(manufacturerTemplateId, cache => default); } /// <summary> /// Inserts manufacturer template /// </summary> /// <param name="manufacturerTemplate">Manufacturer template</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task InsertManufacturerTemplateAsync(ManufacturerTemplate manufacturerTemplate) { await _manufacturerTemplateRepository.InsertAsync(manufacturerTemplate); } /// <summary> /// Updates the manufacturer template /// </summary> /// <param name="manufacturerTemplate">Manufacturer template</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task UpdateManufacturerTemplateAsync(ManufacturerTemplate manufacturerTemplate) { await _manufacturerTemplateRepository.UpdateAsync(manufacturerTemplate); } #endregion }
ManufacturerTemplateService
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Acceptance.Specs/TypeForwarding.cs
{ "start": 126, "end": 2662 }
public class ____ { [Test] public void UseImplementedNonVirtualMethod() { var testAbstractClass = Substitute.ForTypeForwardingTo<ITestInterface, TestSealedNonVirtualClass>(); Assert.That(testAbstractClass.MethodReturnsSameInt(1), Is.EqualTo(1)); Assert.That(testAbstractClass.CalledTimes, Is.EqualTo(1)); testAbstractClass.Received().MethodReturnsSameInt(1); Assert.That(testAbstractClass.CalledTimes, Is.EqualTo(1)); } [Test] public void UseSubstitutedNonVirtualMethod() { var testInterface = Substitute.ForTypeForwardingTo<ITestInterface, TestSealedNonVirtualClass>(); testInterface.Configure().MethodReturnsSameInt(1).Returns(2); Assert.That(testInterface.MethodReturnsSameInt(1), Is.EqualTo(2)); Assert.That(testInterface.MethodReturnsSameInt(3), Is.EqualTo(3)); testInterface.ReceivedWithAnyArgs(2).MethodReturnsSameInt(default); Assert.That(testInterface.CalledTimes, Is.EqualTo(1)); } [Test] public void UseSubstitutedNonVirtualMethodHonorsDoNotCallBase() { var testInterface = Substitute.ForTypeForwardingTo<ITestInterface, TestSealedNonVirtualClass>(); testInterface.Configure().MethodReturnsSameInt(1).Returns(2); testInterface.WhenForAnyArgs(x => x.MethodReturnsSameInt(default)).DoNotCallBase(); Assert.That(testInterface.MethodReturnsSameInt(1), Is.EqualTo(2)); Assert.That(testInterface.MethodReturnsSameInt(3), Is.EqualTo(0)); testInterface.ReceivedWithAnyArgs(2).MethodReturnsSameInt(default); Assert.That(testInterface.CalledTimes, Is.EqualTo(0)); } [Test] public void PartialSubstituteCallsConstructorWithParameters() { var testInterface = Substitute.ForTypeForwardingTo<ITestInterface, TestSealedNonVirtualClass>(50); Assert.That(testInterface.MethodReturnsSameInt(1), Is.EqualTo(1)); Assert.That(testInterface.CalledTimes, Is.EqualTo(51)); } [Test] public void PartialSubstituteFailsIfClassDoesntImplementInterface() { Assert.Throws<CanNotForwardCallsToClassNotImplementingInterfaceException>( () => Substitute.ForTypeForwardingTo<ITestInterface, TestRandomConcreteClass>()); } [Test] public void PartialSubstituteFailsIfClassIsAbstract() { Assert.Throws<CanNotForwardCallsToAbstractClassException>( () => Substitute.ForTypeForwardingTo<ITestInterface, TestAbstractClassWithInterface>(), "The provided
TypeForwarding
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests/Firebird/Curd/FirebirdSelectTest.cs
{ "start": 69322, "end": 74746 }
public class ____ { [Column(IsIdentity = true)] public int id { get; set; } public int model3333Id333 { get; set; } public string title444 { get; set; } } [Fact] public void Include_OneToMany() { var model1 = new TiOtmModel1 { m1name = DateTime.Now.Second.ToString() }; model1.id = (int)g.firebird.Insert(model1).ExecuteIdentity(); var model2 = new TiOtmModel2 { model2id = model1.id, m2setting = DateTime.Now.Second.ToString() }; g.firebird.Insert(model2).ExecuteAffrows(); var model3_1 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__111" }; model3_1.id = (int)g.firebird.Insert(model3_1).ExecuteIdentity(); var model3_2 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__222" }; model3_2.id = (int)g.firebird.Insert(model3_2).ExecuteIdentity(); var model3_3 = new TiOtmModel3 { model2111Idaaa = model1.id, title = "testmodel3__333" }; model3_3.id = (int)g.firebird.Insert(model3_2).ExecuteIdentity(); var model4s = new[] { new TiOtmModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__111" }, new TiOtmModel4{ model3333Id333 = model3_1.id, title444 = "testmodel3_4__222" }, new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__111" }, new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__222" }, new TiOtmModel4{ model3333Id333 = model3_2.id, title444 = "testmodel3_4__333" } }; Assert.Equal(5, g.firebird.Insert(model4s).ExecuteAffrows()); var t0 = g.firebird.Select<TiOtmModel2>() .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id)) .Where(a => a.model2id <= model1.id) .ToList(); var t1 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id)) .Where(a => a.id <= model1.id) .ToList(); var t2 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id), then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id))) .Where(a => a.id <= model1.id) .ToList(); var t00 = g.firebird.Select<TiOtmModel2>() .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id)) .Where(a => a.model2id <= model1.id) .ToList(); var t11 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id)) .Where(a => a.id <= model1.id) .ToList(); var t22 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id), then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id))) .Where(a => a.id <= model1.id) .ToList(); //---- Select ---- var at0 = g.firebird.Select<TiOtmModel2>() .IncludeMany(a => a.childs.Where(m3 => m3.model2111Idaaa == a.model2id).Select(m3 => new TiOtmModel3 { id = m3.id })) .Where(a => a.model2id <= model1.id) .ToList(); var at1 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id).Select(m3 => new TiOtmModel3 { id = m3.id })) .Where(a => a.id <= model1.id) .ToList(); var at2 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Where(m3 => m3.model2111Idaaa == a.model2.model2id).Select(m3 => new TiOtmModel3 { id = m3.id }), then => then.IncludeMany(m3 => m3.childs2.Where(m4 => m4.model3333Id333 == m3.id).Select(m4 => new TiOtmModel4 { id = m4.id }))) .Where(a => a.id <= model1.id) .ToList(); var at00 = g.firebird.Select<TiOtmModel2>() .IncludeMany(a => a.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2id).Select(m3 => new TiOtmModel3 { id = m3.id })) .Where(a => a.model2id <= model1.id) .ToList(); var at11 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id).Select(m3 => new TiOtmModel3 { id = m3.id })) .Where(a => a.id <= model1.id) .ToList(); var at22 = g.firebird.Select<TiOtmModel1>() .IncludeMany(a => a.model2.childs.Take(1).Where(m3 => m3.model2111Idaaa == a.model2.model2id).Select(m3 => new TiOtmModel3 { id = m3.id }), then => then.IncludeMany(m3 => m3.childs2.Take(2).Where(m4 => m4.model3333Id333 == m3.id).Select(m4 => new TiOtmModel4 { id = m4.id }))) .Where(a => a.id <= model1.id) .ToList(); }
TiOtmModel4
csharp
microsoft__FASTER
cs/src/core/Device/ShardedStorageDevice.cs
{ "start": 2822, "end": 6691 }
class ____ : IPartitionScheme { public IList<IDevice> Devices { get; } private readonly long chunkSize; /// <summary> /// Constructs a UniformPartitionScheme to shard data uniformly across given devices. Suppose we have 3 devices and the following logical write: /// [chunk 1][chunk 2][chunk 3][chunk 4]... /// chunk 1 is written on device 0, 2 on device 1, 3 on device 2, 4 on device 0, etc. /// </summary> /// <param name="chunkSize">size of each chunk</param> /// <param name="devices">the devices to compose from</param> public UniformPartitionScheme(long chunkSize, IList<IDevice> devices) { Debug.Assert(devices.Count != 0, "There cannot be zero shards"); Debug.Assert(chunkSize > 0, "chunk size should not be negative"); Debug.Assert((chunkSize & (chunkSize - 1)) == 0, "Chunk size must be a power of 2"); this.Devices = devices; this.chunkSize = chunkSize; foreach (IDevice device in Devices) { Debug.Assert(chunkSize % device.SectorSize == 0, "A single device sector cannot be partitioned"); } } /// <summary> /// vararg version of <see cref="UniformPartitionScheme(long, IList{IDevice})"/> /// </summary> /// <param name="chunkSize"></param> /// <param name="devices"></param> public UniformPartitionScheme(long chunkSize, params IDevice[] devices) : this(chunkSize, (IList<IDevice>)devices) { } /// <summary> /// <see cref="IPartitionScheme.MapRange(long, long, out int, out long, out long)"/> /// </summary> /// <param name="startAddress"></param> /// <param name="endAddress"></param> /// <param name="shard"></param> /// <param name="shardStartAddress"></param> /// <param name="shardEndAddress"></param> /// <returns></returns> public long MapRange(long startAddress, long endAddress, out int shard, out long shardStartAddress, out long shardEndAddress) { long chunkId = startAddress / chunkSize; shard = (int)(chunkId % Devices.Count); shardStartAddress = chunkId / Devices.Count * chunkSize + startAddress % chunkSize; long chunkEndAddress = (chunkId + 1) * chunkSize; if (endAddress > chunkEndAddress) { shardEndAddress = shardStartAddress + chunkSize; return chunkEndAddress; } else { shardEndAddress = endAddress - startAddress + shardStartAddress; return endAddress; } } /// <summary> /// <see cref="IPartitionScheme.MapSectorSize(long, int)"/> /// </summary> /// <param name="sectorSize"></param> /// <param name="shard"></param> /// <returns></returns> public long MapSectorSize(long sectorSize, int shard) { var numChunks = sectorSize / chunkSize; // ceiling of (a div b) is (a + b - 1) / b where div is mathematical division and / is integer division return (numChunks + Devices.Count - 1) / Devices.Count * chunkSize; } } /// <summary> /// A <see cref="ShardedStorageDevice"/> logically composes multiple <see cref="IDevice"/> into a single storage device /// by sharding writes into different devices according to a supplied <see cref="IPartitionScheme"/>. The goal is to be /// able to issue large reads and writes in parallel into multiple devices and improve throughput. Beware that this /// code does not contain error detection or correction mechanism to cope with increased failure from more devices. /// </summary>
UniformPartitionScheme
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Platform/IReadableBitmapImpl.cs
{ "start": 56, "end": 232 }
public interface ____ { PixelFormat? Format { get; } ILockedFramebuffer Lock(); } //TODO12: Remove me once we can change IReadableBitmapImpl [Unstable]
IReadableBitmapImpl
csharp
unoplatform__uno
src/SamplesApp/UnoIslands.WinForms/Form1.cs
{ "start": 33, "end": 126 }
public partial class ____ : Form { public Form1() { InitializeComponent(); } } }
Form1
csharp
dotnet__aspnetcore
src/Components/Endpoints/test/RazorComponentEndpointDataSourceTest.cs
{ "start": 13496, "end": 13779 }
public class ____ : IComponent { public void Attach(RenderHandle renderHandle) { throw new NotImplementedException(); } public Task SetParametersAsync(ParameterView parameters) { throw new NotImplementedException(); } } [Route("/counter")]
Index
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Meetings/Application/MeetingCommentingConfigurations/DisableMeetingCommentingConfiguration/DisableMeetingCommentingConfigurationCommand.cs
{ "start": 209, "end": 465 }
public class ____ : CommandBase { public Guid MeetingId { get; } public DisableMeetingCommentingConfigurationCommand(Guid meetingId) { MeetingId = meetingId; } } }
DisableMeetingCommentingConfigurationCommand
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml/Performance/Performance_Dopes.xaml.cs
{ "start": 854, "end": 6341 }
partial class ____ : Page { volatile bool breakTest = false; const int max = 600; private readonly UnitTestDispatcherCompat _dispatcher; public Performance_Dopes() { this.InitializeComponent(); _dispatcher = UnitTestDispatcherCompat.From(this); } private void StartTestST() { var rand = new Random(0); breakTest = false; var width = absolute.ActualWidth; var height = absolute.ActualHeight; const int step = 20; var labels = new TextBlock[step * 2]; var processed = 0; long prevTicks = 0; long prevMs = 0; int prevProcessed = 0; double avgSum = 0; int avgN = 0; var sw = new Stopwatch(); Action loop = null; loop = () => { var now = sw.ElapsedMilliseconds; if (breakTest) { var avg = avgSum / avgN; dopes.Text = string.Format("{0:0.00} Dopes/s (AVG)", avg).PadLeft(21); return; } //60hz, 16ms to build the frame while (sw.ElapsedMilliseconds - now < 16) { var label = new TextBlock() { Text = "Dope", Foreground = new SolidColorBrush(Color.FromArgb(0xFF, (byte)(rand.NextDouble() * 255), (byte)(rand.NextDouble() * 255), (byte)(rand.NextDouble() * 255))) }; label.RenderTransform = new RotateTransform() { Angle = rand.NextDouble() * 360 }; Canvas.SetLeft(label, rand.NextDouble() * width); Canvas.SetTop(label, rand.NextDouble() * height); if (processed > max) { absolute.Children.RemoveAt(0); } absolute.Children.Add(label); processed++; if (sw.ElapsedMilliseconds - prevMs > 500) { var r = (double)(processed - prevProcessed) / ((double)(sw.ElapsedTicks - prevTicks) / Stopwatch.Frequency); prevTicks = sw.ElapsedTicks; prevProcessed = processed; if (processed > max) { dopes.Text = string.Format("{0:0.00} Dopes/s", r).PadLeft(15); avgSum += r; avgN++; } prevMs = sw.ElapsedMilliseconds; } } _ = _dispatcher.RunAsync(UnitTestDispatcherCompat.Priority.Low, () => loop()); }; sw.Start(); _ = _dispatcher.RunAsync(UnitTestDispatcherCompat.Priority.Normal, () => loop()); } private void StartTestReuseST() { var rand = new Random(0); breakTest = false; var width = absolute.ActualWidth; var height = absolute.ActualHeight; const int step = 20; var labels = new TextBlock[step * 2]; var processed = 0; long prevTicks = 0; long prevMs = 0; int prevProcessed = 0; double avgSum = 0; int avgN = 0; var sw = new Stopwatch(); Action loop = null; System.Collections.Concurrent.ConcurrentBag<TextBlock> _cache = new System.Collections.Concurrent.ConcurrentBag<TextBlock>(); loop = () => { var now = sw.ElapsedMilliseconds; if (breakTest) { var avg = avgSum / avgN; dopes.Text = string.Format("{0:0.00} Dopes/s (AVG)", avg).PadLeft(21); return; } //60hz, 16ms to build the frame while (sw.ElapsedMilliseconds - now < 16) { if (!_cache.TryTake(out var label)) { label = new TextBlock(); } label.Text = "Dope"; label.Foreground = new SolidColorBrush(Color.FromArgb(0xFF, (byte)(rand.NextDouble() * 255), (byte)(rand.NextDouble() * 255), (byte)(rand.NextDouble() * 255))); label.RenderTransform = new RotateTransform() { Angle = rand.NextDouble() * 360 }; Canvas.SetLeft(label, rand.NextDouble() * width); Canvas.SetTop(label, rand.NextDouble() * height); if (processed > max) { _cache.Add(absolute.Children[0] as TextBlock); absolute.Children.RemoveAt(0); } absolute.Children.Add(label); processed++; if (sw.ElapsedMilliseconds - prevMs > 500) { var r = (double)(processed - prevProcessed) / ((double)(sw.ElapsedTicks - prevTicks) / Stopwatch.Frequency); prevTicks = sw.ElapsedTicks; prevProcessed = processed; if (processed > max) { dopes.Text = string.Format("{0:0.00} Dopes/s", r).PadLeft(15); avgSum += r; avgN++; } prevMs = sw.ElapsedMilliseconds; } } _ = _dispatcher.RunAsync(UnitTestDispatcherCompat.Priority.Low, () => loop()); }; sw.Start(); _ = _dispatcher.RunAsync(UnitTestDispatcherCompat.Priority.Low, () => loop()); } private void SetControlsAtStart() { startChangeST.Visibility = startST.Visibility = startGridST.Visibility = Visibility.Collapsed; stop.Visibility = dopes.Visibility = Visibility.Visible; absolute.Children.Clear(); grid.Children.Clear(); dopes.Text = "Warming up.."; } private void startMT_Clicked(System.Object sender, object e) { SetControlsAtStart(); //StartTestMT2(); } private void startST_Clicked(System.Object sender, object e) { SetControlsAtStart(); StartTestST(); } private void startGridST_Clicked(System.Object sender, object e) { SetControlsAtStart(); //StartTestGridST(); } private void startChangeST_Clicked(System.Object sender, object e) { SetControlsAtStart(); //StartTestChangeST(); } private void startChangeReuse_Clicked(System.Object sender, object e) { SetControlsAtStart(); StartTestReuseST(); } private void Stop_Clicked(System.Object sender, object e) { breakTest = true; stop.Visibility = Visibility.Collapsed; startChangeST.Visibility = startST.Visibility = startGridST.Visibility = Visibility.Visible; } } }
Performance_Dopes
csharp
dotnet__extensions
src/Libraries/Microsoft.Extensions.AI.Evaluation.Quality/EquivalenceEvaluator.cs
{ "start": 1906, "end": 10260 }
public sealed class ____ : IEvaluator { /// <summary> /// Gets the <see cref="EvaluationMetric.Name"/> of the <see cref="NumericMetric"/> returned by /// <see cref="EquivalenceEvaluator"/>. /// </summary> public static string EquivalenceMetricName => "Equivalence"; /// <inheritdoc/> public IReadOnlyCollection<string> EvaluationMetricNames { get; } = [EquivalenceMetricName]; // Note: We intentionally don't set MaxOutputTokens below. // See https://github.com/dotnet/extensions/issues/6814, https://github.com/dotnet/extensions/issues/6945 // and https://github.com/dotnet/extensions/issues/7002. private static readonly ChatOptions _chatOptions = new ChatOptions { Temperature = 0.0f, TopP = 1.0f, PresencePenalty = 0.0f, FrequencyPenalty = 0.0f, ResponseFormat = ChatResponseFormat.Text }; /// <inheritdoc/> public async ValueTask<EvaluationResult> EvaluateAsync( IEnumerable<ChatMessage> messages, ChatResponse modelResponse, ChatConfiguration? chatConfiguration = null, IEnumerable<EvaluationContext>? additionalContext = null, CancellationToken cancellationToken = default) { _ = Throw.IfNull(modelResponse); _ = Throw.IfNull(chatConfiguration); var metric = new NumericMetric(EquivalenceMetricName); var result = new EvaluationResult(metric); metric.MarkAsBuiltIn(); if (string.IsNullOrWhiteSpace(modelResponse.Text)) { metric.AddDiagnostics( EvaluationDiagnostic.Error($"The {nameof(modelResponse)} supplied for evaluation was null or empty.")); return result; } if (additionalContext?.OfType<EquivalenceEvaluatorContext>().FirstOrDefault() is not EquivalenceEvaluatorContext context) { metric.AddDiagnostics( EvaluationDiagnostic.Error( $"A value of type {nameof(EquivalenceEvaluatorContext)} was not found in the {nameof(additionalContext)} collection.")); return result; } _ = messages.TryGetUserRequest(out ChatMessage? userRequest); List<ChatMessage> evaluationInstructions = GetEvaluationInstructions(userRequest, modelResponse, context); (ChatResponse evaluationResponse, TimeSpan evaluationDuration) = await TimingHelper.ExecuteWithTimingAsync(() => chatConfiguration.ChatClient.GetResponseAsync( evaluationInstructions, _chatOptions, cancellationToken)).ConfigureAwait(false); _ = metric.TryParseEvaluationResponseWithValue(evaluationResponse, evaluationDuration); metric.AddOrUpdateContext(context); metric.Interpretation = metric.InterpretScore(); return result; } private static List<ChatMessage> GetEvaluationInstructions( ChatMessage? userRequest, ChatResponse modelResponse, EquivalenceEvaluatorContext context) { const string SystemPrompt = """ You are an AI assistant. You will be given the definition of an evaluation metric for assessing the quality of an answer in a question-answering task. Your job is to compute an accurate evaluation score using the provided evaluation metric. You should return a single integer value between 1 to 5 representing the evaluation metric. You will include no other text or information. """; List<ChatMessage> evaluationInstructions = [new ChatMessage(ChatRole.System, SystemPrompt)]; string renderedUserRequest = userRequest?.RenderText() ?? string.Empty; string renderedModelResponse = modelResponse.RenderText(); string groundTruth = context.GroundTruth; string evaluationPrompt = $$""" Equivalence, as a metric, measures the similarity between the predicted answer and the correct answer. If the information and content in the predicted answer is similar or equivalent to the correct answer, then the value of the Equivalence metric should be high, else it should be low. Given the question, correct answer, and predicted answer, determine the value of Equivalence metric using the following rating scale: One star: the predicted answer is not at all similar to the correct answer Two stars: the predicted answer is mostly not similar to the correct answer Three stars: the predicted answer is somewhat similar to the correct answer Four stars: the predicted answer is mostly similar to the correct answer Five stars: the predicted answer is completely similar to the correct answer This rating value should always be an integer between 1 and 5. So the rating produced should be 1 or 2 or 3 or 4 or 5. The examples below show the Equivalence score for a question, a correct answer, and a predicted answer. question: What is the role of ribosomes? correct answer: Ribosomes are cellular structures responsible for protein synthesis. They interpret the genetic information carried by messenger RNA (mRNA) and use it to assemble amino acids into proteins. predicted answer: Ribosomes participate in carbohydrate breakdown by removing nutrients from complex sugar molecules. stars: 1 question: Why did the Titanic sink? correct answer: The Titanic sank after it struck an iceberg during its maiden voyage in 1912. The impact caused the ship's hull to breach, allowing water to flood into the vessel. The ship's design, lifeboat shortage, and lack of timely rescue efforts contributed to the tragic loss of life. predicted answer: The sinking of the Titanic was a result of a large iceberg collision. This caused the ship to take on water and eventually sink, leading to the death of many passengers due to a shortage of lifeboats and insufficient rescue attempts. stars: 2 question: What causes seasons on Earth? correct answer: Seasons on Earth are caused by the tilt of the Earth's axis and its revolution around the Sun. As the Earth orbits the Sun, the tilt causes different parts of the planet to receive varying amounts of sunlight, resulting in changes in temperature and weather patterns. predicted answer: Seasons occur because of the Earth's rotation and its elliptical orbit around the Sun. The tilt of the Earth's axis causes regions to be subjected to different sunlight intensities, which leads to temperature fluctuations and alternating weather conditions. stars: 3 question: How does photosynthesis work? correct answer: Photosynthesis is a process by which green plants and some other organisms convert light energy into chemical energy. This occurs as light is absorbed by chlorophyll molecules, and then carbon dioxide and water are converted into glucose and oxygen through a series of reactions. predicted answer: In photosynthesis, sunlight is transformed into nutrients by plants and certain microorganisms. Light is captured by chlorophyll molecules, followed by the conversion of carbon dioxide and water into sugar and oxygen through multiple reactions. stars: 4 question: What are the health benefits of regular exercise? correct answer: Regular exercise can help maintain a healthy weight, increase muscle and bone strength, and reduce the risk of chronic diseases. It also promotes mental well-being by reducing stress and improving overall mood. predicted answer: Routine physical activity can contribute to maintaining ideal body weight, enhancing muscle and bone strength, and preventing chronic illnesses. In addition, it supports mental health by alleviating stress and augmenting general mood. stars: 5 question: {{renderedUserRequest}} correct answer:{{groundTruth}} predicted answer: {{renderedModelResponse}} stars: """; evaluationInstructions.Add(new ChatMessage(ChatRole.User, evaluationPrompt)); return evaluationInstructions; } }
EquivalenceEvaluator
csharp
ChilliCream__graphql-platform
src/HotChocolate/Utilities/src/Utilities.Introspection/Models/Directive.cs
{ "start": 68, "end": 452 }
internal class ____ { public string Name { get; set; } public string Description { get; set; } public ICollection<InputField> Args { get; set; } public ICollection<string> Locations { get; set; } public bool? IsRepeatable { get; set; } public bool OnOperation { get; set; } public bool OnFragment { get; set; } public bool OnField { get; set; } }
Directive
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding101OneToOneTestBase.cs
{ "start": 58637, "end": 59291 }
public class ____ : Context101 { public DbSet<Blog> Blogs => Set<Blog>(); public DbSet<BlogHeader> BlogHeaders => Set<BlogHeader>(); protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Blog>(b => { b.HasKey(e => new { e.Id1, e.Id2 }); b.HasOne(e => e.Header) .WithOne(e => e.Blog) .HasPrincipalKey<Blog>(e => new { e.Id1, e.Id2 }) .IsRequired(); }); }
BlogContext0
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.Tax.FixedOrByCountryStateZip/Migrations/UpgradeTo470/LocalizationMigration.cs
{ "start": 371, "end": 1484 }
public class ____ : MigrationBase { public override void Down() { //add the downgrade logic if necessary } public override void Up() { if (!DataSettingsManager.IsDatabaseInstalled()) return; var localizationService = EngineContext.Current.Resolve<ILocalizationService>(); var (languageId, _) = this.GetLanguageData(); //use localizationService to add, update and delete localization resources localizationService.AddOrUpdateLocaleResource(new Dictionary<string, string> { ["Plugins.Tax.FixedOrByCountryStateZip.SwitchRate"] = @" <p> You are going to change the way the tax rate is calculated. This will cause the tax rate to be calculated based on the settings specified on the configuration page. </p> <p> Any current tax rate settings will be saved, but will not be active until you return to this tax calculation method. </p>", }, languageId); } }
LocalizationMigration
csharp
dotnet__maui
src/Controls/src/Core/LegacyLayouts/ConstraintExpression.cs
{ "start": 330, "end": 2329 }
public class ____ : IMarkupExtension<Constraint> { public ConstraintExpression() { Factor = 1.0; } public double Constant { get; set; } public string ElementName { get; set; } public double Factor { get; set; } public string Property { get; set; } public ConstraintType Type { get; set; } object IMarkupExtension.ProvideValue(IServiceProvider serviceProvider) { return (this as IMarkupExtension<Constraint>).ProvideValue(serviceProvider); } public Constraint ProvideValue(IServiceProvider serviceProvider) { MethodInfo minfo; switch (Type) { default: case ConstraintType.RelativeToParent: if (string.IsNullOrEmpty(Property)) return null; minfo = typeof(View).GetProperties().First(pi => pi.Name == Property && pi.CanRead && pi.GetMethod.IsPublic).GetMethod; return Constraint.RelativeToParent(p => (double)minfo.Invoke(p, Array.Empty<object>()) * Factor + Constant); case ConstraintType.Constant: return Constraint.Constant(Constant); case ConstraintType.RelativeToView: if (string.IsNullOrEmpty(Property)) return null; if (string.IsNullOrEmpty(ElementName)) return null; minfo = typeof(View).GetProperties().First(pi => pi.Name == Property && pi.CanRead && pi.GetMethod.IsPublic).GetMethod; var referenceProvider = serviceProvider.GetService<IReferenceProvider>(); View view; if (referenceProvider != null) view = (View)referenceProvider.FindByName(ElementName); else { //legacy path var valueProvider = serviceProvider.GetService<IProvideValueTarget>(); if (valueProvider == null || !(valueProvider.TargetObject is INameScope)) return null; view = ((INameScope)valueProvider.TargetObject).FindByName<View>(ElementName); } return Constraint.RelativeToView(view, delegate (RelativeLayout p, View v) { return (double)minfo.Invoke(v, Array.Empty<object>()) * Factor + Constant; }); } } } }
ConstraintExpression
csharp
dotnet__aspire
src/Components/Aspire.Azure.Messaging.EventHubs/AzureMessagingEventHubsSettings.cs
{ "start": 5933, "end": 6160 }
public sealed class ____ : AzureMessagingEventHubsSettings { } /// <summary> /// Represents additional settings for configuring a <see cref="EventHubConsumerClient"/>. /// </summary>
AzureMessagingEventHubsBufferedProducerSettings
csharp
protobuf-net__protobuf-net
assorted/MonoDto/Orders.cs
{ "start": 611, "end": 1098 }
public class ____ { [ProtoMember(1)] public int Id { get; set; } [ProtoMember(2)] public string CustomerRef { get; set; } [ProtoMember(3)] public DateTime OrderDate { get; set; } [ProtoMember(4)] public DateTime DueDate { get; set; } private List<OrderDetail> lines; [ProtoMember(5)] public List<OrderDetail> Lines { get { return lines ?? (lines = new List<OrderDetail>()); } } } [ProtoContract]
OrderHeader
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/CSharp5162Tests.cs
{ "start": 5270, "end": 5513 }
private class ____ { public int Id { get; set; } public string Name { get; set; } public DateTime ActiveSince { get; set; } public bool IsActive { get; set; } } } }
PascalDocument
csharp
AutoMapper__AutoMapper
src/UnitTests/IMappingExpression/IncludeMembers.cs
{ "start": 20792, "end": 20965 }
private class ____ : IValueConverter<string, string> { public string Convert(string sourceMember, ResolutionContext context) => sourceMember; } }
ValueConverter
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/src/ServiceStack.OrmLite/Async/WriteExpressionCommandExtensionsAsync.cs
{ "start": 211, "end": 9918 }
internal static class ____ { internal static Task<int> UpdateOnlyFieldsAsync<T>(this IDbCommand dbCmd, T model, SqlExpression<T> onlyFields, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); dbCmd.UpdateOnlySql(model, onlyFields); commandFilter?.Invoke(dbCmd); return dbCmd.ExecNonQueryAsync(token); } internal static Task<int> UpdateOnlyFieldsAsync<T>(this IDbCommand dbCmd, T obj, Expression<Func<T, object>> onlyFields, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); if (onlyFields == null) throw new ArgumentNullException(nameof(onlyFields)); var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Update(onlyFields); q.Where(where); return dbCmd.UpdateOnlyFieldsAsync(obj, q, commandFilter, token); } internal static Task<int> UpdateOnlyFieldsAsync<T>(this IDbCommand dbCmd, T obj, string[] onlyFields, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); if (onlyFields == null) throw new ArgumentNullException(nameof(onlyFields)); var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Update(onlyFields); q.Where(where); return dbCmd.UpdateOnlyFieldsAsync(obj, q, commandFilter, token); } internal static Task<int> UpdateOnlyAsync<T>(this IDbCommand dbCmd, Expression<Func<T>> updateFields, SqlExpression<T> q, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); var cmd = dbCmd.InitUpdateOnly(updateFields, q); commandFilter?.Invoke(cmd); return cmd.ExecNonQueryAsync(token); } internal static Task<int> UpdateOnlyAsync<T>(this IDbCommand dbCmd, Expression<Func<T>> updateFields, string whereExpression, IEnumerable<IDbDataParameter> sqlParams, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); var cmd = dbCmd.InitUpdateOnly(updateFields, whereExpression, sqlParams); commandFilter?.Invoke(cmd); return cmd.ExecNonQueryAsync(token); } public static Task<int> UpdateAddAsync<T>(this IDbCommand dbCmd, Expression<Func<T>> updateFields, SqlExpression<T> q, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); var cmd = dbCmd.InitUpdateAdd(updateFields, q); commandFilter?.Invoke(cmd); return cmd.ExecNonQueryAsync(token); } public static Task<int> UpdateOnlyAsync<T>(this IDbCommand dbCmd, Dictionary<string, object> updateFields, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter = null, CancellationToken token = default) { OrmLiteUtils.AssertNotAnonType<T>(); if (updateFields == null) throw new ArgumentNullException(nameof(updateFields)); OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateFields.ToFilterType<T>()); var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Where(where); q.PrepareUpdateStatement(dbCmd, updateFields); return dbCmd.UpdateAndVerifyAsync<T>(commandFilter, updateFields.ContainsKey(ModelDefinition.RowVersionName), token); } public static Task<int> UpdateOnlyAsync<T>(this IDbCommand dbCmd, Dictionary<string, object> updateFields, Action<IDbCommand> commandFilter = null, CancellationToken token = default) { return dbCmd.UpdateOnlyReferencesAsync<T>(updateFields, dbFields => { var whereExpr = dbCmd.GetDialectProvider().GetUpdateOnlyWhereExpression<T>(dbFields, out var exprArgs); dbCmd.PrepareUpdateOnly<T>(dbFields, whereExpr, exprArgs); return dbCmd.UpdateAndVerifyAsync<T>(commandFilter, dbFields.ContainsKey(ModelDefinition.RowVersionName), token); }, token); } public static Task<int> UpdateOnlyAsync<T>(this IDbCommand dbCmd, Dictionary<string, object> updateFields, string whereExpression, object[] whereParams, Action<IDbCommand> commandFilter = null, CancellationToken token = default) { return dbCmd.UpdateOnlyReferencesAsync<T>(updateFields, dbFields => { var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Where(whereExpression, whereParams); q.PrepareUpdateStatement(dbCmd, dbFields); return dbCmd.UpdateAndVerifyAsync<T>(commandFilter, dbFields.ContainsKey(ModelDefinition.RowVersionName), token); }, token); } public static async Task<int> UpdateOnlyReferencesAsync<T>(this IDbCommand dbCmd, Dictionary<string, object> updateFields, Func<Dictionary<string, object>, Task<int>> fn, CancellationToken token = default) { OrmLiteUtils.AssertNotAnonType<T>(); if (updateFields == null) throw new ArgumentNullException(nameof(updateFields)); OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateFields.ToFilterType<T>()); var dbFields = updateFields; var modelDef = ModelDefinition<T>.Definition; var hasReferences = modelDef.HasAnyReferences(updateFields.Keys); if (hasReferences) { dbFields = new Dictionary<string, object>(); foreach (var entry in updateFields) { if (!modelDef.IsReference(entry.Key)) dbFields[entry.Key] = entry.Value; } } var ret = await fn(dbFields).ConfigAwait(); if (hasReferences) { var instance = updateFields.FromObjectDictionary<T>(); await dbCmd.SaveAllReferencesAsync(instance, token).ConfigAwait(); } return ret; } internal static Task<int> UpdateNonDefaultsAsync<T>(this IDbCommand dbCmd, T item, Expression<Func<T, bool>> obj, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, item); var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Where(obj); q.PrepareUpdateStatement(dbCmd, item, excludeDefaults: true); return dbCmd.ExecNonQueryAsync(token); } internal static Task<int> UpdateAsync<T>(this IDbCommand dbCmd, T item, Expression<Func<T, bool>> expression, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, item); var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Where(expression); q.PrepareUpdateStatement(dbCmd, item); commandFilter?.Invoke(dbCmd); return dbCmd.ExecNonQueryAsync(token); } internal static Task<int> UpdateAsync<T>(this IDbCommand dbCmd, object updateOnly, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); OrmLiteConfig.UpdateFilter?.Invoke(dbCmd, updateOnly.ToFilterType<T>()); var q = dbCmd.GetDialectProvider().SqlExpression<T>(); var whereSql = q.Where(where).WhereExpression; q.CopyParamsTo(dbCmd); dbCmd.PrepareUpdateAnonSql<T>(dbCmd.GetDialectProvider(), updateOnly, whereSql); commandFilter?.Invoke(dbCmd); return dbCmd.ExecNonQueryAsync(token); } internal static Task InsertOnlyAsync<T>(this IDbCommand dbCmd, T obj, string[] onlyFields, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); OrmLiteConfig.InsertFilter?.Invoke(dbCmd, obj); var dialectProvider = dbCmd.GetDialectProvider(); var sql = dialectProvider.ToInsertRowStatement(dbCmd, obj, onlyFields); dialectProvider.SetParameterValues<T>(dbCmd, obj); return dbCmd.ExecuteSqlAsync(sql, token); } public static Task<int> InsertOnlyAsync<T>(this IDbCommand dbCmd, Expression<Func<T>> insertFields, CancellationToken token) { OrmLiteUtils.AssertNotAnonType<T>(); return dbCmd.InitInsertOnly(insertFields).ExecNonQueryAsync(token); } internal static Task<int> DeleteAsync<T>(this IDbCommand dbCmd, Expression<Func<T, bool>> where, Action<IDbCommand> commandFilter, CancellationToken token) { var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Where(where); return dbCmd.DeleteAsync(q, commandFilter, token); } internal static Task<int> DeleteAsync<T>(this IDbCommand dbCmd, SqlExpression<T> q, Action<IDbCommand> commandFilter, CancellationToken token) { var sql = q.ToDeleteRowStatement(); return dbCmd.ExecuteSqlAsync(sql, q.Params, commandFilter, token); } internal static Task<int> DeleteWhereAsync<T>(this IDbCommand dbCmd, string whereFilter, object[] whereParams, Action<IDbCommand> commandFilter, CancellationToken token) { var q = dbCmd.GetDialectProvider().SqlExpression<T>(); q.Where(whereFilter, whereParams); var sql = q.ToDeleteRowStatement(); return dbCmd.ExecuteSqlAsync(sql, q.Params, commandFilter, token); } }
WriteExpressionCommandExtensionsAsync
csharp
jbogard__MediatR
test/MediatR.Tests/MicrosoftExtensionsDI/Handlers.cs
{ "start": 1219, "end": 1391 }
public class ____ : IRequestHandler<Ding> { public Task Handle(Ding message, CancellationToken cancellationToken) => Task.CompletedTask; }
DingAsyncHandler
csharp
dotnet__orleans
src/Orleans.Core.Abstractions/Core/IGrainBase.cs
{ "start": 1453, "end": 15028 }
public static class ____ { /// <summary> /// Deactivate this grain activation after the current grain method call is completed. /// This call will mark this activation of the current grain to be deactivated and removed at the end of the current method. /// The next call to this grain will result in a different activation to be used, which typical means a new activation will be created automatically by the runtime. /// </summary> public static void DeactivateOnIdle(this IGrainBase grain) => grain.GrainContext.Deactivate(new(DeactivationReasonCode.ApplicationRequested, $"{nameof(DeactivateOnIdle)} was called.")); /// <summary> /// Starts an attempt to migrating this instance to another location. /// Migration captures the current <see cref="RequestContext"/>, making it available to the activation's placement director so that it can consider it when selecting a new location. /// Migration will occur asynchronously, when no requests are executing, and will not occur if the activation's placement director does not select an alternative location. /// </summary> public static void MigrateOnIdle(this IGrainBase grain) => grain.GrainContext.Migrate(RequestContext.CallContextData?.Value.Values); /// <summary> /// Creates a grain timer. /// </summary> /// <param name="callback">The timer callback, which will be invoked whenever the timer becomes due.</param> /// <param name="state">The state passed to the callback.</param> /// <param name="options"> /// The options for creating the timer. /// </param> /// <typeparam name="TState">The type of the <paramref name="state"/> parameter.</typeparam> /// <returns> /// The <see cref="IGrainTimer"/> instance which represents the timer. /// </returns> /// <remarks> /// <para> /// Grain timers do not keep grains active by default. Setting <see cref="GrainTimerCreationOptions.KeepAlive"/> to /// <see langword="true"/> causes each timer tick to extend the grain activation's lifetime. /// If the timer ticks are infrequent, the grain can still be deactivated due to idleness. /// When a grain is deactivated, all active timers are discarded. /// </para> /// <para> /// Until the <see cref="Task"/> returned from the callback is resolved, the next timer tick will not be scheduled. /// That is to say, a timer callback will never be concurrently executed with itself. /// If <see cref="GrainTimerCreationOptions.Interleave"/> is set to <see langword="true"/>, the timer callback will be allowed /// to interleave with with other grain method calls and other timers. /// If <see cref="GrainTimerCreationOptions.Interleave"/> is set to <see langword="false"/>, the timer callback will respect the /// reentrancy setting of the grain, just like a typical grain method call. /// </para> /// <para> /// The timer may be stopped at any time by calling the <see cref="IGrainTimer"/>'s <see cref="IDisposable.Dispose"/> method. /// Disposing a timer prevents any further timer ticks from being scheduled. /// </para> /// <para> /// The timer due time and period can be updated by calling its <see cref="IGrainTimer.Change(TimeSpan, TimeSpan)"/> method. /// Each time the timer is updated, the next timer tick will be scheduled based on the updated due time. /// Subsequent ticks will be scheduled after the updated period elapses. /// Note that this behavior is the same as the <see cref="Timer.Change(TimeSpan, TimeSpan)"/> method. /// </para> /// <para> /// Exceptions thrown from the callback will be logged, but will not prevent the next timer tick from being queued. /// </para> /// </remarks> public static IGrainTimer RegisterGrainTimer<TState>(this IGrainBase grain, Func<TState, CancellationToken, Task> callback, TState state, GrainTimerCreationOptions options) { ArgumentNullException.ThrowIfNull(callback); if (grain is Grain grainClass) { ArgumentNullException.ThrowIfNull(callback); grainClass.EnsureRuntime(); return grainClass.Runtime.TimerRegistry.RegisterGrainTimer(grainClass.GrainContext, callback, state, options); } return grain.GrainContext.ActivationServices.GetRequiredService<ITimerRegistry>().RegisterGrainTimer(grain.GrainContext, callback, state, options); } /// <summary> /// Creates a grain timer. /// </summary> /// <param name="grain">The grain instance.</param> /// <param name="callback">The timer callback, which will be invoked whenever the timer becomes due.</param> /// <param name="options"> /// The options for creating the timer. /// </param> /// <returns> /// The <see cref="IGrainTimer"/> instance which represents the timer. /// </returns> /// <remarks> /// <para> /// Grain timers do not keep grains active by default. Setting <see cref="GrainTimerCreationOptions.KeepAlive"/> to /// <see langword="true"/> causes each timer tick to extend the grain activation's lifetime. /// If the timer ticks are infrequent, the grain can still be deactivated due to idleness. /// When a grain is deactivated, all active timers are discarded. /// </para> /// <para> /// Until the <see cref="Task"/> returned from the callback is resolved, the next timer tick will not be scheduled. /// That is to say, a timer callback will never be concurrently executed with itself. /// If <see cref="GrainTimerCreationOptions.Interleave"/> is set to <see langword="true"/>, the timer callback will be allowed /// to interleave with with other grain method calls and other timers. /// If <see cref="GrainTimerCreationOptions.Interleave"/> is set to <see langword="false"/>, the timer callback will respect the /// reentrancy setting of the grain, just like a typical grain method call. /// </para> /// <para> /// The timer may be stopped at any time by calling the <see cref="IGrainTimer"/>'s <see cref="IDisposable.Dispose"/> method. /// Disposing a timer prevents any further timer ticks from being scheduled. /// </para> /// <para> /// The timer due time and period can be updated by calling its <see cref="IGrainTimer.Change(TimeSpan, TimeSpan)"/> method. /// Each time the timer is updated, the next timer tick will be scheduled based on the updated due time. /// Subsequent ticks will be scheduled after the updated period elapses. /// Note that this behavior is the same as the <see cref="Timer.Change(TimeSpan, TimeSpan)"/> method. /// </para> /// <para> /// Exceptions thrown from the callback will be logged, but will not prevent the next timer tick from being queued. /// </para> /// </remarks> public static IGrainTimer RegisterGrainTimer(this IGrainBase grain, Func<CancellationToken, Task> callback, GrainTimerCreationOptions options) { ArgumentNullException.ThrowIfNull(callback); return RegisterGrainTimer(grain, static (callback, cancellationToken) => callback(cancellationToken), callback, options); } public static IGrainTimer RegisterGrainTimer(this IGrainBase grain, Func<Task> callback, GrainTimerCreationOptions options) { ArgumentNullException.ThrowIfNull(callback); return RegisterGrainTimer(grain, static (callback, cancellationToken) => callback(), callback, options); } /// <inheritdoc cref="RegisterGrainTimer(IGrainBase, Func{Task}, GrainTimerCreationOptions)"/> /// <param name="state">The state passed to the callback.</param> /// <typeparam name="TState">The type of the <paramref name="state"/> parameter.</typeparam> public static IGrainTimer RegisterGrainTimer<TState>(this IGrainBase grain, Func<TState, Task> callback, TState state, GrainTimerCreationOptions options) { ArgumentNullException.ThrowIfNull(callback); return RegisterGrainTimer(grain, static (state, _) => state.Callback(state.State), (Callback: callback, State: state), options); } /// <summary> /// Creates a grain timer. /// </summary> /// <param name="grain">The grain instance.</param> /// <param name="callback">The timer callback, which will be invoked whenever the timer becomes due.</param> /// <param name="dueTime"> /// A <see cref="TimeSpan"/> representing the amount of time to delay before invoking the callback method specified when the <see cref="IGrainTimer"/> was constructed. /// Specify <see cref="Timeout.InfiniteTimeSpan"/> to prevent the timer from starting. /// Specify <see cref="TimeSpan.Zero"/> to start the timer immediately. /// </param> /// <param name="period"> /// The time interval between invocations of the callback method specified when the <see cref="IGrainTimer"/> was constructed. /// Specify <see cref="Timeout.InfiniteTimeSpan "/> to disable periodic signaling. /// </param> /// <returns> /// The <see cref="IGrainTimer"/> instance which represents the timer. /// </returns> /// <remarks> /// <para> /// Grain timers do not keep grains active by default. Setting <see cref="GrainTimerCreationOptions.KeepAlive"/> to /// <see langword="true"/> causes each timer tick to extend the grain activation's lifetime. /// If the timer ticks are infrequent, the grain can still be deactivated due to idleness. /// When a grain is deactivated, all active timers are discarded. /// </para> /// <para> /// Until the <see cref="Task"/> returned from the callback is resolved, the next timer tick will not be scheduled. /// That is to say, a timer callback will never be concurrently executed with itself. /// If <see cref="GrainTimerCreationOptions.Interleave"/> is set to <see langword="true"/>, the timer callback will be allowed /// to interleave with with other grain method calls and other timers. /// If <see cref="GrainTimerCreationOptions.Interleave"/> is set to <see langword="false"/>, the timer callback will respect the /// reentrancy setting of the grain, just like a typical grain method call. /// </para> /// <para> /// The timer may be stopped at any time by calling the <see cref="IGrainTimer"/>'s <see cref="IDisposable.Dispose"/> method. /// Disposing a timer prevents any further timer ticks from being scheduled. /// </para> /// <para> /// The timer due time and period can be updated by calling its <see cref="IGrainTimer.Change(TimeSpan, TimeSpan)"/> method. /// Each time the timer is updated, the next timer tick will be scheduled based on the updated due time. /// Subsequent ticks will be scheduled after the updated period elapses. /// Note that this behavior is the same as the <see cref="Timer.Change(TimeSpan, TimeSpan)"/> method. /// </para> /// <para> /// Exceptions thrown from the callback will be logged, but will not prevent the next timer tick from being queued. /// </para> /// </remarks> public static IGrainTimer RegisterGrainTimer(this IGrainBase grain, Func<Task> callback, TimeSpan dueTime, TimeSpan period) => RegisterGrainTimer(grain, callback, new() { DueTime = dueTime, Period = period }); /// <inheritdoc cref="RegisterGrainTimer(IGrainBase, Func{Task}, TimeSpan, TimeSpan)"/> public static IGrainTimer RegisterGrainTimer(this IGrainBase grain, Func<CancellationToken, Task> callback, TimeSpan dueTime, TimeSpan period) => RegisterGrainTimer(grain, callback, new() { DueTime = dueTime, Period = period }); /// <inheritdoc cref="RegisterGrainTimer(IGrainBase, Func{Task}, TimeSpan, TimeSpan)"/> /// <param name="state">The state passed to the callback.</param> /// <typeparam name="TState">The type of the <paramref name="state"/> parameter.</typeparam> public static IGrainTimer RegisterGrainTimer<TState>(this IGrainBase grain, Func<TState, Task> callback, TState state, TimeSpan dueTime, TimeSpan period) => RegisterGrainTimer(grain, callback, state, new() { DueTime = dueTime, Period = period }); /// <inheritdoc cref="RegisterGrainTimer(IGrainBase, Func{Task}, TimeSpan, TimeSpan)"/> /// <param name="state">The state passed to the callback.</param> /// <typeparam name="TState">The type of the <paramref name="state"/> parameter.</typeparam> public static IGrainTimer RegisterGrainTimer<TState>(this IGrainBase grain, Func<TState, CancellationToken, Task> callback, TState state, TimeSpan dueTime, TimeSpan period) => RegisterGrainTimer(grain, callback, state, new() { DueTime = dueTime, Period = period }); } /// <summary> /// An informational reason code for deactivation. /// </summary> [GenerateSerializer]
GrainBaseExtensions
csharp
microsoft__FASTER
cs/src/core/Index/Interfaces/FasterEqualityComparer.cs
{ "start": 3207, "end": 3842 }
public sealed class ____ : IFasterEqualityComparer<long> { /// <summary> /// Equals /// </summary> /// <param name="k1"></param> /// <param name="k2"></param> /// <returns></returns> public bool Equals(ref long k1, ref long k2) => k1 == k2; /// <summary> /// GetHashCode64 /// </summary> /// <param name="k"></param> /// <returns></returns> public long GetHashCode64(ref long k) => Utility.GetHashCode(k); } /// <summary> /// Deterministic equality comparer for longs /// </summary>
LongFasterEqualityComparer
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Networking.NetworkOperators/MobileBroadbandPcoDataChangeTriggerDetails.cs
{ "start": 310, "end": 1345 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal MobileBroadbandPcoDataChangeTriggerDetails() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Networking.NetworkOperators.MobileBroadbandPco UpdatedData { get { throw new global::System.NotImplementedException("The member MobileBroadbandPco MobileBroadbandPcoDataChangeTriggerDetails.UpdatedData is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=MobileBroadbandPco%20MobileBroadbandPcoDataChangeTriggerDetails.UpdatedData"); } } #endif // Forced skipping of method Windows.Networking.NetworkOperators.MobileBroadbandPcoDataChangeTriggerDetails.UpdatedData.get } }
MobileBroadbandPcoDataChangeTriggerDetails
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.Extensions.Tests/Protoc/Services.cs
{ "start": 1663383, "end": 1679267 }
partial class ____ : pb::IMessage<QueryOrRockstarsFields> #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE , pb::IBufferMessage #endif { private static readonly pb::MessageParser<QueryOrRockstarsFields> _parser = new pb::MessageParser<QueryOrRockstarsFields>(() => new QueryOrRockstarsFields()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pb::MessageParser<QueryOrRockstarsFields> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public static pbr::MessageDescriptor Descriptor { get { return global::ServiceStack.Extensions.Tests.Protoc.ServicesReflection.Descriptor.MessageTypes[132]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public QueryOrRockstarsFields() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public QueryOrRockstarsFields(QueryOrRockstarsFields other) : this() { skip_ = other.skip_; take_ = other.take_; orderBy_ = other.orderBy_; orderByDesc_ = other.orderByDesc_; include_ = other.include_; fields_ = other.fields_; meta_ = other.meta_.Clone(); firstName_ = other.firstName_; lastName_ = other.lastName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public QueryOrRockstarsFields Clone() { return new QueryOrRockstarsFields(this); } /// <summary>Field number for the "Skip" field.</summary> public const int SkipFieldNumber = 1; private int skip_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int Skip { get { return skip_; } set { skip_ = value; } } /// <summary>Field number for the "Take" field.</summary> public const int TakeFieldNumber = 2; private int take_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int Take { get { return take_; } set { take_ = value; } } /// <summary>Field number for the "OrderBy" field.</summary> public const int OrderByFieldNumber = 3; private string orderBy_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OrderBy { get { return orderBy_; } set { orderBy_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "OrderByDesc" field.</summary> public const int OrderByDescFieldNumber = 4; private string orderByDesc_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string OrderByDesc { get { return orderByDesc_; } set { orderByDesc_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Include" field.</summary> public const int IncludeFieldNumber = 5; private string include_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Include { get { return include_; } set { include_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Fields" field.</summary> public const int FieldsFieldNumber = 6; private string fields_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string Fields { get { return fields_; } set { fields_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "Meta" field.</summary> public const int MetaFieldNumber = 7; private static readonly pbc::MapField<string, string>.Codec _map_meta_codec = new pbc::MapField<string, string>.Codec(pb::FieldCodec.ForString(10, ""), pb::FieldCodec.ForString(18, ""), 58); private readonly pbc::MapField<string, string> meta_ = new pbc::MapField<string, string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public pbc::MapField<string, string> Meta { get { return meta_; } } /// <summary>Field number for the "FirstName" field.</summary> public const int FirstNameFieldNumber = 201; private string firstName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string FirstName { get { return firstName_; } set { firstName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "LastName" field.</summary> public const int LastNameFieldNumber = 202; private string lastName_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public string LastName { get { return lastName_; } set { lastName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override bool Equals(object other) { return Equals(other as QueryOrRockstarsFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public bool Equals(QueryOrRockstarsFields other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (Skip != other.Skip) return false; if (Take != other.Take) return false; if (OrderBy != other.OrderBy) return false; if (OrderByDesc != other.OrderByDesc) return false; if (Include != other.Include) return false; if (Fields != other.Fields) return false; if (!Meta.Equals(other.Meta)) return false; if (FirstName != other.FirstName) return false; if (LastName != other.LastName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override int GetHashCode() { int hash = 1; if (Skip != 0) hash ^= Skip.GetHashCode(); if (Take != 0) hash ^= Take.GetHashCode(); if (OrderBy.Length != 0) hash ^= OrderBy.GetHashCode(); if (OrderByDesc.Length != 0) hash ^= OrderByDesc.GetHashCode(); if (Include.Length != 0) hash ^= Include.GetHashCode(); if (Fields.Length != 0) hash ^= Fields.GetHashCode(); hash ^= Meta.GetHashCode(); if (FirstName.Length != 0) hash ^= FirstName.GetHashCode(); if (LastName.Length != 0) hash ^= LastName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void WriteTo(pb::CodedOutputStream output) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE output.WriteRawMessage(this); #else if (Skip != 0) { output.WriteRawTag(8); output.WriteInt32(Skip); } if (Take != 0) { output.WriteRawTag(16); output.WriteInt32(Take); } if (OrderBy.Length != 0) { output.WriteRawTag(26); output.WriteString(OrderBy); } if (OrderByDesc.Length != 0) { output.WriteRawTag(34); output.WriteString(OrderByDesc); } if (Include.Length != 0) { output.WriteRawTag(42); output.WriteString(Include); } if (Fields.Length != 0) { output.WriteRawTag(50); output.WriteString(Fields); } meta_.WriteTo(output, _map_meta_codec); if (FirstName.Length != 0) { output.WriteRawTag(202, 12); output.WriteString(FirstName); } if (LastName.Length != 0) { output.WriteRawTag(210, 12); output.WriteString(LastName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) { if (Skip != 0) { output.WriteRawTag(8); output.WriteInt32(Skip); } if (Take != 0) { output.WriteRawTag(16); output.WriteInt32(Take); } if (OrderBy.Length != 0) { output.WriteRawTag(26); output.WriteString(OrderBy); } if (OrderByDesc.Length != 0) { output.WriteRawTag(34); output.WriteString(OrderByDesc); } if (Include.Length != 0) { output.WriteRawTag(42); output.WriteString(Include); } if (Fields.Length != 0) { output.WriteRawTag(50); output.WriteString(Fields); } meta_.WriteTo(ref output, _map_meta_codec); if (FirstName.Length != 0) { output.WriteRawTag(202, 12); output.WriteString(FirstName); } if (LastName.Length != 0) { output.WriteRawTag(210, 12); output.WriteString(LastName); } if (_unknownFields != null) { _unknownFields.WriteTo(ref output); } } #endif [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public int CalculateSize() { int size = 0; if (Skip != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Skip); } if (Take != 0) { size += 1 + pb::CodedOutputStream.ComputeInt32Size(Take); } if (OrderBy.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderBy); } if (OrderByDesc.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(OrderByDesc); } if (Include.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Include); } if (Fields.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(Fields); } size += meta_.CalculateSize(_map_meta_codec); if (FirstName.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(FirstName); } if (LastName.Length != 0) { size += 2 + pb::CodedOutputStream.ComputeStringSize(LastName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(QueryOrRockstarsFields other) { if (other == null) { return; } if (other.Skip != 0) { Skip = other.Skip; } if (other.Take != 0) { Take = other.Take; } if (other.OrderBy.Length != 0) { OrderBy = other.OrderBy; } if (other.OrderByDesc.Length != 0) { OrderByDesc = other.OrderByDesc; } if (other.Include.Length != 0) { Include = other.Include; } if (other.Fields.Length != 0) { Fields = other.Fields; } meta_.Add(other.meta_); if (other.FirstName.Length != 0) { FirstName = other.FirstName; } if (other.LastName.Length != 0) { LastName = other.LastName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] public void MergeFrom(pb::CodedInputStream input) { #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE input.ReadRawMessage(this); #else uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 8: { Skip = input.ReadInt32(); break; } case 16: { Take = input.ReadInt32(); break; } case 26: { OrderBy = input.ReadString(); break; } case 34: { OrderByDesc = input.ReadString(); break; } case 42: { Include = input.ReadString(); break; } case 50: { Fields = input.ReadString(); break; } case 58: { meta_.AddEntriesFrom(input, _map_meta_codec); break; } case 1610: { FirstName = input.ReadString(); break; } case 1618: { LastName = input.ReadString(); break; } } } #endif } #if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE [global::System.Diagnostics.DebuggerNonUserCodeAttribute] [global::System.CodeDom.Compiler.GeneratedCode("protoc", null)] void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input); break; case 8: { Skip = input.ReadInt32(); break; } case 16: { Take = input.ReadInt32(); break; } case 26: { OrderBy = input.ReadString(); break; } case 34: { OrderByDesc = input.ReadString(); break; } case 42: { Include = input.ReadString(); break; } case 50: { Fields = input.ReadString(); break; } case 58: { meta_.AddEntriesFrom(ref input, _map_meta_codec); break; } case 1610: { FirstName = input.ReadString(); break; } case 1618: { LastName = input.ReadString(); break; } } } } #endif } public sealed
QueryOrRockstarsFields
csharp
bitwarden__server
src/Api/AdminConsole/Models/Response/Organizations/OrganizationKeysResponseModel.cs
{ "start": 223, "end": 646 }
public class ____ : ResponseModel { public OrganizationKeysResponseModel(Organization org) : base("organizationKeys") { if (org == null) { throw new ArgumentNullException(nameof(org)); } PublicKey = org.PublicKey; PrivateKey = org.PrivateKey; } public string PublicKey { get; set; } public string PrivateKey { get; set; } }
OrganizationKeysResponseModel
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Abstractions/test/ModelBinding/ModelMetadataTest.cs
{ "start": 501, "end": 1354 }
struct ____ { } [Theory] [InlineData(typeof(string))] [InlineData(typeof(Nullable<int>))] [InlineData(typeof(int))] public void IsComplexType_ReturnsFalseForSimpleTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.False(modelMetadata.IsComplexType); } [Theory] [InlineData(typeof(object))] [InlineData(typeof(IDisposable))] [InlineData(typeof(IsComplexTypeModel))] [InlineData(typeof(Nullable<IsComplexTypeModel>))] public void IsComplexType_ReturnsTrueForComplexTypes(Type type) { // Arrange & Act var modelMetadata = new TestModelMetadata(type); // Assert Assert.True(modelMetadata.IsComplexType); } // IsCollectionType / IsEnumerableType
IsComplexTypeModel
csharp
microsoft__semantic-kernel
dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelHelperUtilsTests.cs
{ "start": 281, "end": 2941 }
public class ____ { [Fact] public void ItRegistersHelperWhenNameIsUnique() { // Arrange var handlebarsInstance = HandlebarsDotNet.Handlebars.Create(); string helperName = "uniqueHelper"; static object helper(Context context, Arguments arguments) => "Unique Helper Output"; // Act KernelHelpersUtils.RegisterHelperSafe(handlebarsInstance, helperName, (HandlebarsReturnHelper)helper); // Assert Assert.True(handlebarsInstance.Configuration.Helpers.ContainsKey(helperName)); } [Fact] public void ItThrowsInvalidOperationExceptionWhenNameIsAlreadyRegistered() { // Arrange var handlebarsInstance = HandlebarsDotNet.Handlebars.Create(); string helperName = "alreadyRegisteredHelper"; object helper1(Context context, Arguments arguments) => "Helper 1 Output"; object helper2(Context context, Arguments arguments) => "Helper 2 Output"; handlebarsInstance.RegisterHelper(helperName, (HandlebarsReturnHelper)helper1); // Act & Assert Assert.Throws<InvalidOperationException>(() => KernelHelpersUtils.RegisterHelperSafe(handlebarsInstance, helperName, (HandlebarsReturnHelper)helper2)); } [Theory] [InlineData(null, false)] [InlineData(typeof(string), false)] [InlineData(typeof(nuint), true)] [InlineData(typeof(nint), true)] [InlineData(typeof(sbyte), true)] [InlineData(typeof(short), true)] [InlineData(typeof(int), true)] [InlineData(typeof(long), true)] [InlineData(typeof(byte), true)] [InlineData(typeof(ushort), true)] [InlineData(typeof(uint), true)] [InlineData(typeof(ulong), true)] [InlineData(typeof(double), true)] [InlineData(typeof(float), true)] [InlineData(typeof(decimal), true)] public void IsNumericTypeWorksCorrectly(Type? type, bool expectedResult) { Assert.Equal(expectedResult, KernelHelpersUtils.IsNumericType(type)); } [Theory] [MemberData(nameof(NumberInputs))] public void TryParseAnyNumberWorksCorrectly(string number, bool expectedResult) { Assert.Equal(expectedResult, KernelHelpersUtils.TryParseAnyNumber(number)); } public static TheoryData<string, bool> NumberInputs => new() { { 1234567890123456789L.ToString(CultureInfo.InvariantCulture), true }, { 9876543210987654321UL.ToString(CultureInfo.InvariantCulture), true }, { 123.456.ToString(CultureInfo.InvariantCulture), true }, { 123456789.0123456789m.ToString(CultureInfo.InvariantCulture), true }, { "test", false }, }; }
KernelHelperUtilsTests
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Joins/Pattern.Generated.cs
{ "start": 2053, "end": 4668 }
public class ____<TSource1, TSource2> : Pattern { internal Pattern(IObservable<TSource1> first, IObservable<TSource2> second) { First = first; Second = second; } internal IObservable<TSource1> First { get; } internal IObservable<TSource2> Second { get; } /// <summary> /// Creates a pattern that matches when all three observable sequences have an available element. /// </summary> /// <typeparam name="TSource3">The type of the elements in the third observable sequence.</typeparam> /// <param name="other">Observable sequence to match with the two previous sequences.</param> /// <returns>Pattern object that matches when all observable sequences have an available element.</returns> /// <exception cref="ArgumentNullException"><paramref name="other"/> is null.</exception> public Pattern<TSource1, TSource2, TSource3> And<TSource3>(IObservable<TSource3> other) { if (other == null) { throw new ArgumentNullException(nameof(other)); } return new Pattern<TSource1, TSource2, TSource3>(First, Second, other); } /// <summary> /// Matches when all observable sequences have an available element and projects the elements by invoking the selector function. /// </summary> /// <typeparam name="TResult">The type of the elements in the result sequence, returned by the selector function.</typeparam> /// <param name="selector">Selector that will be invoked for elements in the source sequences.</param> /// <returns>Plan that produces the projected results, to be fed (with other plans) to the When operator.</returns> /// <exception cref="ArgumentNullException"><paramref name="selector"/> is null.</exception> public Plan<TResult> Then<TResult>(Func<TSource1, TSource2, TResult> selector) { if (selector == null) { throw new ArgumentNullException(nameof(selector)); } return new Plan<TSource1, TSource2, TResult>(this, selector); } } /// <summary> /// Represents a join pattern over three observable sequences. /// </summary> /// <typeparam name="TSource1">The type of the elements in the first source sequence.</typeparam> /// <typeparam name="TSource2">The type of the elements in the second source sequence.</typeparam> /// <typeparam name="TSource3">The type of the elements in the third source sequence.</typeparam>
Pattern
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web/Areas/Admin/Controllers/AuthenticationController.cs
{ "start": 536, "end": 7349 }
public partial class ____ : BaseAdminController { #region Fields protected readonly ExternalAuthenticationSettings _externalAuthenticationSettings; protected readonly IAuthenticationPluginManager _authenticationPluginManager; protected readonly IEventPublisher _eventPublisher; protected readonly IExternalAuthenticationMethodModelFactory _externalAuthenticationMethodModelFactory; protected readonly IMultiFactorAuthenticationMethodModelFactory _multiFactorAuthenticationMethodModelFactory; protected readonly IMultiFactorAuthenticationPluginManager _multiFactorAuthenticationPluginManager; protected readonly IPermissionService _permissionService; protected readonly ISettingService _settingService; protected readonly MultiFactorAuthenticationSettings _multiFactorAuthenticationSettings; #endregion #region Ctor public AuthenticationController(ExternalAuthenticationSettings externalAuthenticationSettings, IAuthenticationPluginManager authenticationPluginManager, IEventPublisher eventPublisher, IExternalAuthenticationMethodModelFactory externalAuthenticationMethodModelFactory, IMultiFactorAuthenticationMethodModelFactory multiFactorAuthenticationMethodModelFactory, IMultiFactorAuthenticationPluginManager multiFactorAuthenticationPluginManager, IPermissionService permissionService, ISettingService settingService, MultiFactorAuthenticationSettings multiFactorAuthenticationSettings) { _externalAuthenticationSettings = externalAuthenticationSettings; _authenticationPluginManager = authenticationPluginManager; _eventPublisher = eventPublisher; _externalAuthenticationMethodModelFactory = externalAuthenticationMethodModelFactory; _multiFactorAuthenticationMethodModelFactory = multiFactorAuthenticationMethodModelFactory; _multiFactorAuthenticationPluginManager = multiFactorAuthenticationPluginManager; _permissionService = permissionService; _settingService = settingService; _multiFactorAuthenticationSettings = multiFactorAuthenticationSettings; } #endregion #region External Authentication [CheckPermission(StandardPermission.Configuration.MANAGE_EXTERNAL_AUTHENTICATION_METHODS)] public virtual IActionResult ExternalMethods() { //prepare model var model = _externalAuthenticationMethodModelFactory .PrepareExternalAuthenticationMethodSearchModel(new ExternalAuthenticationMethodSearchModel()); return View(model); } [HttpPost] [CheckPermission(StandardPermission.Configuration.MANAGE_EXTERNAL_AUTHENTICATION_METHODS)] public virtual async Task<IActionResult> ExternalMethods(ExternalAuthenticationMethodSearchModel searchModel) { //prepare model var model = await _externalAuthenticationMethodModelFactory.PrepareExternalAuthenticationMethodListModelAsync(searchModel); return Json(model); } [HttpPost] [CheckPermission(StandardPermission.Configuration.MANAGE_EXTERNAL_AUTHENTICATION_METHODS)] public virtual async Task<IActionResult> ExternalMethodUpdate(ExternalAuthenticationMethodModel model) { var method = await _authenticationPluginManager.LoadPluginBySystemNameAsync(model.SystemName); if (_authenticationPluginManager.IsPluginActive(method)) { if (!model.IsActive) { //mark as disabled _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Remove(method.PluginDescriptor.SystemName); await _settingService.SaveSettingAsync(_externalAuthenticationSettings); } } else { if (model.IsActive) { //mark as active _externalAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Add(method.PluginDescriptor.SystemName); await _settingService.SaveSettingAsync(_externalAuthenticationSettings); } } var pluginDescriptor = method.PluginDescriptor; pluginDescriptor.DisplayOrder = model.DisplayOrder; //update the description file pluginDescriptor.Save(); //raise event await _eventPublisher.PublishAsync(new PluginUpdatedEvent(pluginDescriptor)); return new NullJsonResult(); } #endregion #region Multi-factor Authentication [CheckPermission(StandardPermission.Configuration.MANAGE_MULTIFACTOR_AUTHENTICATION_METHODS)] public virtual IActionResult MultiFactorMethods() { //prepare model var model = _multiFactorAuthenticationMethodModelFactory .PrepareMultiFactorAuthenticationMethodSearchModel(new MultiFactorAuthenticationMethodSearchModel()); return View(model); } [HttpPost] [CheckPermission(StandardPermission.Configuration.MANAGE_MULTIFACTOR_AUTHENTICATION_METHODS)] public virtual async Task<IActionResult> MultiFactorMethods(MultiFactorAuthenticationMethodSearchModel searchModel) { //prepare model var model = await _multiFactorAuthenticationMethodModelFactory.PrepareMultiFactorAuthenticationMethodListModelAsync(searchModel); return Json(model); } [HttpPost] [CheckPermission(StandardPermission.Configuration.MANAGE_MULTIFACTOR_AUTHENTICATION_METHODS)] public virtual async Task<IActionResult> MultiFactorMethodUpdate(MultiFactorAuthenticationMethodModel model) { var method = await _multiFactorAuthenticationPluginManager.LoadPluginBySystemNameAsync(model.SystemName); if (_multiFactorAuthenticationPluginManager.IsPluginActive(method)) { if (!model.IsActive) { //mark as disabled _multiFactorAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Remove(method.PluginDescriptor.SystemName); await _settingService.SaveSettingAsync(_multiFactorAuthenticationSettings); } } else { if (model.IsActive) { //mark as active _multiFactorAuthenticationSettings.ActiveAuthenticationMethodSystemNames.Add(method.PluginDescriptor.SystemName); await _settingService.SaveSettingAsync(_multiFactorAuthenticationSettings); } } var pluginDescriptor = method.PluginDescriptor; pluginDescriptor.DisplayOrder = model.DisplayOrder; //update the description file pluginDescriptor.Save(); //raise event await _eventPublisher.PublishAsync(new PluginUpdatedEvent(pluginDescriptor)); return new NullJsonResult(); } #endregion }
AuthenticationController
csharp
dotnet__efcore
test/EFCore.Sqlite.FunctionalTests/BulkUpdates/TPHFiltersInheritanceBulkUpdatesSqliteTest.cs
{ "start": 212, "end": 6764 }
public class ____( TPHFiltersInheritanceBulkUpdatesSqliteFixture fixture, ITestOutputHelper testOutputHelper) : FiltersInheritanceBulkUpdatesRelationalTestBase< TPHFiltersInheritanceBulkUpdatesSqliteFixture>(fixture, testOutputHelper) { [ConditionalFact] public virtual void Check_all_tests_overridden() => TestHelpers.AssertAllMethodsOverridden(GetType()); public override async Task Delete_where_hierarchy(bool async) { await base.Delete_where_hierarchy(async); AssertSql( """ DELETE FROM "Animals" AS "a" WHERE "a"."CountryId" = 1 AND "a"."Name" = 'Great spotted kiwi' """); } public override async Task Delete_where_hierarchy_subquery(bool async) { await base.Delete_where_hierarchy_subquery(async); AssertSql( """ @p0='3' @p='0' DELETE FROM "Animals" AS "a" WHERE "a"."Id" IN ( SELECT "a0"."Id" FROM "Animals" AS "a0" WHERE "a0"."CountryId" = 1 AND "a0"."Name" = 'Great spotted kiwi' ORDER BY "a0"."Name" LIMIT @p0 OFFSET @p ) """); } public override async Task Delete_where_hierarchy_derived(bool async) { await base.Delete_where_hierarchy_derived(async); AssertSql( """ DELETE FROM "Animals" AS "a" WHERE "a"."Discriminator" = 'Kiwi' AND "a"."CountryId" = 1 AND "a"."Name" = 'Great spotted kiwi' """); } public override async Task Delete_where_using_hierarchy(bool async) { await base.Delete_where_using_hierarchy(async); AssertSql( """ DELETE FROM "Countries" AS "c" WHERE ( SELECT COUNT(*) FROM "Animals" AS "a" WHERE "a"."CountryId" = 1 AND "c"."Id" = "a"."CountryId" AND "a"."CountryId" > 0) > 0 """); } public override async Task Delete_where_using_hierarchy_derived(bool async) { await base.Delete_where_using_hierarchy_derived(async); AssertSql( """ DELETE FROM "Countries" AS "c" WHERE ( SELECT COUNT(*) FROM "Animals" AS "a" WHERE "a"."CountryId" = 1 AND "c"."Id" = "a"."CountryId" AND "a"."Discriminator" = 'Kiwi' AND "a"."CountryId" > 0) > 0 """); } public override async Task Delete_where_keyless_entity_mapped_to_sql_query(bool async) { await base.Delete_where_keyless_entity_mapped_to_sql_query(async); AssertSql(); } public override async Task Delete_GroupBy_Where_Select_First(bool async) { await base.Delete_GroupBy_Where_Select_First(async); AssertSql(); } public override async Task Delete_GroupBy_Where_Select_First_2(bool async) { await base.Delete_GroupBy_Where_Select_First_2(async); AssertSql(); } public override async Task Delete_GroupBy_Where_Select_First_3(bool async) { await base.Delete_GroupBy_Where_Select_First_3(async); AssertSql( """ DELETE FROM "Animals" AS "a" WHERE "a"."CountryId" = 1 AND "a"."Id" IN ( SELECT ( SELECT "a1"."Id" FROM "Animals" AS "a1" WHERE "a1"."CountryId" = 1 AND "a0"."CountryId" = "a1"."CountryId" LIMIT 1) FROM "Animals" AS "a0" WHERE "a0"."CountryId" = 1 GROUP BY "a0"."CountryId" HAVING COUNT(*) < 3 ) """); } public override async Task Update_base_type(bool async) { await base.Update_base_type(async); AssertExecuteUpdateSql( """ @p='Animal' (Size = 6) UPDATE "Animals" AS "a" SET "Name" = @p WHERE "a"."CountryId" = 1 AND "a"."Name" = 'Great spotted kiwi' """); } public override async Task Update_base_type_with_OfType(bool async) { await base.Update_base_type_with_OfType(async); AssertExecuteUpdateSql( """ @p='NewBird' (Size = 7) UPDATE "Animals" AS "a" SET "Name" = @p WHERE "a"."CountryId" = 1 AND "a"."Discriminator" = 'Kiwi' """); } public override async Task Update_where_hierarchy_subquery(bool async) { await base.Update_where_hierarchy_subquery(async); AssertExecuteUpdateSql(); } public override async Task Update_base_property_on_derived_type(bool async) { await base.Update_base_property_on_derived_type(async); AssertExecuteUpdateSql( """ @p='SomeOtherKiwi' (Size = 13) UPDATE "Animals" AS "a" SET "Name" = @p WHERE "a"."Discriminator" = 'Kiwi' AND "a"."CountryId" = 1 """); } public override async Task Update_derived_property_on_derived_type(bool async) { await base.Update_derived_property_on_derived_type(async); AssertExecuteUpdateSql( """ @p='0' UPDATE "Animals" AS "a" SET "FoundOn" = @p WHERE "a"."Discriminator" = 'Kiwi' AND "a"."CountryId" = 1 """); } public override async Task Update_where_using_hierarchy(bool async) { await base.Update_where_using_hierarchy(async); AssertExecuteUpdateSql( """ @p='Monovia' (Size = 7) UPDATE "Countries" AS "c" SET "Name" = @p WHERE ( SELECT COUNT(*) FROM "Animals" AS "a" WHERE "a"."CountryId" = 1 AND "c"."Id" = "a"."CountryId" AND "a"."CountryId" > 0) > 0 """); } public override async Task Update_base_and_derived_types(bool async) { await base.Update_base_and_derived_types(async); AssertExecuteUpdateSql( """ @p='Kiwi' (Size = 4) @p0='0' UPDATE "Animals" AS "a" SET "Name" = @p, "FoundOn" = @p0 WHERE "a"."Discriminator" = 'Kiwi' AND "a"."CountryId" = 1 """); } public override async Task Update_where_using_hierarchy_derived(bool async) { await base.Update_where_using_hierarchy_derived(async); AssertExecuteUpdateSql( """ @p='Monovia' (Size = 7) UPDATE "Countries" AS "c" SET "Name" = @p WHERE ( SELECT COUNT(*) FROM "Animals" AS "a" WHERE "a"."CountryId" = 1 AND "c"."Id" = "a"."CountryId" AND "a"."Discriminator" = 'Kiwi' AND "a"."CountryId" > 0) > 0 """); } public override async Task Update_where_keyless_entity_mapped_to_sql_query(bool async) { await base.Update_where_keyless_entity_mapped_to_sql_query(async); AssertExecuteUpdateSql(); } protected override void ClearLog() => Fixture.TestSqlLoggerFactory.Clear(); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); private void AssertExecuteUpdateSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected, forUpdate: true); }
TPHFiltersInheritanceBulkUpdatesSqliteTest
csharp
SixLabors__ImageSharp
tests/ImageSharp.Tests/ColorProfiles/CieLabAndRgbConversionTests.cs
{ "start": 265, "end": 2130 }
public class ____ { private static readonly ApproximateColorProfileComparer Comparer = new(.0002F); private static readonly ColorProfileConverter Converter = new(); [Theory] [InlineData(0, 0, 0, 0, 0, 0)] [InlineData(0.9999999, 0, 0.384345, 55.063, 82.54871, 23.16505)] public void Convert_Rgb_to_CieLab(float r, float g, float b2, float l, float a, float b) { // Arrange Rgb input = new(r, g, b2); CieLab expected = new(l, a, b); ColorProfileConverter converter = new(); Span<Rgb> inputSpan = new Rgb[5]; inputSpan.Fill(input); Span<CieLab> actualSpan = new CieLab[5]; // Act CieLab actual = converter.Convert<Rgb, CieLab>(input); converter.Convert<Rgb, CieLab>(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, Comparer); for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], Comparer); } } [Theory] [InlineData(0, 0, 0, 0, 0, 0)] [InlineData(55.063, 82.54871, 23.16505, 0.9999999, 0, 0.384345)] public void Convert_CieLab_to_Rgb(float l, float a, float b, float r, float g, float b2) { // Arrange CieLab input = new(l, a, b); Rgb expected = new(r, g, b2); ColorProfileConverter converter = new(); Span<CieLab> inputSpan = new CieLab[5]; inputSpan.Fill(input); Span<Rgb> actualSpan = new Rgb[5]; // Act Rgb actual = converter.Convert<CieLab, Rgb>(input); converter.Convert<CieLab, Rgb>(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, Comparer); for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], Comparer); } } }
CieLabAndRgbConversionTests
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Internal/UnityEqualityComparer.cs
{ "start": 8418, "end": 8850 }
sealed class ____ : IEqualityComparer<Vector2Int> { public bool Equals(Vector2Int self, Vector2Int vector) { return self.x.Equals(vector.x) && self.y.Equals(vector.y); } public int GetHashCode(Vector2Int obj) { return obj.x.GetHashCode() ^ obj.y.GetHashCode() << 2; } }
Vector2IntEqualityComparer
csharp
dotnet__maui
src/Core/tests/DeviceTests/Handlers/Editor/EditorHandlerTests.iOS.cs
{ "start": 298, "end": 10368 }
public partial class ____ { #if IOS [Fact(DisplayName = "Placeholder Size is the same as control")] public async Task PlaceholderFontHasTheSameSize() { var sizeFont = 22; var editor = new EditorStub() { Text = "Text", Font = Font.SystemFontOfSize(sizeFont) }; var nativePlaceholderSize = await GetValueAsync(editor, handler => { return GetNativePlaceholder(handler).Font.PointSize; }); Assert.True(nativePlaceholderSize == sizeFont); } #endif [Fact(DisplayName = "Placeholder Toggles Correctly When Text Changes")] public async Task PlaceholderTogglesCorrectlyWhenTextChanges() { var editor = new EditorStub(); bool testPassed = false; await InvokeOnMainThreadAsync(() => { var handler = CreateHandler(editor); Assert.False(GetNativePlaceholder(handler).Hidden); editor.Text = "test"; handler.UpdateValue(nameof(EditorStub.Text)); Assert.True(GetNativePlaceholder(handler).Hidden); editor.Text = ""; Assert.False(GetNativePlaceholder(handler).Hidden); testPassed = true; }); Assert.True(testPassed); } [Fact(DisplayName = "Placeholder Hidden When Control Has Text")] public async Task PlaceholderHiddenWhenControlHasText() { var editor = new EditorStub() { Text = "Text" }; var isHidden = await GetValueAsync(editor, handler => { return GetNativePlaceholder(handler).Hidden; }); Assert.True(isHidden); } [Fact(DisplayName = "Placeholder Visible When Control No Text")] public async Task PlaceholderVisibleWhenControlHasNoText() { var editor = new EditorStub(); var isHidden = await GetValueAsync(editor, handler => { return GetNativePlaceholder(handler).Hidden; }); Assert.False(isHidden); } [Fact(DisplayName = "Placeholder Hidden When Control Has Attributed Text")] public async Task PlaceholderHiddenWhenControlHasAttributedText() { var editor = new EditorStub() { Text = "Text", CharacterSpacing = 43 }; var isHidden = await GetValueAsync(editor, handler => { return GetNativePlaceholder(handler).Hidden; }); Assert.True(isHidden); } [Fact(DisplayName = "Placeholder CharacterSpacing Initializes Correctly")] public async Task PlaceholderCharacterSpacingInitializesCorrectly() { string originalText = "Test"; var xplatCharacterSpacing = 4; var editor = new EditorStub() { CharacterSpacing = xplatCharacterSpacing, Placeholder = originalText }; var values = await GetValueAsync(editor, (handler) => { return new { ViewValue = editor.CharacterSpacing, PlatformViewValue = GetNativePlaceholderCharacterSpacing(handler) }; }); Assert.Equal(xplatCharacterSpacing, values.ViewValue); Assert.Equal(xplatCharacterSpacing, values.PlatformViewValue); } [Fact(DisplayName = "CharacterSpacing Initializes Correctly")] public async Task CharacterSpacingInitializesCorrectly() { string originalText = "Test"; var xplatCharacterSpacing = 4; var editor = new EditorStub() { CharacterSpacing = xplatCharacterSpacing, Text = originalText }; var values = await GetValueAsync(editor, (handler) => { return new { ViewValue = editor.CharacterSpacing, PlatformViewValue = GetNativeCharacterSpacing(handler) }; }); Assert.Equal(xplatCharacterSpacing, values.ViewValue); Assert.Equal(xplatCharacterSpacing, values.PlatformViewValue); } [Fact(DisplayName = "Horizontal TextAlignment Updates Correctly")] public async Task HorizontalTextAlignmentInitializesCorrectly() { var xplatHorizontalTextAlignment = TextAlignment.End; var editorStub = new EditorStub() { Text = "Test", HorizontalTextAlignment = xplatHorizontalTextAlignment }; UITextAlignment expectedValue = UITextAlignment.Right; var values = await GetValueAsync(editorStub, (handler) => { return new { ViewValue = editorStub.HorizontalTextAlignment, PlatformViewValue = GetNativeHorizontalTextAlignment(handler) }; }); Assert.Equal(xplatHorizontalTextAlignment, values.ViewValue); values.PlatformViewValue.AssertHasFlag(expectedValue); } [Theory(DisplayName = "IsEnabled Initializes Correctly")] [InlineData(false)] [InlineData(true)] public async Task IsEnabledInitializesCorrectly(bool isEnabled) { var xplatIsEnabled = isEnabled; var editor = new EditorStub() { IsEnabled = xplatIsEnabled, Text = "Test" }; var values = await GetValueAsync(editor, (handler) => { return new { ViewValue = editor.IsEnabled, PlatformViewValue = GetNativeIsEnabled(handler) }; }); Assert.Equal(xplatIsEnabled, values.ViewValue); Assert.Equal(xplatIsEnabled, values.PlatformViewValue); } static MauiTextView GetNativeEditor(EditorHandler editorHandler) => editorHandler.PlatformView; string GetNativeText(EditorHandler editorHandler) => GetNativeEditor(editorHandler).Text; internal static void SetNativeText(EditorHandler editorHandler, string text) => GetNativeEditor(editorHandler).Text = text; internal static int GetCursorStartPosition(EditorHandler editorHandler) { var control = GetNativeEditor(editorHandler); return (int)control.GetOffsetFromPosition(control.BeginningOfDocument, control.SelectedTextRange.Start); } internal static void UpdateCursorStartPosition(EditorHandler editorHandler, int position) { var control = GetNativeEditor(editorHandler); var endPosition = control.GetPosition(control.BeginningOfDocument, position); control.SelectedTextRange = control.GetTextRange(endPosition, endPosition); } UILabel GetNativePlaceholder(EditorHandler editorHandler) { var editor = GetNativeEditor(editorHandler); foreach (var view in editor.Subviews) { if (view is UILabel label) return label; } return null; } string GetNativePlaceholderText(EditorHandler editorHandler) => GetNativeEditor(editorHandler).PlaceholderText; Color GetNativePlaceholderColor(EditorHandler editorHandler) => GetNativeEditor(editorHandler).PlaceholderTextColor.ToColor(); double GetNativeCharacterSpacing(EditorHandler editorHandler) { var editor = GetNativeEditor(editorHandler); return editor.AttributedText.GetCharacterSpacing(); } double GetNativePlaceholderCharacterSpacing(EditorHandler editorHandler) { return GetNativePlaceholder(editorHandler).AttributedText.GetCharacterSpacing(); } double GetNativeUnscaledFontSize(EditorHandler editorHandler) => GetNativeEditor(editorHandler).Font.PointSize; bool GetNativeIsReadOnly(EditorHandler editorHandler) => !GetNativeEditor(editorHandler).Editable; bool GetNativeIsTextPredictionEnabled(EditorHandler editorHandler) => GetNativeEditor(editorHandler).AutocorrectionType == UITextAutocorrectionType.Yes; bool GetNativeIsSpellCheckEnabled(EditorHandler editorHandler) => GetNativeEditor(editorHandler).SpellCheckingType == UITextSpellCheckingType.Yes; Color GetNativeTextColor(EditorHandler editorHandler) => GetNativeEditor(editorHandler).TextColor.ToColor(); UITextAlignment GetNativeHorizontalTextAlignment(EditorHandler editorHandler) => GetNativeEditor(editorHandler).TextAlignment; bool GetNativeIsNumericKeyboard(EditorHandler editorHandler) => GetNativeEditor(editorHandler).KeyboardType == UIKeyboardType.DecimalPad; bool GetNativeIsEmailKeyboard(EditorHandler editorHandler) => GetNativeEditor(editorHandler).KeyboardType == UIKeyboardType.EmailAddress; bool GetNativeIsTelephoneKeyboard(EditorHandler editorHandler) => GetNativeEditor(editorHandler).KeyboardType == UIKeyboardType.PhonePad; bool GetNativeIsUrlKeyboard(EditorHandler editorHandler) => GetNativeEditor(editorHandler).KeyboardType == UIKeyboardType.Url; bool GetNativeIsTextKeyboard(EditorHandler editorHandler) { var nativeEditor = GetNativeEditor(editorHandler); return nativeEditor.AutocapitalizationType == UITextAutocapitalizationType.Sentences && nativeEditor.AutocorrectionType == UITextAutocorrectionType.Yes && nativeEditor.SpellCheckingType == UITextSpellCheckingType.Yes; } bool GetNativeIsChatKeyboard(EditorHandler editorHandler) { var nativeEditor = GetNativeEditor(editorHandler); return nativeEditor.AutocapitalizationType == UITextAutocapitalizationType.Sentences && nativeEditor.AutocorrectionType == UITextAutocorrectionType.Yes && nativeEditor.SpellCheckingType == UITextSpellCheckingType.Yes; } int GetNativeCursorPosition(EditorHandler editorHandler) { var nativeEditor = GetNativeEditor(editorHandler); if (nativeEditor != null && nativeEditor.SelectedTextRange != null) return (int)nativeEditor.GetOffsetFromPosition(nativeEditor.BeginningOfDocument, nativeEditor.SelectedTextRange.Start); return -1; } bool GetNativeIsEnabled(EditorHandler editorHandler) => GetNativeEditor(editorHandler).Editable; int GetNativeSelectionLength(EditorHandler editorHandler) { var nativeEditor = GetNativeEditor(editorHandler); if (nativeEditor != null && nativeEditor.SelectedTextRange != null) return (int)nativeEditor.GetOffsetFromPosition(nativeEditor.SelectedTextRange.Start, nativeEditor.SelectedTextRange.End); return -1; } TextAlignment GetNativeVerticalTextAlignment(EditorHandler editorHandler) => GetNativeEditor(editorHandler).VerticalTextAlignment; TextAlignment GetNativeVerticalTextAlignment(TextAlignment textAlignment) => textAlignment; #if !MACCATALYST [Fact(DisplayName = "Completed Event Fires")] public async Task CompletedEventFiresFromTappingDone() { var editor = new EditorStub() { Text = "Test" }; int completedCount = 0; editor.Completed += (_, _) => completedCount++; await InvokeOnMainThreadAsync(() => { var handler = CreateHandler(editor); TapDoneOnInputAccessoryView(handler.PlatformView); }); Assert.Equal(1, completedCount); } #endif } }
EditorHandlerTests
csharp
StackExchange__StackExchange.Redis
src/StackExchange.Redis/VectorSetLink.cs
{ "start": 329, "end": 762 }
struct ____(RedisValue member, double score) { /// <summary> /// The linked member name/identifier. /// </summary> public RedisValue Member { get; } = member; /// <summary> /// The similarity score between the queried member and this linked member. /// </summary> public double Score { get; } = score; /// <inheritdoc/> public override string ToString() => $"{Member}: {Score}"; }
VectorSetLink
csharp
dotnet__orleans
src/AdoNet/Orleans.Streaming.AdoNet/AdoNetStreamMessageAck.cs
{ "start": 209, "end": 407 }
internal record ____( string ServiceId, string ProviderId, string QueueId, long MessageId) { public AdoNetStreamMessageAck() : this("", "", "", 0) { } }
AdoNetStreamMessageAck
csharp
grpc__grpc-dotnet
src/Grpc.Net.Client/Balancer/RoundRobinBalancer.cs
{ "start": 3166, "end": 3540 }
public sealed class ____ : LoadBalancerFactory { /// <inheritdoc /> public override string Name { get; } = LoadBalancingConfig.RoundRobinPolicyName; /// <inheritdoc /> public override LoadBalancer Create(LoadBalancerOptions options) { return new RoundRobinBalancer(options.Controller, options.LoggerFactory); } } #endif
RoundRobinBalancerFactory
csharp
MassTransit__MassTransit
src/Transports/MassTransit.KafkaIntegration/ProduceExtensions.cs
{ "start": 8642, "end": 9366 }
class ____ TException : Exception { return source.Add(new FaultedProduceActivity<TInstance, TData, TException, TMessage>( MessageFactory<TMessage>.Create(messageFactory, contextCallback))); } public static ExceptionActivityBinder<TInstance, TData, TException> Produce<TInstance, TData, TException, TMessage>( this ExceptionActivityBinder<TInstance, TData, TException> source, Func<BehaviorExceptionContext<TInstance, TData, TException>, Task<SendTuple<TMessage>>> messageFactory, Action<SendContext<TMessage>> contextCallback = null) where TInstance : class, SagaStateMachineInstance where TData :
where
csharp
dotnetcore__FreeSql
Providers/FreeSql.Provider.Firebird/FirebirdDbFirst.cs
{ "start": 300, "end": 20708 }
class ____ : IDbFirst { IFreeSql _orm; protected CommonUtils _commonUtils; protected CommonExpression _commonExpression; public FirebirdDbFirst(IFreeSql orm, CommonUtils commonUtils, CommonExpression commonExpression) { _orm = orm; _commonUtils = commonUtils; _commonExpression = commonExpression; } public int GetDbType(DbColumnInfo column) => (int)GetFbDbType(column); FbDbType GetFbDbType(DbColumnInfo column) { var dbtype = column.DbTypeText; var isarray = dbtype?.EndsWith("[]") == true; if (isarray) dbtype = dbtype.Remove(dbtype.Length - 2); FbDbType ret = FbDbType.VarChar; switch (dbtype?.ToLower().TrimStart('_')) { case "bigint": ret = FbDbType.BigInt; break; case "blob": ret = FbDbType.Binary; break; case "nchar": case "char": case "character": ret = FbDbType.Char; break; case "date": ret = FbDbType.Date; break; case "decimal": ret = FbDbType.Decimal; break; case "double": case "double precision": ret = FbDbType.Double; break; case "float": ret = FbDbType.Float; break; case "integer": case "int": ret = FbDbType.Integer; break; case "numeric": case "numeric precision": ret = FbDbType.Numeric; break; case "smallint": ret = FbDbType.SmallInt; break; case "time": ret = FbDbType.Time; break; case "timestamp": ret = FbDbType.TimeStamp; break; case "varchar": case "char varying": case "character varying": ret = FbDbType.VarChar; break; case "text": ret = FbDbType.Text; break; case "boolean": ret = FbDbType.Boolean; break; case "char(36)": ret = FbDbType.Guid; break; } return isarray ? (ret | FbDbType.Array) : ret; } static readonly Dictionary<int, DbToCs> _dicDbToCs = new Dictionary<int, DbToCs>() { { (int)FbDbType.SmallInt, new DbToCs("(short?)", "short.Parse({0})", "{0}.ToString()", "short?", typeof(short), typeof(short?), "{0}.Value", "GetInt16") }, { (int)FbDbType.Integer, new DbToCs("(int?)", "int.Parse({0})", "{0}.ToString()", "int?", typeof(int), typeof(int?), "{0}.Value", "GetInt32") }, { (int)FbDbType.BigInt, new DbToCs("(long?)", "long.Parse({0})", "{0}.ToString()", "long?", typeof(long), typeof(long?), "{0}.Value", "GetInt64") }, { (int)FbDbType.Numeric, new DbToCs("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, { (int)FbDbType.Float, new DbToCs("(float?)", "float.Parse({0})", "{0}.ToString()", "float?", typeof(float), typeof(float?), "{0}.Value", "GetFloat") }, { (int)FbDbType.Double, new DbToCs("(double?)", "double.Parse({0})", "{0}.ToString()", "double?", typeof(double), typeof(double?), "{0}.Value", "GetDouble") }, { (int)FbDbType.Decimal, new DbToCs("(decimal?)", "decimal.Parse({0})", "{0}.ToString()", "decimal?", typeof(decimal), typeof(decimal?), "{0}.Value", "GetDecimal") }, { (int)FbDbType.Char, new DbToCs("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, { (int)FbDbType.VarChar, new DbToCs("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, { (int)FbDbType.Text, new DbToCs("", "{0}.Replace(StringifySplit, \"|\")", "{0}.Replace(\"|\", StringifySplit)", "string", typeof(string), typeof(string), "{0}", "GetString") }, { (int)FbDbType.TimeStamp, new DbToCs("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, { (int)FbDbType.Date, new DbToCs("(DateTime?)", "new DateTime(long.Parse({0}))", "{0}.Ticks.ToString()", "DateTime?", typeof(DateTime), typeof(DateTime?), "{0}.Value", "GetDateTime") }, { (int)FbDbType.Time, new DbToCs("(TimeSpan?)", "TimeSpan.Parse(double.Parse({0}))", "{0}.Ticks.ToString()", "TimeSpan?", typeof(TimeSpan), typeof(TimeSpan?), "{0}.Value", "GetValue") }, { (int)FbDbType.Boolean, new DbToCs("(bool?)", "{0} == \"1\"", "{0} == true ? \"1\" : \"0\"", "bool?", typeof(bool), typeof(bool?), "{0}.Value", "GetBoolean") }, { (int)FbDbType.Binary, new DbToCs("(byte[])", "Convert.FromBase64String({0})", "Convert.ToBase64String({0})", "byte[]", typeof(byte[]), typeof(byte[]), "{0}", "GetValue") }, { (int)FbDbType.Guid, new DbToCs("(Guid?)", "Guid.Parse({0})", "{0}.ToString()", "Guid", typeof(Guid), typeof(Guid?), "{0}", "GetString") }, }; public string GetCsConvert(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csConvert : trydc.csConvert.Replace("?", "")) : null; public string GetCsParse(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csParse : null; public string GetCsStringify(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csStringify : null; public string GetCsType(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? (column.IsNullable ? trydc.csType : trydc.csType.Replace("?", "")) : null; public Type GetCsTypeInfo(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeInfo : null; public string GetCsTypeValue(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.csTypeValue : null; public string GetDataReaderMethod(DbColumnInfo column) => _dicDbToCs.TryGetValue(column.DbType, out var trydc) ? trydc.dataReaderMethod : null; public List<string> GetDatabases() { var sql = @" select trim(rdb$owner_name) from rdb$roles"; var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); return ds.Select(a => a.FirstOrDefault()?.ToString()).Distinct().ToList(); } public bool ExistsTable(string name, bool ignoreCase) { if (string.IsNullOrEmpty(name)) return false; var tbname = _commonUtils.SplitTableName(name); if (ignoreCase) tbname = tbname.Select(a => a.ToUpper()).ToArray(); var sql = $" select 1 from rdb$relations where rdb$system_flag=0 and {(ignoreCase ? "upper(trim(rdb$relation_name))" : "trim(rdb$relation_name)")} = {_commonUtils.FormatSql("{0}", tbname.Last())}"; return string.Concat(_orm.Ado.ExecuteScalar(CommandType.Text, sql)) == "1"; } public DbTableInfo GetTableByName(string name, bool ignoreCase = true) => GetTables(null, name, ignoreCase)?.FirstOrDefault(); public List<DbTableInfo> GetTablesByDatabase(params string[] database) => GetTables(database, null, false); public List<DbTableInfo> GetTables(string[] database, string tablename, bool ignoreCase) { string[] tbname = null; if (string.IsNullOrEmpty(tablename) == false) { tbname = _commonUtils.SplitTableName(tablename); if (ignoreCase) tbname = tbname.Select(a => a.ToUpper()).ToArray(); } var loc1 = new List<DbTableInfo>(); var loc2 = new Dictionary<string, DbTableInfo>(); var loc3 = new Dictionary<string, Dictionary<string, DbColumnInfo>>(); var sql = @" select trim(rdb$relation_name) as id, trim(rdb$owner_name) as owner, trim(rdb$relation_name) as name, trim(rdb$description) as comment, rdb$relation_type as type from rdb$relations where rdb$system_flag=0" + (tbname == null ? "" : $" and {(ignoreCase ? "upper(trim(rdb$relation_name))" : "trim(rdb$relation_name)")} = {_commonUtils.FormatSql("{0}", tbname.Last())}"); var ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); if (ds == null) return loc1; var loc6 = new List<string[]>(); var loc66 = new List<string[]>(); var loc6_1000 = new List<string>(); var loc66_1000 = new List<string>(); foreach (var row in ds) { var table_id = string.Concat(row[0]); var schema = string.Concat(row[1]); var table = string.Concat(row[2]); var comment = string.Concat(row[3]); DbTableType type = DbTableType.TABLE; switch (string.Concat(row[4])) { case "1": type = DbTableType.VIEW; break; } if (database?.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); schema = ""; } loc2.Add(table_id, new DbTableInfo { Id = table_id, Schema = schema, Name = table, Comment = comment, Type = type }); loc3.Add(table_id, new Dictionary<string, DbColumnInfo>()); switch (type) { case DbTableType.TABLE: case DbTableType.VIEW: loc6_1000.Add(table.Replace("'", "''")); if (loc6_1000.Count >= 500) { loc6.Add(loc6_1000.ToArray()); loc6_1000.Clear(); } break; case DbTableType.StoreProcedure: loc66_1000.Add(table.Replace("'", "''")); if (loc66_1000.Count >= 500) { loc66.Add(loc66_1000.ToArray()); loc66_1000.Clear(); } break; } } if (loc6_1000.Count > 0) loc6.Add(loc6_1000.ToArray()); if (loc66_1000.Count > 0) loc66.Add(loc66_1000.ToArray()); if (loc6.Count == 0) return loc1; var loc8 = new StringBuilder().Append("("); for (var loc8idx = 0; loc8idx < loc6.Count; loc8idx++) { if (loc8idx > 0) loc8.Append(" OR "); loc8.Append("trim(d.rdb$relation_name) in ("); for (var loc8idx2 = 0; loc8idx2 < loc6[loc8idx].Length; loc8idx2++) { if (loc8idx2 > 0) loc8.Append(","); loc8.Append($"'{loc6[loc8idx][loc8idx2]}'"); } loc8.Append(")"); } loc8.Append(")"); sql = $@" select trim(d.rdb$relation_name), trim(a.rdb$field_name), case when b.rdb$field_sub_type = 2 then 'DECIMAL' when b.rdb$field_type = 14 then 'CHAR' when b.rdb$field_type = 37 then 'VARCHAR' when b.rdb$field_type = 8 then 'INTEGER' when b.rdb$field_type = 16 then 'BIGINT' when b.rdb$field_type = 27 then 'DOUBLE PRECISION' when b.rdb$field_type = 7 then 'SMALLINT' else (select trim(rdb$type_name) from rdb$types where rdb$type = b.rdb$field_type and rdb$field_name = 'RDB$FIELD_TYPE' rows 1) || coalesce((select ' SUB_TYPE ' || rdb$type from rdb$types where b.rdb$field_type = 261 and rdb$type = b.rdb$field_sub_type and rdb$field_name = 'RDB$FIELD_SUB_TYPE' rows 1),'') end || trim(case when b.rdb$dimensions = 1 then '[]' else '' end), b.rdb$character_length, case when b.rdb$field_sub_type = 2 then (select 'DECIMAL(' || rdb$field_precision || ',' || abs(rdb$field_scale) || ')' from rdb$types where b.rdb$field_sub_type = 2 and rdb$type = b.rdb$field_sub_type and rdb$field_name = 'RDB$FIELD_SUB_TYPE' rows 1) when b.rdb$field_type = 14 then 'CHAR(' || b.rdb$character_length || ')' when b.rdb$field_type = 37 then 'VARCHAR(' || b.rdb$character_length || ')' when b.rdb$field_type = 8 then 'INTEGER' when b.rdb$field_type = 16 then 'BIGINT' when b.rdb$field_type = 27 then 'DOUBLE PRECISION' when b.rdb$field_type = 7 then 'SMALLINT' else (select trim(rdb$type_name) from rdb$types where rdb$type = b.rdb$field_type and rdb$field_name = 'RDB$FIELD_TYPE' rows 1) || coalesce((select ' SUB_TYPE ' || rdb$type from rdb$types where b.rdb$field_type = 261 and rdb$type = b.rdb$field_sub_type and rdb$field_name = 'RDB$FIELD_SUB_TYPE' rows 1),'') end || trim(case when b.rdb$dimensions = 1 then '[]' else '' end), case when a.rdb$null_flag = 1 then 0 else 1 end, {((_orm.Ado as FirebirdAdo)?.IsFirebird2_5 == true ? "0" : "case when a.rdb$identity_type = 1 then 1 else 0 end")}, a.rdb$description, a.rdb$default_value from rdb$relation_fields a inner join rdb$fields b on b.rdb$field_name = a.rdb$field_source inner join rdb$relations d on d.rdb$relation_name = a.rdb$relation_name where a.rdb$system_flag = 0 and {loc8} order by a.rdb$relation_name, a.rdb$field_position "; ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); if (ds == null) return loc1; var position = 0; foreach (var row in ds) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]); string type = string.Concat(row[2]).Trim(); //long max_length = long.Parse(string.Concat(row[3])); string sqlType = string.Concat(row[4]).Trim(); var m_len = Regex.Match(sqlType, @"\w+\((\d+)"); int max_length = m_len.Success ? int.Parse(m_len.Groups[1].Value) : -1; bool is_nullable = string.Concat(row[5]) == "1"; bool is_identity = string.Concat(row[6]) == "1"; string comment = string.Concat(row[7]); string defaultValue = string.Concat(row[8]); if (max_length == 0) max_length = -1; if (database?.Length == 1) { table_id = table_id.Substring(table_id.IndexOf('.') + 1); } loc3[table_id].Add(column, new DbColumnInfo { Name = column, MaxLength = max_length, IsIdentity = is_identity, IsNullable = is_nullable, IsPrimary = false, DbTypeText = type, DbTypeTextFull = sqlType, Table = loc2[table_id], Comment = comment, DefaultValue = defaultValue, Position = ++position }); loc3[table_id][column].DbType = this.GetDbType(loc3[table_id][column]); loc3[table_id][column].CsType = this.GetCsTypeInfo(loc3[table_id][column]); } sql = string.Format(@" select trim(d.rdb$relation_name), trim(c.rdb$field_name), trim(d.rdb$index_name), case when d.rdb$unique_flag = 1 then 1 else 0 end, case when exists(select first 1 1 from rdb$relation_constraints where rdb$index_name = d.rdb$index_name and rdb$constraint_type = 'PRIMARY KEY') then 1 else 0 end, 0, 0 from rdb$indices d inner join rdb$index_segments c on c.rdb$index_name = d.rdb$index_name where {0}", loc8); ds = _orm.Ado.ExecuteArray(CommandType.Text, sql); if (ds == null) return loc1; var indexColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>(); var uniqueColumns = new Dictionary<string, Dictionary<string, DbIndexInfo>>(); foreach (var row in ds) { string table_id = string.Concat(row[0]); string column = string.Concat(row[1]); string index_id = string.Concat(row[2]); bool is_unique = string.Concat(row[3]) == "1"; bool is_primary_key = string.Concat(row[4]) == "1"; bool is_clustered = string.Concat(row[5]) == "1"; bool is_desc = string.Concat(row[6]) == "1"; if (database?.Length == 1) table_id = table_id.Substring(table_id.IndexOf('.') + 1); if (loc3.ContainsKey(table_id) == false || loc3[table_id].ContainsKey(column) == false) continue; var loc9 = loc3[table_id][column]; if (loc9.IsPrimary == false && is_primary_key) loc9.IsPrimary = is_primary_key; Dictionary<string, DbIndexInfo> loc10 = null; DbIndexInfo loc11 = null; if (!indexColumns.TryGetValue(table_id, out loc10)) indexColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>()); if (!loc10.TryGetValue(index_id, out loc11)) loc10.Add(index_id, loc11 = new DbIndexInfo { Name = index_id }); loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc }); if (is_unique && !is_primary_key) { if (!uniqueColumns.TryGetValue(table_id, out loc10)) uniqueColumns.Add(table_id, loc10 = new Dictionary<string, DbIndexInfo>()); if (!loc10.TryGetValue(index_id, out loc11)) loc10.Add(index_id, loc11 = new DbIndexInfo { Name = index_id }); loc11.Columns.Add(new DbIndexColumnInfo { Column = loc9, IsDesc = is_desc }); } } foreach (string table_id in indexColumns.Keys) { foreach (var column in indexColumns[table_id]) loc2[table_id].IndexesDict.Add(column.Key, column.Value); } foreach (string table_id in uniqueColumns.Keys) { foreach (var column in uniqueColumns[table_id]) { column.Value.Columns.Sort((c1, c2) => c1.Column.Name.CompareTo(c2.Column.Name)); loc2[table_id].UniquesDict.Add(column.Key, column.Value); } } foreach (var table_id in loc3.Keys) { foreach (var loc5 in loc3[table_id].Values) { loc2[table_id].Columns.Add(loc5); if (loc5.IsIdentity) loc2[table_id].Identitys.Add(loc5); if (loc5.IsPrimary) loc2[table_id].Primarys.Add(loc5); } } foreach (var loc4 in loc2.Values) { //if (loc4.Primarys.Count == 0 && loc4.UniquesDict.Count > 0) //{ // foreach (var loc5 in loc4.UniquesDict.First().Value.Columns) // { // loc5.Column.IsPrimary = true; // loc4.Primarys.Add(loc5.Column); // } //} loc4.Primarys.Sort((c1, c2) => c1.Name.CompareTo(c2.Name)); loc4.Columns.Sort((c1, c2) => { int compare = c2.IsPrimary.CompareTo(c1.IsPrimary); if (compare == 0) { bool b1 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c1.Name).Any()).Any(); bool b2 = loc4.ForeignsDict.Values.Where(fk => fk.Columns.Where(c3 => c3.Name == c2.Name).Any()).Any(); compare = b2.CompareTo(b1); } if (compare == 0) compare = c1.Name.CompareTo(c2.Name); return compare; }); loc1.Add(loc4); } loc1.Sort((t1, t2) => { var ret = t1.Schema.CompareTo(t2.Schema); if (ret == 0) ret = t1.Name.CompareTo(t2.Name); return ret; }); loc2.Clear(); loc3.Clear(); return loc1; } public List<DbEnumInfo> GetEnumsByDatabase(params string[] database) { return new List<DbEnumInfo>(); } } }
FirebirdDbFirst
csharp
ServiceStack__ServiceStack.OrmLite
src/ServiceStack.OrmLite/Expressions/SqlExpression.cs
{ "start": 125732, "end": 130019 }
public static class ____ { public static IDbDataParameter CreateParam(this IDbConnection db, string name, object value = null, Type fieldType = null, DbType? dbType = null, byte? precision = null, byte? scale = null, int? size = null) { return db.GetDialectProvider().CreateParam(name, value, fieldType, dbType, precision, scale, size); } public static IDbDataParameter CreateParam(this IOrmLiteDialectProvider dialectProvider, string name, object value = null, Type fieldType = null, DbType? dbType = null, byte? precision = null, byte? scale = null, int? size = null) { var p = dialectProvider.CreateParam(); p.ParameterName = dialectProvider.GetParam(name); dialectProvider.ConfigureParam(p, value, dbType); if (precision != null) p.Precision = precision.Value; if (scale != null) p.Scale = scale.Value; if (size != null) p.Size = size.Value; return p; } internal static void ConfigureParam(this IOrmLiteDialectProvider dialectProvider, IDbDataParameter p, object value, DbType? dbType) { if (value != null) { dialectProvider.InitDbParam(p, value.GetType()); p.Value = dialectProvider.GetParamValue(value, value.GetType()); } else { p.Value = DBNull.Value; } // Can't check DbType in PostgreSQL before p.Value is assinged if (p.Value is string strValue && strValue.Length > p.Size) { var stringConverter = dialectProvider.GetStringConverter(); p.Size = strValue.Length > stringConverter.StringLength ? strValue.Length : stringConverter.StringLength; } if (dbType != null) p.DbType = dbType.Value; } public static IDbDataParameter AddQueryParam(this IOrmLiteDialectProvider dialectProvider, IDbCommand dbCmd, object value, FieldDefinition fieldDef) => dialectProvider.AddParam(dbCmd, value, fieldDef, paramFilter: dialectProvider.InitQueryParam); public static IDbDataParameter AddUpdateParam(this IOrmLiteDialectProvider dialectProvider, IDbCommand dbCmd, object value, FieldDefinition fieldDef) => dialectProvider.AddParam(dbCmd, value, fieldDef, paramFilter: dialectProvider.InitUpdateParam); public static IDbDataParameter AddParam(this IOrmLiteDialectProvider dialectProvider, IDbCommand dbCmd, object value, FieldDefinition fieldDef, Action<IDbDataParameter> paramFilter) { var paramName = dbCmd.Parameters.Count.ToString(); var parameter = dialectProvider.CreateParam(paramName, value, fieldDef?.ColumnType); paramFilter?.Invoke(parameter); if (fieldDef != null) dialectProvider.SetParameter(fieldDef, parameter); dbCmd.Parameters.Add(parameter); return parameter; } public static string GetInsertParam(this IOrmLiteDialectProvider dialectProvider, IDbCommand dbCmd, object value, FieldDefinition fieldDef) { var p = dialectProvider.AddUpdateParam(dbCmd, value, fieldDef); return fieldDef.CustomInsert != null ? string.Format(fieldDef.CustomInsert, p.ParameterName) : p.ParameterName; } public static string GetUpdateParam(this IOrmLiteDialectProvider dialectProvider, IDbCommand dbCmd, object value, FieldDefinition fieldDef) { var p = dialectProvider.AddUpdateParam(dbCmd, value, fieldDef); return fieldDef.CustomUpdate != null ? string.Format(fieldDef.CustomUpdate, p.ParameterName) : p.ParameterName; } } }
DbDataParameterExtensions
csharp
dotnet__aspnetcore
src/Http/Routing/test/UnitTests/RoutingServiceCollectionExtensionsTests.cs
{ "start": 412, "end": 1595 }
public class ____ { [Fact] public void AddRouting_ThrowsOnNull_ServicesParameter() { var ex = Record.Exception(() => { RoutingServiceCollectionExtensions.AddRouting(null); }); Assert.IsType<ArgumentNullException>(ex); Assert.Equal("services", (ex as ArgumentNullException).ParamName); } [Fact] public void AddRoutingWithOptions_ThrowsOnNull_ConfigureOptionsParameter() { var services = new ServiceCollection(); var ex = Record.Exception(() => { RoutingServiceCollectionExtensions.AddRouting(services, null); }); Assert.IsType<ArgumentNullException>(ex); Assert.Equal("configureOptions", (ex as ArgumentNullException).ParamName); } [Fact] public void AddRoutingWithOptions_ThrowsOnNull_ServicesParameter() { var ex = Record.Exception(() => { RoutingServiceCollectionExtensions.AddRouting(null, options => { }); }); Assert.IsType<ArgumentNullException>(ex); Assert.Equal("services", (ex as ArgumentNullException).ParamName); }
RoutingServiceCollectionExtensionsTests
csharp
icsharpcode__ILSpy
ILSpy/Metadata/CorTables/NestedClassTableTreeNode.cs
{ "start": 1342, "end": 2101 }
class ____ : MetadataTableTreeNode<NestedClassTableTreeNode.NestedClassEntry> { public NestedClassTableTreeNode(MetadataFile metadataFile) : base(TableIndex.NestedClass, metadataFile) { } protected override IReadOnlyList<NestedClassEntry> LoadTable() { var list = new List<NestedClassEntry>(); var metadata = metadataFile.Metadata; var length = metadata.GetTableRowCount(TableIndex.NestedClass); ReadOnlySpan<byte> ptr = metadata.AsReadOnlySpan(); int typeDefSize = metadataFile.Metadata.GetTableRowCount(TableIndex.TypeDef) < ushort.MaxValue ? 2 : 4; for (int rid = 1; rid <= length; rid++) { list.Add(new NestedClassEntry(metadataFile, ptr, rid, typeDefSize)); } return list; } readonly
NestedClassTableTreeNode
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/JsonDrivenTests/JsonDrivenRunAdminCommandTest.cs
{ "start": 810, "end": 5082 }
internal sealed class ____ : JsonDrivenTestRunnerTest { // private fields private BsonDocument _command; private readonly MongoClientSettings _mongoClientSettings; private ReadConcern _readConcern = new ReadConcern(); private ReadPreference _readPreference; private BsonDocument _result; private IClientSessionHandle _session; public JsonDrivenRunAdminCommandTest(IMongoClient mongoClient, IJsonDrivenTestRunner testRunner, Dictionary<string, object> objectMap) : base(testRunner, objectMap) { _mongoClientSettings = mongoClient.Settings.Clone(); _mongoClientSettings.ClusterConfigurator = null; } public override void Arrange(BsonDocument document) { var expectedNames = new[] { "name", "object", "command_name", "arguments", "result", "databaseOptions" }; JsonDrivenHelper.EnsureAllFieldsAreValid(document, expectedNames); base.Arrange(document); if (document.Contains("command_name")) { var actualCommandName = _command.GetElement(0).Name; var expectedCommandName = document["command_name"].AsString; if (actualCommandName != expectedCommandName) { throw new FormatException($"Actual command name \"{actualCommandName}\" does not match expected command name \"{expectedCommandName}\"."); } } } // protected methods protected override void AssertResult() { var aspectAsserter = new BsonDocumentAspectAsserter(); aspectAsserter.AssertAspects(_result, _expectedResult.AsBsonDocument); } protected override void CallMethod(CancellationToken cancellationToken) { using (var client = DriverTestConfiguration.CreateMongoClient(_mongoClientSettings)) { if (_session == null) { _result = GetAdminDatabase(client).RunCommand<BsonDocument>(_command, _readPreference, cancellationToken); } else { _result = GetAdminDatabase(client).RunCommand<BsonDocument>(_session, _command, _readPreference, cancellationToken); } } } protected override async Task CallMethodAsync(CancellationToken cancellationToken) { using (var client = DriverTestConfiguration.CreateMongoClient(_mongoClientSettings)) { if (_session == null) { _result = await GetAdminDatabase(client).RunCommandAsync<BsonDocument>(_command, _readPreference, cancellationToken).ConfigureAwait(false); } else { _result = await GetAdminDatabase(client).RunCommandAsync<BsonDocument>(_session, _command, _readPreference, cancellationToken).ConfigureAwait(false); } } } protected override void SetArgument(string name, BsonValue value) { switch (name) { case "command": _command = value.AsBsonDocument; return; case "databaseOptions": if (value.AsBsonDocument.TryGetValue("readConcern", out var readConcernValue)) { _readConcern = ReadConcern.FromBsonDocument(readConcernValue.AsBsonDocument); } return; case "readPreference": _readPreference = ReadPreference.FromBsonDocument(value.AsBsonDocument); return; case "session": _session = (IClientSessionHandle)_objectMap[value.AsString]; return; } base.SetArgument(name, value); } // private methods private IMongoDatabase GetAdminDatabase(IMongoClient mongoClient) { return mongoClient.GetDatabase(DatabaseNamespace.Admin.DatabaseName).WithReadConcern(_readConcern); } } }
JsonDrivenRunAdminCommandTest
csharp
cake-build__cake
src/Cake.Common/Tools/InspectCode/InspectCodeVerbosity.cs
{ "start": 340, "end": 1045 }
public enum ____ { /// <summary> /// Verbosity: OFF. /// </summary> Off = 1, /// <summary> /// Verbosity: FATAL. /// </summary> Fatal = 2, /// <summary> /// Verbosity: ERROR. /// </summary> Error = 3, /// <summary> /// Verbosity: WARN. /// </summary> Warn = 4, /// <summary> /// Verbosity: INFO. /// </summary> Info = 5, /// <summary> /// Verbosity: VERBOSE. /// </summary> Verbose = 6, /// <summary> /// Verbosity: TRACE. /// </summary> Trace = 7 } }
InspectCodeVerbosity
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Subscription/SubscriptionExecutionStrategyTests.cs
{ "start": 33060, "end": 33657 }
private class ____ : IObserver<TIn> { private readonly Func<TIn, TOut> _transform; private readonly IObserver<TOut> _target; public Observer(IObserver<TOut> target, Func<TIn, TOut> transform) { _transform = transform; _target = target; } public void OnCompleted() => _target.OnCompleted(); public void OnError(Exception error) => _target.OnError(error); public void OnNext(TIn value) => _target.OnNext(_transform(value)); } } #endregion }
Observer
csharp
protobuf-net__protobuf-net
src/protobuf-net.Test/ThirdParty/NHibernateProxies.cs
{ "start": 3991, "end": 7553 }
class ____ : Foo { } [Fact] public void AttemptToSerializeUnknownSubtypeShouldFail_Runtime() { Assert.Throws<InvalidOperationException>(() => { var model = BuildModel(); model.Serialize(Stream.Null, new Bar()); }); } [Fact] public void AttemptToSerializeUnknownSubtypeShouldFail_CompileInPlace() { Assert.Throws<InvalidOperationException>(() => { var model = BuildModel(); model.CompileInPlace(); model.Serialize(Stream.Null, new Bar()); }); } [Fact] public void AttemptToSerializeUnknownSubtypeShouldFail_Compile() { Assert.Throws<InvalidOperationException>(() => { var model = BuildModel().Compile(); model.Serialize(Stream.Null, new Bar()); }); } [Fact] public void AttemptToSerializeWrapperUnknownSubtypeShouldFail_Runtime() { Assert.Throws<InvalidOperationException>(() => { var model = BuildModel(); model.Serialize(Stream.Null, new FooWrapper { Foo = new Bar() }); }); } [Fact] public void AttemptToSerializeWrapperUnknownSubtypeShouldFail_CompileInPlace() { Assert.Throws<InvalidOperationException>(() => { var model = BuildModel(); model.CompileInPlace(); model.Serialize(Stream.Null, new FooWrapper { Foo = new Bar() }); }); } [Fact] public void AttemptToSerializeWrapperUnknownSubtypeShouldFail_Compile() { Assert.Throws<InvalidOperationException>(() => { var model = BuildModel().Compile(); model.Serialize(Stream.Null, new FooWrapper { Foo = new Bar() }); }); } [Fact] public void CanRoundTripProxyToRegular() { var model = BuildModel(); Foo foo = new Foo { Id = 1234, Name = "abcd" }, proxy = new FooProxy(foo), clone; Assert.NotNull(foo); Assert.NotNull(proxy); clone = (Foo)model.DeepClone(foo); CompareFoo(foo, clone, "Runtime/Foo"); clone = (Foo)model.DeepClone(proxy); CompareFoo(proxy, clone, "Runtime/FooProxy"); model.CompileInPlace(); clone = (Foo)model.DeepClone(foo); CompareFoo(foo, clone, "CompileInPlace/Foo"); clone = (Foo)model.DeepClone(proxy); CompareFoo(proxy, clone, "CompileInPlace/FooProxy"); var compiled = model.Compile(); clone = (Foo)compiled.DeepClone(foo); CompareFoo(foo, clone, "Compile/Foo"); clone = (Foo)compiled.DeepClone(proxy); CompareFoo(proxy, clone, "Compile/FooProxy"); } #pragma warning disable IDE0060 // Remove unused parameter private static void CompareFoo(Foo original, Foo clone, string message) #pragma warning restore IDE0060 // Remove unused parameter { Assert.NotNull(clone); //, message); Assert.NotSame(original, clone); Assert.Equal(original.Id, clone.Id); //, message + ": Id"); Assert.Equal(original.Name, clone.Name); //, message + ": Name"); Assert.Equal(typeof(Foo), clone.GetType()); //, message); } } } #endif
Bar
csharp
bitwarden__server
test/Core.Test/Tools/AutoFixture/SendFixtures.cs
{ "start": 648, "end": 893 }
internal class ____ : ICustomization { public void Customize(IFixture fixture) { fixture.Customize<Send>(composer => composer .With(s => s.Id, Guid.Empty) .Without(s => s.OrganizationId)); } }
NewUserSend
csharp
dotnet__aspnetcore
src/Components/Web/src/Forms/InputSelect.cs
{ "start": 370, "end": 3528 }
public class ____<[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.All)] TValue> : InputBase<TValue> { private readonly bool _isMultipleSelect; /// <summary> /// Constructs an instance of <see cref="InputSelect{TValue}"/>. /// </summary> public InputSelect() { _isMultipleSelect = typeof(TValue).IsArray; } /// <summary> /// Gets or sets the child content to be rendering inside the select element. /// </summary> [Parameter] public RenderFragment? ChildContent { get; set; } /// <summary> /// Gets or sets the <c>select</c> <see cref="ElementReference"/>. /// <para> /// May be <see langword="null"/> if accessed before the component is rendered. /// </para> /// </summary> [DisallowNull] public ElementReference? Element { get; protected set; } /// <inheritdoc /> protected override void BuildRenderTree(RenderTreeBuilder builder) { builder.OpenElement(0, "select"); builder.AddMultipleAttributes(1, AdditionalAttributes); builder.AddAttributeIfNotNullOrEmpty(2, "name", NameAttributeValue); builder.AddAttributeIfNotNullOrEmpty(3, "class", CssClass); builder.AddAttribute(4, "multiple", _isMultipleSelect); if (_isMultipleSelect) { builder.AddAttribute(5, "value", BindConverter.FormatValue(CurrentValue)?.ToString()); builder.AddAttribute(6, "onchange", EventCallback.Factory.CreateBinder<string?[]?>(this, SetCurrentValueAsStringArray, default)); builder.SetUpdatesAttributeName("value"); } else { builder.AddAttribute(7, "value", CurrentValueAsString); builder.AddAttribute(8, "onchange", EventCallback.Factory.CreateBinder<string?>(this, __value => CurrentValueAsString = __value, default)); builder.SetUpdatesAttributeName("value"); } builder.AddElementReferenceCapture(9, __selectReference => Element = __selectReference); builder.AddContent(10, ChildContent); builder.CloseElement(); } /// <inheritdoc /> protected override bool TryParseValueFromString(string? value, [MaybeNullWhen(false)] out TValue result, [NotNullWhen(false)] out string? validationErrorMessage) => this.TryParseSelectableValueFromString(value, out result, out validationErrorMessage); /// <inheritdoc /> protected override string? FormatValueAsString(TValue? value) { // We special-case bool values because BindConverter reserves bool conversion for conditional attributes. if (typeof(TValue) == typeof(bool)) { return (bool)(object)value! ? "true" : "false"; } else if (typeof(TValue) == typeof(bool?)) { return value is not null && (bool)(object)value ? "true" : "false"; } return base.FormatValueAsString(value); } private void SetCurrentValueAsStringArray(string?[]? value) { CurrentValue = BindConverter.TryConvertTo<TValue>(value, CultureInfo.CurrentCulture, out var result) ? result : default; } }
InputSelect
csharp
louthy__language-ext
LanguageExt.Core/Monads/Alternative Monads/Try/Operators/Try.Operators.Functor.cs
{ "start": 112, "end": 6068 }
partial class ____ { extension<A, B>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<B> operator *(Func<A, B> f, K<Try, A> ma) => +ma.Map(f); /// <summary> /// Functor map operator /// </summary> public static Try<B> operator *(K<Try, A> ma, Func<A, B> f) => +ma.Map(f); } extension<A, B, C>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, C>> operator * ( Func<A, B, C> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, C>> operator * ( K<Try, A> ma, Func<A, B, C> f) => curry(f) * ma; } extension<A, B, C, D>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, D>>> operator * ( Func<A, B, C, D> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, D>>> operator * ( K<Try, A> ma, Func<A, B, C, D> f) => curry(f) * ma; } extension<A, B, C, D, E>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, E>>>> operator * ( Func<A, B, C, D, E> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, E>>>> operator * ( K<Try, A> ma, Func<A, B, C, D, E> f) => curry(f) * ma; } extension<A, B, C, D, E, F>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, F>>>>> operator * ( Func<A, B, C, D, E, F> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, F>>>>> operator * ( K<Try, A> ma, Func<A, B, C, D, E, F> f) => curry(f) * ma; } extension<A, B, C, D, E, F, G>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, G>>>>>> operator * ( Func<A, B, C, D, E, F, G> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, G>>>>>> operator * ( K<Try, A> ma, Func<A, B, C, D, E, F, G> f) => curry(f) * ma; } extension<A, B, C, D, E, F, G, H>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, H>>>>>>> operator * ( Func<A, B, C, D, E, F, G, H> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, H>>>>>>> operator * ( K<Try, A> ma, Func<A, B, C, D, E, F, G, H> f) => curry(f) * ma; } extension<A, B, C, D, E, F, G, H, I>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, Func<H, I>>>>>>>> operator * ( Func<A, B, C, D, E, F, G, H, I> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, Func<H, I>>>>>>>> operator * ( K<Try, A> ma, Func<A, B, C, D, E, F, G, H, I> f) => curry(f) * ma; } extension<A, B, C, D, E, F, G, H, I, J>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, Func<H, Func<I, J>>>>>>>>> operator * ( Func<A, B, C, D, E, F, G, H, I, J> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, Func<H, Func<I, J>>>>>>>>> operator * ( K<Try, A> ma, Func<A, B, C, D, E, F, G, H, I, J> f) => curry(f) * ma; } extension<A, B, C, D, E, F, G, H, I, J, K>(K<Try, A> _) { /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, Func<H, Func<I, Func<J, K>>>>>>>>>> operator * ( Func<A, B, C, D, E, F, G, H, I, J, K> f, K<Try, A> ma) => curry(f) * ma; /// <summary> /// Functor map operator /// </summary> public static Try<Func<B, Func<C, Func<D, Func<E, Func<F, Func<G, Func<H, Func<I, Func<J, K>>>>>>>>>> operator * ( K<Try, A> ma, Func<A, B, C, D, E, F, G, H, I, J, K> f) => curry(f) * ma; } }
TryExtensions
csharp
CommunityToolkit__WindowsCommunityToolkit
Microsoft.Toolkit.Win32.WpfCore.SampleApp/MainWindow.xaml.cs
{ "start": 657, "end": 8235 }
public partial class ____ : Window { public MainWindow() { InitializeComponent(); // IMPORTANT: Look at App.xaml.cs for handling toast activation } private async void ButtonPopToast_Click(object sender, RoutedEventArgs e) { if (ToastNotificationManagerCompat.CreateToastNotifier().Setting != NotificationSetting.Enabled) { MessageBox.Show("Notifications are disabled from the system settings."); return; } string title = "Andrew sent you a picture"; string content = "Check this out, The Enchantments!"; string image = "https://picsum.photos/364/202?image=883"; int conversationId = 5; // Construct the toast content and show it! new ToastContentBuilder() // Arguments that are returned when the user clicks the toast or a button .AddArgument("action", MyToastActions.ViewConversation) .AddArgument("conversationId", conversationId) // Visual content .AddText(title) .AddText(content) .AddInlineImage(new Uri(await DownloadImageToDisk(image))) .AddAppLogoOverride(new Uri(await DownloadImageToDisk("https://unsplash.it/64?image=1005")), ToastGenericAppLogoCrop.Circle) // Text box for typing a reply .AddInputTextBox("tbReply", "Type a reply") // Buttons .AddButton(new ToastButton() .SetContent("Reply") .AddArgument("action", MyToastActions.Reply) .SetBackgroundActivation()) .AddButton(new ToastButton() .SetContent("Like") .AddArgument("action", MyToastActions.Like) .SetBackgroundActivation()) .AddButton(new ToastButton() .SetContent("View") .AddArgument("action", MyToastActions.ViewImage) .AddArgument("imageUrl", image)) // And show the toast! .Show(); } private static bool _hasPerformedCleanup; private static async Task<string> DownloadImageToDisk(string httpImage) { // Toasts can live for up to 3 days, so we cache images for up to 3 days. // Note that this is a very simple cache that doesn't account for space usage, so // this could easily consume a lot of space within the span of 3 days. try { if (ToastNotificationManagerCompat.CanUseHttpImages) { return httpImage; } var directory = Directory.CreateDirectory(System.IO.Path.GetTempPath() + "WindowsNotifications.DesktopToasts.Images"); if (!_hasPerformedCleanup) { // First time we run, we'll perform cleanup of old images _hasPerformedCleanup = true; foreach (var d in directory.EnumerateDirectories()) { if (d.CreationTimeUtc.Date < DateTime.UtcNow.Date.AddDays(-3)) { d.Delete(true); } } } var dayDirectory = directory.CreateSubdirectory(DateTime.UtcNow.Day.ToString()); string imagePath = dayDirectory.FullName + "\\" + (uint)httpImage.GetHashCode(); if (File.Exists(imagePath)) { return imagePath; } HttpClient c = new HttpClient(); using (var stream = await c.GetStreamAsync(httpImage)) { using (var fileStream = File.OpenWrite(imagePath)) { stream.CopyTo(fileStream); } } return imagePath; } catch { return string.Empty; } } internal void ShowConversation(int conversationId) { ContentBody.Content = new TextBlock() { Text = "You've just opened conversation " + conversationId, FontWeight = FontWeights.Bold }; } internal void ShowImage(string imageUrl) { ContentBody.Content = new Image() { Source = new BitmapImage(new Uri(imageUrl)) }; } private void ButtonClearToasts_Click(object sender, RoutedEventArgs e) { ToastNotificationManagerCompat.History.Clear(); } private async void ButtonScheduleToast_Click(object sender, RoutedEventArgs e) { // Schedule a toast to appear in 5 seconds new ToastContentBuilder() // Arguments that are returned when the user clicks the toast or a button .AddArgument("action", MyToastActions.ViewConversation) .AddArgument("conversationId", 7764) .AddText("Scheduled toast notification") .Schedule(DateTime.Now.AddSeconds(5)); // Inform the user var tb = new TextBlock() { Text = "Toast scheduled to appear in 5 seconds", FontWeight = FontWeights.Bold }; ContentBody.Content = tb; // And after 5 seconds, clear the informational message await Task.Delay(5000); if (ContentBody.Content == tb) { ContentBody.Content = null; } } private async void ButtonProgressToast_Click(object sender, RoutedEventArgs e) { const string tag = "progressToast"; new ToastContentBuilder() .AddArgument("action", MyToastActions.ViewConversation) .AddArgument("conversationId", 423) .AddText("Sending image to conversation...") .AddVisualChild(new AdaptiveProgressBar() { Value = new BindableProgressBarValue("progress"), Status = "Sending..." }) .Show(toast => { toast.Tag = tag; toast.Data = new NotificationData(new Dictionary<string, string>() { { "progress", "0" } }); }); double progress = 0; while (progress < 1) { await Task.Delay(new Random().Next(1000, 3000)); progress += (new Random().NextDouble() * 0.15) + 0.1; ToastNotificationManagerCompat.CreateToastNotifier().Update( new NotificationData(new Dictionary<string, string>() { { "progress", progress.ToString() } }), tag); } new ToastContentBuilder() .AddArgument("action", MyToastActions.ViewConversation) .AddArgument("conversationId", 423) .AddText("Sent image to conversation!") .Show(toast => { toast.Tag = tag; }); } } }
MainWindow
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml/Performance/Performance_ImageUpscaling.xaml.cs
{ "start": 355, "end": 618 }
partial class ____ : Page { public Performance_ImageUpscaling() { this.InitializeComponent(); Loaded += (s, e) => { colorStoryboard.Begin(); }; Unloaded += (s, e) => { colorStoryboard.Stop(); }; } } }
Performance_ImageUpscaling
csharp
dotnet__BenchmarkDotNet
src/BenchmarkDotNet.Disassembler.x64/DataContracts.cs
{ "start": 510, "end": 689 }
public class ____ : SourceCode { public string Text { get; set; } public string FilePath { get; set; } public int LineNumber { get; set; } }
Sharp
csharp
MassTransit__MassTransit
tests/MassTransit.HangfireIntegration.Tests/SchedulerLoadInMemory_Specs.cs
{ "start": 3414, "end": 3548 }
public class ____ : CorrelatedBy<Guid> { public Guid CorrelationId { get; set; } } } }
Stopped
csharp
unoplatform__uno
src/Uno.UI.RemoteControl/RemoteControlClient.cs
{ "start": 6996, "end": 7125 }
private record ____(RemoteControlClient Owner, Uri EndPoint, Stopwatch Since, WebSocket? Socket) : IAsyncDisposable {
Connection
csharp
AutoFixture__AutoFixture
Src/AutoFixture/DictionaryFiller.cs
{ "start": 348, "end": 3032 }
public class ____ : ISpecimenCommand { /// <summary> /// Adds many items to a dictionary. /// </summary> /// <param name="specimen">The dictionary to which items should be added.</param> /// <param name="context">The context which can be used to resolve other specimens.</param> /// <remarks> /// <para> /// This method mainly exists to support AutoFixture's infrastructure code (particularly /// <see cref="MultipleCustomization" /> and is not intended for use in user code. /// </para> /// </remarks> /// <exception cref="ArgumentException"> /// <paramref name="specimen"/> is not an instance of <see cref="IDictionary{TKey, TValue}" />. /// </exception> [EditorBrowsable(EditorBrowsableState.Never)] [Obsolete("Use the instance method Execute instead.", true)] public static void AddMany(object specimen, ISpecimenContext context) { new DictionaryFiller().Execute(specimen, context); } /// <summary> /// Adds many items to a dictionary. /// </summary> /// <param name="specimen">The dictionary to which items should be added.</param> /// <param name="context">The context which can be used to resolve other specimens.</param> /// <exception cref="ArgumentException"> /// <paramref name="specimen"/> is not an instance of <see cref="IDictionary{TKey, TValue}" />. /// </exception> public void Execute(object specimen, ISpecimenContext context) { if (specimen == null) throw new ArgumentNullException(nameof(specimen)); if (context == null) throw new ArgumentNullException(nameof(context)); var typeArguments = specimen.GetType().GetTypeInfo().GetGenericArguments(); if (typeArguments.Length != 2) throw new ArgumentException("The specimen must be an instance of IDictionary<TKey, TValue>.", nameof(specimen)); if (!typeof(IDictionary<,>).MakeGenericType(typeArguments).GetTypeInfo().IsAssignableFrom(specimen.GetType())) throw new ArgumentException("The specimen must be an instance of IDictionary<TKey, TValue>.", nameof(specimen)); var filler = (ISpecimenCommand)Activator.CreateInstance( typeof(Filler<,>).MakeGenericType(typeArguments)); filler.Execute(specimen, context); } [SuppressMessage("Microsoft.Performance", "CA1812:AvoidUninstantiatedInternalClasses", Justification = "It's activated via reflection.")]
DictionaryFiller