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
atata-framework__atata
src/Atata/Terms/Formatting/SnakeTermFormatter.cs
{ "start": 19, "end": 187 }
public class ____ : ITermFormatter { public string Format(string[] words, CultureInfo culture) => string.Join("_", words).ToLower(culture); }
SnakeTermFormatter
csharp
grandnode__grandnode2
src/Web/Grand.Web.Admin/Models/Messages/NewsletterCategoryModel.cs
{ "start": 1148, "end": 1517 }
public class ____ : ILocalizedModelLocal { [GrandResourceDisplayName("admin.marketing.NewsletterCategory.Fields.Name")] public string Name { get; set; } [GrandResourceDisplayName("admin.marketing.NewsletterCategory.Fields.Description")] public string Description { get; set; } public string LanguageId { get; set; } }
NewsletterCategoryLocalizedModel
csharp
files-community__Files
src/Files.App/Data/EventArguments/LayoutPreferenceEventArgs.cs
{ "start": 112, "end": 603 }
public sealed class ____ { public readonly bool IsAdaptiveLayoutUpdateRequired; public readonly LayoutPreferencesItem LayoutPreference; internal LayoutPreferenceEventArgs(LayoutPreferencesItem layoutPref) => LayoutPreference = layoutPref; internal LayoutPreferenceEventArgs(LayoutPreferencesItem layoutPref, bool isAdaptiveLayoutUpdateRequired) => (LayoutPreference, IsAdaptiveLayoutUpdateRequired) = (layoutPref, isAdaptiveLayoutUpdateRequired); } }
LayoutPreferenceEventArgs
csharp
SixLabors__Fonts
tests/SixLabors.Fonts.Tests/ImageComparison/ImageComparer.cs
{ "start": 198, "end": 2063 }
public abstract class ____ { public static ImageComparer Exact { get; } = Tolerant(0, 0); /// <summary> /// Returns an instance of <see cref="TolerantImageComparer"/>. /// Individual Manhattan pixel difference is only added to total image difference when the individual difference is over 'perPixelManhattanThreshold'. /// </summary> /// <param name="imageThreshold">The maximal tolerated difference represented by a value between 0 and 1.</param> /// <param name="perPixelManhattanThreshold">Gets the threshold of the individual pixels before they accumulate towards the overall difference.</param> /// <returns>A ImageComparer instance.</returns> public static ImageComparer Tolerant( float imageThreshold = TolerantImageComparer.DefaultImageThreshold, int perPixelManhattanThreshold = 0) => new TolerantImageComparer(imageThreshold, perPixelManhattanThreshold); /// <summary> /// Returns Tolerant(imageThresholdInPercent/100) /// </summary> /// <param name="imageThresholdInPercent">The maximal tolerated difference represented by a value between 0 and 100.</param> /// <param name="perPixelManhattanThreshold">Gets the threshold of the individual pixels before they accumulate towards the overall difference.</param> /// <returns>A ImageComparer instance.</returns> public static ImageComparer TolerantPercentage(float imageThresholdInPercent, int perPixelManhattanThreshold = 0) => Tolerant(imageThresholdInPercent / 100F, perPixelManhattanThreshold); public abstract ImageSimilarityReport<TPixelA, TPixelB> CompareImagesOrFrames<TPixelA, TPixelB>( int index, ImageFrame<TPixelA> expected, ImageFrame<TPixelB> actual) where TPixelA : unmanaged, IPixel<TPixelA> where TPixelB : unmanaged, IPixel<TPixelB>; }
ImageComparer
csharp
grpc__grpc-dotnet
src/Shared/Server/ServerDynamicAccessConstants.cs
{ "start": 842, "end": 1347 }
internal static class ____ { /// <summary> /// Specifies the member types that should be dynamically accessed for gRPC services. /// Includes public constructors, public methods, and non-public methods. /// </summary> internal const DynamicallyAccessedMemberTypes ServiceAccessibility = DynamicallyAccessedMemberTypes.PublicConstructors | DynamicallyAccessedMemberTypes.PublicMethods | DynamicallyAccessedMemberTypes.NonPublicMethods; }
ServerDynamicAccessConstants
csharp
cake-build__cake
src/Cake.Common.Tests/Unit/Build/AppVeyor/Data/AppVeyorProjectInfoTests.cs
{ "start": 775, "end": 1176 }
public sealed class ____ { [Fact] public void Should_Return_Correct_Value() { // Given var info = new AppVeyorInfoFixture().CreateProjectInfo(); // When var result = info.Name; // Then Assert.Equal("Cake", result); } }
TheNameProperty
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Email/EmailMailboxCapabilities.cs
{ "start": 305, "end": 14570 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal EmailMailboxCapabilities() { } #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 bool CanSmartSend { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanSmartSend is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanSmartSend"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanSmartSend"); } } #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 bool CanUpdateMeetingResponses { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanUpdateMeetingResponses is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanUpdateMeetingResponses"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanUpdateMeetingResponses"); } } #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 bool CanServerSearchMailbox { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanServerSearchMailbox is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanServerSearchMailbox"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanServerSearchMailbox"); } } #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 bool CanServerSearchFolders { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanServerSearchFolders is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanServerSearchFolders"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanServerSearchFolders"); } } #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 bool CanForwardMeetings { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanForwardMeetings is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanForwardMeetings"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanForwardMeetings"); } } #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 bool CanProposeNewTimeForMeetings { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanProposeNewTimeForMeetings is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanProposeNewTimeForMeetings"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanProposeNewTimeForMeetings"); } } #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 bool CanGetAndSetInternalAutoReplies { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanGetAndSetInternalAutoReplies is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanGetAndSetInternalAutoReplies"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanGetAndSetInternalAutoReplies"); } } #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 bool CanGetAndSetExternalAutoReplies { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanGetAndSetExternalAutoReplies is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanGetAndSetExternalAutoReplies"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanGetAndSetExternalAutoReplies"); } } #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 bool CanValidateCertificates { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanValidateCertificates is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanValidateCertificates"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanValidateCertificates"); } } #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 bool CanResolveRecipients { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanResolveRecipients is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanResolveRecipients"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanResolveRecipients"); } } #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 bool CanMoveFolder { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanMoveFolder is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanMoveFolder"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanMoveFolder"); } } #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 bool CanEmptyFolder { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanEmptyFolder is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanEmptyFolder"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanEmptyFolder"); } } #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 bool CanDeleteFolder { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanDeleteFolder is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanDeleteFolder"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanDeleteFolder"); } } #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 bool CanCreateFolder { get { throw new global::System.NotImplementedException("The member bool EmailMailboxCapabilities.CanCreateFolder is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20EmailMailboxCapabilities.CanCreateFolder"); } set { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.ApplicationModel.Email.EmailMailboxCapabilities", "bool EmailMailboxCapabilities.CanCreateFolder"); } } #endif // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanForwardMeetings.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanGetAndSetExternalAutoReplies.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanGetAndSetInternalAutoReplies.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanUpdateMeetingResponses.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanServerSearchFolders.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanServerSearchMailbox.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanProposeNewTimeForMeetings.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanSmartSend.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanResolveRecipients.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanValidateCertificates.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanEmptyFolder.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanCreateFolder.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanDeleteFolder.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanMoveFolder.get // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanForwardMeetings.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanGetAndSetExternalAutoReplies.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanGetAndSetInternalAutoReplies.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanUpdateMeetingResponses.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanServerSearchFolders.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanServerSearchMailbox.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanProposeNewTimeForMeetings.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanSmartSend.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanResolveRecipients.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanValidateCertificates.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanEmptyFolder.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanCreateFolder.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanDeleteFolder.set // Forced skipping of method Windows.ApplicationModel.Email.EmailMailboxCapabilities.CanMoveFolder.set } }
EmailMailboxCapabilities
csharp
unoplatform__uno
src/Uno.UI.Tests/Windows_UI_XAML_Controls/ContentDialogTests/Given_ContentDialog.cs
{ "start": 287, "end": 786 }
public class ____ { [TestInitialize] public void Init() { UnitTestsApp.App.EnsureApplication(); } [TestMethod] public void When_Has_DataContext() { var dc = "Starfish"; var border = new Border(); var dialog = new ContentDialog { DataContext = dc, Content = border }; dialog.ForceLoaded(); Assert.AreEqual("Starfish", dialog.DataContext); var dummy = dialog.ShowAsync(); Assert.AreEqual("Starfish", border.DataContext); } } }
Given_ContentDialog
csharp
nunit__nunit
src/NUnitFramework/framework/Constraints/EqualStringWithoutUsingConstraint.cs
{ "start": 522, "end": 6052 }
public class ____ : Constraint { #region Static and Instance Fields private readonly string? _expected; private bool _caseInsensitive; private bool _ignoringWhiteSpace; private bool _ignoreLineEndingFormat; private bool _clipStrings; #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="EqualConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public EqualStringWithoutUsingConstraint(string? expected) : base(expected) { _expected = expected; _clipStrings = true; } #endregion /// <summary> /// Gets the expected value. /// </summary> public string? Expected => _expected; #region Constraint Modifiers /// <summary> /// Flag the constraint to ignore case and return self. /// </summary> public EqualStringWithoutUsingConstraint IgnoreCase { get { _caseInsensitive = true; return this; } } /// <summary> /// Flag the constraint to ignore white space and return self. /// </summary> public EqualStringWithoutUsingConstraint IgnoreWhiteSpace { get { _ignoringWhiteSpace = true; return this; } } /// <summary> /// Flag the constraint to ignore line ending format (\r vs. \n vs. \r\n) and return self. /// </summary> public EqualStringWithoutUsingConstraint IgnoreLineEndingFormat { get { _ignoreLineEndingFormat = true; return this; } } /// <summary> /// Flag the constraint to suppress string clipping /// and return self. /// </summary> public EqualStringWithoutUsingConstraint NoClip { get { _clipStrings = false; return this; } } #endregion #region Public Methods /// <summary> /// Test whether the constraint is satisfied by a given value /// </summary> /// <param name="actual">The value to be tested</param> /// <returns>True for success, false for failure</returns> public ConstraintResult ApplyTo(string? actual) { bool hasSucceeded; if (actual is null) { hasSucceeded = _expected is null; } else if (_expected is null) { hasSucceeded = false; } else { hasSucceeded = StringsComparer.Equals(_expected, actual, _caseInsensitive, _ignoringWhiteSpace, _ignoreLineEndingFormat); } return ConstraintResult(actual, hasSucceeded); } /// <inheritdoc/> /// <remarks> /// I wish we could hide this method, but it is public in the base class. /// </remarks> public sealed override ConstraintResult ApplyTo<TActual>(TActual actual) { bool hasSucceeded; if (actual is null) { hasSucceeded = _expected is null; } else if (actual is string actualString) { return ApplyTo(actualString); } else if (actual is IEquatable<string> equatableString) { if (_caseInsensitive || _ignoringWhiteSpace || _ignoreLineEndingFormat) { throw new InvalidOperationException("Cannot use IgnoreCase or IgnoreWhiteSpace or IgnoreLineEndingFormat with IEquatable<string>."); } hasSucceeded = equatableString.Equals(_expected); } else if (_expected is null) { hasSucceeded = false; } else { // We fall back to pre 4.3 EqualConstraint behavior // But if the actual value cannot be convert to a string nor can be compared to one // not sure if that makes any difference. return new EqualConstraint(_expected).ApplyTo(actual); } return ConstraintResult(actual, hasSucceeded); } private ConstraintResult ConstraintResult<T>(T actual, bool hasSucceeded) { return new EqualConstraintResult(this, actual, _caseInsensitive, _ignoringWhiteSpace, _ignoreLineEndingFormat, _clipStrings, hasSucceeded); } /// <summary> /// The Description of what this constraint tests, for /// use in messages and in the ConstraintResult. /// </summary> public override string Description { get { var sb = new StringBuilder(MsgUtils.FormatValue(_expected)); if (_caseInsensitive) sb.Append(", ignoring case"); if (_ignoringWhiteSpace) sb.Append(", ignoring white-space"); if (_ignoreLineEndingFormat) sb.Append(", ignoring line ending format"); return sb.ToString(); } } #endregion } }
EqualStringWithoutUsingConstraint
csharp
nunit__nunit
src/NUnitFramework/tests/Internal/TypeHelperTests.cs
{ "start": 2404, "end": 2991 }
public class ____<T3, T4> { } } #endregion #region FullName [Test] public void TestValidFullName() { Type type = typeof(TypeHelperTests); Assert.That(type.FullName(), Is.EqualTo(type.FullName)); } [Test] public void TestInvalidFullName() { Type type = typeof(Generic<>).GetGenericArguments()[0]; Assert.That(type.FullName, Is.Null); Assert.That(() => type.FullName(), Throws.InvalidOperationException); }
D
csharp
EventStore__EventStore
src/KurrentDB.Projections.Core.Tests/Services/Jint/when_defining_a_js_projection.cs
{ "start": 7901, "end": 8599 }
public class ____ : TestFixtureWithInterpretedProjection { protected override void Given() { _projection = @" fromAll().when({ some: function(state, event) { return state; } }).filterBy(function(s) {return true;}); "; _state = @"{""count"": 0}"; } [Test, Category(_projectionType)] public void source_definition_is_correct() { var expected = SourceDefinitionBuilder.From(b => { b.FromAll(); b.IncludeEvent("some"); b.SetDefinesStateTransform(); b.SetOutputState(); }); AssertEx.AreEqual(expected, _source); } }
with_filter_by
csharp
dotnet__aspnetcore
src/Hosting/Server.IntegrationTesting/src/Common/RetryHelper.cs
{ "start": 276, "end": 3063 }
public class ____ { /// <summary> /// Retries every 1 sec for 60 times by default. /// </summary> /// <param name="retryBlock"></param> /// <param name="logger"></param> /// <param name="cancellationToken"></param> /// <param name="retryCount"></param> public static async Task<HttpResponseMessage> RetryRequest( Func<Task<HttpResponseMessage>> retryBlock, ILogger logger, CancellationToken cancellationToken = default, int retryCount = 60) { for (var retry = 0; retry < retryCount; retry++) { if (cancellationToken.IsCancellationRequested) { logger.LogInformation("Failed to connect, retry canceled."); throw new OperationCanceledException("Failed to connect, retry canceled.", cancellationToken); } try { logger.LogWarning("Retry count {retryCount}..", retry + 1); var response = await retryBlock().ConfigureAwait(false); if (response.StatusCode == HttpStatusCode.ServiceUnavailable) { // Automatically retry on 503. May be application is still booting. logger.LogWarning("Retrying a service unavailable error."); continue; } return response; // Went through successfully } catch (Exception exception) { if (retry == retryCount - 1) { logger.LogError(0, exception, "Failed to connect, retry limit exceeded."); throw; } else { if (exception is HttpRequestException || exception is WebException) { logger.LogWarning("Failed to complete the request : {0}.", exception.Message); await Task.Delay(1 * 1000); //Wait for a while before retry. } } } } logger.LogInformation("Failed to connect, retry limit exceeded."); throw new OperationCanceledException("Failed to connect, retry limit exceeded."); } public static void RetryOperation( Action retryBlock, Action<Exception> exceptionBlock, int retryCount = 3, int retryDelayMilliseconds = 0) { for (var retry = 0; retry < retryCount; ++retry) { try { retryBlock(); break; } catch (Exception exception) { exceptionBlock(exception); } Thread.Sleep(retryDelayMilliseconds); } } }
RetryHelper
csharp
louthy__language-ext
LanguageExt.Tests/Transformer/Traverse/Arr/Sync/Validation.cs
{ "start": 175, "end": 1512 }
public class ____ { [Fact] public void FailIsSingletonFail() { var ma = Fail<Error, Arr<int>>(Error.New("alt")); var mb = ma.KindT<Validation<Error>, Arr, Arr<int>, int>() .SequenceM() .AsT<Arr, Validation<Error>, Validation<Error, int>, int>() .As(); var mc = Array(Fail<Error, int>(Error.New("alt"))); Assert.True(mb == mc); } [Fact] public void SuccessEmptyIsEmpty() { var ma = Success<Error, Arr<int>>(Empty); var mb = ma.KindT<Validation<Error>, Arr, Arr<int>, int>() .SequenceM() .AsT<Arr, Validation<Error>, Validation<Error, int>, int>() .As(); var mc = Array<Validation<Error, int>>(); Assert.True(mb == mc); } [Fact] public void SuccessNonEmptyArrIsArrSuccesses() { var ma = Success<Error, Arr<int>>(Array(1, 2, 3, 4)); var mb = ma.KindT<Validation<Error>, Arr, Arr<int>, int>() .SequenceM() .AsT<Arr, Validation<Error>, Validation<Error, int>, int>() .As(); var mc = Array(Success<Error, int>(1), Success<Error, int>(2), Success<Error, int>(3), Success<Error, int>(4)); Assert.True(mb == mc); } }
ValidationArr
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 337057, "end": 337277 }
public class ____ { public int Id { get; set; } public RelatedEntity1546 ParentEntity { get; set; } public IEnumerable<RelatedEntity1548> ChildEntities { get; set; } }
RelatedEntity1547
csharp
ServiceStack__ServiceStack
ServiceStack.Blazor/tests/UI.Gallery/Gallery.Server/ServiceInterface/FormServices.cs
{ "start": 83, "end": 182 }
public class ____ : Service { public object Any(ComboBoxExamples request) => request; }
FormServices
csharp
dotnet__orleans
test/Grains/TestGrainInterfaces/EventSourcing/IAccountGrain.cs
{ "start": 1243, "end": 1414 }
public class ____ : Transaction { [Id(0)] public uint DepositAmount { get; set; } } [Serializable] [GenerateSerializer]
DepositTransaction
csharp
domaindrivendev__Swashbuckle.AspNetCore
test/Swashbuckle.AspNetCore.Newtonsoft.Test/Fixtures/AdditionalPropertyJsonContractResolver.cs
{ "start": 113, "end": 289 }
public class ____ : DefaultContractResolver { public const string AdditionalPropertyName = "AdditionalPropertyFromContractResolver";
AdditionalPropertyJsonContractResolver
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Services/Tax/TaxCategoryService.cs
{ "start": 128, "end": 2614 }
public partial class ____ : ITaxCategoryService { #region Fields protected readonly IRepository<TaxCategory> _taxCategoryRepository; #endregion #region Ctor public TaxCategoryService(IRepository<TaxCategory> taxCategoryRepository) { _taxCategoryRepository = taxCategoryRepository; } #endregion #region Methods /// <summary> /// Deletes a tax category /// </summary> /// <param name="taxCategory">Tax category</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task DeleteTaxCategoryAsync(TaxCategory taxCategory) { await _taxCategoryRepository.DeleteAsync(taxCategory); } /// <summary> /// Gets all tax categories /// </summary> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the ax categories /// </returns> public virtual async Task<IList<TaxCategory>> GetAllTaxCategoriesAsync() { var taxCategories = await _taxCategoryRepository.GetAllAsync(query => { return from tc in query orderby tc.DisplayOrder, tc.Id select tc; }, cache => default); return taxCategories; } /// <summary> /// Gets a tax category /// </summary> /// <param name="taxCategoryId">Tax category identifier</param> /// <returns> /// A task that represents the asynchronous operation /// The task result contains the ax category /// </returns> public virtual async Task<TaxCategory> GetTaxCategoryByIdAsync(int taxCategoryId) { return await _taxCategoryRepository.GetByIdAsync(taxCategoryId, cache => default); } /// <summary> /// Inserts a tax category /// </summary> /// <param name="taxCategory">Tax category</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task InsertTaxCategoryAsync(TaxCategory taxCategory) { await _taxCategoryRepository.InsertAsync(taxCategory); } /// <summary> /// Updates the tax category /// </summary> /// <param name="taxCategory">Tax category</param> /// <returns>A task that represents the asynchronous operation</returns> public virtual async Task UpdateTaxCategoryAsync(TaxCategory taxCategory) { await _taxCategoryRepository.UpdateAsync(taxCategory); } #endregion }
TaxCategoryService
csharp
MassTransit__MassTransit
src/MassTransit/SagaStateMachine/MassTransitStateMachine.cs
{ "start": 96224, "end": 96989 }
class ____<TStateMachine> : StateMachineRegistration where TStateMachine : MassTransitStateMachine<TInstance> { readonly PropertyInfo _propertyInfo; public TriggerEventRegistration(PropertyInfo propertyInfo) { _propertyInfo = propertyInfo; } public void Declare(object stateMachine) { var machine = (TStateMachine)stateMachine; var existing = _propertyInfo.GetValue(machine); if (existing != null) return; machine.DeclarePropertyBasedEvent(prop => machine.DeclareTriggerEvent(prop.Name), _propertyInfo); } }
TriggerEventRegistration
csharp
moq__moq4
src/Moq.Tests/ActionObserverFixture.cs
{ "start": 9911, "end": 10574 }
public interface ____ { IY this[int index] { get; set; } int this[int index1, int index2] { get; set; } IY GetY(); IY GetY(int arg); void Void(); void VoidWithShort(short arg); void VoidWithInt(int arg); void VoidWithLong(long arg); void VoidWithNullableInt(int? arg); void VoidWithIntString(int arg1, string arg2); void VoidWithObject(object arg); void VoidWithEnum(Color arg); void VoidWithNullableEnum(Color? arg); }
IX
csharp
microsoft__PowerToys
src/modules/cmdpal/ext/ProcessMonitorExtension/ProcessItem.cs
{ "start": 248, "end": 537 }
internal sealed class ____ { internal Process Process { get; init; } internal int ProcessId { get; init; } internal string Name { get; init; } internal string ExePath { get; init; } internal long Memory { get; init; } internal long CPU { get; init; } }
ProcessItem
csharp
dotnet__maui
src/Controls/samples/Controls.Sample/Pages/Core/GesturesPage.xaml.cs
{ "start": 41, "end": 140 }
public partial class ____ { public GesturesPage() { InitializeComponent(); } } }
GesturesPage
csharp
fluentassertions__fluentassertions
Tests/FluentAssertions.Equivalency.Specs/SelectionRulesSpecs.Interfaces.cs
{ "start": 5121, "end": 5698 }
interface ____ // Act Action action = () => subject.Should().BeEquivalentTo(expected, opt => opt.ExcludingMissingMembers()); // Assert action.Should().Throw<XunitException>(); } [Fact] public void When_respecting_declared_types_explicit_interface_member_on_interfaced_expectation_should_be_used() { // Arrange IVehicle expected = new ExplicitVehicle { VehicleId = 2 // instance member }; expected.VehicleId = 1; //
member
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.Misc.RFQ/Models/Admin/RequestQuoteModel.cs
{ "start": 224, "end": 1593 }
public record ____ : BaseNopEntityModel { public int CustomerId { get; set; } [NopResourceDisplayName("Plugins.Misc.RFQ.Fields.CustomerEmail")] public string CustomerEmail { get; set; } [NopResourceDisplayName("Plugins.Misc.RFQ.Fields.RequestQuote.CreatedOn")] public DateTime CreatedOnUtc { get; set; } [NopResourceDisplayName("Plugins.Misc.RFQ.Fields.RequestQuote.Status")] public string Status { get; set; } public RequestQuoteStatus StatusType { get; set; } [NopResourceDisplayName("Plugins.Misc.RFQ.Fields.CustomerNotes")] public string CustomerNotes { get; set; } [NopResourceDisplayName("Plugins.Misc.RFQ.Fields.QuoteId")] public int? QuoteId { get; set; } [NopResourceDisplayName("Plugins.Misc.RFQ.Fields.AdminNotes")] public string AdminNotes { get; set; } public bool DisplaySaveButtons => StatusType != RequestQuoteStatus.Canceled && StatusType != RequestQuoteStatus.QuoteIsCreated; public bool DisplayDeleteRequestButton => StatusType != RequestQuoteStatus.QuoteIsCreated; public bool DisplayCreateQuoteButton => DisplaySaveButtons; public bool DisplayCancelRequestButton => StatusType != RequestQuoteStatus.Canceled && StatusType != RequestQuoteStatus.QuoteIsCreated; public List<RequestQuoteItemModel> Items { get; set; } }
RequestQuoteModel
csharp
cake-build__cake
src/Cake.Common/Tools/DotNet/Workload/Search/DotNetWorkload.cs
{ "start": 329, "end": 1012 }
public class ____ { /// <summary> /// Initializes a new instance of the <see cref="DotNetWorkload" /> class. /// </summary> /// <param name="id">The workload Id.</param> /// <param name="description">The workload description.</param> public DotNetWorkload(string id, string description) { Id = id; Description = description; } /// <summary> /// Gets the workload Id. /// </summary> public string Id { get; } /// <summary> /// Gets the workload description. /// </summary> public string Description { get; } } }
DotNetWorkload
csharp
dotnet__maui
src/Controls/src/Core/Internals/ProfilePage.cs
{ "start": 1678, "end": 4600 }
public static class ____ { const long MS = TimeSpan.TicksPerMillisecond; /// <include file="../../../docs/Microsoft.Maui.Controls.Internals/ContentPageEx.xml" path="//Member[@MemberName='Data']/Docs/*" /> public static List<ProfileDatum> Data = new List<ProfileDatum>(); private static void ASSERT(bool condition) { if (!condition) throw new Exception("assert"); } private static long GatherTicks(ref int i) { var current = Data[i++]; var depth = current.Depth; var total = current.Ticks; while (i < Data.Count) { var next = Data[i]; if (next.Depth < depth) break; if (next.Depth > depth) { current.SubTicks = GatherTicks(ref i); ASSERT(current.Ticks >= current.SubTicks); continue; } i++; current = next; total += current.Ticks; } return total; } private static void AppendProfile(StringBuilder sb, long profiledMs, bool showZeros) { foreach (var datum in Data) { var depth = datum.Depth; var name = datum.Name; if (datum.Id != null) name += $" ({datum.Id})"; var ticksMs = datum.Ticks / MS; var exclusiveTicksMs = (datum.Ticks - datum.SubTicks) / MS; var percentage = (int)Math.Round(ticksMs / (double)profiledMs * 100); if (!showZeros && percentage == 0) continue; var line = $"{name} = {ticksMs}ms"; if (exclusiveTicksMs != ticksMs) line += $" ({exclusiveTicksMs}ms)"; line += $", {percentage}%"; sb.AppendLine("".PadLeft(depth * 2) + line); } } /// <param name="page">The page parameter.</param> public static void LoadProfile(this ContentPage page) { Profile.Stop(); foreach (var datum in Profile.Data) { Data.Add(new ProfileDatum() { Name = datum.Name, Id = datum.Id, Depth = datum.Depth, Ticks = datum.Ticks < 0 ? 0L : (long)datum.Ticks }); } var i = 0; var profiledMs = GatherTicks(ref i) / MS; var scrollView = new ScrollView(); var label = new Label(); var controls = new Grid(); var buttonA = new Button() { Text = "0s", HeightRequest = 62 }; controls.Add(buttonA); var grid = new Grid { RowDefinitions = new RowDefinitionCollection { new RowDefinition { Height = new GridLength(1, GridUnitType.Star) }, new RowDefinition { Height = GridLength.Auto }, }, ColumnDefinitions = new ColumnDefinitionCollection { new ColumnDefinition { Width = GridLength.Star }, } }; page.Content = grid; grid.Add(scrollView, 0, 0); grid.Add(controls, 0, 1); scrollView.Content = label; var showZeros = false; Action update = delegate () { var sb = new StringBuilder(); sb.AppendLine($"Profiled: {profiledMs}ms"); AppendProfile(sb, profiledMs, showZeros); label.Text = sb.ToString(); }; buttonA.Clicked += delegate { showZeros = !showZeros; update(); }; update(); } } }
ContentPageEx
csharp
jellyfin__jellyfin
tests/Jellyfin.Server.Integration.Tests/Controllers/BaseJellyfinTestController.cs
{ "start": 305, "end": 387 }
public class ____ : BaseJellyfinApiController { } }
BaseJellyfinTestController
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/SnapPointsType.cs
{ "start": 54, "end": 197 }
public enum ____ { None, [NotImplemented] Optional, Mandatory, [NotImplemented] OptionalSingle, MandatorySingle, } }
SnapPointsType
csharp
dotnet__efcore
test/EFCore.Specification.Tests/Query/AdHocNavigationsQueryTestBase.cs
{ "start": 42765, "end": 44080 }
protected class ____(DbContextOptions options) : DbContext(options) { protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<PrincipalOneToOne>().Navigation(e => e.Dependent).AutoInclude(); modelBuilder.Entity<DependentOneToOne>().Navigation(e => e.Principal).AutoInclude(); modelBuilder.Entity<PrincipalOneToMany>().Navigation(e => e.Dependents).AutoInclude(); modelBuilder.Entity<DependentOneToMany>().Navigation(e => e.Principal).AutoInclude(); modelBuilder.Entity<PrincipalManyToMany>().Navigation(e => e.Dependents).AutoInclude(); modelBuilder.Entity<DependentManyToMany>().Navigation(e => e.Principals).AutoInclude(); modelBuilder.Entity<CycleA>().Navigation(e => e.Bs).AutoInclude(); modelBuilder.Entity<CycleB>().Navigation(e => e.C).AutoInclude(); modelBuilder.Entity<CycleC>().Navigation(e => e.As).AutoInclude(); } public Task SeedAsync() { Add(new PrincipalOneToOne { Dependent = new DependentOneToOne() }); Add( new PrincipalOneToMany { Dependents = [new DependentOneToMany(), new DependentOneToMany()] }); return SaveChangesAsync(); }
Context22568
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/SimpleContainer.cs
{ "start": 3704, "end": 5739 }
public static class ____ { public static T Resolve<T>(this IResolver container) { var ret = container is IRequest req ? req.TryResolve<T>() : container.TryResolve<T>(); if (ret == null) throw new Exception($"Error trying to resolve Service '{typeof(T).Name}' or one of its autowired dependencies."); return ret; } public static T Resolve<T>(this IContainer container) => (T)container.Resolve(typeof(T)); public static bool Exists<T>(this IContainer container) => container.Exists(typeof(T)); public static IContainer AddTransient<TService>(this IContainer container) => container.AddTransient(typeof(TService), container.CreateFactory(typeof(TService))); public static IContainer AddTransient<TService>(this IContainer container, Func<TService> factory) => container.AddTransient(typeof(TService), () => factory()); public static IContainer AddTransient<TService, TImpl>(this IContainer container) where TImpl : TService => container.AddTransient(typeof(TService), container.CreateFactory(typeof(TImpl))); public static IContainer AddTransient(this IContainer container, Type type) => container.AddTransient(type, container.CreateFactory(type)); public static IContainer AddSingleton<TService>(this IContainer container) => container.AddSingleton(typeof(TService), container.CreateFactory(typeof(TService))); public static IContainer AddSingleton<TService>(this IContainer container, Func<TService> factory) => container.AddSingleton(typeof(TService), () => factory()); public static IContainer AddSingleton<TService, TImpl>(this IContainer container) where TImpl : TService => container.AddSingleton(typeof(TService), container.CreateFactory(typeof(TImpl))); public static IContainer AddSingleton(this IContainer container, Type type) => container.AddSingleton(type, container.CreateFactory(type)); }
ContainerExtensions
csharp
EventStore__EventStore
src/KurrentDB.Projections.Core.Tests/Services/Jint/when_defining_a_js_projection.cs
{ "start": 3067, "end": 3800 }
public class ____ : TestFixtureWithInterpretedProjection { protected override void Given() { _projection = @" fromCategories(['category1', 'category2', 'category3']).when({ $any: function(state, event) { return state; }}); "; _state = @"{""count"": 0}"; } [Test, Category(_projectionType)] public void source_definition_is_correct() { var expected = SourceDefinitionBuilder.From(b => { b.AllEvents(); b.FromStream("$ce-category1"); b.FromStream("$ce-category2"); b.FromStream("$ce-category3"); }); AssertEx.AreEqual(expected, _source); } } [TestFixture]
with_multiple_from_categories
csharp
protobuf-net__protobuf-net
src/protobuf-net.Test/CompatibilityLevelAmbientAutoTupleTests.cs
{ "start": 7574, "end": 7936 }
public class ____ { [ProtoMember(1)] [CompatibilityLevel(CompatibilityLevel.Level300)] public (DateTime, TimeSpan) Value { get; set; } [ProtoMember(2)] public List<(DateTime, TimeSpan)> List { get; } = new List<(DateTime, TimeSpan)>(); } [ProtoContract]
HybridInvalidModel
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.Catalog/Areas/Catalog/ViewModels/CategoryMenuItem.cs
{ "start": 106, "end": 658 }
public class ____ { public CategoryMenuItem() { ChildItems = new List<CategoryMenuItem>(); } public long Id { get; set; } public string Name { get; set; } public string Slug { get; set; } public CategoryMenuItem Parent { get; set; } public IList<CategoryMenuItem> ChildItems { get; set; } public void AddChildItem(CategoryMenuItem childItem) { childItem.Parent = this; ChildItems.Add(childItem); } } }
CategoryMenuItem
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs
{ "start": 93437, "end": 93558 }
public interface ____ { UniTask OnTransformParentChangedAsync(); }
IAsyncOnTransformParentChangedHandler
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Commands/EvaluateCommand.cs
{ "start": 1562, "end": 3370 }
public enum ____ { Maximize, Minimize, Info, } public readonly string LoadName; public readonly bool IsVector; public readonly Objective MetricTarget; public readonly string Name; public readonly bool CanBeWeighted; private readonly Regex _loadNamePattern; private readonly string _groupName; private readonly string _nameFormat; public MetricColumn(string loadName, string name, Objective target = Objective.Maximize, bool canBeWeighted = true, bool isVector = false, Regex namePattern = null, string groupName = null, string nameFormat = null) { Contracts.CheckValue(loadName, nameof(loadName)); Contracts.CheckValue(name, nameof(name)); LoadName = loadName; Name = name; MetricTarget = target; CanBeWeighted = canBeWeighted; IsVector = isVector; _loadNamePattern = namePattern; _groupName = groupName; _nameFormat = nameFormat; } public string GetNameMatch(string input) { if (_loadNamePattern == null) { if (input.Equals(LoadName, StringComparison.OrdinalIgnoreCase) || (CanBeWeighted && input == "Weighted" + LoadName)) return Name; return null; } if (string.IsNullOrEmpty(_groupName) || string.IsNullOrEmpty(_nameFormat)) return null; var match = _loadNamePattern.Match(input); if (!match.Success) return null; var s = match.Groups[_groupName]; return string.Format(_nameFormat, s); } } // REVIEW: Move this
Objective
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Core/WindowSizeChangedEventArgs.cs
{ "start": 250, "end": 755 }
public partial class ____ : global::Windows.UI.Core.ICoreWindowEventArgs { // Skipping already declared property Handled // Skipping already declared property Size // Forced skipping of method Windows.UI.Core.WindowSizeChangedEventArgs.Size.get // Forced skipping of method Windows.UI.Core.WindowSizeChangedEventArgs.Handled.get // Forced skipping of method Windows.UI.Core.WindowSizeChangedEventArgs.Handled.set // Processing: Windows.UI.Core.ICoreWindowEventArgs } }
WindowSizeChangedEventArgs
csharp
dotnet__orleans
src/Orleans.Runtime/Catalog/ActivationData.cs
{ "start": 78649, "end": 78884 }
public sealed class ____(Dictionary<string, object>? requestContext, CancellationTokenSource cts) : Command(cts) { public Dictionary<string, object>? RequestContext { get; } = requestContext; }
Activate
csharp
dotnet__maui
src/Templates/src/templates/maui-mobile/Resources/Fonts/FluentUI.cs
{ "start": 115, "end": 253 }
class ____ 'public' in order to use it outside its assembly // you should also change the fields from 'const' to 'public static readonly'
to
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/ContainerTests/Common_Tests/RequestClientOutbox_Specs.cs
{ "start": 5073, "end": 5389 }
class ____ : IConsumer<ActivityRequest> { public Task Consume(ConsumeContext<ActivityRequest> context) { return context.RespondAsync<ActivityResponse>(new { Value = $"Hello, {context.Message.Value}" }); } }
ActivityRequestConsumer
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Specs/Infrastructure/ReflectionHelper.cs
{ "start": 121, "end": 385 }
public class ____ { public static MethodInfo GetMethod(Expression<Action> methodCall) { var methodCallExpression = (MethodCallExpression) methodCall.Body; return methodCallExpression.Method; } } }
ReflectionHelper
csharp
SixLabors__ImageSharp
src/ImageSharp/Formats/Tiff/PhotometricInterpretation/BlackIsZeroTiffColor{TPixel}.cs
{ "start": 475, "end": 1567 }
internal class ____<TPixel> : TiffBaseColorDecoder<TPixel> where TPixel : unmanaged, IPixel<TPixel> { private readonly ushort bitsPerSample0; private readonly float factor; public BlackIsZeroTiffColor(TiffBitsPerSample bitsPerSample) { this.bitsPerSample0 = bitsPerSample.Channel0; this.factor = (1 << this.bitsPerSample0) - 1f; } /// <inheritdoc/> public override void Decode(ReadOnlySpan<byte> data, Buffer2D<TPixel> pixels, int left, int top, int width, int height) { BitReader bitReader = new(data); for (int y = top; y < top + height; y++) { Span<TPixel> pixelRow = pixels.DangerousGetRowSpan(y).Slice(left, width); for (int x = 0; x < pixelRow.Length; x++) { int value = bitReader.ReadBits(this.bitsPerSample0); float intensity = value / this.factor; pixelRow[x] = TPixel.FromScaledVector4(new Vector4(intensity, intensity, intensity, 1f)); } bitReader.NextRow(); } } }
BlackIsZeroTiffColor
csharp
RicoSuter__NJsonSchema
src/NJsonSchema.CodeGeneration.TypeScript/Models/EnumTemplateModel.cs
{ "start": 603, "end": 1398 }
public class ____ { private readonly JsonSchema _schema; private readonly TypeScriptGeneratorSettings _settings; /// <summary>Initializes a new instance of the <see cref="EnumTemplateModel" /> class.</summary> /// <param name="typeName">Name of the type.</param> /// <param name="schema">The schema.</param> /// <param name="settings">The settings.</param> public EnumTemplateModel(string typeName, JsonSchema schema, TypeScriptGeneratorSettings settings) { _schema = schema; _settings = settings; Name = typeName; } /// <summary>Gets the name of the enum.</summary> public string Name { get; } /// <summary>Gets a value indicating whether the
EnumTemplateModel
csharp
dotnet__aspnetcore
src/Http/Owin/src/OwinConstants.cs
{ "start": 2130, "end": 3339 }
internal static class ____ { public const string ClientCertificate = "ssl.ClientCertificate"; public const string LoadClientCertAsync = "ssl.LoadClientCertAsync"; public const string RemoteIpAddress = "server.RemoteIpAddress"; public const string RemotePort = "server.RemotePort"; public const string LocalIpAddress = "server.LocalIpAddress"; public const string LocalPort = "server.LocalPort"; public const string ConnectionId = "server.ConnectionId"; public const string TraceOutput = "host.TraceOutput"; public const string Addresses = "host.Addresses"; public const string AppName = "host.AppName"; public const string Capabilities = "server.Capabilities"; public const string OnSendingHeaders = "server.OnSendingHeaders"; public const string OnAppDisposing = "host.OnAppDisposing"; public const string Scheme = "scheme"; public const string Host = "host"; public const string Port = "port"; public const string Path = "path"; } #endregion #region SendFiles v0.3.0 // http://owin.org/spec/extensions/owin-SendFile-Extension-v0.3.0.htm
CommonKeys
csharp
rabbitmq__rabbitmq-dotnet-client
projects/Test/OAuth2/TestCredentialsRefresher.cs
{ "start": 2658, "end": 6049 }
public class ____ { private readonly ITestOutputHelper _testOutputHelper; public TestCredentialsRefresher(ITestOutputHelper testOutputHelper) { _testOutputHelper = testOutputHelper; } [Fact] public async Task TestRefreshToken() { var expectedValidUntil = TimeSpan.FromSeconds(1); var tcs = new TaskCompletionSource<Credentials>(TaskCreationOptions.RunContinuationsAsynchronously); var credentialsProvider = new MockCredentialsProvider(_testOutputHelper, expectedValidUntil); Task cb(Credentials? argCreds, Exception? ex, CancellationToken argToken) { if (argCreds is null) { tcs.SetException(new NullReferenceException("argCreds is null, huh?")); } else { tcs.SetResult(argCreds); } return Task.CompletedTask; } Credentials credentials; using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5))) { using (CancellationTokenRegistration ctr = cts.Token.Register(() => tcs.TrySetCanceled())) { var credentialRefresher = new CredentialsRefresher(credentialsProvider, cb, cts.Token); credentials = await tcs.Task; } } Assert.Equal(nameof(MockCredentialsProvider), credentials.Name); Assert.Equal("guest", credentials.UserName); Assert.Equal("guest", credentials.Password); Assert.Equal(expectedValidUntil, credentials.ValidUntil); } [Fact] public async Task TestRefreshTokenFailed() { string exceptionMessage = nameof(TestCredentialsRefresher); var expectedException = new Exception(exceptionMessage); var expectedValidUntil = TimeSpan.FromSeconds(1); var tcs = new TaskCompletionSource<Credentials?>(TaskCreationOptions.RunContinuationsAsynchronously); var credentialsProvider = new MockCredentialsProvider(_testOutputHelper, expectedValidUntil, expectedException); ushort callbackCount = 0; Task cb(Credentials? argCreds, Exception? ex, CancellationToken argToken) { callbackCount++; if (ex != null) { tcs.SetException(ex); } return Task.CompletedTask; } Credentials? credentials = null; using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(5))) { using (CancellationTokenRegistration ctr = cts.Token.Register(() => tcs.TrySetCanceled())) { var credentialRefresher = new CredentialsRefresher(credentialsProvider, cb, cts.Token); try { credentials = await tcs.Task; } catch (Exception ex) { Assert.Same(expectedException, ex); } } } Assert.Null(credentials); Assert.Equal(1, callbackCount); } } }
TestCredentialsRefresher
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests.Provider.GBase/GBase/GBaseExpression/ConvertTest.cs
{ "start": 909, "end": 6155 }
class ____ { public int Id { get; set; } public string Name { get; set; } public List<TestTypeInfo> Types { get; set; } } [Fact] public void ToBoolean() { var data = new List<object>(); //data.Add(select.Where(a => (Convert.ToBoolean(a.Clicks) ? 1 : 0) > 0).ToList()); //data.Add(select.Where(a => (bool.Parse(a.Clicks.ToString()) ? 1 : 0) > 0).ToList()); } [Fact] public void ToByte() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToByte(a.Clicks % 255) > 0).ToList()); data.Add(select.Where(a => byte.Parse((a.Clicks % 255).ToString()) > 0).ToList()); } [Fact] public void ToChar() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToChar(a.Clicks) == '1').ToList()); data.Add(select.Where(a => char.Parse(a.Clicks.ToString()) == '1').ToList()); } [Fact] public void ToDateTime() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToDateTime(a.CreateTime.ToString()).Year > 0).ToList()); data.Add(select.Where(a => DateTime.Parse(a.CreateTime.ToString()).Year > 0).ToList()); } [Fact] public void ToDecimal() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToDecimal(a.Clicks) > 0).ToList()); data.Add(select.Where(a => decimal.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void ToDouble() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToDouble(a.Clicks) > 0).ToList()); data.Add(select.Where(a => double.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void ToInt16() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToInt16(a.Clicks) > 0).ToList()); data.Add(select.Where(a => short.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void ToInt32() { var data = new List<object>(); data.Add(select.Where(a => (int)a.Clicks > 0).ToList()); data.Add(select.Where(a => Convert.ToInt32(a.Clicks) > 0).ToList()); data.Add(select.Where(a => int.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void ToInt64() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToInt64(a.Clicks) > 0).ToList()); data.Add(select.Where(a => long.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void ToSByte() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToSByte(a.Clicks % 128) > 0).ToList()); data.Add(select.Where(a => sbyte.Parse((a.Clicks % 128).ToString()) > 0).ToList()); } [Fact] public void ToSingle() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToSingle(a.Clicks) > 0).ToList()); data.Add(select.Where(a => float.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void this_ToString() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToString(a.Clicks).Equals("")).ToList()); data.Add(select.Where(a => a.Clicks.ToString().Equals("")).ToList()); } [Fact] public void ToUInt16() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToUInt16(a.Clicks) > 0).ToList()); data.Add(select.Where(a => ushort.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void ToUInt32() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToUInt32(a.Clicks) > 0).ToList()); data.Add(select.Where(a => uint.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void ToUInt64() { var data = new List<object>(); data.Add(select.Where(a => Convert.ToUInt64(a.Clicks) > 0).ToList()); data.Add(select.Where(a => ulong.Parse(a.Clicks.ToString()) > 0).ToList()); } [Fact] public void Guid_Parse() { var data = new List<object>(); data.Add(select.Where(a => Guid.Parse(Guid.Empty.ToString()) == Guid.Empty).ToList()); } [Fact] public void Guid_NewGuid() { var data = new List<object>(); //data.Add(select.OrderBy(a => Guid.NewGuid()).Limit(10).ToList()); } [Fact] public void Random() { //var data = new List<object>(); //data.Add(select.Where(a => new Random().Next() > a.Clicks).Limit(10).ToList()); //data.Add(select.Where(a => new Random().NextDouble() > a.Clicks).Limit(10).ToList()); } } }
TestTypeParentInfo
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web/Factories/FilterLevelValueModelFactory.cs
{ "start": 234, "end": 2080 }
public partial class ____ : IFilterLevelValueModelFactory { #region Fields protected readonly ICatalogModelFactory _catalogModelFactory; protected readonly IFilterLevelValueService _filterLevelValueService; protected readonly ILocalizationService _localizationService; #endregion #region Ctor public FilterLevelValueModelFactory(ICatalogModelFactory catalogModelFactory, IFilterLevelValueService filterLevelValueService, ILocalizationService localizationService) { _catalogModelFactory = catalogModelFactory; _filterLevelValueService = filterLevelValueService; _localizationService = localizationService; } #endregion #region Utilities /// <summary> /// Prepare available filter level values /// </summary> /// <param name="items">Filter level value items</param> /// <param name="filterLevelValueEnum">Filter level value enum</param> /// <returns>A task that represents the asynchronous operation</returns> protected virtual async Task PrepareFilterLevelValuesAsync(IList<SelectListItem> items, FilterLevelEnum filterLevelValueEnum, string filterLevelValue = null) { ArgumentNullException.ThrowIfNull(items); var param1 = filterLevelValueEnum == FilterLevelEnum.FilterLevel1 ? filterLevelValue : null; var param2 = filterLevelValueEnum == FilterLevelEnum.FilterLevel2 ? filterLevelValue : null; var param3 = filterLevelValueEnum == FilterLevelEnum.FilterLevel3 ? filterLevelValue : null; //prepare available filter level values var availableFilterLevelValues = (await _filterLevelValueService.GetAllFilterLevelValuesAsync(param1, param2, param3)) .Select(filterLevelValue => { // filter by filter level value
FilterLevelValueModelFactory
csharp
Testably__Testably.Abstractions
Tests/Testably.Abstractions.Testing.Tests/FileSystem/PathMockTests.cs
{ "start": 78, "end": 1478 }
public sealed class ____ { #if CAN_SIMULATE_OTHER_OS [Theory] [InlineAutoData(SimulationMode.Native)] [InlineAutoData(SimulationMode.Linux)] [InlineAutoData(SimulationMode.MacOS)] [InlineAutoData(SimulationMode.Windows)] public async Task GetTempFileName_WithCollisions_ShouldThrowIOException( SimulationMode simulationMode, int fixedRandomValue) { MockFileSystem fileSystem = new(o => o .SimulatingOperatingSystem(simulationMode) .UseRandomProvider(RandomProvider.Generate( intGenerator: new RandomProvider.Generator<int>(() => fixedRandomValue)))); #pragma warning disable CS0618 string result = fileSystem.Path.GetTempFileName(); void Act() { _ = fileSystem.Path.GetTempFileName(); } #pragma warning restore CS0618 await That(Act).ThrowsExactly<IOException>(); await That(fileSystem.File.Exists(result)).IsTrue(); } #else [Theory] [AutoData] public async Task GetTempFileName_WithCollisions_ShouldThrowIOException( int fixedRandomValue) { MockFileSystem fileSystem = new(o => o .UseRandomProvider(RandomProvider.Generate( intGenerator: new RandomProvider.Generator<int>(() => fixedRandomValue)))); string result = fileSystem.Path.GetTempFileName(); void Act() { _ = fileSystem.Path.GetTempFileName(); } await That(Act).ThrowsExactly<IOException>(); await That(fileSystem.File.Exists(result)).IsTrue(); } #endif }
PathMockTests
csharp
Testably__Testably.Abstractions
Source/Testably.Abstractions.Testing/FileSystem/FileStreamFactoryMock.cs
{ "start": 234, "end": 6220 }
internal sealed class ____ : IFileStreamFactory { internal const FileShare DefaultShare = FileShare.Read; private const int DefaultBufferSize = 4096; private const bool DefaultUseAsync = false; private readonly MockFileSystem _fileSystem; internal FileStreamFactoryMock(MockFileSystem fileSystem) { _fileSystem = fileSystem; } #region IFileStreamFactory Members /// <inheritdoc cref="IFileSystemEntity.FileSystem" /> public IFileSystem FileSystem => _fileSystem; /// <inheritdoc cref="IFileStreamFactory.New(string, FileMode)" /> public FileSystemStream New(string path, FileMode mode) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), path, mode); return New(path, mode, mode == FileMode.Append ? FileAccess.Write : FileAccess.ReadWrite, DefaultShare, DefaultBufferSize, DefaultUseAsync); } /// <inheritdoc cref="IFileStreamFactory.New(string, FileMode, FileAccess)" /> public FileSystemStream New(string path, FileMode mode, FileAccess access) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), path, mode, access); return New(path, mode, access, DefaultShare, DefaultBufferSize, DefaultUseAsync); } /// <inheritdoc cref="IFileStreamFactory.New(string, FileMode, FileAccess, FileShare)" /> public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), path, mode, access, share); return New(path, mode, access, share, DefaultBufferSize, DefaultUseAsync); } /// <inheritdoc cref="IFileStreamFactory.New(string, FileMode, FileAccess, FileShare, int)" /> public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), path, mode, access, share, bufferSize); return New(path, mode, access, share, bufferSize, DefaultUseAsync); } /// <inheritdoc cref="IFileStreamFactory.New(string, FileMode, FileAccess, FileShare, int, bool)" /> public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), path, mode, access, share, bufferSize, useAsync); return New(path, mode, access, share, bufferSize, useAsync ? FileOptions.Asynchronous : FileOptions.None); } /// <inheritdoc cref="IFileStreamFactory.New(string, FileMode, FileAccess, FileShare, int, FileOptions)" /> public FileSystemStream New(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), path, mode, access, share, bufferSize, options); return new FileStreamMock(_fileSystem, path, mode, access, share, bufferSize, options); } /// <inheritdoc cref="IFileStreamFactory.New(SafeFileHandle, FileAccess)" /> #if NET6_0_OR_GREATER [ExcludeFromCodeCoverage(Justification = "SafeFileHandle cannot be unit tested.")] #endif public FileSystemStream New(SafeFileHandle handle, FileAccess access) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), handle, access); SafeFileHandleMock safeFileHandleMock = _fileSystem .SafeFileHandleStrategy.MapSafeFileHandle(handle); return New( safeFileHandleMock.Path, safeFileHandleMock.Mode, access, safeFileHandleMock.Share); } /// <inheritdoc cref="IFileStreamFactory.New(SafeFileHandle, FileAccess, int)" /> #if NET6_0_OR_GREATER [ExcludeFromCodeCoverage(Justification = "SafeFileHandle cannot be unit tested.")] #endif public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), handle, access, bufferSize); SafeFileHandleMock safeFileHandleMock = _fileSystem .SafeFileHandleStrategy.MapSafeFileHandle(handle); return New( safeFileHandleMock.Path, safeFileHandleMock.Mode, access, safeFileHandleMock.Share, bufferSize); } /// <inheritdoc cref="IFileStreamFactory.New(SafeFileHandle, FileAccess, int, bool)" /> #if NET6_0_OR_GREATER [ExcludeFromCodeCoverage(Justification = "SafeFileHandle cannot be unit tested.")] #endif public FileSystemStream New(SafeFileHandle handle, FileAccess access, int bufferSize, bool isAsync) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), handle, access, bufferSize, isAsync); SafeFileHandleMock safeFileHandleMock = _fileSystem .SafeFileHandleStrategy.MapSafeFileHandle(handle); return New( safeFileHandleMock.Path, safeFileHandleMock.Mode, access, safeFileHandleMock.Share, bufferSize, isAsync); } #if FEATURE_FILESYSTEM_STREAM_OPTIONS /// <inheritdoc cref="IFileStreamFactory.New(string, FileStreamOptions)" /> public FileSystemStream New(string path, FileStreamOptions options) { using IDisposable registration = _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(New), path, options); return New(path, options.Mode, options.Access, options.Share, options.BufferSize, options.Options); } #endif /// <inheritdoc cref="IFileStreamFactory.Wrap(FileStream)" /> public FileSystemStream Wrap(FileStream fileStream) { _fileSystem.StatisticsRegistration .FileStream.RegisterMethod(nameof(Wrap), fileStream); throw ExceptionFactory.NotSupportedFileStreamWrapping(); } #endregion }
FileStreamFactoryMock
csharp
dotnet__orleans
src/api/Orleans.Serialization/Orleans.Serialization.cs
{ "start": 56038, "end": 56182 }
public partial struct ____ { [Id(0)] public object[] Values; } [RegisterSerializer] public sealed
ArrayListSurrogate
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler.Tests/TestCases/Pretty/Switch.cs
{ "start": 1726, "end": 1944 }
public class ____ { private readonly string s; public ExplicitString(string s) { this.s = s; } public static explicit operator string(ExplicitString v) { return v.s; } }
ExplicitString
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Markup/MarkupExtensions.cs
{ "start": 156, "end": 569 }
public partial class ____ : IMarkupExtensionOverrides { object IMarkupExtensionOverrides.ProvideValue() => ProvideValue(); object IMarkupExtensionOverrides.ProvideValue(IXamlServiceProvider serviceProvider) => ProvideValue(serviceProvider); protected virtual object ProvideValue() => null; protected virtual object ProvideValue(IXamlServiceProvider serviceProvider) => ProvideValue(); } }
MarkupExtension
csharp
dotnet__aspnetcore
src/Html.Abstractions/src/HtmlString.cs
{ "start": 337, "end": 1449 }
public class ____ : IHtmlContent { /// <summary> /// An <see cref="HtmlString"/> instance for <see cref="Environment.NewLine"/>. /// </summary> public static readonly HtmlString NewLine = new HtmlString(Environment.NewLine); /// <summary> /// An <see cref="HtmlString"/> instance for <see cref="string.Empty"/>. /// </summary> public static readonly HtmlString Empty = new HtmlString(string.Empty); /// <summary> /// Creates a new <see cref="HtmlString"/>. /// </summary> /// <param name="value">The HTML encoded value.</param> public HtmlString(string? value) { Value = value; } /// <summary> /// Gets the HTML encoded value. /// </summary> public string? Value { get; } /// <inheritdoc /> public void WriteTo(TextWriter writer, HtmlEncoder encoder) { ArgumentNullException.ThrowIfNull(writer); ArgumentNullException.ThrowIfNull(encoder); writer.Write(Value); } /// <inheritdoc /> public override string ToString() { return Value ?? string.Empty; } }
HtmlString
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/GitHubGateway.cs
{ "start": 22785, "end": 23191 }
public class ____ { public string Id { get; set; } public string Url { get; set; } public string Html_Url { get; set; } public Dictionary<string, GistFile> Files { get; set; } public bool Public { get; set; } public DateTime Created_At { get; set; } public DateTime? Updated_At { get; set; } public string Description { get; set; } public string UserId { get; set; } }
Gist
csharp
FluentValidation__FluentValidation
src/FluentValidation/Resources/Languages/GeorgianLanguage.cs
{ "start": 810, "end": 3820 }
internal class ____ { public const string Culture = "ka"; public static string GetTranslation(string key) => key switch { "EmailValidator" => "'{PropertyName}' არ არის ვალიდური ელ.ფოსტის მისამართი.", "GreaterThanOrEqualValidator" => "'{PropertyName}' უნდა იყოს '{ComparisonValue}'-ზე მეტი ან ტოლი.", "GreaterThanValidator" => "'{PropertyName}' უნდა იყოს '{ComparisonValue}'-ზე მეტი.", "LengthValidator" => "'{PropertyName}' უნდა იყოს {MinLength}-დან {MaxLength} სიმბოლომდე. თქვენ შეიყვანეთ {TotalLength} სიმბოლო.", "MinimumLengthValidator" => "'{PropertyName}'-ის სიგრძე უნდა აღემატებოდეს {MinLength} სიმბოლოს. თქვენ შეიყვანეთ {TotalLength} სიმბოლო.", "MaximumLengthValidator" => "'{PropertyName}'-ის სიგრძე არ უნდა აღემატებოდეს {MaxLength} სიმბოლოს. თქვენ შეიყვანეთ {TotalLength} სიმბოლო.", "LessThanOrEqualValidator" => "'{PropertyName}' უნდა იყოს '{ComparisonValue}'-ზე ნაკლები ან ტოლი.", "LessThanValidator" => "'{PropertyName}' უნდა იყოს '{ComparisonValue}'-ზე ნაკლები.", "NotEmptyValidator" => "'{PropertyName}' არ უნდა იყოს ცარიელი.", "NotEqualValidator" => "'{PropertyName}' არ უნდა უდრიდეს '{ComparisonValue}'-ს.", "NotNullValidator" => "'{PropertyName}' არ უნდა იყოს ცარიელი.", "PredicateValidator" => "'{PropertyName}'-ისთვის განსაზღვრული პირობა არ დაკმაყოფილდა.", "AsyncPredicateValidator" => "'{PropertyName}'-ისთვის განსაზღვრული პირობა არ დაკმაყოფილდა.", "RegularExpressionValidator" => "'{PropertyName}'-ის ფორმატი არასწორია.", "EqualValidator" => "'{PropertyName}' უნდა უდრიდეს '{ComparisonValue}'-ს.", "ExactLengthValidator" => "'{PropertyName}' უნდა უდრიდეს {MaxLength} სიმბოლოს. თქვენ შეიყვანეთ {TotalLength} სიმბოლო.", "InclusiveBetweenValidator" => "'{PropertyName}' უნდა იყოს {From}-დან {To}-მდე (ჩათვლით). თქვენ შეიყვანეთ {PropertyValue}.", "ExclusiveBetweenValidator" => "'{PropertyName}' უნდა იყოს {From}-სა და {To}-ს შორის. თქვენ შეიყვანეთ {PropertyValue}.", "CreditCardValidator" => "'{PropertyName}' არ არის ვალიდური საკრედიტო ბარათის ნომერი.", "ScalePrecisionValidator" => "'{PropertyName}' არ უნდა იყოს ჯამში {ExpectedPrecision} ციფრზე მეტი, {ExpectedScale} ათობითი ციფრის ჩათვლით. თქვენ შეიყვანეთ {Digits} ციფრი და {ActualScale} ათობითი სიმბოლო.", "EmptyValidator" => "'{PropertyName}' უნდა იყოს ცარიელი.", "NullValidator" => "'{PropertyName}' უნდა იყოს ცარიელი.", "EnumValidator" => "'{PropertyValue}' არ შედის '{PropertyName}'-ის დასაშვებ მნიშვნელობებში.", // Additional fallback messages used by clientside validation integration. "Length_Simple" => "'{PropertyName}' უნდა იყოს {MinLength}-დან {MaxLength} სიმბოლომდე.", "MinimumLength_Simple" => "'{PropertyName}'-ის სიგრძე უნდა აღემატებოდეს {MinLength} სიმბოლოს.", "MaximumLength_Simple" => "'{PropertyName}'-ის სიგრძე არ უნდა აღემატებოდეს {MaxLength} სიმბოლოს.", "ExactLength_Simple" => "'{PropertyName}' უნდა უდრიდეს {MaxLength} სიმბოლოს.", "InclusiveBetween_Simple" => "'{PropertyName}' უნდა იყოს {From}-დან {To}-მდე (ჩათვლით).", _ => null, }; }
GeorgianLanguage
csharp
jellyfin__jellyfin
Emby.Server.Implementations/Sorting/ProductionYearComparer.cs
{ "start": 269, "end": 1421 }
public class ____ : IBaseItemComparer { /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public ItemSortBy Type => ItemSortBy.ProductionYear; /// <summary> /// Compares the specified x. /// </summary> /// <param name="x">The x.</param> /// <param name="y">The y.</param> /// <returns>System.Int32.</returns> public int Compare(BaseItem? x, BaseItem? y) { return GetValue(x).CompareTo(GetValue(y)); } /// <summary> /// Gets the date. /// </summary> /// <param name="x">The x.</param> /// <returns>DateTime.</returns> private static int GetValue(BaseItem? x) { if (x is null) { return 0; } if (x.ProductionYear.HasValue) { return x.ProductionYear.Value; } if (x.PremiereDate.HasValue) { return x.PremiereDate.Value.Year; } return 0; } } }
ProductionYearComparer
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Services/Installation/SampleData/SampleCheckoutAttributes.cs
{ "start": 211, "end": 1358 }
public partial class ____ { /// <summary> /// Gets or sets the name /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets a value indicating whether the attribute is required /// </summary> public bool IsRequired { get; set; } /// <summary> /// Gets or sets the attribute control type identifier /// </summary> [JsonConverter(typeof(StringEnumConverter))] public AttributeControlType AttributeControlType { get; set; } /// <summary> /// Gets or sets the display order /// </summary> public int DisplayOrder { get; set; } /// <summary> /// Gets or sets a value indicating whether shippable products are required in order to display this attribute /// </summary> public bool ShippableProductRequired { get; set; } /// <summary> /// Gets or sets the list of checkout attribute values /// </summary> public List<SampleCheckoutAttributeValue> AttributeValues { get; set; } = new(); #region Nested class /// <summary> /// Represents a sample checkout attribute value /// </summary>
SampleCheckoutAttribute
csharp
dotnet__aspnetcore
src/DefaultBuilder/testassets/StartWithIApplicationBuilderUrlApp/Program.cs
{ "start": 559, "end": 1659 }
public class ____ { static void Main(string[] args) { var messageSent = new ManualResetEventSlim(false); using (var host = WebHost.StartWith("http://127.0.0.1:0", app => { app.Run(async context => { var env = context.RequestServices.GetRequiredService<IHostEnvironment>(); await context.Response.WriteAsync(env.ApplicationName); messageSent.Set(); }); })) { // Need these for test deployer to consider host deployment successful // The address written here is used by the client to send requests var addresses = host.ServerFeatures.Get<IServerAddressesFeature>().Addresses; foreach (var address in addresses) { Console.WriteLine($"Now listening on: {address}"); } Console.WriteLine("Application started. Press Ctrl+C to shut down."); // Shut down after message sent or timeout messageSent.Wait(TimeSpan.FromSeconds(30)); } } }
Program
csharp
dotnet__aspire
src/Aspire.Hosting/Dcp/IDashboardEndpointProvider.cs
{ "start": 170, "end": 312 }
internal interface ____ { Task<string> GetResourceServiceUriAsync(CancellationToken cancellationToken = default); }
IDashboardEndpointProvider
csharp
dotnet__aspnetcore
src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcCoreBuilderExtensions.cs
{ "start": 728, "end": 3819 }
public static class ____ { /// <summary> /// Configures Newtonsoft.Json specific features such as input and output formatters. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> public static IMvcCoreBuilder AddNewtonsoftJson(this IMvcCoreBuilder builder) { ArgumentNullException.ThrowIfNull(builder); AddServicesCore(builder.Services); return builder; } /// <summary> /// Configures Newtonsoft.Json specific features such as input and output formatters. /// </summary> /// <param name="builder">The <see cref="IMvcCoreBuilder"/>.</param> /// <param name="setupAction">Callback to configure <see cref="MvcNewtonsoftJsonOptions"/>.</param> /// <returns>The <see cref="IMvcCoreBuilder"/>.</returns> public static IMvcCoreBuilder AddNewtonsoftJson( this IMvcCoreBuilder builder, Action<MvcNewtonsoftJsonOptions> setupAction) { ArgumentNullException.ThrowIfNull(builder); ArgumentNullException.ThrowIfNull(setupAction); AddServicesCore(builder.Services); builder.Services.Configure(setupAction); return builder; } // Internal for testing. internal static void AddServicesCore(IServiceCollection services) { services.TryAddSingleton<ObjectPoolProvider, DefaultObjectPoolProvider>(); services.TryAddEnumerable( ServiceDescriptor.Transient<IConfigureOptions<MvcOptions>, NewtonsoftJsonMvcOptionsSetup>()); services.TryAddEnumerable( ServiceDescriptor.Transient<IApiDescriptionProvider, JsonPatchOperationsArrayProvider>()); var jsonResultExecutor = services.FirstOrDefault(f => f.ServiceType == typeof(IActionResultExecutor<JsonResult>) && f.ImplementationType?.Assembly == typeof(JsonResult).Assembly); if (jsonResultExecutor != null) { services.Remove(jsonResultExecutor); } services.TryAddSingleton<IActionResultExecutor<JsonResult>, NewtonsoftJsonResultExecutor>(); var viewFeaturesAssembly = typeof(IHtmlHelper).Assembly; var tempDataSerializer = services.FirstOrDefault(f => f.ServiceType == typeof(TempDataSerializer) && f.ImplementationType?.Assembly == viewFeaturesAssembly); if (tempDataSerializer != null) { // Replace the default implementation of TempDataSerializer services.Remove(tempDataSerializer); } services.TryAddSingleton<TempDataSerializer, BsonTempDataSerializer>(); // // JSON Helper // var jsonHelper = services.FirstOrDefault( f => f.ServiceType == typeof(IJsonHelper) && f.ImplementationType?.Assembly == viewFeaturesAssembly); if (jsonHelper != null) { services.Remove(jsonHelper); } services.TryAddSingleton<IJsonHelper, NewtonsoftJsonHelper>(); } }
NewtonsoftJsonMvcCoreBuilderExtensions
csharp
dotnet__efcore
test/EFCore.SqlServer.FunctionalTests/FieldsOnlyLoadSqlServerTest.cs
{ "start": 413, "end": 612 }
public class ____ : FieldsOnlyLoadFixtureBase { protected override ITestStoreFactory TestStoreFactory => SqlServerTestStoreFactory.Instance; } }
FieldsOnlyLoadSqlServerFixture
csharp
protobuf-net__protobuf-net
src/BuildToolsUnitTests/DataContractAnalyzerTests.cs
{ "start": 11376, "end": 11966 }
public class ____ { [ProtoMember(42)] public int A {get;set;} } "); var diag = Assert.Single(diagnostics, x => x.Descriptor == DataContractAnalyzer.ReservedFieldNumber); Assert.Equal(DiagnosticSeverity.Warning, diag.Severity); Assert.Equal($"The specified field number [40-50] is explicitly reserved.", diag.GetMessage(CultureInfo.InvariantCulture)); } [Fact] public async Task ReportsReservedField_Name() { var diagnostics = await AnalyzeAsync(@" using ProtoBuf; [ProtoContract, ProtoReserved(""A"")]
Foo
csharp
dotnet__efcore
test/EFCore.Sqlite.FunctionalTests/Query/Ef6GroupBySqliteTest.cs
{ "start": 206, "end": 1959 }
public class ____ : Ef6GroupByTestBase<Ef6GroupBySqliteTest.Ef6GroupBySqliteFixture> { public Ef6GroupBySqliteTest(Ef6GroupBySqliteFixture fixture, ITestOutputHelper testOutputHelper) : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } public override async Task Average_Grouped_from_LINQ_101(bool async) { await base.Average_Grouped_from_LINQ_101(async); AssertSql( """ SELECT "p"."Category", ef_avg("p"."UnitPrice") AS "AveragePrice" FROM "ProductForLinq" AS "p" GROUP BY "p"."Category" """); } public override async Task Max_Grouped_from_LINQ_101(bool async) { await base.Max_Grouped_from_LINQ_101(async); AssertSql( """ SELECT "p"."Category", ef_max("p"."UnitPrice") AS "MostExpensivePrice" FROM "ProductForLinq" AS "p" GROUP BY "p"."Category" """); } public override async Task Min_Grouped_from_LINQ_101(bool async) { await base.Min_Grouped_from_LINQ_101(async); AssertSql( """ SELECT "p"."Category", ef_min("p"."UnitPrice") AS "CheapestPrice" FROM "ProductForLinq" AS "p" GROUP BY "p"."Category" """); } public override async Task Whats_new_2021_sample_3(bool async) => await base.Whats_new_2021_sample_3(async); public override async Task Whats_new_2021_sample_5(bool async) => await base.Whats_new_2021_sample_5(async); public override async Task Whats_new_2021_sample_6(bool async) => await base.Whats_new_2021_sample_6(async); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
Ef6GroupBySqliteTest
csharp
smartstore__Smartstore
src/Smartstore.Core/Content/Menus/Domain/NavigationItem.cs
{ "start": 188, "end": 5152 }
public abstract class ____ : INavigatable, IHideObjectMembers { private bool _selected; private bool _enabled; private string _actionName; private string _controllerName; private string _routeName; private string _url; public NavigationItem() { _enabled = true; } public AttributeDictionary HtmlAttributes { get; set; } = new(); public AttributeDictionary LinkHtmlAttributes { get; set; } = new(); public AttributeDictionary BadgeHtmlAttributes { get; set; } = new(); public RouteValueDictionary RouteValues { get; set; } = new(); [IgnoreDataMember] public ModifiedParameter ModifiedParam { get; } = new(); /// <summary> /// Merges attributes of <see cref="HtmlAttributes"/> and <see cref="LinkHtmlAttributes"/> into one combined dictionary. /// </summary> /// <returns>New attribute dictionary instance with combined attributes.</returns> public AttributeDictionary GetCombinedAttributes() { if (HtmlAttributes == null && LinkHtmlAttributes == null) { return null; } var combined = new AttributeDictionary(); combined.AddRange(HtmlAttributes ?? LinkHtmlAttributes); if (HtmlAttributes != null && LinkHtmlAttributes != null) { combined.Merge(LinkHtmlAttributes); } return combined; } public string ImageUrl { get; set; } public int? ImageId { get; set; } public string IconLibrary { get; set; } public string Icon { get; set; } public string IconClass { get; set; } public string Text { get; set; } public bool Rtl { get; set; } public string Summary { get; set; } public string BadgeText { get; set; } public int BadgeStyle { get; set; } public bool Visible { get; set; } = true; public bool Encoded { get; set; } = true; public bool Selected { get => _selected; set { _selected = value; if (_selected) { _enabled = true; } } } public bool Enabled { get => _enabled; set { _enabled = value; if (!_enabled) { _selected = false; } } } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string ActionName { get => _actionName; set { if (_actionName != value) { _actionName = value; _routeName = _url = null; } } } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string ControllerName { get => _controllerName; set { if (_controllerName != value) { _controllerName = value; _routeName = _url = null; } } } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string RouteName { get => _routeName; set { if (_routeName != value) { _routeName = value; _controllerName = _actionName = _url = null; } } } [JsonProperty(NullValueHandling = NullValueHandling.Ignore)] public string Url { get => _url; set { if (_url != value) { _url = value; _routeName = _controllerName = _actionName = null; RouteValues.Clear(); } } } /// <summary> /// Checks whether action/controller or routeName or url has been specified. /// </summary> public bool HasRoute { get => _actionName != null || _routeName != null || _url != null; } /// <summary> /// Checks whether url has been specified with '#' or 'javascript:void()' or empty string. /// </summary> public bool IsVoid() { // Perf: order from most to least common return _url != null && (_url == "#" || _url.StartsWith("javascript:void") || _url == string.Empty || _url.IsWhiteSpace()); } public override string ToString() { if (Text.HasValue()) { return Text; } return base.ToString(); } } }
NavigationItem
csharp
dotnet__orleans
src/Orleans.Streaming/JsonConverters/StreamImplConverter.cs
{ "start": 263, "end": 2487 }
internal class ____ : JsonConverter { private readonly IRuntimeClient _runtimeClient; public StreamImplConverter(IRuntimeClient runtimeClient) { _runtimeClient = runtimeClient; } public override bool CanConvert(Type objectType) => objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(StreamImpl<>) || objectType.GetGenericTypeDefinition() == typeof(IAsyncStream<>)); public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { var jo = JObject.Load(reader); if (jo != null) { var itemType = objectType.GetGenericArguments()[0]; var fullType = typeof(StreamImpl<>).MakeGenericType(itemType); var streamId = jo["streamId"]?.ToObject<StreamId>(); var providerName = jo["providerName"]?.Value<string>(); var isRewindable = jo["isRewindable"]?.ToObject<bool>(); if (streamId.HasValue && isRewindable.HasValue && !string.IsNullOrWhiteSpace(providerName)) { var provider = _runtimeClient.ServiceProvider.GetRequiredKeyedService<IStreamProvider>(providerName) as IInternalStreamProvider; return Activator.CreateInstance(fullType, new QualifiedStreamId(providerName, streamId.Value), provider, isRewindable.Value, _runtimeClient); } } throw new SerializationException(); } public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { writer.WriteStartObject(); if (value is IAsyncStream target) { writer.WritePropertyName("streamId"); serializer.Serialize(writer, target.StreamId); writer.WritePropertyName("providerName"); serializer.Serialize(writer, target.ProviderName); writer.WritePropertyName("isRewindable"); writer.WriteValue(target.IsRewindable); } writer.WriteEndObject(); } } }
StreamImplConverter
csharp
unoplatform__uno
src/Uno.UI/Controls/BindableDatePicker.Android.cs
{ "start": 277, "end": 2850 }
public partial class ____ : DatePicker { public BindableDatePicker(Context c) : base(c) { LayoutParameters = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.WrapContent); #pragma warning disable CS0618 // Type or member is obsolete #pragma warning disable CA1422 // Validate platform compatibility CalendarViewShown = false; #pragma warning restore CA1422 // Validate platform compatibility #pragma warning restore CS0618 // Type or member is obsolete } ViewStates _monthVisibility; public ViewStates MonthVisibility { get { return _monthVisibility; } set { if (_monthVisibility != value) { _monthVisibility = value; SetVisibility(value, "mMonthPicker", "mMonthSpinner"); } } } ViewStates _yearVisibility; public ViewStates YearVisibility { get { return _yearVisibility; } set { if (_yearVisibility != value) { _yearVisibility = value; SetVisibility(value, "mYearPicker", "mYearSpinner"); } } } ViewStates _dayVisibility; public ViewStates DayVisibility { get { return _dayVisibility; } set { if (_dayVisibility != value) { _dayVisibility = value; SetVisibility(value, "mDayPicker", "mDaySpinner"); } } } private Field[] _declaredFields; public Field[] DeclaredFields { get { if (_declaredFields == null) { _declaredFields = Class.FromType(typeof(DatePicker)).GetDeclaredFields(); } return _declaredFields; } } private void SetVisibility(ViewStates visibility, params string[] memberNames) { try {//http://stackoverflow.com/questions/10401915/hide-year-field-in-android-datepicker var fields = DeclaredFields; foreach (var field in fields) { if (memberNames.Contains(field.Name)) { field.Accessible = true; var picker = (View)field.Get(this); picker.Visibility = visibility; } } } catch (SecurityException) { if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Error)) { this.Log().Error("Can't hide " + string.Join(", ", memberNames)); } } catch (IllegalArgumentException) { if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Error)) { this.Log().Error("Can't hide " + string.Join(", ", memberNames)); } } catch (IllegalAccessException) { if (this.Log().IsEnabled(Uno.Foundation.Logging.LogLevel.Error)) { this.Log().Error("Can't hide " + string.Join(", ", memberNames)); } } } } }
BindableDatePicker
csharp
PrismLibrary__Prism
tests/Avalonia/Prism.Avalonia.Tests/Regions/RegionFixture.cs
{ "start": 248, "end": 13851 }
public class ____ { [Fact] public void WhenRegionConstructed_SortComparisonIsDefault() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); Assert.NotNull(region.SortComparison); Assert.Equal(region.SortComparison, Region.DefaultSortComparison); } [Fact] public void CanAddContentToRegion() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); Assert.Empty(region.Views.Cast<object>()); region.Add(new object()); Assert.Single(region.Views.Cast<object>()); } [Fact] public void CanRemoveContentFromRegion() { IRegion region = new Region(); object view = new object(); region.Add(view); region.Remove(view); Assert.Empty(region.Views.Cast<object>()); } [Fact] public void RemoveInexistentViewThrows() { var ex = Assert.Throws<ArgumentException>(() => { IRegion region = new Region(); object view = new object(); region.Remove(view); Assert.Empty(region.Views.Cast<object>()); }); } [Fact] public void RegionExposesCollectionOfContainedViews() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); object view = new object(); region.Add(view); var views = region.Views; Assert.NotNull(views); Assert.Single(views.Cast<object>()); Assert.Same(view, views.Cast<object>().ElementAt(0)); } [Fact] public void CanAddAndRetrieveNamedViewInstance() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); object myView = new object(); region.Add(myView, "MyView"); object returnedView = region.GetView("MyView"); Assert.NotNull(returnedView); Assert.Same(returnedView, myView); } [Fact] public void AddingDuplicateNamedViewThrows() { var ex = Assert.Throws<InvalidOperationException>(() => { IRegion region = new Region(); region.Add(new object(), "MyView"); region.Add(new object(), "MyView"); }); } [Fact] public void AddNamedViewIsAlsoListedInViewsCollection() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); object myView = new object(); region.Add(myView, "MyView"); Assert.Single(region.Views.Cast<object>()); Assert.Same(myView, region.Views.Cast<object>().ElementAt(0)); } [Fact] public void GetViewReturnsNullWhenViewDoesNotExistInRegion() { IRegion region = new Region(); Assert.Null(region.GetView("InexistentView")); } [Fact] public void GetViewWithNullOrEmptyStringThrows() { var ex = Assert.Throws<ArgumentException>(() => { IRegion region = new Region(); region.GetView(string.Empty); }); } [Fact] public void AddNamedViewWithNullOrEmptyStringNameThrows() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); var ex = Assert.Throws<ArgumentException>(() => { IRegion region = new Region(); region.Add(new object(), string.Empty); }); } [Fact] public void GetViewReturnsNullAfterRemovingViewFromRegion() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); object myView = new object(); region.Add(myView, "MyView"); region.Remove(myView); Assert.Null(region.GetView("MyView")); } [Fact] public void AddViewPassesSameScopeByDefaultToView() { var regionManager = new MockRegionManager(); IRegion region = new Region(); region.RegionManager = regionManager; var myView = new MockDependencyObject(); region.Add(myView); Assert.Same(regionManager, myView.GetValue(RegionManager.RegionManagerProperty)); } [Fact] public void AddViewPassesSameScopeByDefaultToNamedView() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); var regionManager = new MockRegionManager(); IRegion region = new Region(); region.RegionManager = regionManager; var myView = new MockDependencyObject(); region.Add(myView, "MyView"); Assert.Same(regionManager, myView.GetValue(RegionManager.RegionManagerProperty)); } [Fact] public void AddViewPassesDifferentScopeWhenAdding() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); var regionManager = new MockRegionManager(); IRegion region = new Region(); region.RegionManager = regionManager; var myView = new MockDependencyObject(); region.Add(myView, "MyView", true); Assert.NotSame(regionManager, myView.GetValue(RegionManager.RegionManagerProperty)); } [Fact] public void CreatingNewScopesAsksTheRegionManagerForNewInstance() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); var regionManager = new MockRegionManager(); IRegion region = new Region(); region.RegionManager = regionManager; var myView = new object(); region.Add(myView, "MyView", true); Assert.True(regionManager.CreateRegionManagerCalled); } [Fact] public void AddViewReturnsExistingRegionManager() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); var regionManager = new MockRegionManager(); IRegion region = new Region(); region.RegionManager = regionManager; var myView = new object(); var returnedRegionManager = region.Add(myView, "MyView", false); Assert.Same(regionManager, returnedRegionManager); } [Fact] public void AddViewReturnsNewRegionManager() { var regionManager = new MockRegionManager(); IRegion region = new Region(); region.RegionManager = regionManager; var myView = new object(); var returnedRegionManager = region.Add(myView, "MyView", true); Assert.NotSame(regionManager, returnedRegionManager); } [Fact] public void AddingNonDependencyObjectToRegionDoesNotThrow() { IRegion region = new Region(); object model = new object(); region.Add(model); Assert.Single(region.Views.Cast<object>()); } [Fact] public void ActivateNonAddedViewThrows() { var ex = Assert.Throws<ArgumentException>(() => { IRegion region = new Region(); object nonAddedView = new object(); region.Activate(nonAddedView); }); } [Fact] public void DeactivateNonAddedViewThrows() { var ex = Assert.Throws<ArgumentException>(() => { IRegion region = new Region(); object nonAddedView = new object(); region.Deactivate(nonAddedView); }); } [Fact] public void ActivateNullViewThrows() { var ex = Assert.Throws<ArgumentNullException>(() => { IRegion region = new Region(); region.Activate(null); }); } [Fact] public void AddViewRaisesCollectionViewEvent() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); bool viewAddedCalled = false; IRegion region = new Region(); region.Views.CollectionChanged += (sender, e) => { if (e.Action == NotifyCollectionChangedAction.Add) viewAddedCalled = true; }; object model = new object(); Assert.False(viewAddedCalled); region.Add(model); Assert.True(viewAddedCalled); } [Fact] public void ViewAddedEventPassesTheViewAddedInTheEventArgs() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); object viewAdded = null; IRegion region = new Region(); region.Views.CollectionChanged += (sender, e) => { if (e.Action == NotifyCollectionChangedAction.Add) { viewAdded = e.NewItems[0]; } }; object model = new object(); Assert.Null(viewAdded); region.Add(model); Assert.NotNull(viewAdded); Assert.Same(model, viewAdded); } [Fact] public void RemoveViewFiresViewRemovedEvent() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); bool viewRemoved = false; IRegion region = new Region(); object model = new object(); region.Views.CollectionChanged += (sender, e) => { if (e.Action == NotifyCollectionChangedAction.Remove) viewRemoved = true; }; region.Add(model); Assert.False(viewRemoved); region.Remove(model); Assert.True(viewRemoved); } [Fact] public void ViewRemovedEventPassesTheViewRemovedInTheEventArgs() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); object removedView = null; IRegion region = new Region(); region.Views.CollectionChanged += (sender, e) => { if (e.Action == NotifyCollectionChangedAction.Remove) removedView = e.OldItems[0]; }; object model = new object(); region.Add(model); Assert.Null(removedView); region.Remove(model); Assert.Same(model, removedView); } [Fact] public void ShowViewFiresViewShowedEvent() { bool viewActivated = false; IRegion region = new Region(); object model = new object(); region.ActiveViews.CollectionChanged += (o, e) => { if (e.Action == NotifyCollectionChangedAction.Add && e.NewItems.Contains(model)) viewActivated = true; }; region.Add(model); Assert.False(viewActivated); region.Activate(model); Assert.True(viewActivated); } [Fact] public void AddingSameViewTwiceThrows() { object view = new object(); IRegion region = new Region(); region.Add(view); try { region.Add(view); //Assert.Fail(); } catch (InvalidOperationException ex) { Assert.Equal("View already exists in region.", ex.Message); } catch { //Assert.Fail(); } } [Fact] public void RemovingViewAlsoRemovesItFromActiveViews() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); object model = new object(); region.Add(model); region.Activate(model); Assert.True(region.ActiveViews.Contains(model)); region.Remove(model); Assert.False(region.ActiveViews.Contains(model)); } [Fact] public void ShouldGetNotificationWhenContextChanges() { ContainerLocator.SetContainerExtension(Mock.Of<IContainerExtension>()); IRegion region = new Region(); bool contextChanged = false; region.PropertyChanged += (s, args) => { if (args.PropertyName == "Context") contextChanged = true; }; region.Context = "MyNewContext"; Assert.True(contextChanged); } [Fact] public void ChangingNameOnceItIsSetThrows() { var ex = Assert.Throws<InvalidOperationException>(() => { var region = new Region { Name = "MyRegion" }; region.Name = "ChangedRegionName"; }); }
RegionFixture
csharp
dotnet__machinelearning
src/Microsoft.Data.Analysis/PrimitiveDataFrameColumn.BinaryOperationAPIs.ExplodedColumns.cs
{ "start": 444149, "end": 444706 }
public partial class ____ { public BooleanDataFrameColumn Xor(BooleanDataFrameColumn column, bool inPlace = false) { if (column.Length != Length) { throw new ArgumentException(Strings.MismatchedColumnLengths, nameof(column)); } BooleanDataFrameColumn retColumn = inPlace ? this : CloneAsBooleanColumn(); retColumn.ColumnContainer.HandleOperation(BinaryOperation.Xor, column.ColumnContainer); return retColumn; } }
BooleanDataFrameColumn
csharp
nunit__nunit
src/NUnitFramework/tests/Attributes/ValuesAttributeEnumTests.cs
{ "start": 3712, "end": 3933 }
enum ____ in no particular order */ ++_countNullableEnums; } [Test] public void TestNullableInEnum([Values] in EnumValues? enumValue) { /* runs with null and all
values
csharp
MassTransit__MassTransit
src/MassTransit/Configuration/ServiceInstanceOptions.cs
{ "start": 55, "end": 888 }
public class ____ : OptionsSet { public ServiceInstanceOptions() { EndpointNameFormatter = DefaultEndpointNameFormatter.Instance; } public IEndpointNameFormatter EndpointNameFormatter { get; private set; } /// <summary> /// Enable the job service endpoints, so that <see cref="IJobConsumer{TJob}" /> consumers /// can be configured. /// </summary> public ServiceInstanceOptions EnableJobServiceEndpoints() { Options<JobServiceOptions>(); return this; } public ServiceInstanceOptions SetEndpointNameFormatter(IEndpointNameFormatter endpointNameFormatter) { EndpointNameFormatter = endpointNameFormatter; return this; } } }
ServiceInstanceOptions
csharp
smartstore__Smartstore
src/Smartstore/ComponentModel/MapperFactory.cs
{ "start": 11714, "end": 11885 }
struct ____(Type type, int order) { public Type Type { get; } = type; public int Order { get; } = order; } readonly
MapperType
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml/FrameworkElementTests/XamlEvent_Leak.xaml.cs
{ "start": 2098, "end": 2340 }
private class ____ { private Action<int> _update; private static int _counter; public Holder(Action<int> update) { _update = update; _update(++_counter); } ~Holder() { _update(--_counter); } } } }
Holder
csharp
dotnetcore__CAP
src/DotNetCore.CAP/Persistence/MediumMessage.cs
{ "start": 242, "end": 552 }
public class ____ { public string DbId { get; set; } = default!; public Message Origin { get; set; } = default!; public string Content { get; set; } = default!; public DateTime Added { get; set; } public DateTime? ExpiresAt { get; set; } public int Retries { get; set; } }
MediumMessage
csharp
xunit__xunit
src/xunit.v2.tests/Sdk/Frameworks/Runners/TestCollectionRunnerTests.cs
{ "start": 197, "end": 7072 }
public class ____ { [Fact] public static async void Messages() { var summary = new RunSummary { Total = 4, Failed = 2, Skipped = 1, Time = 21.12m }; var messageBus = new SpyMessageBus(); var testCase = Mocks.TestCase<ClassUnderTest>("Passing"); var runner = TestableTestCollectionRunner.Create(messageBus, new[] { testCase }, summary); var result = await runner.RunAsync(); Assert.Equal(result.Total, summary.Total); Assert.Equal(result.Failed, summary.Failed); Assert.Equal(result.Skipped, summary.Skipped); Assert.Equal(result.Time, summary.Time); Assert.False(runner.TokenSource.IsCancellationRequested); Assert.Collection(messageBus.Messages, msg => { var starting = Assert.IsAssignableFrom<ITestCollectionStarting>(msg); Assert.Same(testCase.TestMethod.TestClass.TestCollection, starting.TestCollection); }, msg => { var finished = Assert.IsAssignableFrom<ITestCollectionFinished>(msg); Assert.Same(testCase.TestMethod.TestClass.TestCollection, finished.TestCollection); Assert.Equal(21.12m, finished.ExecutionTime); Assert.Equal(4, finished.TestsRun); Assert.Equal(2, finished.TestsFailed); Assert.Equal(1, finished.TestsSkipped); } ); } [Fact] public static async void FailureInQueueOfTestCollectionStarting_DoesNotQueueTestCollectionFinished_DoesNotRunTestClasses() { var messages = new List<IMessageSinkMessage>(); var messageBus = Substitute.For<IMessageBus>(); messageBus .QueueMessage(null) .ReturnsForAnyArgs(callInfo => { var msg = callInfo.Arg<IMessageSinkMessage>(); messages.Add(msg); if (msg is ITestCollectionStarting) throw new InvalidOperationException(); return true; }); var runner = TestableTestCollectionRunner.Create(messageBus); await Assert.ThrowsAsync<InvalidOperationException>(() => runner.RunAsync()); var starting = Assert.Single(messages); Assert.IsAssignableFrom<ITestCollectionStarting>(starting); Assert.Empty(runner.ClassesRun); } [Fact] public static async void RunTestClassAsync_AggregatorIncludesPassedInExceptions() { var messageBus = new SpyMessageBus(); var ex = new DivideByZeroException(); var runner = TestableTestCollectionRunner.Create(messageBus, aggregatorSeedException: ex); await runner.RunAsync(); Assert.Same(ex, runner.RunTestClassAsync_AggregatorResult); Assert.Empty(messageBus.Messages.OfType<ITestCollectionCleanupFailure>()); } [Fact] public static async void FailureInAfterTestCollectionStarting_GivesErroredAggregatorToTestClassRunner_NoCleanupFailureMessage() { var messageBus = new SpyMessageBus(); var runner = TestableTestCollectionRunner.Create(messageBus); var ex = new DivideByZeroException(); runner.AfterTestCollectionStarting_Callback = aggregator => aggregator.Add(ex); await runner.RunAsync(); Assert.Same(ex, runner.RunTestClassAsync_AggregatorResult); Assert.Empty(messageBus.Messages.OfType<ITestCollectionCleanupFailure>()); } [Fact] public static async void FailureInBeforeTestCollectionFinished_ReportsCleanupFailure_DoesNotIncludeExceptionsFromAfterTestCollectionStarting() { var messageBus = new SpyMessageBus(); var testCases = new[] { Mocks.TestCase<TestAssemblyRunnerTests.RunAsync>("Messages") }; var runner = TestableTestCollectionRunner.Create(messageBus, testCases); var startingException = new DivideByZeroException(); var finishedException = new InvalidOperationException(); runner.AfterTestCollectionStarting_Callback = aggregator => aggregator.Add(startingException); runner.BeforeTestCollectionFinished_Callback = aggregator => aggregator.Add(finishedException); await runner.RunAsync(); var cleanupFailure = Assert.Single(messageBus.Messages.OfType<ITestCollectionCleanupFailure>()); Assert.Same(testCases[0].TestMethod.TestClass.TestCollection, cleanupFailure.TestCollection); Assert.Equal(testCases, cleanupFailure.TestCases); Assert.Equal(typeof(InvalidOperationException).FullName, cleanupFailure.ExceptionTypes.Single()); } [Fact] public static async void Cancellation_TestCollectionStarting_DoesNotCallExtensibilityCallbacks() { var messageBus = new SpyMessageBus(msg => !(msg is ITestCollectionStarting)); var runner = TestableTestCollectionRunner.Create(messageBus); await runner.RunAsync(); Assert.True(runner.TokenSource.IsCancellationRequested); Assert.False(runner.AfterTestCollectionStarting_Called); Assert.False(runner.BeforeTestCollectionFinished_Called); } [Fact] public static async void Cancellation_TestCollectionFinished_CallsExtensibilityCallbacks() { var messageBus = new SpyMessageBus(msg => !(msg is ITestCollectionFinished)); var runner = TestableTestCollectionRunner.Create(messageBus); await runner.RunAsync(); Assert.True(runner.TokenSource.IsCancellationRequested); Assert.True(runner.AfterTestCollectionStarting_Called); Assert.True(runner.BeforeTestCollectionFinished_Called); } [Fact] public static async void Cancellation_TestCollectionCleanupFailure_SetsCancellationToken() { var messageBus = new SpyMessageBus(msg => !(msg is ITestCollectionCleanupFailure)); var runner = TestableTestCollectionRunner.Create(messageBus); runner.BeforeTestCollectionFinished_Callback = aggregator => aggregator.Add(new Exception()); await runner.RunAsync(); Assert.True(runner.TokenSource.IsCancellationRequested); } [Fact] public static async void TestsAreGroupedByCollection() { var passing1 = Mocks.TestCase<ClassUnderTest>("Passing"); var other1 = Mocks.TestCase<ClassUnderTest>("Other"); var passing2 = Mocks.TestCase<ClassUnderTest2>("Passing"); var other2 = Mocks.TestCase<ClassUnderTest2>("Other"); var runner = TestableTestCollectionRunner.Create(testCases: new[] { passing1, passing2, other2, other1 }); await runner.RunAsync(); Assert.Collection(runner.ClassesRun, tuple => { Assert.Equal("TestCollectionRunnerTests+ClassUnderTest", tuple.Item1.Name); Assert.Collection(tuple.Item2, testCase => Assert.Same(passing1, testCase), testCase => Assert.Same(other1, testCase) ); }, tuple => { Assert.Equal("TestCollectionRunnerTests+ClassUnderTest2", tuple.Item1.Name); Assert.Collection(tuple.Item2, testCase => Assert.Same(passing2, testCase), testCase => Assert.Same(other2, testCase) ); } ); } [Fact] public static async void SignalingCancellationStopsRunningClasses() { var passing1 = Mocks.TestCase<ClassUnderTest>("Passing"); var passing2 = Mocks.TestCase<ClassUnderTest2>("Passing"); var runner = TestableTestCollectionRunner.Create(testCases: new[] { passing1, passing2 }, cancelInRunTestClassAsync: true); await runner.RunAsync(); var tuple = Assert.Single(runner.ClassesRun); Assert.Equal("TestCollectionRunnerTests+ClassUnderTest", tuple.Item1.Name); }
TestCollectionRunnerTests
csharp
unoplatform__uno
src/Uno.Foundation/Uno.Core.Extensions/Uno.Core.Extensions.Compatibility/Extensions/IIndentedStringBuilder.cs
{ "start": 809, "end": 2368 }
internal interface ____ { /// <summary> /// Gets the current indentation level /// </summary> int CurrentLevel { get; } /// <summary> /// Appends text using the current indentation level /// </summary> /// <param name="text"></param> void Append(string text); /// <summary> /// Appends a line using the current indentation level /// </summary> void AppendLine(); /// <summary> /// Writes the provided text and adds line using the current indentation level /// </summary> void AppendMultiLineIndented(string text); /// <summary> /// Creates an indentation block /// </summary> /// <param name="count">The indentation level of the new block.</param> /// <returns>A disposable that will close the block</returns> IDisposable Block(int count = 1); /// <summary> /// Creates an indentation block, e.g. using a C# curly braces. /// </summary> /// <returns>A disposable that will close the block</returns> IDisposable Block(IFormatProvider formatProvider, string pattern, params object[] parameters); /// <summary> /// Adds an indentation /// </summary> /// <param name="count"></param> /// <returns></returns> IDisposable Indent(int count = 1); /// <summary> /// Provides a string representing the complete builder. /// </summary> string ToString(); public void AppendIndented(string text); public void AppendIndented(ReadOnlySpan<char> text); void AppendFormatIndented(IFormatProvider formatProvider, string text, params object[] replacements); } }
IIndentedStringBuilder
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Execution/Results/SelectionMapExecutor.cs
{ "start": 231, "end": 8604 }
internal static class ____ { public static IValueNode? Map( CompositeResultElement result, IValueSelectionNode valueSelection, ISchemaDefinition schema, ref PooledArrayWriter? writer) { var context = new Context(schema, result, ref writer); return Visit(valueSelection, context); } private static IValueNode? Visit(IValueSelectionNode node, Context context) { switch (node) { case ChoiceValueSelectionNode choice: return Visit(choice, context); case PathNode path: return Visit(path, context); case ObjectValueSelectionNode objectValue: return Visit(objectValue, context); case PathObjectValueSelectionNode objectValue: return Visit(objectValue, context); case PathListValueSelectionNode listValue: return Visit(listValue, context); default: throw new NotSupportedException("Unknown value selection node type."); } } private static IValueNode? Visit(ChoiceValueSelectionNode node, Context context) { foreach (var branch in node.Branches) { var value = Visit(branch, context); if (value is null) { continue; } return value; } return null; } private static IValueNode? Visit(PathNode node, Context context) { var result = ResolvePath(context.Schema, context.Result, node); var resultValueKind = result.ValueKind; if (resultValueKind is JsonValueKind.Undefined) { return null; } // Note: to capture data from the introspection // system we would need to also cover raw field results. if (result.Selection is { IsLeaf: true }) { if (resultValueKind is JsonValueKind.Null) { return NullValueNode.Default; } if (resultValueKind is JsonValueKind.Array) { var items = new List<IValueNode>(); context.Writer ??= new PooledArrayWriter(); var parser = new JsonValueParser(buffer: context.Writer); foreach (var item in result.EnumerateArray()) { if (item.ValueKind is JsonValueKind.Null) { items.Add(NullValueNode.Default); continue; } items.Add(parser.Parse(item.GetRawValue(includeQuotes: true))); } return new ListValueNode(items); } context.Writer ??= new PooledArrayWriter(); var scalarParser = new JsonValueParser(buffer: context.Writer); return scalarParser.Parse(result.GetRawValue(includeQuotes: true)); } throw new InvalidSelectionMapPathException(node); } private static IValueNode? Visit(ObjectValueSelectionNode node, Context context) { var result = context.Result; var resultValueKind = result.ValueKind; if (resultValueKind is not JsonValueKind.Object) { throw new InvalidOperationException("Only object results are supported."); } var fields = new List<ObjectFieldNode>(); foreach (var field in node.Fields) { var value = field.ValueSelection is null ? Visit(new PathNode(new PathSegmentNode(field.Name)), context) : Visit(field.ValueSelection, context); if (value is null) { return null; } fields.Add(new ObjectFieldNode(field.Name.Value, value)); } fields.Capacity = fields.Count; return new ObjectValueNode(fields); } private static IValueNode? Visit(PathObjectValueSelectionNode node, Context context) { var result = ResolvePath(context.Schema, context.Result, node.Path); var resultValueKind = result.ValueKind; if (resultValueKind is JsonValueKind.Null or JsonValueKind.Undefined) { return null; } if (resultValueKind is not JsonValueKind.Object) { throw new InvalidOperationException("Only object results are supported."); } return Visit(node.ObjectValueSelection, context.WithResult(result)); } private static IValueNode? Visit(ListValueSelectionNode node, Context context) { var result = context.Result; var resultValueKind = result.ValueKind; if (resultValueKind is not JsonValueKind.Array) { return null; } var items = new List<IValueNode>(); foreach (var item in result.EnumerateArray()) { if (item.ValueKind is JsonValueKind.Null) { items.Add(NullValueNode.Default); continue; } var value = Visit(node.ElementSelection, context.WithResult(item)); if (value is null) { return null; } items.Add(value); } return new ListValueNode(items); } private static IValueNode? Visit(PathListValueSelectionNode node, Context context) { var result = ResolvePath(context.Schema, context.Result, node.Path); var resultValueKind = result.ValueKind; switch (resultValueKind) { case JsonValueKind.Undefined: return null; case JsonValueKind.Null: return NullValueNode.Default; case JsonValueKind.Array: return Visit(node.ListValueSelection, context.WithResult(result)); default: return null; } } private static CompositeResultElement ResolvePath( ISchemaDefinition schema, CompositeResultElement result, PathNode path) { if (result.ValueKind is not JsonValueKind.Object) { throw new InvalidOperationException("Only object results are supported."); } if (path.TypeName is not null) { var type = schema.Types.GetType<IOutputTypeDefinition>(path.TypeName.Value); if (!type.IsAssignableFrom(result.AssertSelectionSet().Type)) { return default; } } var currentSegment = path.PathSegment; var currentResult = result; var currentValueKind = result.ValueKind; while (currentSegment is not null && currentValueKind is not JsonValueKind.Null and not JsonValueKind.Undefined) { if (!currentResult.TryGetProperty(currentSegment.FieldName.Value, out var fieldResult)) { return default; } var fieldResultValueKind = fieldResult.ValueKind; if (fieldResultValueKind is JsonValueKind.Null) { return default; } if (currentSegment.TypeName is not null) { if (fieldResultValueKind is not JsonValueKind.Object) { throw new InvalidSelectionMapPathException(path); } currentResult = fieldResult; currentValueKind = fieldResultValueKind; var type = schema.Types.GetType<IOutputTypeDefinition>(currentSegment.TypeName.Value); if (!type.IsAssignableFrom(currentResult.AssertSelectionSet().Type)) { return default; } currentSegment = currentSegment.PathSegment; continue; } if (currentSegment.PathSegment is not null) { if (fieldResultValueKind is not JsonValueKind.Object) { throw new InvalidSelectionMapPathException(path); } currentResult = fieldResult; currentSegment = currentSegment.PathSegment; continue; } return fieldResult; } return currentResult; } private readonly ref
ResultDataMapper
csharp
MonoGame__MonoGame
MonoGame.Framework/Platform/Audio/OpenAL.cs
{ "start": 971, "end": 1091 }
internal enum ____ { UnpackBlockAlignmentSoft = 0x200C, LoopSoftPointsExt = 0x2015, }
ALBufferi
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/Middleware/DynamicRouter_Specs.cs
{ "start": 3327, "end": 3508 }
public interface ____<TVendorRecord> : VendorContext where TVendorRecord : VendorRecord { TVendorRecord Record { get; } }
VendorContext
csharp
grpc__grpc-dotnet
perf/benchmarkapps/QpsWorker/Infrastructure/ClientRunner.cs
{ "start": 974, "end": 13504 }
public class ____ { private const double SecondsToNanos = 1e9; private readonly List<GrpcChannel> _channels; private readonly ClientType _clientType; private readonly RpcType _rpcType; private readonly PayloadConfig _payloadConfig; private readonly ILogger _logger; private readonly Lazy<byte[]> _cachedByteBufferRequest; private readonly ThreadLocal<Histogram> _threadLocalHistogram; private readonly List<Task> _runnerTasks; private readonly CancellationTokenSource _stoppedCts = new CancellationTokenSource(); private readonly TimeStats _timeStats = new TimeStats(); private readonly AtomicCounter _statsResetCount = new AtomicCounter(); /// <summary> /// Creates a started client runner. /// </summary> public static ClientRunner Start(ILoggerFactory loggerFactory, ClientConfig config) { var logger = loggerFactory.CreateLogger<ClientRunner>(); logger.LogDebug("ClientConfig: {0}", config); if (config.AsyncClientThreads != 0) { logger.LogWarning("ClientConfig.AsyncClientThreads is not supported for C#. Ignoring the value"); } if (config.CoreLimit != 0) { logger.LogWarning("ClientConfig.CoreLimit is not supported for C#. Ignoring the value"); } if (config.CoreList.Count > 0) { logger.LogWarning("ClientConfig.CoreList is not supported for C#. Ignoring the value"); } var configRoot = ConfigHelpers.GetConfiguration(); var clientLoggerFactory = LoggerFactory.Create(builder => { if (Enum.TryParse<LogLevel>(configRoot["LogLevel"], out var logLevel) && logLevel != LogLevel.None) { logger.LogInformation($"Console Logging enabled with level '{logLevel}'"); builder.AddSimpleConsole(o => o.TimestampFormat = "ss.ffff ").SetMinimumLevel(logLevel); } }); var channels = CreateChannels( config.ClientChannels, config.ServerTargets, config.SecurityParams, clientLoggerFactory); return new ClientRunner(channels, config.ClientType, config.RpcType, config.OutstandingRpcsPerChannel, config.LoadParams, config.PayloadConfig, config.HistogramParams, logger); } private static List<GrpcChannel> CreateChannels( int clientChannels, IEnumerable<string> serverTargets, SecurityParams securityParams, ILoggerFactory clientLoggerFactory) { GrpcPreconditions.CheckArgument(clientChannels > 0, "clientChannels needs to be at least 1."); GrpcPreconditions.CheckArgument(serverTargets.Count() > 0, "at least one serverTarget needs to be specified."); var result = new List<GrpcChannel>(); for (var i = 0; i < clientChannels; i++) { var target = serverTargets.ElementAt(i % serverTargets.Count()); // Contents of "securityParams" (useTestCa and sslTargetHostOverride) are basically ignored. // Instead the client just uses TLS and disable any certificate checks. var prefix = (securityParams == null) ? "http://" : "https://"; var channel = GrpcChannel.ForAddress(prefix + target, new GrpcChannelOptions { HttpHandler = new SocketsHttpHandler { EnableMultipleHttp2Connections = true, SslOptions = new SslClientAuthenticationOptions { // Ignore TLS certificate errors. RemoteCertificateValidationCallback = (_, __, ___, ____) => true } }, LoggerFactory = clientLoggerFactory }); result.Add(channel); } return result; } public ClientRunner(List<GrpcChannel> channels, ClientType clientType, RpcType rpcType, int outstandingRpcsPerChannel, LoadParams loadParams, PayloadConfig payloadConfig, HistogramParams histogramParams, ILogger logger) { GrpcPreconditions.CheckArgument(outstandingRpcsPerChannel > 0, nameof(outstandingRpcsPerChannel)); GrpcPreconditions.CheckNotNull(histogramParams, nameof(histogramParams)); GrpcPreconditions.CheckNotNull(loadParams, nameof(loadParams)); GrpcPreconditions.CheckNotNull(payloadConfig, nameof(payloadConfig)); _channels = new List<GrpcChannel>(channels); _clientType = clientType; _rpcType = rpcType; _payloadConfig = payloadConfig; _logger = logger; _cachedByteBufferRequest = new Lazy<byte[]>(() => new byte[payloadConfig.BytebufParams.ReqSize]); _threadLocalHistogram = new ThreadLocal<Histogram>(() => new Histogram(histogramParams.Resolution, histogramParams.MaxPossible), true); _runnerTasks = new List<Task>(); foreach (var channel in _channels) { for (var i = 0; i < outstandingRpcsPerChannel; i++) { var timer = CreateTimer(loadParams, 1.0 / _channels.Count / outstandingRpcsPerChannel); _runnerTasks.Add(RunClientAsync(channel, timer)); } } } public ClientStats GetStats(bool reset) { var histogramData = new HistogramData(); foreach (var hist in _threadLocalHistogram.Values) { hist.GetSnapshot(histogramData, reset); } var timeSnapshot = _timeStats.GetSnapshot(reset); if (reset) { _statsResetCount.Increment(); } _logger.LogInformation( $"[ClientRunnerImpl.GetStats] GC collection counts: gen0 {GC.CollectionCount(0)}, gen1 {GC.CollectionCount(1)}, gen2 {GC.CollectionCount(2)}, (histogram reset count:{_statsResetCount.Count}, seconds since reset: {timeSnapshot.WallClockTime.TotalSeconds})"); return new ClientStats { Latencies = histogramData, TimeElapsed = timeSnapshot.WallClockTime.TotalSeconds, TimeUser = timeSnapshot.UserProcessorTime.TotalSeconds, TimeSystem = timeSnapshot.PrivilegedProcessorTime.TotalSeconds }; } public async Task StopAsync() { _stoppedCts.Cancel(); foreach (var runnerTask in _runnerTasks) { await runnerTask; } foreach (var channel in _channels) { await channel.ShutdownAsync(); } } private void RunUnary(GrpcChannel channel, IInterarrivalTimer timer) { var client = new BenchmarkService.BenchmarkServiceClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!_stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); client.UnaryCall(request); stopwatch.Stop(); // spec requires data point in nanoseconds. _threadLocalHistogram.Value!.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); timer.WaitForNext(); } } private async Task RunUnaryAsync(GrpcChannel channel, IInterarrivalTimer timer) { var client = new BenchmarkService.BenchmarkServiceClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); while (!_stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await client.UnaryCallAsync(request); stopwatch.Stop(); // spec requires data point in nanoseconds. _threadLocalHistogram.Value!.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } } private async Task RunStreamingPingPongAsync(GrpcChannel channel, IInterarrivalTimer timer) { var client = new BenchmarkService.BenchmarkServiceClient(channel); var request = CreateSimpleRequest(); var stopwatch = new Stopwatch(); using (var call = client.StreamingCall()) { while (!_stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. _threadLocalHistogram.Value!.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); if (await call.ResponseStream.MoveNext()) { throw new InvalidOperationException("Expected response stream end."); } } } private async Task RunGenericStreamingAsync(GrpcChannel channel, IInterarrivalTimer timer) { var request = _cachedByteBufferRequest.Value; var stopwatch = new Stopwatch(); var invoker = channel.CreateCallInvoker(); using (var call = invoker.AsyncDuplexStreamingCall(GenericService.StreamingCallMethod, host: null, new CallOptions())) { while (!_stoppedCts.Token.IsCancellationRequested) { stopwatch.Restart(); await call.RequestStream.WriteAsync(request); await call.ResponseStream.MoveNext(); stopwatch.Stop(); // spec requires data point in nanoseconds. _threadLocalHistogram.Value!.AddObservation(stopwatch.Elapsed.TotalSeconds * SecondsToNanos); await timer.WaitForNextAsync(); } // finish the streaming call await call.RequestStream.CompleteAsync(); if (await call.ResponseStream.MoveNext()) { throw new InvalidOperationException("Expected response stream end."); } } } private Task RunClientAsync(GrpcChannel channel, IInterarrivalTimer timer) { if (_payloadConfig.PayloadCase == PayloadConfig.PayloadOneofCase.BytebufParams) { GrpcPreconditions.CheckArgument(_clientType == ClientType.AsyncClient, "Generic client only supports async API"); GrpcPreconditions.CheckArgument(_rpcType == RpcType.Streaming, "Generic client only supports streaming calls"); return RunGenericStreamingAsync(channel, timer); } GrpcPreconditions.CheckNotNull(_payloadConfig.SimpleParams, "SimpleParams"); if (_clientType == ClientType.SyncClient) { GrpcPreconditions.CheckArgument(_rpcType == RpcType.Unary, "Sync client can only be used for Unary calls in C#"); // create a dedicated thread for the synchronous client return Task.Factory.StartNew(() => RunUnary(channel, timer), TaskCreationOptions.LongRunning); } else if (_clientType == ClientType.AsyncClient) { switch (_rpcType) { case RpcType.Unary: return RunUnaryAsync(channel, timer); case RpcType.Streaming: return RunStreamingPingPongAsync(channel, timer); } } throw new ArgumentException("Unsupported configuration."); } private SimpleRequest CreateSimpleRequest() { GrpcPreconditions.CheckNotNull(_payloadConfig.SimpleParams, "SimpleParams"); return new SimpleRequest { Payload = CreateZerosPayload(_payloadConfig.SimpleParams.ReqSize), ResponseSize = _payloadConfig.SimpleParams.RespSize }; } private static Payload CreateZerosPayload(int size) { return new Payload { Body = ByteString.CopyFrom(new byte[size]) }; } private static IInterarrivalTimer CreateTimer(LoadParams loadParams, double loadMultiplier) { switch (loadParams.LoadCase) { case LoadParams.LoadOneofCase.ClosedLoop: return new ClosedLoopInterarrivalTimer(); case LoadParams.LoadOneofCase.Poisson: return new PoissonInterarrivalTimer(loadParams.Poisson.OfferedLoad * loadMultiplier); default: throw new ArgumentException("Unknown load type"); } } }
ClientRunner
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp.EntityFrameworkCore/EntityFrameworkCore/Linq/EfCoreAsyncQueryableExecuter.cs
{ "start": 259, "end": 1883 }
public class ____ : IAsyncQueryableExecuter, ISingletonDependency { private readonly ICancellationTokenProvider _cancellationTokenProvider; public EfCoreAsyncQueryableExecuter(ICancellationTokenProvider cancellationTokenProvider) { _cancellationTokenProvider = cancellationTokenProvider; } public Task<int> CountAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { return ExecuteAsync(queryable, (q, token) => q.CountAsync(token), cancellationToken); } public Task<List<T>> ToListAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { return ExecuteAsync(queryable, (q, token) => q.ToListAsync(token), cancellationToken); } public Task<T> FirstOrDefaultAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { return ExecuteAsync(queryable, (q, token) => q.FirstOrDefaultAsync(token), cancellationToken); } public Task<bool> AnyAsync<T>(IQueryable<T> queryable, CancellationToken cancellationToken = default) { return ExecuteAsync(queryable, (q, token) => q.AnyAsync(token), cancellationToken); } private async Task<TResult> ExecuteAsync<T, TResult>(IQueryable<T> queryable, Func<IQueryable<T>, CancellationToken, Task<TResult>> executeMethod, CancellationToken cancellationToken = default) { cancellationToken = _cancellationTokenProvider.FallbackToProvider(cancellationToken); return await executeMethod(queryable, cancellationToken).ConfigureAwait(false); } }
EfCoreAsyncQueryableExecuter
csharp
Xabaril__AspNetCore.Diagnostics.HealthChecks
src/HealthChecks.UI.K8s.Operator/Operator/HealthChecksPushService.cs
{ "start": 195, "end": 2997 }
public class ____ { private static readonly JsonSerializerOptions _options = new() { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; #pragma warning disable IDE1006 // Naming Styles public static async Task PushNotification( //TODO: rename public API #pragma warning restore IDE1006 // Naming Styles WatchEventType eventType, HealthCheckResource resource, V1Service uiService, V1Service notificationService, V1Secret endpointSecret, ILogger<K8sOperator> logger, IHttpClientFactory httpClientFactory) { var address = KubernetesAddressFactory.CreateHealthAddress(notificationService, resource); var uiAddress = KubernetesAddressFactory.CreateAddress(uiService, resource); dynamic healthCheck = new { Type = eventType, notificationService.Metadata.Name, Uri = address }; using var client = httpClientFactory.CreateClient(); try { string type = healthCheck.Type.ToString(); string name = healthCheck.Name; string uri = healthCheck.Uri; logger.LogInformation("[PushService] Namespace {Namespace} - Sending Type: {type} - Service {name} with uri : {uri} to ui endpoint: {address}", resource.Metadata.NamespaceProperty, type, name, uri, uiAddress); var key = Encoding.UTF8.GetString(endpointSecret.Data["key"]); using var request = new HttpRequestMessage(HttpMethod.Post, $"{uiAddress}{Constants.PUSH_SERVICE_PATH}?{Constants.PUSH_SERVICE_AUTH_KEY}={key}") { Content = new StringContent(JsonSerializer.Serialize(healthCheck, _options), Encoding.UTF8, "application/json") }; using var response = await client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead); logger.LogInformation("[PushService] Notification result for {name} - status code: {statuscode}", notificationService.Metadata.Name, response.StatusCode); } catch (Exception ex) { logger.LogError("Error notifying healthcheck service: {message}", ex.Message); } } private static (string address, V1ServicePort? port) GetServiceAddress(V1Service service) { string IpAddress; if (service.Spec.Type == ServiceType.LoadBalancer) { var ingress = service.Status?.LoadBalancer?.Ingress?.FirstOrDefault(); IpAddress = ingress == null ? service.Spec.ClusterIP : ingress.Ip ?? ingress.Hostname; } else { IpAddress = service.Spec.ClusterIP; } return (IpAddress, service.Spec.Ports.FirstOrDefault()); } }
HealthChecksPushService
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL/Utilities/StringUtils.cs
{ "start": 101, "end": 4731 }
public static class ____ { /// <summary> /// Given array of strings [ "A", "B", "C" ] return one string "'A', 'B' or 'C'". /// </summary> public static string QuotedOrList(IEnumerable<string> items, int maxLength = 5) //TODO: make internal in v5 and change items type { string[] itemsArray = items.Take(maxLength).ToArray(); int index = 0; return itemsArray .Select(x => $"'{x}'") .Aggregate((list, quoted) => list + (itemsArray.Length > 2 ? ", " : " ") + (++index == itemsArray.Length - 1 ? "or " : "") + quoted); } /// <summary> /// Given an invalid input string and a list of valid options, returns a filtered /// list of valid options sorted based on their similarity with the input. /// </summary> public static string[] SuggestionList(string input, IEnumerable<string>? options) { if (options == null) { return Array.Empty<string>(); } var optionsByDistance = new Dictionary<string, int>(); var inputThreshold = input.Length / 2; foreach (string t in options) { var distance = DamerauLevenshteinDistance(input, t, inputThreshold); var threshold = Math.Max(inputThreshold, Math.Max(t.Length / 2, 1)); if (distance <= threshold) { optionsByDistance[t] = distance; } } return optionsByDistance.OrderBy(x => x.Value).Select(x => x.Key).ToArray(); } /// <summary> /// Computes the Damerau-Levenshtein Distance between two strings, represented as arrays of /// integers, where each integer represents the code point of a character in the source string. /// Includes an optional threshold which can be used to indicate the maximum allowable distance. /// http://stackoverflow.com/a/9454016/279764 /// </summary> /// <param name="source">An array of the code points of the first string</param> /// <param name="target">An array of the code points of the second string</param> /// <param name="threshold">Maximum allowable distance</param> /// <returns>Int.MaxValue if threshold exceeded; otherwise the Damerau-Levenshtein distance between the strings</returns> public static int DamerauLevenshteinDistance(string source, string target, int threshold) { int length1 = source.Length; int length2 = target.Length; // Return trivial case - difference in string lengths exceeds threshold if (Math.Abs(length1 - length2) > threshold) return int.MaxValue; // Ensure arrays [i] / length1 use shorter length if (length1 > length2) { Swap(ref target, ref source); Swap(ref length1, ref length2); } int maxi = length1; int maxj = length2; int[] dCurrent = new int[maxi + 1]; int[] dMinus1 = new int[maxi + 1]; int[] dMinus2 = new int[maxi + 1]; int[] dSwap; for (int i = 0; i <= maxi; i++) dCurrent[i] = i; int jm1 = 0, im1, im2; for (int j = 1; j <= maxj; j++) { // Rotate dSwap = dMinus2; dMinus2 = dMinus1; dMinus1 = dCurrent; dCurrent = dSwap; // Initialize int minDistance = int.MaxValue; dCurrent[0] = j; im1 = 0; im2 = -1; for (int i = 1; i <= maxi; i++) { int cost = source[im1] == target[jm1] ? 0 : 1; int del = dCurrent[im1] + 1; int ins = dMinus1[i] + 1; int sub = dMinus1[im1] + cost; //Fastest execution for min value of 3 integers int min = (del > ins) ? (ins > sub ? sub : ins) : (del > sub ? sub : del); if (i > 1 && j > 1 && source[im2] == target[jm1] && source[im1] == target[j - 2]) min = Math.Min(min, dMinus2[im2] + cost); dCurrent[i] = min; if (min < minDistance) minDistance = min; im1++; im2++; } jm1++; if (minDistance > threshold) return int.MaxValue; } int result = dCurrent[maxi]; return result > threshold ? int.MaxValue : result; static void Swap<T>(ref T arg1, ref T arg2) { T temp = arg1; arg1 = arg2; arg2 = temp; } } }
StringUtils
csharp
dotnet__aspnetcore
src/Components/Server/src/Circuits/CircuitPersistenceManager.cs
{ "start": 553, "end": 7416 }
internal partial class ____( IOptions<CircuitOptions> circuitOptions, ServerComponentSerializer serverComponentSerializer, ICircuitPersistenceProvider circuitPersistenceProvider, IDataProtectionProvider dataProtectionProvider) { public async Task PauseCircuitAsync(CircuitHost circuit, bool saveStateToClient = false, CancellationToken cancellation = default) { await circuit.Renderer.Dispatcher.InvokeAsync(async () => { var renderer = circuit.Renderer; var persistenceManager = circuit.Services.GetRequiredService<ComponentStatePersistenceManager>(); var collector = new CircuitPersistenceManagerCollector(circuitOptions, serverComponentSerializer, circuit.Renderer); using var subscription = persistenceManager.State.RegisterOnPersisting( collector.PersistRootComponents, RenderMode.InteractiveServer); await persistenceManager.PersistStateAsync(collector, renderer); if (saveStateToClient) { await SaveStateToClient(circuit, collector.PersistedCircuitState, cancellation); } else { await circuitPersistenceProvider.PersistCircuitAsync( circuit.CircuitId, collector.PersistedCircuitState, cancellation); } }); } internal async Task SaveStateToClient(CircuitHost circuit, PersistedCircuitState state, CancellationToken cancellation = default) { var (rootComponents, applicationState) = await ToProtectedStateAsync(state); if (!await circuit.SendPersistedStateToClient(rootComponents, applicationState, cancellation)) { try { await circuitPersistenceProvider.PersistCircuitAsync( circuit.CircuitId, state, cancellation); } catch (Exception) { // At this point, we give up as we haven't been able to save the state to the client nor the server. return; } } } internal async Task<(string rootComponents, string applicationState)> ToProtectedStateAsync(PersistedCircuitState state) { // Root components descriptors are already protected and serialized as JSON, we just convert the bytes to a string. var rootComponents = Encoding.UTF8.GetString(state.RootComponents); // The application state we protect in the same way we do for prerendering. var store = new ProtectedPrerenderComponentApplicationStore(dataProtectionProvider); await store.PersistStateAsync(state.ApplicationState); return (rootComponents, store.PersistedState); } internal PersistedCircuitState FromProtectedState(string rootComponents, string applicationState) { var rootComponentsBytes = Encoding.UTF8.GetBytes(rootComponents); var prerenderedState = new ProtectedPrerenderComponentApplicationStore(applicationState, dataProtectionProvider); var state = new PersistedCircuitState { RootComponents = rootComponentsBytes, ApplicationState = prerenderedState.ExistingState }; return state; } internal ProtectedPrerenderComponentApplicationStore ToComponentApplicationStore(Dictionary<string, byte[]> applicationState) { return new ProtectedPrerenderComponentApplicationStore(applicationState, dataProtectionProvider); } public async Task<PersistedCircuitState> ResumeCircuitAsync(CircuitId circuitId, CancellationToken cancellation = default) { return await circuitPersistenceProvider.RestoreCircuitAsync(circuitId, cancellation); } // We are going to construct a RootComponentOperationBatch but we are going to replace the descriptors from the client with the // descriptors that we have persisted when pausing the circuit. // The way pausing and resuming works is that when the client starts the resume process, it 'simulates' that an SSR has happened and // queues an 'Add' operation for each server-side component that is on the document. // That ends up calling UpdateRootComponents with the old descriptors and no application state. // On the server side, we replace the descriptors with the ones that we have persisted. We can't use the original descriptors because // those have a lifetime of ~ 5 minutes, after which we are not able to unprotect them anymore. internal static RootComponentOperationBatch ToRootComponentOperationBatch( IServerComponentDeserializer serverComponentDeserializer, byte[] rootComponents, string serializedComponentOperations) { // Deserialize the existing batch the client has sent but ignore the markers if (!serverComponentDeserializer.TryDeserializeRootComponentOperations( serializedComponentOperations, out var batch, deserializeDescriptors: false)) { return null; } var persistedMarkers = TryDeserializeMarkers(rootComponents); if (persistedMarkers == null) { return null; } if (batch.Operations.Length != persistedMarkers.Count) { return null; } // Ensure that all operations in the batch are `Add` operations. for (var i = 0; i < batch.Operations.Length; i++) { var operation = batch.Operations[i]; if (operation.Type != RootComponentOperationType.Add) { return null; } // Retrieve the marker from the persisted root components, replace it and deserialize the descriptor if (!persistedMarkers.TryGetValue(operation.SsrComponentId, out var marker)) { return null; } operation.Marker = marker; if (!serverComponentDeserializer.TryDeserializeWebRootComponentDescriptor(operation.Marker.Value, out var descriptor)) { return null; } operation.Descriptor = descriptor; } return batch; static Dictionary<int, ComponentMarker> TryDeserializeMarkers(byte[] rootComponents) { if (rootComponents == null || rootComponents.Length == 0) { return null; } try { return JsonSerializer.Deserialize<Dictionary<int, ComponentMarker>>( rootComponents, JsonSerializerOptionsProvider.Options); } catch { return null; } } }
CircuitPersistenceManager
csharp
getsentry__sentry-dotnet
src/Sentry/Protocol/Envelopes/EnvelopeItem.cs
{ "start": 203, "end": 16792 }
public sealed class ____ : ISerializable, IDisposable { private const string TypeKey = "type"; internal const string TypeValueEvent = "event"; internal const string TypeValueFeedback = "feedback"; internal const string TypeValueUserReport = "user_report"; internal const string TypeValueTransaction = "transaction"; internal const string TypeValueSpan = "span"; internal const string TypeValueSession = "session"; internal const string TypeValueCheckIn = "check_in"; internal const string TypeValueAttachment = "attachment"; internal const string TypeValueClientReport = "client_report"; internal const string TypeValueProfile = "profile"; internal const string TypeValueMetric = "statsd"; internal const string TypeValueCodeLocations = "metric_meta"; internal const string TypeValueLog = "log"; private const string LengthKey = "length"; private const string FileNameKey = "filename"; /// <summary> /// Header associated with this envelope item. /// </summary> public IReadOnlyDictionary<string, object?> Header { get; } /// <summary> /// Item payload. /// </summary> public ISerializable Payload { get; } internal DataCategory DataCategory => TryGetType() switch { // Yes, the "event" item type corresponds to the "error" data category TypeValueEvent => DataCategory.Error, // These ones are equivalent TypeValueTransaction => DataCategory.Transaction, TypeValueSpan => DataCategory.Span, TypeValueSession => DataCategory.Session, TypeValueAttachment => DataCategory.Attachment, TypeValueProfile => DataCategory.Profile, // Not all envelope item types equate to data categories // Specifically, user_report and client_report just use "default" _ => DataCategory.Default }; /// <summary> /// Initializes an instance of <see cref="EnvelopeItem"/>. /// </summary> public EnvelopeItem(IReadOnlyDictionary<string, object?> header, ISerializable payload) { Header = header; Payload = payload; } /// <summary> /// Tries to get item type. /// </summary> public string? TryGetType() => Header.GetValueOrDefault(TypeKey) as string; /// <summary> /// Tries to get payload length. /// </summary> public long? TryGetLength() => Header.GetValueOrDefault(LengthKey) switch { null => null, var value => Convert.ToInt64(value) // can be int, long, or another numeric type }; internal long? TryGetOrRecalculateLength() { if (TryGetLength() is { } headerLength) { return headerLength; } if (Payload is StreamSerializable streamSerializable) { return streamSerializable.Source.TryGetLength(); } return null; } /// <summary> /// Returns the file name or null if no name exists. /// </summary> /// <returns>The file name or null.</returns> public string? TryGetFileName() => Header.GetValueOrDefault(FileNameKey) as string; private async Task<MemoryStream> BufferPayloadAsync(IDiagnosticLogger? logger, CancellationToken cancellationToken) { var buffer = new MemoryStream(); if (Payload is JsonSerializable jsonSerializable) { // There's no advantage to buffer fully-materialized in-memory objects asynchronously, // and there's some minor overhead in doing so. Thus we will serialize synchronously. // ReSharper disable once MethodHasAsyncOverloadWithCancellation jsonSerializable.Serialize(buffer, logger); } else { await Payload.SerializeAsync(buffer, logger, cancellationToken).ConfigureAwait(false); } buffer.Seek(0, SeekOrigin.Begin); return buffer; } private MemoryStream BufferPayload(IDiagnosticLogger? logger) { var buffer = new MemoryStream(); Payload.Serialize(buffer, logger); buffer.Seek(0, SeekOrigin.Begin); return buffer; } private static async Task SerializeHeaderAsync( Stream stream, IReadOnlyDictionary<string, object?> header, IDiagnosticLogger? logger, CancellationToken cancellationToken) { var writer = new Utf8JsonWriter(stream); await using (writer.ConfigureAwait(false)) { writer.WriteDictionaryValue(header, logger); await writer.FlushAsync(cancellationToken).ConfigureAwait(false); } } private static void SerializeHeader( Stream stream, IReadOnlyDictionary<string, object?> header, IDiagnosticLogger? logger) { using var writer = new Utf8JsonWriter(stream); writer.WriteDictionaryValue(header, logger); writer.Flush(); } /// <inheritdoc /> public async Task SerializeAsync(Stream stream, IDiagnosticLogger? logger, CancellationToken cancellationToken = default) { // Always calculate the length of the payload, as Sentry will reject envelopes that have incorrect lengths // in item headers. Don't trust any previously calculated value to be correct. // See https://github.com/getsentry/sentry-dotnet/issues/1956 var payloadBuffer = await BufferPayloadAsync(logger, cancellationToken).ConfigureAwait(false); #if NETFRAMEWORK || NETSTANDARD2_0 using (payloadBuffer) #else await using (payloadBuffer.ConfigureAwait(false)) #endif { // Write to the outbound stream asynchronously. It's likely either an HttpRequestStream or a FileStream. // Header var headerWithLength = Header.ToDict(); headerWithLength[LengthKey] = payloadBuffer.Length; await SerializeHeaderAsync(stream, headerWithLength, logger, cancellationToken).ConfigureAwait(false); await stream.WriteNewlineAsync(cancellationToken).ConfigureAwait(false); // Payload await payloadBuffer.CopyToAsync(stream, cancellationToken).ConfigureAwait(false); } } /// <inheritdoc /> public void Serialize(Stream stream, IDiagnosticLogger? logger) { // Always calculate the length of the payload, as Sentry will reject envelopes that have incorrect lengths // in item headers. Don't trust any previously calculated value to be correct. // See https://github.com/getsentry/sentry-dotnet/issues/1956 using var payloadBuffer = BufferPayload(logger); // Header var headerWithLength = Header.ToDict(); headerWithLength[LengthKey] = payloadBuffer.Length; SerializeHeader(stream, headerWithLength, logger); stream.WriteNewline(); // Payload payloadBuffer.CopyTo(stream); } /// <inheritdoc /> public void Dispose() => (Payload as IDisposable)?.Dispose(); /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="event"/>. /// </summary> public static EnvelopeItem FromEvent(SentryEvent @event) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueEvent }; return new EnvelopeItem(header, new JsonSerializable(@event)); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from a feedback <paramref name="event"/>. /// </summary> public static EnvelopeItem FromFeedback(SentryEvent @event) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueFeedback }; return new EnvelopeItem(header, new JsonSerializable(@event)); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="transaction"/>. /// </summary> public static EnvelopeItem FromTransaction(SentryTransaction transaction) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueTransaction }; return new EnvelopeItem(header, new JsonSerializable(transaction)); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from one or more <paramref name="codeLocations"/>. /// </summary> internal static EnvelopeItem FromCodeLocations(CodeLocations codeLocations) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueCodeLocations }; // Note that metrics are serialized using statsd encoding (not JSON) return new EnvelopeItem(header, new JsonSerializable(codeLocations)); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="metric"/>. /// </summary> internal static EnvelopeItem FromMetric(Metric metric) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueMetric }; // Note that metrics are serialized using statsd encoding (not JSON) return new EnvelopeItem(header, metric); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="source"/>. /// </summary> internal static EnvelopeItem FromProfileInfo(ISerializable source) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueProfile }; return new EnvelopeItem(header, source); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="sessionUpdate"/>. /// </summary> public static EnvelopeItem FromSession(SessionUpdate sessionUpdate) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueSession }; return new EnvelopeItem(header, new JsonSerializable(sessionUpdate)); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="checkIn"/>. /// </summary> public static EnvelopeItem FromCheckIn(SentryCheckIn checkIn) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueCheckIn }; return new EnvelopeItem(header, new JsonSerializable(checkIn)); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="attachment"/>. /// </summary> public static EnvelopeItem FromAttachment(SentryAttachment attachment) { var stream = attachment.Content.GetStream(); return FromAttachment(attachment, stream); } internal static EnvelopeItem FromAttachment(SentryAttachment attachment, Stream stream) { var attachmentType = attachment.Type switch { AttachmentType.Minidump => "event.minidump", AttachmentType.AppleCrashReport => "event.applecrashreport", AttachmentType.UnrealContext => "unreal.context", AttachmentType.UnrealLogs => "unreal.logs", AttachmentType.ViewHierarchy => "event.view_hierarchy", _ => "event.attachment" }; var header = new Dictionary<string, object?>(5, StringComparer.Ordinal) { [TypeKey] = TypeValueAttachment, [LengthKey] = stream.TryGetLength(), [FileNameKey] = attachment.FileName, ["attachment_type"] = attachmentType, ["content_type"] = attachment.ContentType }; return new EnvelopeItem(header, new StreamSerializable(stream)); } /// <summary> /// Creates an <see cref="EnvelopeItem"/> from <paramref name="report"/>. /// </summary> internal static EnvelopeItem FromClientReport(ClientReport report) { var header = new Dictionary<string, object?>(1, StringComparer.Ordinal) { [TypeKey] = TypeValueClientReport }; return new EnvelopeItem(header, new JsonSerializable(report)); } internal static EnvelopeItem FromLog(StructuredLog log) { var header = new Dictionary<string, object?>(3, StringComparer.Ordinal) { [TypeKey] = TypeValueLog, ["item_count"] = log.Length, ["content_type"] = "application/vnd.sentry.items.log+json", }; return new EnvelopeItem(header, new JsonSerializable(log)); } private static async Task<Dictionary<string, object?>> DeserializeHeaderAsync( Stream stream, CancellationToken cancellationToken = default) { var buffer = await stream.ReadLineAsync(cancellationToken).ConfigureAwait(false); return Json.Parse(buffer, JsonExtensions.GetDictionaryOrNull) ?? throw new InvalidOperationException("Envelope item header is malformed."); } private static async Task<ISerializable> DeserializePayloadAsync( Stream stream, IReadOnlyDictionary<string, object?> header, CancellationToken cancellationToken = default) { var payloadLength = header.GetValueOrDefault(LengthKey) switch { null => (long?)null, var value => Convert.ToInt64(value) }; var payloadType = header.GetValueOrDefault(TypeKey) as string; // Event if (string.Equals(payloadType, TypeValueEvent, StringComparison.OrdinalIgnoreCase)) { var bufferLength = (int)(payloadLength ?? stream.Length); var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false); var sentryEvent = Json.Parse(buffer, SentryEvent.FromJson); return new JsonSerializable(sentryEvent); } // Transaction if (string.Equals(payloadType, TypeValueTransaction, StringComparison.OrdinalIgnoreCase)) { var bufferLength = (int)(payloadLength ?? stream.Length); var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false); var transaction = Json.Parse(buffer, SentryTransaction.FromJson); return new JsonSerializable(transaction); } // Session if (string.Equals(payloadType, TypeValueSession, StringComparison.OrdinalIgnoreCase)) { var bufferLength = (int)(payloadLength ?? stream.Length); var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false); var sessionUpdate = Json.Parse(buffer, SessionUpdate.FromJson); return new JsonSerializable(sessionUpdate); } // Client Report if (string.Equals(payloadType, TypeValueClientReport, StringComparison.OrdinalIgnoreCase)) { var bufferLength = (int)(payloadLength ?? stream.Length); var buffer = await stream.ReadByteChunkAsync(bufferLength, cancellationToken).ConfigureAwait(false); var clientReport = Json.Parse(buffer, ClientReport.FromJson); return new JsonSerializable(clientReport); } // Arbitrary payload var payloadStream = new PartialStream(stream, stream.Position, payloadLength); if (payloadLength is not null) { stream.Seek(payloadLength.Value, SeekOrigin.Current); } else { stream.Seek(0, SeekOrigin.End); } return new StreamSerializable(payloadStream); } /// <summary> /// Deserializes envelope item from stream. /// </summary> public static async Task<EnvelopeItem> DeserializeAsync( Stream stream, CancellationToken cancellationToken = default) { var header = await DeserializeHeaderAsync(stream, cancellationToken).ConfigureAwait(false); var payload = await DeserializePayloadAsync(stream, header, cancellationToken).ConfigureAwait(false); // Swallow trailing newlines (some envelopes may have them after payloads) await stream.SkipNewlinesAsync(cancellationToken).ConfigureAwait(false); // Always remove the length header on deserialization so it will get re-calculated if later serialized. // We cannot trust the length to be identical when round-tripped. // See https://github.com/getsentry/sentry-dotnet/issues/1956 header.Remove(LengthKey); return new EnvelopeItem(header, payload); } }
EnvelopeItem
csharp
dotnet__efcore
test/EFCore.Specification.Tests/FindTestBase.cs
{ "start": 30465, "end": 30695 }
protected class ____ { public int Prop { get; set; } public Owned2 NestedOwned { get; set; } public List<Owned2> NestedOwnedCollection { get; set; } } [Owned]
Owned1
csharp
dotnet__efcore
test/EFCore.InMemory.FunctionalTests/ModelBuilding/InMemoryModelBuilderTest.cs
{ "start": 1829, "end": 2078 }
public class ____ : ModelBuilderFixtureBase { public override TestHelpers TestHelpers => InMemoryTestHelpers.Instance; public override bool ForeignKeysHaveIndexes => false; } }
InMemoryModelBuilderFixture
csharp
pythonnet__pythonnet
src/runtime/StateSerialization/TypeManagerState.cs
{ "start": 352, "end": 449 }
internal class ____ { public Dictionary<MaybeType, PyType> Cache { get; set; } }
TypeManagerState
csharp
dotnet__efcore
test/EFCore.Cosmos.FunctionalTests/Query/Translations/GuidTranslationsCosmosTest.cs
{ "start": 199, "end": 1674 }
public class ____ : GuidTranslationsTestBase<BasicTypesQueryCosmosFixture> { public GuidTranslationsCosmosTest(BasicTypesQueryCosmosFixture fixture, ITestOutputHelper testOutputHelper) : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } public override async Task New_with_constant() { await base.New_with_constant(); AssertSql( """ SELECT VALUE c FROM root c WHERE (c["Guid"] = "df36f493-463f-4123-83f9-6b135deeb7ba") """); } public override async Task New_with_parameter() { await base.New_with_parameter(); AssertSql( """ @p='df36f493-463f-4123-83f9-6b135deeb7ba' SELECT VALUE c FROM root c WHERE (c["Guid"] = @p) """); } public override async Task ToString_projection() { await base.ToString_projection(); AssertSql( """ SELECT VALUE c["Guid"] FROM root c """); } public override async Task NewGuid() { // Cosmos client evaluation. Issue #17246. await AssertTranslationFailed(() => base.NewGuid()); AssertSql(); } [ConditionalFact] public virtual void Check_all_tests_overridden() => TestHelpers.AssertAllMethodsOverridden(GetType()); private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); }
GuidTranslationsCosmosTest
csharp
dotnet__maui
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/XFIssue/Issue2470.cs
{ "start": 115, "end": 1499 }
public class ____ : _IssuesUITest { const string Generate = "Generate"; const string Results = "Results"; public Issue2470(TestDevice testDevice) : base(testDevice) { } public override string Issue => "ObservableCollection changes do not update ListView"; [Test] [Category(UITestCategories.ListView)] public void ObservableCollectionChangeListView() { App.WaitForElement("Switch"); // Tab 1 App.Tap("Switch"); App.TapTab(Results, isTopTab: true); // Tab 2 App.WaitForElementTillPageNavigationSettled("Entry 0 of 5"); App.WaitForElement("Entry 1 of 5"); App.WaitForElement("Entry 2 of 5"); App.WaitForElement("Entry 3 of 5"); App.WaitForElement("Entry 4 of 5"); App.TapTab(Generate, isTopTab: true); // Tab 1 App.WaitForElementTillPageNavigationSettled("Switch"); App.Tap("Switch"); App.TapTab(Results, isTopTab: true); // Tab 2 App.WaitForElementTillPageNavigationSettled("Entry 0 of 2"); App.WaitForElement("Entry 1 of 2"); // Tab 1 App.TapTab(Generate, isTopTab: true); App.WaitForElementTillPageNavigationSettled("Switch"); App.Tap("Switch"); App.TapTab(Results, isTopTab: true); // Tab 2 App.WaitForElementTillPageNavigationSettled("Entry 0 of 5"); App.WaitForElement("Entry 1 of 5"); App.WaitForElement("Entry 2 of 5"); App.WaitForElement("Entry 3 of 5"); App.WaitForElement("Entry 4 of 5"); } }
Issue2470
csharp
dotnet__orleans
test/Orleans.CodeGenerator.Tests/snapshots/OrleansSourceGeneratorTests.TestWithOmitDefaultMemberValuesAnnotation.verified.cs
{ "start": 993, "end": 5282 }
public sealed class ____ : global::Orleans.Serialization.Codecs.IFieldCodec<global::TestProject.DemoClass>, global::Orleans.Serialization.Serializers.IBaseCodec<global::TestProject.DemoClass> { private readonly global::System.Type _codecFieldType = typeof(global::TestProject.DemoClass); [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Serialize<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, global::TestProject.DemoClass instance) where TBufferWriter : global::System.Buffers.IBufferWriter<byte> { uint previousFieldId = 0U; if (instance.Value is object) { global::Orleans.Serialization.Codecs.StringCodec.WriteField(ref writer, 0U - previousFieldId, instance.Value); previousFieldId = 0U; } } [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void Deserialize<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::TestProject.DemoClass instance) { uint id = 0U; global::Orleans.Serialization.WireProtocol.Field header = default; while (true) { reader.ReadFieldHeader(ref header); if (header.IsEndBaseOrEndObject) break; id += header.FieldIdDelta; if (id == 0U) { instance.Value = global::Orleans.Serialization.Codecs.StringCodec.ReadValue(ref reader, header); reader.ReadFieldHeader(ref header); } reader.ConsumeEndBaseOrEndObject(ref header); break; } } [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public void WriteField<TBufferWriter>(ref global::Orleans.Serialization.Buffers.Writer<TBufferWriter> writer, uint fieldIdDelta, global::System.Type expectedType, global::TestProject.DemoClass @value) where TBufferWriter : global::System.Buffers.IBufferWriter<byte> { if (@value is null || @value.GetType() == typeof(global::TestProject.DemoClass)) { if (ReferenceCodec.TryWriteReferenceField(ref writer, fieldIdDelta, expectedType, @value)) return; writer.WriteStartObject(fieldIdDelta, expectedType, _codecFieldType); Serialize(ref writer, @value); writer.WriteEndObject(); } else writer.SerializeUnexpectedType(fieldIdDelta, expectedType, @value); } [global::System.Runtime.CompilerServices.MethodImplAttribute(global::System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)] public global::TestProject.DemoClass ReadValue<TReaderInput>(ref global::Orleans.Serialization.Buffers.Reader<TReaderInput> reader, global::Orleans.Serialization.WireProtocol.Field field) { if (field.IsReference) return ReferenceCodec.ReadReference<global::TestProject.DemoClass, TReaderInput>(ref reader, field); field.EnsureWireTypeTagDelimited(); global::System.Type valueType = field.FieldType; if (valueType is null || valueType == _codecFieldType) { var result = new global::TestProject.DemoClass(); ReferenceCodec.RecordObject(reader.Session, result); Deserialize(ref reader, result); return result; } return reader.DeserializeUnexpectedType<TReaderInput, global::TestProject.DemoClass>(ref field); } } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("OrleansCodeGen", "10.0.0.0"), global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Never), global::System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverageAttribute]
Codec_DemoClass
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.System.RemoteSystems/RemoteSystemSessionJoinResult.cs
{ "start": 303, "end": 1994 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal RemoteSystemSessionJoinResult() { } #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.System.RemoteSystems.RemoteSystemSession Session { get { throw new global::System.NotImplementedException("The member RemoteSystemSession RemoteSystemSessionJoinResult.Session is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=RemoteSystemSession%20RemoteSystemSessionJoinResult.Session"); } } #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.System.RemoteSystems.RemoteSystemSessionJoinStatus Status { get { throw new global::System.NotImplementedException("The member RemoteSystemSessionJoinStatus RemoteSystemSessionJoinResult.Status is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=RemoteSystemSessionJoinStatus%20RemoteSystemSessionJoinResult.Status"); } } #endif // Forced skipping of method Windows.System.RemoteSystems.RemoteSystemSessionJoinResult.Status.get // Forced skipping of method Windows.System.RemoteSystems.RemoteSystemSessionJoinResult.Session.get } }
RemoteSystemSessionJoinResult
csharp
atata-framework__atata
src/Atata/Components/Fields/NumberInput`1.cs
{ "start": 459, "end": 560 }
public class ____<TOwner> : Input<decimal?, TOwner> where TOwner : PageObject<TOwner> { }
NumberInput
csharp
abpframework__abp
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Utils/PlatformHelper.cs
{ "start": 85, "end": 1082 }
public class ____ { public static OSPlatform GetOperatingSystem() { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { //MAC return OSPlatform.OSX; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return OSPlatform.Linux; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return OSPlatform.Windows; } throw new Exception("Cannot determine operating system!"); } public static RuntimePlatform GetPlatform() { if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { return RuntimePlatform.LinuxOrMacOs; } if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { return RuntimePlatform.Windows; } throw new Exception("Cannot determine runtime platform!"); } }
PlatformHelper
csharp
App-vNext__Polly
src/Polly/PolicyResult.cs
{ "start": 2237, "end": 6470 }
public class ____<TResult> { internal PolicyResult(TResult result, OutcomeType outcome, Exception finalException, ExceptionType? exceptionType, Context context) : this(result, outcome, finalException, exceptionType, default, null, context) { } internal PolicyResult(TResult result, OutcomeType outcome, Exception finalException, ExceptionType? exceptionType, TResult finalHandledResult, FaultType? faultType, Context context) { Result = result; Outcome = outcome; FinalException = finalException; ExceptionType = exceptionType; FinalHandledResult = finalHandledResult; FaultType = faultType; Context = context; } /// <summary> /// Gets the outcome of executing the policy. /// </summary> public OutcomeType Outcome { get; } /// <summary> /// Gets the final exception captured. Will be null if policy executed without exception. /// </summary> public Exception FinalException { get; } /// <summary> /// Gets the exception type of the final exception captured. Will be null if policy executed successfully. /// </summary> public ExceptionType? ExceptionType { get; } /// <summary> /// Gets the result of executing the policy. Will be default(TResult) if the policy failed. /// </summary> public TResult Result { get; } /// <summary> /// Gets the final handled result captured. Will be default(TResult) if the policy executed successfully, or terminated with an exception. /// </summary> public TResult FinalHandledResult { get; } /// <summary> /// Gets the fault type of the final fault captured. Will be null if policy executed successfully. /// </summary> public FaultType? FaultType { get; } /// <summary> /// Gets the context for this execution. /// </summary> public Context Context { get; } /// <summary> /// Builds a <see cref="PolicyResult" /> representing a successful execution through the policy. /// </summary> /// <param name="result">The result returned by execution through the policy.</param> /// <param name="context">The policy execution context.</param> /// <returns> /// A <see cref="PolicyResult" /> representing a successful execution through the policy. /// </returns> public static PolicyResult<TResult> Successful(TResult result, Context context) => new(result, OutcomeType.Successful, null, null, context); /// <summary> /// Builds a <see cref="PolicyResult" /> representing a failed execution through the policy. /// </summary> /// <param name="exception">The exception.</param> /// <param name="exceptionType">The exception type.</param> /// <param name="context">The policy execution context.</param> /// <returns> /// A <see cref="PolicyResult" /> representing a failed execution through the policy. /// </returns> public static PolicyResult<TResult> Failure(Exception exception, ExceptionType exceptionType, Context context) { var faultType = exceptionType == Polly.ExceptionType.HandledByThisPolicy ? Polly.FaultType.ExceptionHandledByThisPolicy : Polly.FaultType.UnhandledException; return new PolicyResult<TResult>( default, OutcomeType.Failure, exception, exceptionType, default, faultType, context); } /// <summary> /// Builds a <see cref="PolicyResult" /> representing a failed execution through the policy. /// </summary> /// <param name="handledResult">The result returned by execution through the policy, which was treated as a handled failure.</param> /// <param name="context">The policy execution context.</param> /// <returns> /// A <see cref="PolicyResult" /> representing a failed execution through the policy. /// </returns> public static PolicyResult<TResult> Failure(TResult handledResult, Context context) => new(default, OutcomeType.Failure, null, null, handledResult, Polly.FaultType.ResultHandledByThisPolicy, context); } /// <summary> /// Represents the outcome of executing a policy. /// </summary>
PolicyResult
csharp
grpc__grpc-dotnet
examples/Uploader/Server/Services/UploaderService.cs
{ "start": 699, "end": 2024 }
public class ____ : Uploader.UploaderBase { private readonly ILogger _logger; private readonly IConfiguration _config; public UploaderService(ILoggerFactory loggerFactory, IConfiguration config) { _logger = loggerFactory.CreateLogger<UploaderService>(); _config = config; } public override async Task<UploadFileResponse> UploadFile(IAsyncStreamReader<UploadFileRequest> requestStream, ServerCallContext context) { var uploadId = Path.GetRandomFileName(); var uploadPath = Path.Combine(_config["StoredFilesPath"]!, uploadId); Directory.CreateDirectory(uploadPath); await using var writeStream = File.Create(Path.Combine(uploadPath, "data.bin")); await foreach (var message in requestStream.ReadAllAsync()) { if (message.Metadata != null) { await File.WriteAllTextAsync(Path.Combine(uploadPath, "metadata.json"), message.Metadata.ToString()); } if (message.Data != null) { await writeStream.WriteAsync(message.Data.Memory); } } return new UploadFileResponse { Id = uploadId }; } } }
UploaderService
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Execution.Types/Metadata/SourceInterfaceType.cs
{ "start": 1502, "end": 1631 }
interface ____ in the source schema. /// </summary> public ImmutableHashSet<string> Implements { get; } = implements; }
type
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Subjects/SubjectBase.cs
{ "start": 273, "end": 614 }
class ____ objects that are both an observable sequence as well as an observer. /// </summary> /// <typeparam name="T">The type of the elements processed by the subject.</typeparam> #pragma warning disable CA1063 // (Overridable IDisposable.) This analyzer wants us to make breaking changes to its public API, which we can't do.
for
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Tenants/Services/FeatureProfilesManager.cs
{ "start": 149, "end": 1430 }
public class ____ { private readonly IDocumentManager<FeatureProfilesDocument> _documentManager; public FeatureProfilesManager(IDocumentManager<FeatureProfilesDocument> documentManager) => _documentManager = documentManager; /// <summary> /// Loads the feature profiles document from the store for updating and that should not be cached. /// </summary> public Task<FeatureProfilesDocument> LoadFeatureProfilesDocumentAsync() => _documentManager.GetOrCreateMutableAsync(); /// <summary> /// Gets the feature profiles document from the cache for sharing and that should not be updated. /// </summary> public Task<FeatureProfilesDocument> GetFeatureProfilesDocumentAsync() => _documentManager.GetOrCreateImmutableAsync(); public async Task RemoveFeatureProfileAsync(string id) { var document = await LoadFeatureProfilesDocumentAsync(); document.FeatureProfiles.Remove(id); await _documentManager.UpdateAsync(document); } public async Task UpdateFeatureProfileAsync(string id, FeatureProfile profile) { var document = await LoadFeatureProfilesDocumentAsync(); document.FeatureProfiles[id] = profile; await _documentManager.UpdateAsync(document); } }
FeatureProfilesManager
csharp
dotnet__aspnetcore
src/Logging.AzureAppServices/src/FileLoggerConfigureOptions.cs
{ "start": 292, "end": 845 }
internal sealed class ____ : BatchLoggerConfigureOptions, IConfigureOptions<AzureFileLoggerOptions> { private readonly IWebAppContext _context; public FileLoggerConfigureOptions(IConfiguration configuration, IWebAppContext context) : base(configuration, "AzureDriveEnabled") { _context = context; } public void Configure(AzureFileLoggerOptions options) { base.Configure(options); options.LogDirectory = Path.Combine(_context.HomeFolder, "LogFiles", "Application"); } }
FileLoggerConfigureOptions
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Core/Servers/TopologyVersion.cs
{ "start": 1110, "end": 9947 }
public sealed class ____ : IEquatable<TopologyVersion>, IConvertibleToBsonDocument { #region static // public static methods /// <summary> /// Compares a local TopologyVersion with a server's TopologyVersion and indicates whether the local /// TopologyVersion is staler, fresher, or equal to the server's TopologyVersion. /// Per the SDAM specification, if the ProcessIds are not equal, this method assumes that /// <paramref name="y"/> is more recent. This means that this method does not exhibit /// the reversal properties of inequalities i.e. a "&lt;" b does not imply b "&gt;" a. /// </summary> /// <param name="x">The first TopologyVersion.</param> /// <param name="y">The other TopologyVersion.</param> /// <returns> /// Less than zero indicates that the <paramref name="x"/> is staler than the <paramref name="y"/>. /// Zero indicates that the <paramref name="x"/> description is equal to the <paramref name="y"/>. /// Greater than zero indicates that the <paramref name="x"/> is fresher than the <paramref name="y"/>. /// </returns> public static int CompareTopologyVersion(TopologyVersion x, TopologyVersion y) { if (x == null || y == null) { return -1; } if (x.ProcessId == y.ProcessId) { return x.Counter.CompareTo(y.Counter); } return -1; } /// <summary> /// Attempts to create a TopologyVersion from the supplied BsonDocument. /// </summary> /// <param name="document">The document. Should contain an ObjectId named "processId" and a BsonInt64 named "counter".</param> /// <returns>A TopologyVersion if one could be constructed from the supplied document and null otherwise.</returns> public static TopologyVersion FromBsonDocument(BsonDocument document) { if (document.TryGetValue("processId", out var processIdValue) && processIdValue is BsonObjectId processId && document.TryGetValue("counter", out var counterValue) && counterValue is BsonInt64 counter) { return new TopologyVersion(processId.Value, counter.Value); } return null; } internal static TopologyVersion FromMongoCommandResponse(BsonDocument response) { if (response != null && response.TryGetValue("topologyVersion", out var topologyVersionValue) && topologyVersionValue is BsonDocument topologyVersion) { return FromBsonDocument(topologyVersion); } return null; } internal static TopologyVersion FromMongoCommandException(MongoCommandException commandException) { return FromMongoCommandResponse(commandException.Result); } /// <summary> /// Gets whether or not <paramref name="x"/> is fresher than <paramref name="y"/>. /// Comparing topology descriptions freshness does not exhibit the reversal property of /// inequalities e.g. a.IsFresherThan(b) (a "&lt;" b) does not imply /// !b.IsFresherThan(a) (b "&gt;" a) /// See <seealso cref="CompareTopologyVersion(TopologyVersion, TopologyVersion)"/> for more information. /// In the case that this.Equals(<paramref name="y"/>), <paramref name="y"/> will be considered to be fresher. /// </summary> /// <param name="x">The first TopologyVersion.</param> /// <param name="y">The other TopologyVersion.</param> /// <returns> /// Whether or not this TopologyVersion is fresher than <paramref name="y"/>. /// </returns> public static bool IsFresherThan(TopologyVersion x, TopologyVersion y) => CompareTopologyVersion(x, y) > 0; /// <summary> /// Gets whether or not <paramref name="x"/> is fresher than or Equal to <paramref name="y"/>. /// Comparing topology descriptions freshness does not exhibit the reversal property of /// inequalities e.g. a.IsFresherThan(b) (a "&lt;" b) does not imply /// !b.IsFresherThan(a) (b "&gt;" a) /// See <seealso cref="CompareTopologyVersion(TopologyVersion, TopologyVersion)"/> for more information. /// In the case that this.Equals(<paramref name="y"/>), <paramref name="y"/> will be considered to be fresher. /// </summary> /// <param name="x">The first TopologyVersion.</param> /// <param name="y">The other TopologyVersion.</param> /// <returns> /// Whether or not this TopologyVersion is fresher than <paramref name="y"/>. /// </returns> public static bool IsFresherThanOrEqualTo(TopologyVersion x, TopologyVersion y) => CompareTopologyVersion(x, y) >= 0; /// <summary> /// Gets whether or not <paramref name="x"/> is staler than or Equal to <paramref name="y"/>. /// Comparing topology descriptions freshness does not exhibit the reversal property of /// inequalities e.g. a.IsStalerThan(b) (a "&lt;" b) does not imply /// !b.IsStalerThan(a) (b "&gt;" a). /// See <seealso cref="CompareTopologyVersion(TopologyVersion, TopologyVersion)"/> for more information. /// In the case that this == <paramref name="y"/>, <paramref name="y"/> will be considered to be fresher. /// </summary> /// <param name="x">The first TopologyVersion.</param> /// <param name="y">The other TopologyVersion.</param> /// <returns> /// Whether or not this TopologyVersion is staler than <paramref name="y"/>. /// </returns> public static bool IsStalerThan(TopologyVersion x, TopologyVersion y) => CompareTopologyVersion(x, y) < 0; /// <summary> /// Gets whether or not <paramref name="x"/> is staler than or Equal to <paramref name="y"/>. /// Comparing topology descriptions freshness does not exhibit the reversal property of /// inequalities e.g. a.IsStalerThan(b) (a "&lt;" b) does not imply /// !b.IsStalerThan(a) (b "&gt;" a). /// See <seealso cref="CompareTopologyVersion(TopologyVersion, TopologyVersion)"/> for more information. /// In the case that this == <paramref name="y"/>, <paramref name="y"/> will be considered to be fresher. /// </summary> /// <param name="x">The first TopologyVersion.</param> /// <param name="y">The other TopologyVersion.</param> /// <returns> /// Whether or not this TopologyVersion is staler than <paramref name="y"/>. /// </returns> public static bool IsStalerThanOrEqualTo(TopologyVersion x, TopologyVersion y) => CompareTopologyVersion(x, y) <= 0; #endregion // private fields private readonly long _counter; private readonly int _hashCode; private readonly ObjectId _processId; // constructors /// <summary> /// Initializes a new instance of the <see cref="TopologyVersion"/> class. /// </summary> /// <param name="processId">The process identifier.</param> /// <param name="counter">The counter.</param> public TopologyVersion(ObjectId processId, long counter) { _processId = processId; _counter = counter; _hashCode = new Hasher().Hash(_processId).Hash(_counter).GetHashCode(); } // public properties // properties /// <summary> /// Gets the process identifier. /// </summary> /// <value> /// The process identifier. /// </value> public long Counter => _counter; // properties /// <summary> /// Gets the process identifier. /// </summary> /// <value> /// The process identifier. /// </value> public ObjectId ProcessId => _processId; // public methods /// <inheritdoc /> public override bool Equals(object obj) { return Equals(obj as TopologyVersion); } /// <inheritdoc /> public bool Equals(TopologyVersion other) { if (object.ReferenceEquals(other, null)) { return false; } return _counter == other._counter && _processId == other._processId; } /// <inheritdoc/> public override int GetHashCode() => _hashCode; /// <inheritdoc/> public BsonDocument ToBsonDocument() => new BsonDocument { { "processId", _processId }, { "counter", _counter } }; /// <inheritdoc/> public override string ToString() => ToBsonDocument().ToJson(); } }
TopologyVersion
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.PointOfService/BarcodeScannerImagePreviewReceivedEventArgs.cs
{ "start": 305, "end": 1360 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal BarcodeScannerImagePreviewReceivedEventArgs() { } #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.Storage.Streams.IRandomAccessStreamWithContentType Preview { get { throw new global::System.NotImplementedException("The member IRandomAccessStreamWithContentType BarcodeScannerImagePreviewReceivedEventArgs.Preview is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IRandomAccessStreamWithContentType%20BarcodeScannerImagePreviewReceivedEventArgs.Preview"); } } #endif // Forced skipping of method Windows.Devices.PointOfService.BarcodeScannerImagePreviewReceivedEventArgs.Preview.get } }
BarcodeScannerImagePreviewReceivedEventArgs