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
dotnet__maui
src/Essentials/src/Magnetometer/Magnetometer.android.cs
{ "start": 1024, "end": 1606 }
class ____ : Java.Lang.Object, ISensorEventListener { internal MagnetometerListener(Action<MagnetometerData> callback) { DataCallback = callback; } readonly Action<MagnetometerData> DataCallback; void ISensorEventListener.OnAccuracyChanged(Sensor? sensor, SensorStatus accuracy) { } void ISensorEventListener.OnSensorChanged(SensorEvent? e) { var values = e?.Values ?? Array.Empty<float>(); if (values.Count < 3) return; var data = new MagnetometerData(values[0], values[1], values[2]); DataCallback?.Invoke(data); } } }
MagnetometerListener
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToAggregationExpressionTranslators/MethodTranslators/PowMethodToAggregationExpressionTranslator.cs
{ "start": 968, "end": 2257 }
internal static class ____ { public static TranslatedExpression Translate(TranslationContext context, MethodCallExpression expression) { var method = expression.Method; var arguments = expression.Arguments; if (method.IsOneOf(MathMethod.Pow)) { var xExpression = arguments[0]; var yExpression = arguments[1]; var xTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, xExpression); var yTranslation = ExpressionToAggregationExpressionTranslator.Translate(context, yExpression); SerializationHelper.EnsureRepresentationIsNumeric(expression, xExpression, xTranslation); SerializationHelper.EnsureRepresentationIsNumeric(expression, yExpression, yTranslation); var xAst = ConvertHelper.RemoveWideningConvert(xTranslation); var yAst = ConvertHelper.RemoveWideningConvert(yTranslation); var ast = AstExpression.Pow(xAst, yAst); return new TranslatedExpression(expression, ast, new DoubleSerializer()); } throw new ExpressionNotSupportedException(expression); } } }
PowMethodToAggregationExpressionTranslator
csharp
MiniProfiler__dotnet
src/MiniProfiler.AspNetCore.Mvc/Internal/ProfilingViewComponentInvoker.cs
{ "start": 233, "end": 1348 }
public class ____ : IViewComponentInvoker { private readonly IViewComponentInvoker _defaultViewComponentInvoker; /// <summary> /// Creates a new <see cref="ProfilingViewComponentInvoker"/>. /// </summary> /// <param name="defaultViewComponentInvoker">The <see cref="IViewComponentInvoker"/> to wrap.</param> public ProfilingViewComponentInvoker(IViewComponentInvoker defaultViewComponentInvoker) => _defaultViewComponentInvoker = defaultViewComponentInvoker; /// <summary> /// Invokes the wrapped view component, wrapped in a profiler step. /// </summary> /// <param name="context">The <see cref="ViewComponentContext"/>.</param> public async Task InvokeAsync(ViewComponentContext context) { var viewComponentName = context.ViewComponentDescriptor.ShortName; using (MiniProfiler.Current.Step("ViewComponent: " + viewComponentName)) { await _defaultViewComponentInvoker.InvokeAsync(context); } } } }
ProfilingViewComponentInvoker
csharp
dotnet__efcore
test/EFCore.Tests/Metadata/Conventions/PropertyDiscoveryConventionTest.cs
{ "start": 4241, "end": 5015 }
private class ____ { public static int Static { get; set; } public int WriteOnly { // ReSharper disable once ValueParameterNotUsed set { } } public int ReadOnly { get; } public int PrivateGetter { private get; set; } public int this[int index] { get => 0; // ReSharper disable once ValueParameterNotUsed set { } } } [ConditionalFact] public void IsValidProperty_returns_false_when_invalid() { var entityBuilder = CreateInternalEntityBuilder<EntityWithInvalidProperties>(); RunConvention(entityBuilder); Assert.Empty(entityBuilder.Metadata.GetProperties()); }
EntityWithInvalidProperties
csharp
xunit__xunit
src/xunit.v3.core.tests/CulturedFactAttributeTests.cs
{ "start": 1109, "end": 1940 }
class ____ { [CulturedFact(["fr-FR"])] public void TestMethod() => Assert.Equal("fr-FR", CultureInfo.CurrentCulture.Name); } [Fact] public async ValueTask MultipleCultures() { var results = await RunForResultsAsync(typeof(TestClassWithMultipleCultures)); var passed = Assert.Single(results.OfType<TestPassedWithDisplayName>()); Assert.Equal($"{typeof(TestClassWithMultipleCultures).FullName}.{nameof(TestClassWithMultipleCultures.TestMethod)}[fr-FR]", passed.TestDisplayName); var failed = Assert.Single(results.OfType<TestFailedWithDisplayName>()); Assert.Equal($"{typeof(TestClassWithMultipleCultures).FullName}.{nameof(TestClassWithMultipleCultures.TestMethod)}[en-US]", failed.TestDisplayName); Assert.Equal(typeof(EqualException).FullName, failed.ExceptionTypes.Single()); }
TestClassWithSingleCulture
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Execution/Nodes/ExecutionNodeResult.cs
{ "start": 111, "end": 442 }
internal sealed record ____( int Id, Activity? Activity, ExecutionStatus Status, TimeSpan Duration, Exception? Exception, ImmutableArray<ExecutionNode> DependentsToExecute, ImmutableArray<VariableValues> VariableValueSets, (Uri? Uri, string? ContentType) TransportDetails = default);
ExecutionNodeResult
csharp
abpframework__abp
modules/cms-kit/src/Volo.CmsKit.Admin.Application.Contracts/Volo/CmsKit/Admin/Menus/UpdateMainMenuInput.cs
{ "start": 66, "end": 144 }
public class ____ { public bool IsMainMenu { get; set; } }
UpdateMainMenuInput
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests.Provider.Custom/MySql/MySqlExpression/StringTest.cs
{ "start": 677, "end": 956 }
class ____ { [Column(IsIdentity = true)] public int Guid { get; set; } public int ParentId { get; set; } public TestTypeParentInfo Parent { get; set; } public string Name { get; set; } }
TestTypeInfo
csharp
neuecc__MessagePack-CSharp
tests/MessagePack.SourceGenerator.Tests/MsgPack00xAnalyzerTests.cs
{ "start": 29009, "end": 29538 }
public class ____ : Base { public new string {|MsgPack018:Prop|} { get; set; } public new string {|MsgPack018:Field|}; public new string {|MsgPack018:TwoFaced|}; } """; await VerifyCS.VerifyAnalyzerAsync(test); } [Fact] public async Task AbstractFormatterDoesNotAttractAttention() { string test = /* lang=c#-test */ """ using MessagePack; using MessagePack.Formatters;
Derived
csharp
dotnet__reactive
AsyncRx.NET/System.Reactive.Async/Linq/Operators/ElementAt.cs
{ "start": 274, "end": 856 }
public partial class ____ { public static IAsyncObservable<TSource> ElementAt<TSource>(this IAsyncObservable<TSource> source, int index) { if (source == null) throw new ArgumentNullException(nameof(source)); if (index < 0) throw new ArgumentOutOfRangeException(nameof(index)); return Create( source, index, static (source, index, observer) => source.SubscribeSafeAsync(AsyncObserver.ElementAt(observer, index))); } }
AsyncObservable
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Documentation/PerformanceTests.cs
{ "start": 2262, "end": 2906 }
public class ____ : DefaultContractResolver { public new static readonly ConverterContractResolver Instance = new ConverterContractResolver(); protected override JsonContract CreateContract(Type objectType) { JsonContract contract = base.CreateContract(objectType); // this will only be called once and then cached if (objectType == typeof(DateTime) || objectType == typeof(DateTimeOffset)) { contract.Converter = new JavaScriptDateTimeConverter(); } return contract; } } #endregion
ConverterContractResolver
csharp
louthy__language-ext
LanguageExt.Core/Class Instances/TInt.cs
{ "start": 166, "end": 6210 }
public struct ____ : Num<int>, Bool<int> { /// <summary> /// Equality test /// </summary> /// <param name="x">The left hand side of the equality operation</param> /// <param name="y">The right hand side of the equality operation</param> /// <returns>True if x and y are equal</returns> [Pure] public static bool Equals(int x, int y) => x == y; /// <summary> /// Compare two values /// </summary> /// <param name="x">Left hand side of the compare operation</param> /// <param name="y">Right hand side of the compare operation</param> /// <returns> /// if x greater than y : 1 /// /// if x less than y : -1 /// /// if x equals y : 0 /// </returns> [Pure] public static int Compare(int x, int y) => x.CompareTo(y); /// <summary> /// Find the sum of two numbers /// </summary> /// <param name="x">left hand side of the addition operation</param> /// <param name="y">right hand side of the addition operation</param> /// <returns>The sum of x and y</returns> [Pure] public static int Add(int x, int y) => x + y; /// <summary> /// Find the difference between two values /// </summary> /// <param name="x">left hand side of the subtraction operation</param> /// <param name="y">right hand side of the subtraction operation</param> /// <returns>The difference between x and y</returns> [Pure] public static int Subtract(int x, int y) => x - y; /// <summary> /// Find the product of two numbers /// </summary> /// <param name="x">left hand side of the product operation</param> /// <param name="y">right hand side of the product operation</param> /// <returns>The product of x and y</returns> [Pure] public static int Multiply(int x, int y) => x * y; /// <summary> /// Divide two numbers /// </summary> /// <param name="x">left hand side of the division operation</param> /// <param name="y">right hand side of the division operation</param> /// <returns>x / y</returns> [Pure] public static int Divide(int x, int y) => x / y; /// <summary> /// Find the absolute value of a number /// </summary> /// <param name="x">The value to find the absolute value of</param> /// <returns>The non-negative absolute value of x</returns> [Pure] public static int Abs(int x) => Math.Abs(x); /// <summary> /// Find the sign of x /// </summary> /// <param name="x">The value to find the sign of</param> /// <returns>-1, 0, or +1</returns> [Pure] public static int Signum(int x) => Math.Sign(x); /// <summary> /// Generate a numeric value from an integer /// </summary> /// <param name="x">The integer to use</param> /// <returns>The equivalent of x in the Num〈A〉</returns> [Pure] public static int FromInteger(int x) => x; /// <summary> /// Generate a numeric value from a float /// </summary> /// <param name="x">The float to use</param> /// <returns>The equivalent of x in the Num〈A〉</returns> [Pure] public static int FromDecimal(decimal x) => (int)x; /// <summary> /// Generate a numeric value from a double /// </summary> /// <param name="x">The double to use</param> /// <returns>The equivalent of x in the Num〈A〉</returns> [Pure] public static int FromFloat(float x) => (int)x; /// <summary> /// Generate a numeric value from a decimal /// </summary> /// <param name="x">The decimal to use</param> /// <returns>The equivalent of x in the Num〈A〉</returns> [Pure] public static int FromDouble(double x) => (int)x; /// <summary> /// Negate the value /// </summary> /// <param name="x">Value to negate</param> /// <returns>The negated source value</returns> [Pure] public static int Negate(int x) => -x; /// <summary> /// Get the hash-code of the provided value /// </summary> /// <returns>Hash code of x</returns> [Pure] public static int GetHashCode(int x) => x.GetHashCode(); /// <summary> /// Returns True /// </summary> /// <returns>True</returns> [Pure] public static int True() => -1; /// <summary> /// Returns False /// </summary> /// <returns>False</returns> [Pure] public static int False() => 0; /// <summary> /// Returns the result of the bitwise AND operation between `a` and `b` /// </summary> /// <returns>The result of the bitwise AND operation between `a` and `b`</returns> [Pure] public static int And(int a, int b) => a & b; /// <summary> /// Returns the result of the bitwise OR operation between `a` and `b` /// </summary> /// <returns>The result of the bitwise OR operation between `a` and `b`</returns> [Pure] public static int Or(int a, int b) => a | b; /// <summary> /// Returns the result of the bitwise NOT operation on `a` /// </summary> /// <returns>The result of the bitwise NOT operation on `a`</returns> [Pure] public static int Not(int a) => ~a; /// <summary> /// Returns the result of the bitwise exclusive-OR operation between `a` and `b` /// </summary> /// <returns>The result of the bitwise exclusive-OR operation between `a` and `b`</returns> [Pure] public static int XOr(int a, int b) => a ^ b; /// <summary> /// Logical implication /// </summary> /// <returns>If `a` is true that implies `b`, else `true`</returns> [Pure] public static int Implies(int a, int b) => And(a, True()) == False() ? True() : b; /// <summary> /// Bitwise bi-conditional. /// </summary> /// <returns>`Not(XOr(a, b))`</returns> [Pure] public static int BiCondition(int a, int b) => Not(XOr(a, b)); }
TInt
csharp
xunit__xunit
src/xunit.v3.core/Runners/TestRunner.cs
{ "start": 13243, "end": 13499 }
class ____ has been disposed. /// </summary> /// <param name="ctxt">The context that describes the current test</param> protected virtual void PostInvoke(TContext ctxt) { } /// <summary> /// Override this method to call code just after the test
instance
csharp
dotnetcore__Util
src/Util.Domain/Extending/ExtraProperty.cs
{ "start": 125, "end": 1583 }
public class ____<TProperty> where TProperty : class { /// <summary> /// 扩展属性集合 /// </summary> private ExtraPropertyDictionary _properties; /// <summary> /// 属性实例 /// </summary> private TProperty _property; /// <summary> /// 属性名 /// </summary> private readonly string _propertyName; /// <summary> /// 初始化扩展属性 /// </summary> /// <param name="propertyName">属性名</param> public ExtraProperty( string propertyName ) { _propertyName = propertyName; } /// <summary> /// 获取属性 /// </summary> /// <param name="properties">扩展属性集合</param> public TProperty GetProperty( ExtraPropertyDictionary properties ) { _properties = properties ?? new ExtraPropertyDictionary(); var property = _properties.GetProperty<TProperty>( _propertyName ); if ( property == null ) return null; if( _property == property ) return _property; _property = property; _properties.SetProperty( _propertyName, _property ); return _property; } /// <summary> /// 设置属性 /// </summary> /// <param name="properties">扩展属性集合</param> /// <param name="property">属性实例</param> public void SetProperty( ExtraPropertyDictionary properties,TProperty property ) { _properties = properties; _property = property; _properties.SetProperty( _propertyName, _property ); } }
ExtraProperty
csharp
MassTransit__MassTransit
tests/MassTransit.RabbitMqTransport.Tests/BuildTopology_Specs.cs
{ "start": 5503, "end": 7872 }
public class ____ { [Test] public void Should_include_a_binding_for_the_second_interface_only() { _publishTopology.GetMessageTopology<SecondInterface>() .Apply(_builder); var topology = _builder.BuildBrokerTopology(); var singleInterfaceName = _nameFormatter.GetMessageName(typeof(FirstInterface)); var interfaceName = _nameFormatter.GetMessageName(typeof(SecondInterface)); Assert.Multiple(() => { Assert.That(topology.Exchanges.Any(x => x.ExchangeName == interfaceName), Is.True); Assert.That(topology.Exchanges, Has.Length.EqualTo(2)); Assert.That(topology.ExchangeBindings, Has.Length.EqualTo(1)); }); Assert.Multiple(() => { Assert.That(topology.ExchangeBindings.Any(x => x.Source.ExchangeName == interfaceName && x.Destination.ExchangeName == singleInterfaceName), Is.True); Assert.That(topology.Exchanges.Any(x => x.ExchangeName == singleInterfaceName), Is.True); }); } [Test] public void Should_include_a_binding_for_the_single_interface() { _publishTopology.GetMessageTopology<SingleInterface>() .Apply(_builder); var topology = _builder.BuildBrokerTopology(); var singleInterfaceName = _nameFormatter.GetMessageName(typeof(SingleInterface)); Assert.Multiple(() => { Assert.That(topology.Exchanges.Any(x => x.ExchangeName == singleInterfaceName), Is.True); Assert.That(topology.Exchanges, Has.Length.EqualTo(1)); Assert.That(topology.ExchangeBindings, Is.Empty); }); } [SetUp] public void Setup() { _nameFormatter = new RabbitMqMessageNameFormatter(); _publishTopology = new RabbitMqPublishTopology(RabbitMqBusFactory.CreateMessageTopology()); _builder = new PublishEndpointBrokerTopologyBuilder(); } RabbitMqMessageNameFormatter _nameFormatter; IRabbitMqPublishTopologyConfigurator _publishTopology; PublishEndpointBrokerTopologyBuilder _builder; } [TestFixture]
Using_flattened_topology_to_bind_publishers
csharp
ardalis__Specification
tests/Ardalis.Specification.Tests/Builders/Builder_OrderBy.cs
{ "start": 63, "end": 2328 }
public record ____(int Id, string FirstName, string LastName); [Fact] public void DoesNothing_GivenNoOrderBy() { var spec1 = new Specification<Customer>(); var spec2 = new Specification<Customer, string>(); spec1.OrderExpressions.Should().BeEmpty(); spec2.OrderExpressions.Should().BeEmpty(); } [Fact] public void DoesNothing_GivenOrderByWithFalseCondition() { var spec1 = new Specification<Customer>(); spec1.Query .OrderBy(x => x.FirstName, false); var spec2 = new Specification<Customer, string>(); spec2.Query .OrderBy(x => x.FirstName, false); spec1.OrderExpressions.Should().BeEmpty(); spec2.OrderExpressions.Should().BeEmpty(); } [Fact] public void AddsOrderBy_GivenOrderBy() { Expression<Func<Customer, object?>> expr = x => x.FirstName; var spec1 = new Specification<Customer>(); spec1.Query .OrderBy(expr); var spec2 = new Specification<Customer, string>(); spec2.Query .OrderBy(expr); spec1.OrderExpressions.Should().ContainSingle(); spec1.OrderExpressions.First().KeySelector.Should().BeSameAs(expr); spec1.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy); spec2.OrderExpressions.Should().ContainSingle(); spec2.OrderExpressions.First().KeySelector.Should().BeSameAs(expr); spec2.OrderExpressions.First().OrderType.Should().Be(OrderTypeEnum.OrderBy); } [Fact] public void AddsOrderBy_GivenMultipleOrderBy() { var spec1 = new Specification<Customer>(); spec1.Query .OrderBy(x => x.FirstName) .OrderBy(x => x.LastName); var spec2 = new Specification<Customer, string>(); spec2.Query .OrderBy(x => x.FirstName) .OrderBy(x => x.LastName); spec1.OrderExpressions.Should().HaveCount(2); spec1.OrderExpressions.Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.OrderBy)); spec2.OrderExpressions.Should().HaveCount(2); spec2.OrderExpressions.Should().AllSatisfy(x => x.OrderType.Should().Be(OrderTypeEnum.OrderBy)); } }
Customer
csharp
grpc__grpc-dotnet
test/Grpc.Net.Client.Tests/GrpcCallSerializationContextTests.cs
{ "start": 10381, "end": 11609 }
private class ____ : GrpcCall { public TestGrpcCall(CallOptions options, GrpcChannel channel) : base(options, channel) { } public override Type RequestType { get; } = typeof(int); public override Type ResponseType { get; } = typeof(string); public override CancellationToken CancellationToken { get; } public override Task<Status> CallTask => Task.FromResult(Status.DefaultCancelled); } private GrpcCallSerializationContext CreateSerializationContext(string? requestGrpcEncoding = null, int? maxSendMessageSize = null) { var channelOptions = new GrpcChannelOptions(); channelOptions.MaxSendMessageSize = maxSendMessageSize; channelOptions.HttpHandler = new NullHttpHandler(); var call = new TestGrpcCall(new CallOptions(), GrpcChannel.ForAddress("http://localhost", channelOptions)); call.RequestGrpcEncoding = requestGrpcEncoding ?? "identity"; return new GrpcCallSerializationContext(call); } private static (bool Compressed, int Length) DecodeHeader(ReadOnlySpan<byte> buffer) { return (buffer[0] == 1, (int)BinaryPrimitives.ReadUInt32BigEndian(buffer.Slice(1))); } }
TestGrpcCall
csharp
MonoGame__MonoGame
MonoGame.Framework.Content.Pipeline/ContextScopeFactory.cs
{ "start": 6216, "end": 7488 }
public abstract class ____ : IContentContext { public abstract string IntermediateDirectory { get; } public abstract ContentBuildLogger Logger { get; } public abstract ContentIdentity SourceIdentity { get; } /// <summary> /// Remove this context operation from the history in the <see cref="ContextScopeFactory"/>. /// If this context was the <see cref="ContextScopeFactory.ActiveContext"/>, then this /// method will reset the <see cref="ContextScopeFactory.ActiveContext"/> value to the next /// most-recent context operation, or null if none exist. /// </summary> public virtual void Dispose() { _contextStack.Value.Remove(this); // if someone else has already claimed the activeContext, then we don't need to care. if (_activeContext.Value != this) return; // either use the "most recent" (aka, last) context, or if the list is empty, // there is no context. _activeContext.Value = _contextStack.Value.Count > 0 ? _contextStack.Value[^1] : null; } }
ContextScope
csharp
serilog__serilog-extensions-logging
test/Serilog.Extensions.Logging.Tests/SerilogLoggerTests.cs
{ "start": 16540, "end": 17044 }
class ____ : IEnumerable<KeyValuePair<string, object>> { readonly int _luckyNumber; public LuckyScope(int luckyNumber) { _luckyNumber = luckyNumber; } public IEnumerator<KeyValuePair<string, object>> GetEnumerator() { yield return new KeyValuePair<string, object>("LuckyNumber", _luckyNumber); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } }
LuckyScope
csharp
IdentityModel__IdentityModel
src/Client/Messages/TokenRequest.cs
{ "start": 288, "end": 534 }
public class ____ : ProtocolRequest { /// <summary> /// Gets or sets the type of the grant. /// </summary> /// <value> /// The type of the grant. /// </value> public string GrantType { get; set; } = default!; }
TokenRequest
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Execution/Text/Json/JsonConstants.cs
{ "start": 42, "end": 7614 }
internal static class ____ { public const int StackallocByteThreshold = 256; public const byte OpenBrace = (byte)'{'; public const byte CloseBrace = (byte)'}'; public const byte OpenBracket = (byte)'['; public const byte CloseBracket = (byte)']'; public const byte Space = (byte)' '; public const byte CarriageReturn = (byte)'\r'; public const byte LineFeed = (byte)'\n'; public const byte Tab = (byte)'\t'; public const byte Comma = (byte)','; public const byte KeyValueSeparator = (byte)':'; public const byte Quote = (byte)'"'; public const byte BackSlash = (byte)'\\'; public const byte Slash = (byte)'/'; public const byte BackSpace = (byte)'\b'; public const byte FormFeed = (byte)'\f'; public const byte Asterisk = (byte)'*'; public const byte Colon = (byte)':'; public const byte Period = (byte)'.'; public const byte Plus = (byte)'+'; public const byte Hyphen = (byte)'-'; public const byte UtcOffsetToken = (byte)'Z'; public const byte TimePrefix = (byte)'T'; public const byte NewLineLineFeed = (byte)'\n'; // \u2028 and \u2029 are considered respectively line and paragraph separators // UTF-8 representation for them is E2, 80, A8/A9 public const byte StartingByteOfNonStandardSeparator = 0xE2; public static ReadOnlySpan<byte> Data => "data"u8; public static ReadOnlySpan<byte> Errors => "errors"u8; public static ReadOnlySpan<byte> Extensions => "extensions"u8; public static ReadOnlySpan<byte> Utf8Bom => [0xEF, 0xBB, 0xBF]; public static ReadOnlySpan<byte> TrueValue => "true"u8; public static ReadOnlySpan<byte> FalseValue => "false"u8; public static ReadOnlySpan<byte> NullValue => "null"u8; public static ReadOnlySpan<byte> NaNValue => "NaN"u8; public static ReadOnlySpan<byte> PositiveInfinityValue => "Infinity"u8; public static ReadOnlySpan<byte> NegativeInfinityValue => "-Infinity"u8; public const int MaximumFloatingPointConstantLength = 9; // Used to search for the end of a number public static ReadOnlySpan<byte> Delimiters => ",}] \n\r\t/"u8; // Explicitly skipping ReverseSolidus since that is handled separately public static ReadOnlySpan<byte> EscapableChars => "\"nrt/ubf"u8; public const int RemoveFlagsBitMask = 0x7FFFFFFF; // In the worst case, an ASCII character represented as a single utf-8 byte could expand 6x when escaped. // For example: '+' becomes '\u0043' // Escaping surrogate pairs (represented by 3 or 4 utf-8 bytes) would expand to 12 bytes (which is still <= 6x). // The same factor applies to utf-16 characters. public const int MaxExpansionFactorWhileEscaping = 6; // In the worst case, a single UTF-16 character could be expanded to 3 UTF-8 bytes. // Only surrogate pairs expand to 4 UTF-8 bytes but that is a transformation of 2 UTF-16 characters going to 4 UTF-8 bytes (factor of 2). // All other UTF-16 characters can be represented by either 1 or 2 UTF-8 bytes. public const int MaxExpansionFactorWhileTranscoding = 3; // When transcoding from UTF8 -> UTF16, the byte count threshold where we rent from the array pool before performing a normal alloc. public const long ArrayPoolMaxSizeBeforeUsingNormalAlloc = #if NET 1024 * 1024 * 1024; // ArrayPool limit increased in .NET 6 #else 1024 * 1024; #endif // The maximum number of characters allowed when writing raw UTF-16 JSON. This is the maximum length that we can guarantee can // be safely transcoded to UTF-8 and fit within an integer-length span, given the max expansion factor of a single character (3). public const int MaxUtf16RawValueLength = int.MaxValue / MaxExpansionFactorWhileTranscoding; public const int MaxEscapedTokenSize = 1_000_000_000; // Max size for already escaped value. public const int MaxUnescapedTokenSize = MaxEscapedTokenSize / MaxExpansionFactorWhileEscaping; // 166_666_666 bytes public const int MaxCharacterTokenSize = MaxEscapedTokenSize / MaxExpansionFactorWhileEscaping; // 166_666_666 characters public const int MaximumFormatBooleanLength = 5; public const int MaximumFormatInt64Length = 20; // 19 + sign (i.e. -9223372036854775808) public const int MaximumFormatUInt32Length = 10; // i.e. 4294967295 public const int MaximumFormatUInt64Length = 20; // i.e. 18446744073709551615 public const int MaximumFormatDoubleLength = 128; // default (i.e. 'G'), using 128 (rather than say 32) to be future-proof. public const int MaximumFormatSingleLength = 128; // default (i.e. 'G'), using 128 (rather than say 32) to be future-proof. public const int MaximumFormatDecimalLength = 31; // default (i.e. 'G') public const int MaximumFormatGuidLength = 36; // default (i.e. 'D'), 8 + 4 + 4 + 4 + 12 + 4 for the hyphens (e.g. 094ffa0a-0442-494d-b452-04003fa755cc) public const int MaximumEscapedGuidLength = MaxExpansionFactorWhileEscaping * MaximumFormatGuidLength; public const int MaximumFormatDateTimeLength = 27; // StandardFormat 'O', e.g. 2017-06-12T05:30:45.7680000 public const int MaximumFormatDateTimeOffsetLength = 33; // StandardFormat 'O', e.g. 2017-06-12T05:30:45.7680000-07:00 public const int MaxDateTimeUtcOffsetHours = 14; // The UTC offset portion of a TimeSpan or DateTime can be no more than 14 hours and no less than -14 hours. public const int DateTimeNumFractionDigits = 7; // TimeSpan and DateTime formats allow exactly up to many digits for specifying the fraction after the seconds. public const int MaxDateTimeFraction = 9_999_999; // The largest fraction expressible by TimeSpan and DateTime formats public const int DateTimeParseNumFractionDigits = 16; // The maximum number of fraction digits the Json DateTime parser allows public const int MaximumDateTimeOffsetParseLength = MaximumFormatDateTimeOffsetLength + (DateTimeParseNumFractionDigits - DateTimeNumFractionDigits); // Like StandardFormat 'O' for DateTimeOffset, but allowing 9 additional (up to 16) fraction digits. public const int MinimumDateTimeParseLength = 10; // YYYY-MM-DD public const int MaximumEscapedDateTimeOffsetParseLength = MaxExpansionFactorWhileEscaping * MaximumDateTimeOffsetParseLength; public const int MaximumLiteralLength = 5; // Must be able to fit null, true, & false. // Encoding Helpers public const char HighSurrogateStart = '\ud800'; public const char HighSurrogateEnd = '\udbff'; public const char LowSurrogateStart = '\udc00'; public const char LowSurrogateEnd = '\udfff'; public const int UnicodePlane01StartValue = 0x10000; public const int HighSurrogateStartValue = 0xD800; public const int HighSurrogateEndValue = 0xDBFF; public const int LowSurrogateStartValue = 0xDC00; public const int LowSurrogateEndValue = 0xDFFF; public const int BitShiftBy10 = 0x400; // The maximum number of parameters a constructor can have where it can be considered // for a path on deserialization where we don't box the constructor arguments. public const int UnboxedParameterCountThreshold = 4; // Two space characters is the default indentation. public const char DefaultIndentCharacter = ' '; public const char TabIndentCharacter = '\t'; public const int DefaultIndentSize = 2; public const int MinimumIndentSize = 0; public const int MaximumIndentSize = 127; // If this value is changed, the impact on the options masking used in the JsonWriterOptions
JsonConstants
csharp
dotnet__orleans
src/Azure/Orleans.Streaming.EventHubs/Providers/Streams/EventHub/EventHubAdapterReceiver.cs
{ "start": 11657, "end": 12323 }
internal class ____ : IBatchContainer { [Id(0)] public StreamPosition Position { get; } public StreamId StreamId => this.Position.StreamId; public StreamSequenceToken SequenceToken => this.Position.SequenceToken; public StreamActivityNotificationBatch(StreamPosition position) { this.Position = position; } public IEnumerable<Tuple<T, StreamSequenceToken>> GetEvents<T>() { throw new NotSupportedException(); } public bool ImportRequestContext() { throw new NotSupportedException(); } }
StreamActivityNotificationBatch
csharp
bitwarden__server
bitwarden_license/src/Commercial.Core/SecretsManager/AuthorizationHandlers/AccessPolicies/ServiceAccountGrantedPoliciesAuthorizationHandler.cs
{ "start": 385, "end": 3601 }
public class ____ : AuthorizationHandler< ServiceAccountGrantedPoliciesOperationRequirement, ServiceAccountGrantedPoliciesUpdates> { private readonly IAccessClientQuery _accessClientQuery; private readonly ICurrentContext _currentContext; private readonly IProjectRepository _projectRepository; private readonly IServiceAccountRepository _serviceAccountRepository; public ServiceAccountGrantedPoliciesAuthorizationHandler(ICurrentContext currentContext, IAccessClientQuery accessClientQuery, IProjectRepository projectRepository, IServiceAccountRepository serviceAccountRepository) { _currentContext = currentContext; _accessClientQuery = accessClientQuery; _serviceAccountRepository = serviceAccountRepository; _projectRepository = projectRepository; } protected override async Task HandleRequirementAsync(AuthorizationHandlerContext context, ServiceAccountGrantedPoliciesOperationRequirement requirement, ServiceAccountGrantedPoliciesUpdates resource) { if (!_currentContext.AccessSecretsManager(resource.OrganizationId)) { return; } // Only users and admins should be able to manipulate access policies var (accessClient, userId) = await _accessClientQuery.GetAccessClientAsync(context.User, resource.OrganizationId); if (accessClient != AccessClientType.User && accessClient != AccessClientType.NoAccessCheck) { return; } switch (requirement) { case not null when requirement == ServiceAccountGrantedPoliciesOperations.Updates: await CanUpdateAsync(context, requirement, resource, accessClient, userId); break; default: throw new ArgumentException("Unsupported operation requirement type provided.", nameof(requirement)); } } private async Task CanUpdateAsync(AuthorizationHandlerContext context, ServiceAccountGrantedPoliciesOperationRequirement requirement, ServiceAccountGrantedPoliciesUpdates resource, AccessClientType accessClient, Guid userId) { var access = await _serviceAccountRepository.AccessToServiceAccountAsync(resource.ServiceAccountId, userId, accessClient); if (access.Write) { var projectIdsToCheck = resource.ProjectGrantedPolicyUpdates.Select(update => update.AccessPolicy.GrantedProjectId!.Value).ToList(); var sameOrganization = await _projectRepository.ProjectsAreInOrganization(projectIdsToCheck, resource.OrganizationId); if (!sameOrganization) { return; } var projectsAccess = await _projectRepository.AccessToProjectsAsync(projectIdsToCheck, userId, accessClient); if (projectsAccess.Count == projectIdsToCheck.Count && projectsAccess.All(a => a.Value.Write)) { context.Succeed(requirement); } } } }
ServiceAccountGrantedPoliciesAuthorizationHandler
csharp
ServiceStack__ServiceStack
ServiceStack.Text/tests/ServiceStack.Text.Benchmarks/MemoryProviderBenchmarks.cs
{ "start": 6033, "end": 6516 }
public class ____ { [Params(10000)] public int N; [Benchmark] public int NetCoreParseInt32() => int.Parse("1234"); [Benchmark] public long NetCoreParseInt34() => long.Parse("1234"); [Benchmark] public int CustomParseInt32() => DefaultMemory.Provider.ParseInt32("1234".AsSpan()); [Benchmark] public long CustomParseInt64() => DefaultMemory.Provider.ParseInt64("1234".AsSpan()); } }
MemoryIntegerBenchmarks
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/Flyout/Flyout_Target.xaml.cs
{ "start": 254, "end": 1283 }
partial class ____ : UserControl { public Flyout_Target() { this.InitializeComponent(); } private void OnClick(object s, RoutedEventArgs e) { result.Text = ""; var flyout = new Microsoft.UI.Xaml.Controls.Flyout() { Content = new Border { Name = "innerContent", Height = 100, Width = 100, Background = new SolidColorBrush(Colors.Red) } }; var target = s as FrameworkElement; flyout.ShowAt(target); var success = flyout.Target == target; result.Text = success ? "success" : "failed"; } private void OnClickFull(object s, RoutedEventArgs e) { result.Text = ""; var target = s as FrameworkElement; var flyout = new Microsoft.UI.Xaml.Controls.Flyout() { Content = new Border { Name = "innerContent", Height = 100, Width = 100, Background = new SolidColorBrush(Colors.Red) }, Placement = Microsoft.UI.Xaml.Controls.Primitives.FlyoutPlacementMode.Full }; flyout.ShowAt(target); } } }
Flyout_Target
csharp
Cysharp__UniTask
src/UniTask/Assets/Plugins/UniTask/Runtime/Triggers/MonoBehaviourMessagesTriggers.cs
{ "start": 66819, "end": 67949 }
public sealed class ____ : AsyncTriggerBase<GameObject> { void OnParticleCollision(GameObject other) { RaiseEvent((other)); } public IAsyncOnParticleCollisionHandler GetOnParticleCollisionAsyncHandler() { return new AsyncTriggerHandler<GameObject>(this, false); } public IAsyncOnParticleCollisionHandler GetOnParticleCollisionAsyncHandler(CancellationToken cancellationToken) { return new AsyncTriggerHandler<GameObject>(this, cancellationToken, false); } public UniTask<GameObject> OnParticleCollisionAsync() { return ((IAsyncOnParticleCollisionHandler)new AsyncTriggerHandler<GameObject>(this, true)).OnParticleCollisionAsync(); } public UniTask<GameObject> OnParticleCollisionAsync(CancellationToken cancellationToken) { return ((IAsyncOnParticleCollisionHandler)new AsyncTriggerHandler<GameObject>(this, cancellationToken, true)).OnParticleCollisionAsync(); } } #endregion #region ParticleSystemStopped
AsyncParticleCollisionTrigger
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Services/Plugins/UploadService.cs
{ "start": 22211, "end": 23425 }
public partial class ____ { /// <summary> /// Gets or sets the type of an uploaded item /// </summary> [JsonProperty(PropertyName = "Type")] [JsonConverter(typeof(StringEnumConverter))] public UploadedItemType? Type { get; set; } /// <summary> /// Gets or sets the system name /// </summary> [JsonProperty(PropertyName = "SystemName")] public string SystemName { get; set; } /// <summary> /// Gets or sets supported versions of nopCommerce /// </summary> [JsonProperty(PropertyName = "SupportedVersion")] public string SupportedVersions { get; set; } /// <summary> /// Gets or sets the path to binary files directory /// </summary> [JsonProperty(PropertyName = "DirectoryPath")] public string DirectoryPath { get; set; } /// <summary> /// Gets or sets the path to source files directory /// </summary> [JsonProperty(PropertyName = "SourceDirectoryPath")] public string SourceDirectoryPath { get; set; } } /// <summary> /// Uploaded item type enumeration /// </summary>
UploadedItem
csharp
smartstore__Smartstore
src/Smartstore.Core/Catalog/Attributes/Domain/ProductAttribute.cs
{ "start": 517, "end": 2708 }
public partial class ____ : EntityWithAttributes, ILocalizedEntity, IDisplayOrder, ISearchAlias { /// <summary> /// Gets or sets the attribute name. /// </summary> /// <example>Color</example> [Required, StringLength(4000)] [LocalizedProperty] public string Name { get; set; } /// <summary> /// Gets or sets the description. /// </summary> [StringLength(4000)] [LocalizedProperty] public string Description { get; set; } /// <inheritdoc/> [StringLength(100)] [LocalizedProperty] public string Alias { get; set; } /// <summary> /// Gets or sets a value indicating whether the attribute can be filtered. /// </summary> public bool AllowFiltering { get; set; } /// <summary> /// Gets or sets the display order. /// </summary> public int DisplayOrder { get; set; } /// <summary> /// Gets or sets the facet template hint. /// Only effective in accordance with MegaSearchPlus module. /// </summary> public FacetTemplateHint FacetTemplateHint { get; set; } /// <summary> /// Gets or sets a value indicating whether option names should be included in the search index. /// Only effective in accordance with MegaSearchPlus module. /// </summary> public bool IndexOptionNames { get; set; } /// <summary> /// Gets or sets optional export mappings. /// </summary> [MaxLength] public string ExportMappings { get; set; } private ICollection<ProductAttributeOptionsSet> _productAttributeOptionsSets; /// <summary> /// Gets or sets the options sets. /// </summary> public ICollection<ProductAttributeOptionsSet> ProductAttributeOptionsSets { get => _productAttributeOptionsSets ?? LazyLoader.Load(this, ref _productAttributeOptionsSets) ?? (_productAttributeOptionsSets ??= new HashSet<ProductAttributeOptionsSet>()); protected set => _productAttributeOptionsSets = value; } } }
ProductAttribute
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/AutoQueryTests.cs
{ "start": 30280, "end": 31093 }
public class ____ : Service { public IAutoQueryDb AutoQuery { get; set; } public async Task<object> Any(QueryMovies query) { using var db = AutoQuery.GetDb(query, base.Request); var q = AutoQuery.CreateQuery(query, base.Request, db); return await AutoQuery.ExecuteAsync(query, q, base.Request, db); } } [Test] public async Task Can_execute_AutoQueryService_in_UnitTest() { var service = appHost.Resolve<MyQueryServices>(); service.Request = new BasicRequest(); var response = (QueryResponse<Movie>) await service.Any( new QueryMovies { Ratings = new[] {"G", "PG-13"} }); Assert.That(response.Results.Count, Is.EqualTo(5)); } } [TestFixture]
MyQueryServices
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Data/Mapping/Builders/Topics/TopicBuilder.cs
{ "start": 188, "end": 589 }
public partial class ____ : NopEntityBuilder<Topic> { #region Methods /// <summary> /// Apply entity configuration /// </summary> /// <param name="table">Create table expression builder</param> public override void MapEntity(CreateTableExpressionBuilder table) { table.WithColumn(nameof(Topic.SystemName)).AsString(400).Nullable(); } #endregion }
TopicBuilder
csharp
jellyfin__jellyfin
src/Jellyfin.Database/Jellyfin.Database.Providers.Sqlite/Migrations/20241112234144_FixMediaStreams2.cs
{ "start": 151, "end": 4767 }
public partial class ____ : Migration { /// <inheritdoc /> protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Profile", table: "MediaStreamInfos", type: "TEXT", nullable: true, oldClrType: typeof(string), oldType: "TEXT"); migrationBuilder.AlterColumn<string>( name: "Path", table: "MediaStreamInfos", type: "TEXT", nullable: true, oldClrType: typeof(string), oldType: "TEXT"); migrationBuilder.AlterColumn<string>( name: "Language", table: "MediaStreamInfos", type: "TEXT", nullable: true, oldClrType: typeof(string), oldType: "TEXT"); migrationBuilder.AlterColumn<bool>( name: "IsInterlaced", table: "MediaStreamInfos", type: "INTEGER", nullable: true, oldClrType: typeof(bool), oldType: "INTEGER"); migrationBuilder.AlterColumn<string>( name: "Codec", table: "MediaStreamInfos", type: "TEXT", nullable: true, oldClrType: typeof(string), oldType: "TEXT"); migrationBuilder.AlterColumn<string>( name: "ChannelLayout", table: "MediaStreamInfos", type: "TEXT", nullable: true, oldClrType: typeof(string), oldType: "TEXT"); migrationBuilder.AlterColumn<string>( name: "AspectRatio", table: "MediaStreamInfos", type: "TEXT", nullable: true, oldClrType: typeof(string), oldType: "TEXT"); } /// <inheritdoc /> protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.AlterColumn<string>( name: "Profile", table: "MediaStreamInfos", type: "TEXT", nullable: false, defaultValue: string.Empty, oldClrType: typeof(string), oldType: "TEXT", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Path", table: "MediaStreamInfos", type: "TEXT", nullable: false, defaultValue: string.Empty, oldClrType: typeof(string), oldType: "TEXT", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Language", table: "MediaStreamInfos", type: "TEXT", nullable: false, defaultValue: string.Empty, oldClrType: typeof(string), oldType: "TEXT", oldNullable: true); migrationBuilder.AlterColumn<bool>( name: "IsInterlaced", table: "MediaStreamInfos", type: "INTEGER", nullable: false, defaultValue: false, oldClrType: typeof(bool), oldType: "INTEGER", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "Codec", table: "MediaStreamInfos", type: "TEXT", nullable: false, defaultValue: string.Empty, oldClrType: typeof(string), oldType: "TEXT", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "ChannelLayout", table: "MediaStreamInfos", type: "TEXT", nullable: false, defaultValue: string.Empty, oldClrType: typeof(string), oldType: "TEXT", oldNullable: true); migrationBuilder.AlterColumn<string>( name: "AspectRatio", table: "MediaStreamInfos", type: "TEXT", nullable: false, defaultValue: string.Empty, oldClrType: typeof(string), oldType: "TEXT", oldNullable: true); } } }
FixMediaStreams2
csharp
ardalis__Specification
samples/Ardalis.Sample.App1/Program.cs
{ "start": 3971, "end": 4044 }
public interface ____<T> : IRepositoryBase<T> where T : class { }
IRepository
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Media/Matrix3DProjection.cs
{ "start": 386, "end": 2495 }
public partial class ____ : global::Microsoft.UI.Xaml.Media.Projection { #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::Microsoft.UI.Xaml.Media.Media3D.Matrix3D ProjectionMatrix { get { return (global::Microsoft.UI.Xaml.Media.Media3D.Matrix3D)this.GetValue(ProjectionMatrixProperty); } set { this.SetValue(ProjectionMatrixProperty, value); } } #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 static global::Microsoft.UI.Xaml.DependencyProperty ProjectionMatrixProperty { get; } = Microsoft.UI.Xaml.DependencyProperty.Register( nameof(ProjectionMatrix), typeof(global::Microsoft.UI.Xaml.Media.Media3D.Matrix3D), typeof(global::Microsoft.UI.Xaml.Media.Matrix3DProjection), new Microsoft.UI.Xaml.FrameworkPropertyMetadata(default(global::Microsoft.UI.Xaml.Media.Media3D.Matrix3D))); #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 Matrix3DProjection() : base() { global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Microsoft.UI.Xaml.Media.Matrix3DProjection", "Matrix3DProjection.Matrix3DProjection()"); } #endif // Forced skipping of method Microsoft.UI.Xaml.Media.Matrix3DProjection.Matrix3DProjection() // Forced skipping of method Microsoft.UI.Xaml.Media.Matrix3DProjection.ProjectionMatrix.get // Forced skipping of method Microsoft.UI.Xaml.Media.Matrix3DProjection.ProjectionMatrix.set // Forced skipping of method Microsoft.UI.Xaml.Media.Matrix3DProjection.ProjectionMatrixProperty.get } }
Matrix3DProjection
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Enumeration/DeviceAccessChangedEventArgs.cs
{ "start": 302, "end": 1853 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal DeviceAccessChangedEventArgs() { } #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.Devices.Enumeration.DeviceAccessStatus Status { get { throw new global::System.NotImplementedException("The member DeviceAccessStatus DeviceAccessChangedEventArgs.Status is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=DeviceAccessStatus%20DeviceAccessChangedEventArgs.Status"); } } #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 string Id { get { throw new global::System.NotImplementedException("The member string DeviceAccessChangedEventArgs.Id is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=string%20DeviceAccessChangedEventArgs.Id"); } } #endif // Forced skipping of method Windows.Devices.Enumeration.DeviceAccessChangedEventArgs.Status.get // Forced skipping of method Windows.Devices.Enumeration.DeviceAccessChangedEventArgs.Id.get } }
DeviceAccessChangedEventArgs
csharp
dotnet__aspnetcore
src/Servers/HttpSys/test/FunctionalTests/Utilities.cs
{ "start": 7844, "end": 8304 }
private sealed class ____ : ILoggerProvider { private readonly ILoggerFactory _loggerFactory; public ForwardingLoggerProvider(ILoggerFactory loggerFactory) { _loggerFactory = loggerFactory; } public void Dispose() { } public ILogger CreateLogger(string categoryName) { return _loggerFactory.CreateLogger(categoryName); } } }
ForwardingLoggerProvider
csharp
abpframework__abp
framework/src/Volo.Abp.Cli.Core/Volo/Abp/Cli/Build/DotNetProjectInfo.cs
{ "start": 96, "end": 593 }
public class ____ { public string RepositoryName { get; set; } public string CsProjPath { get; set; } public bool ShouldBuild { get; set; } public List<DotNetProjectInfo> Dependencies { get; set; } public DotNetProjectInfo(string repositoryName, string csProjPath, bool shouldBuild) { RepositoryName = repositoryName; CsProjPath = csProjPath; ShouldBuild = shouldBuild; Dependencies = new List<DotNetProjectInfo>(); } }
DotNetProjectInfo
csharp
moq__moq4
src/Moq.Tests/Linq/SupportedQuerying.cs
{ "start": 4190, "end": 4296 }
public interface ____ { bool IsValid { get; set; } }
IFoo
csharp
smartstore__Smartstore
src/Smartstore.Core/Migrations/20250704120000_V620.cs
{ "start": 273, "end": 9771 }
internal class ____ : Migration, ILocaleResourcesProvider, IDataSeeder<SmartDbContext> { public override void Up() { } public override void Down() { } public DataSeederStage Stage => DataSeederStage.Early; public bool AbortOnFailure => false; public async Task SeedAsync(SmartDbContext context, CancellationToken cancelToken = default) { await context.MigrateLocaleResourcesAsync(MigrateLocaleResources); } public void MigrateLocaleResources(LocaleResourcesBuilder builder) { builder.AddOrUpdate("Aria.Label.MainNavigation", "Main navigation", "Hauptnavigation"); builder.AddOrUpdate("Aria.Label.PageNavigation", "Page navigation", "Seitennavigation"); builder.AddOrUpdate("Aria.Label.OffCanvasMenuTab", "Shop sections", "Shopbereiche"); builder.AddOrUpdate("Aria.Label.ShowPreviousProducts", "Show previous product group", "Vorherige Produktgruppe anzeigen"); builder.AddOrUpdate("Aria.Label.ShowNextProducts", "Show next product group", "Nächste Produktgruppe anzeigen"); builder.AddOrUpdate("Aria.Label.CommentForm", "Comment form", "Kommentarformular"); builder.AddOrUpdate("Aria.Label.Breadcrumb", "Breadcrumb", "Breadcrumb-Navigation"); builder.AddOrUpdate("Aria.Label.MediaGallery", "Media gallery", "Mediengalerie"); builder.AddOrUpdate("Aria.Label.SearchFilters", "Search filters", "Suchfilter"); builder.AddOrUpdate("Aria.Label.SelectDeselectEntries", "Select or deselect all entries in the list", "Alle Einträge der Liste aus- oder abwählen"); builder.AddOrUpdate("Aria.Label.SelectDeselectEntry", "Select or deselect entry", "Eintrag aus- oder abwählen"); builder.AddOrUpdate("Aria.Description.SearchBox", "Enter a search term. Press the Enter key to view all the results.", "Geben Sie einen Suchbegriff ein. Drücken Sie die Eingabetaste, um alle Ergebnisse aufzurufen."); builder.AddOrUpdate("Aria.Description.InstantSearch", "Enter a search term. Results will appear automatically as you type. Press the Enter key to view all the results.", "Geben Sie einen Suchbegriff ein. Während Sie tippen, erscheinen automatisch erste Ergebnisse. Drücken Sie die Eingabetaste, um alle Ergebnisse aufzurufen."); builder.AddOrUpdate("Aria.Description.AutoSearchBox", "Enter a search term. Results will appear automatically as you type.", "Geben Sie einen Suchbegriff ein. Die Ergebnisse erscheinen automatisch, während Sie tippen."); builder.AddOrUpdate("Aria.Label.CurrencySelector", "Current currency {0} - Change currency", "Aktuelle Währung {0} – Währung wechseln"); builder.AddOrUpdate("Aria.Label.LanguageSelector", "Current language {0} - Change language", "Aktuelle Sprache {0} – Sprache wechseln"); builder.AddOrUpdate("Aria.Label.SocialMediaLinks", "Our social media channels", "Unsere Social-Media-Kanäle"); builder.AddOrUpdate("Aria.Label.Rating", "Rating: {0} out of 5 stars. {1}", "Bewertung: {0} von 5 Sternen. {1}"); builder.AddOrUpdate("Aria.Label.ExpandItem", "Press ENTER for more options to {0}", "Drücken Sie ENTER für mehr Optionen zu {0}"); builder.AddOrUpdate("Aria.Label.ProductOfOrderPlacedOn", "Order {0} from {1}, {2}", "Auftrag {0} vom {1}, {2}"); builder.AddOrUpdate("Aria.Label.PaginatorItemsPerPage", "Results per page:", "Ergebnisse pro Seite:"); builder.AddOrUpdate("Aria.Label.ApplyPriceRange", "Apply price range", "Preisbereich anwenden"); builder.AddOrUpdate("Aria.Label.PriceRange", "Price range", "Preisspanne"); builder.AddOrUpdate("Aria.Label.UploaderProgressBar", "{0} fileupload", "{0} Dateiupload"); builder.AddOrUpdate("Aria.Label.ShowPassword", "Show password", "Passwort anzeigen"); builder.AddOrUpdate("Aria.Label.HidePassword", "Hide password", "Passwort verbergen"); builder.AddOrUpdate("Aria.Label.CheckoutProcess", "Checkout process", "Bestellprozess"); builder.AddOrUpdate("Aria.Label.CheckoutStep.Visited", "Completed", "Abgeschlossen"); builder.AddOrUpdate("Aria.Label.CheckoutStep.Current", "Current step", "Aktueller Schritt"); builder.AddOrUpdate("Aria.Label.CheckoutStep.Pending", "Not visited", "Noch nicht besucht"); builder.AddOrUpdate("Aria.Label.SearchHitCount", "Search results", "Suchergebnisse"); // INFO: Must be generic for Cart, Compare & Wishlist builder.AddOrUpdate("Aria.Label.OffCanvasCartTab", "My articles", "Meine Artikel"); builder.AddOrUpdate("Search.SearchBox.Clear", "Clear search term", "Suchbegriff löschen"); builder.AddOrUpdate("Common.ScrollUp", "Scroll up", "Nach oben scrollen"); builder.AddOrUpdate("Common.SelectAction", "Select action", "Aktion wählen"); builder.AddOrUpdate("Common.ExpandCollapse", "Expand/collapse", "Auf-/zuklappen"); builder.AddOrUpdate("Common.DeleteSelected", "Delete selected", "Ausgewählte löschen"); builder.AddOrUpdate("Common.Consent", "Consent", "Zustimmung"); builder.AddOrUpdate("Common.SelectView", "Select view", "Ansicht wählen"); builder.AddOrUpdate("Common.SecurityPrompt", "Security prompt", "Sicherheitsabfrage"); builder.AddOrUpdate("Common.SkipToMainContent", "Skip to main content", "Zum Hauptinhalt springen"); builder.Delete( "Account.BackInStockSubscriptions.DeleteSelected", "PrivateMessages.Inbox.DeleteSelected"); builder.AddOrUpdate("Admin.Configuration.Settings.General.Common.Captcha.Hint", "CAPTCHAs are used for security purposes to help distinguish between human and machine users. They are typically used to verify that internet forms are being" + " filled out by humans and not robots (bots), which are often misused for this purpose. reCAPTCHA accounts are created at <a" + " class=\"alert-link\" href=\"https://cloud.google.com/security/products/recaptcha?hl=en\" target=\"_blank\">Google</a>. Select <b>Task (v2)</b> as the reCAPTCHA type.", "CAPTCHAs dienen der Sicherheit, indem sie dabei helfen, zu unterscheiden, ob ein Nutzer ein Mensch oder eine Maschine ist. In der Regel wird diese Funktion genutzt," + " um zu überprüfen, ob Internetformulare von Menschen oder Robotern (Bots) ausgefüllt werden, da Bots hier oft missbräuchlich eingesetzt werden." + " reCAPTCHA-Konten werden bei <a class=\"alert-link\" href=\"https://cloud.google.com/security/products/recaptcha?hl=de\" target=\"_blank\">Google</a>" + " angelegt. Wählen Sie als reCAPTCHA-Typ <b>Aufgabe (v2)</b> aus."); builder.AddOrUpdate("Polls.TotalVotes", "{0} votes cast.", "{0} abgegebene Stimmen."); builder.AddOrUpdate("Blog.RSS.Hint", "Opens the RSS feed with the latest blog posts. Subscribe with an RSS reader to stay informed.", "Öffnet den RSS-Feed mit aktuellen Blogbeiträgen. Mit einem RSS-Reader abonnieren und informiert bleiben."); builder.AddOrUpdate("News.RSS.Hint", "Opens the RSS feed with the latest news. Subscribe with an RSS reader to stay informed.", "Öffnet den RSS-Feed mit aktuellen News. Mit einem RSS-Reader abonnieren und informiert bleiben."); builder.AddOrUpdate("Order.CannotCompleteUnpaidOrder", "An order with a payment status of \"{0}\" cannot be completed.", "Ein Auftrag mit dem Zahlungsstatus \"{0}\" kann nicht abgeschlossen werden."); builder.AddOrUpdate("Account.CustomerOrders.RecurringOrders.Cancel", "Cancel repeat delivery for order {0}", "Regelmäßige Lieferung für Auftrag {0} abbrechen"); builder.AddOrUpdate("Account.Avatar.AvatarChanged", "The avatar has been changed.", "Der Avatar wurde geändert."); builder.AddOrUpdate("Account.Avatar.AvatarRemoved", "The avatar has been removed.", "Der Avatar wurde entfernt."); builder.AddOrUpdate("RewardPoints.History", "History of your reward points", "Ihr Bonuspunkteverlauf"); builder.AddOrUpdate("Reviews.Overview.NoReviews", "There are no reviews for this product yet.", "Zu diesem Produkt liegen noch keine Bewertungen vor."); builder.AddOrUpdate("DownloadableProducts.IAgree", "I have read and agree to the user agreement.", "Ich habe die Nutzungsvereinbarung gelesen und bin einverstanden."); builder.AddOrUpdate("Common.FormFields.Required.Hint", "* Input fields with an asterisk are mandatory and must be filled in.", "* Eingabefelder mit Sternchen sind Pflichtfelder und müssen ausgefüllt werden."); builder.Delete("Categories.Breadcrumb.Top"); builder.AddOrUpdate("Order.ShipmentStatusEvents", "Status of your shipment", "Status Ihrer Sendung"); builder.AddOrUpdate("BackInStockSubscriptions.PopupTitle", "Email when available", "E-Mail bei Verfügbarkeit"); } } }
V620
csharp
dotnet__aspnetcore
src/Security/Authentication/OpenIdConnect/src/OpenIdConnectChallengeProperties.cs
{ "start": 410, "end": 2142 }
public class ____ : OAuthChallengeProperties { /// <summary> /// The parameter key for the "max_age" argument being used for a challenge request. /// </summary> public static readonly string MaxAgeKey = OpenIdConnectParameterNames.MaxAge; /// <summary> /// The parameter key for the "prompt" argument being used for a challenge request. /// </summary> public static readonly string PromptKey = OpenIdConnectParameterNames.Prompt; /// <summary> /// Initializes a new instance of <see cref="OpenIdConnectChallengeProperties"/>. /// </summary> public OpenIdConnectChallengeProperties() { } /// <summary> /// Initializes a new instance of <see cref="OpenIdConnectChallengeProperties"/>. /// </summary> /// <inheritdoc /> public OpenIdConnectChallengeProperties(IDictionary<string, string?> items) : base(items) { } /// <summary> /// Initializes a new instance of <see cref="OpenIdConnectChallengeProperties"/>. /// </summary> /// <inheritdoc /> public OpenIdConnectChallengeProperties(IDictionary<string, string?> items, IDictionary<string, object?> parameters) : base(items, parameters) { } /// <summary> /// The "max_age" parameter value being used for a challenge request. /// </summary> public TimeSpan? MaxAge { get => GetParameter<TimeSpan?>(MaxAgeKey); set => SetParameter(MaxAgeKey, value); } /// <summary> /// The "prompt" parameter value being used for a challenge request. /// </summary> public string? Prompt { get => GetParameter<string>(PromptKey); set => SetParameter(PromptKey, value); } }
OpenIdConnectChallengeProperties
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/ServiceGatewayTests.cs
{ "start": 1996, "end": 2172 }
public class ____ : IReturn<SGSyncPostValidationAsyncExternal> { public string Value { get; set; } public string Required { get; set; } }
SGSyncPostValidationAsyncExternal
csharp
MonoGame__MonoGame
MonoGame.Framework.Content.Pipeline/Graphics/VertexChannelCollection.cs
{ "start": 510, "end": 15104 }
public sealed class ____ : IList<VertexChannel>, ICollection<VertexChannel>, IEnumerable<VertexChannel>, IEnumerable { List<VertexChannel> channels; VertexContent vertexContent; /// <summary> /// Gets the number of vertex channels in the collection. /// </summary> public int Count { get { return channels.Count; } } /// <summary> /// Gets or sets the vertex channel at the specified index position. /// </summary> public VertexChannel this[int index] { get { return channels[index]; } set { channels[index] = value; } } /// <summary> /// Gets or sets the vertex channel with the specified name. /// </summary> public VertexChannel this[string name] { get { var index = IndexOf(name); if (index < 0) throw new ArgumentException("name"); return channels[index]; } set { var index = IndexOf(name); if (index < 0) throw new ArgumentException("name"); channels[index] = value; } } /// <summary> /// Determines whether the collection is read-only. /// </summary> bool ICollection<VertexChannel>.IsReadOnly { get { return false; } } /// <summary> /// Creates an instance of VertexChannelCollection. /// </summary> /// <param name="vertexContent">The VertexContent object that owns this collection.</param> internal VertexChannelCollection(VertexContent vertexContent) { this.vertexContent = vertexContent; channels = new List<VertexChannel>(); _insertOverload = GetType().GetMethods().First(m => m.Name == "Insert" && m.IsGenericMethodDefinition); } /// <summary> /// Adds a new vertex channel to the end of the collection. /// </summary> /// <typeparam name="ElementType">Type of the channel.</typeparam> /// <param name="name">Name of the new channel.</param> /// <param name="channelData">Initial data for the new channel. If null, the channel is filled with the default value for that type.</param> /// <returns>The newly added vertex channel.</returns> public VertexChannel<ElementType> Add<ElementType>(string name, IEnumerable<ElementType> channelData) { return Insert(channels.Count, name, channelData); } /// <summary> /// Adds a new vertex channel to the end of the collection. /// </summary> /// <param name="name">Name of the new channel.</param> /// <param name="elementType">Type of data to be contained in the new channel.</param> /// <param name="channelData">Initial data for the new channel. If null, the channel is filled with the default value for that type.</param> /// <returns>The newly added vertex channel.</returns> public VertexChannel Add(string name, Type elementType, IEnumerable channelData) { return Insert(channels.Count, name, elementType, channelData); } /// <summary> /// Removes all vertex channels from the collection. /// </summary> public void Clear() { channels.Clear(); } /// <summary> /// Determines whether the collection contains the specified vertex channel. /// </summary> /// <param name="name">Name of the channel being searched for.</param> /// <returns>true if the channel was found; false otherwise.</returns> public bool Contains(string name) { return channels.Exists(c => { return c.Name == name; }); } /// <summary> /// Determines whether the collection contains the specified vertex channel. /// </summary> /// <param name="item">The channel being searched for.</param> /// <returns>true if the channel was found; false otherwise.</returns> public bool Contains(VertexChannel item) { return channels.Contains(item); } /// <summary> /// Converts the channel, at the specified index, to another vector format. /// </summary> /// <typeparam name="TargetType">Type of the target format. Can be one of the following: Single, Vector2, Vector3, Vector4, IPackedVector</typeparam> /// <param name="index">Index of the channel to be converted.</param> /// <returns>New channel in the specified format.</returns> public VertexChannel<TargetType> ConvertChannelContent<TargetType>(int index) { if (index < 0 || index >= channels.Count) throw new ArgumentOutOfRangeException("index"); // Get the channel at that index var channel = this[index]; // Remove it because we cannot add a new channel with the same name RemoveAt(index); VertexChannel<TargetType> result = null; try { // Insert a new converted channel at the same index result = Insert(index, channel.Name, channel.ReadConvertedContent<TargetType>()); } catch { // If anything went wrong, put the old channel back... channels.Insert(index, channel); // ...before throwing the exception again throw; } // Return the new converted channel return result; } /// <summary> /// Converts the channel, specified by name to another vector format. /// </summary> /// <typeparam name="TargetType">Type of the target format. Can be one of the following: Single, Vector2, Vector3, Vector4, IPackedVector</typeparam> /// <param name="name">Name of the channel to be converted.</param> /// <returns>New channel in the specified format.</returns> public VertexChannel<TargetType> ConvertChannelContent<TargetType>(string name) { var index = IndexOf(name); if (index < 0) throw new ArgumentException("name"); return ConvertChannelContent<TargetType>(index); } /// <summary> /// Gets the vertex channel with the specified index and content type. /// </summary> /// <typeparam name="T">Type of a vertex channel.</typeparam> /// <param name="index">Index of a vertex channel.</param> /// <returns>The vertex channel.</returns> public VertexChannel<T> Get<T>(int index) { if (index < 0 || index >= channels.Count) throw new ArgumentOutOfRangeException("index"); var channel = this[index]; // Make sure the channel type is as expected if (channel.ElementType != typeof(T)) throw new InvalidOperationException("Mismatched channel type"); return (VertexChannel<T>)channel; } /// <summary> /// Gets the vertex channel with the specified name and content type. /// </summary> /// <typeparam name="T">Type of the vertex channel.</typeparam> /// <param name="name">Name of a vertex channel.</param> /// <returns>The vertex channel.</returns> public VertexChannel<T> Get<T>(string name) { var index = IndexOf(name); if (index < 0) throw new ArgumentException("name"); return Get<T>(index); } /// <summary> /// Gets an enumerator that iterates through the vertex channels of a collection. /// </summary> /// <returns>Enumerator for the collection.</returns> public IEnumerator<VertexChannel> GetEnumerator() { return channels.GetEnumerator(); } /// <summary> /// Determines the index of a vertex channel with the specified name. /// </summary> /// <param name="name">Name of the vertex channel being searched for.</param> /// <returns>Index of the vertex channel.</returns> public int IndexOf(string name) { if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); return channels.FindIndex((v) => v.Name == name); } /// <summary> /// Determines the index of the specified vertex channel. /// </summary> /// <param name="item">Vertex channel being searched for.</param> /// <returns>Index of the vertex channel.</returns> public int IndexOf(VertexChannel item) { if (item == null) throw new ArgumentNullException("item"); return channels.IndexOf(item); } /// <summary> /// Inserts a new vertex channel at the specified position. /// </summary> /// <typeparam name="ElementType">Type of the new channel.</typeparam> /// <param name="index">Index for channel insertion.</param> /// <param name="name">Name of the new channel.</param> /// <param name="channelData">The new channel.</param> /// <returns>The inserted vertex channel.</returns> public VertexChannel<ElementType> Insert<ElementType>(int index, string name, IEnumerable<ElementType> channelData) { if ((index < 0) || (index > channels.Count)) throw new ArgumentOutOfRangeException("index"); if (string.IsNullOrEmpty(name)) throw new ArgumentNullException("name"); // Don't insert a channel with the same name if (IndexOf(name) >= 0) throw new ArgumentException("Vertex channel with name " + name + " already exists"); var channel = new VertexChannel<ElementType>(name); if (channelData != null) { // Insert the values from the enumerable into the channel channel.InsertRange(0, channelData); // Make sure we have the right number of vertices if (channel.Count != vertexContent.VertexCount) throw new ArgumentOutOfRangeException("channelData"); } else { // Insert enough default values to fill the channel channel.InsertRange(0, new ElementType[vertexContent.VertexCount]); } channels.Insert(index, channel); return channel; } // this reference the above Insert method and is initialized in the constructor private readonly MethodInfo _insertOverload; /// <summary> /// Inserts a new vertex channel at the specified position. /// </summary> /// <param name="index">Index for channel insertion.</param> /// <param name="name">Name of the new channel.</param> /// <param name="elementType">Type of the new channel.</param> /// <param name="channelData">Initial data for the new channel. If null, it is filled with the default value.</param> /// <returns>The inserted vertex channel.</returns> public VertexChannel Insert(int index, string name, Type elementType, IEnumerable channelData) { // Call the generic version of this method return (VertexChannel) _insertOverload.MakeGenericMethod(elementType).Invoke(this, new object[] { index, name, channelData }); } /// <summary> /// Removes the specified vertex channel from the collection. /// </summary> /// <param name="name">Name of the vertex channel being removed.</param> /// <returns>true if the channel was removed; false otherwise.</returns> public bool Remove(string name) { var index = IndexOf(name); if (index >= 0) { channels.RemoveAt(index); return true; } return false; } /// <summary> /// Removes the specified vertex channel from the collection. /// </summary> /// <param name="item">The vertex channel being removed.</param> /// <returns>true if the channel was removed; false otherwise.</returns> public bool Remove(VertexChannel item) { return channels.Remove(item); } /// <summary> /// Removes the vertex channel at the specified index position. /// </summary> /// <param name="index">Index of the vertex channel being removed.</param> public void RemoveAt(int index) { channels.RemoveAt(index); } /// <summary> /// Adds a new vertex channel to the collection. /// </summary> /// <param name="item">Vertex channel to be added.</param> void ICollection<VertexChannel>.Add(VertexChannel item) { channels.Add(item); } /// <summary> /// Copies the elements of the collection to an array, starting at the specified index. /// </summary> /// <param name="array">The destination array.</param> /// <param name="arrayIndex">The index at which to begin copying elements.</param> void ICollection<VertexChannel>.CopyTo(VertexChannel[] array, int arrayIndex) { channels.CopyTo(array, arrayIndex); } /// <summary> /// Inserts an item at the specified index. /// </summary> /// <param name="index">The zero-based index at which item should be inserted.</param> /// <param name="item">The item to insert.</param> void IList<VertexChannel>.Insert(int index, VertexChannel item) { channels.Insert(index, item); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns>An object that can be used to iterate through the collection.</returns> IEnumerator IEnumerable.GetEnumerator() { return channels.GetEnumerator(); } } }
VertexChannelCollection
csharp
AvaloniaUI__Avalonia
src/Avalonia.Vulkan/UnmanagedInterop/VulkanStructs.cs
{ "start": 4804, "end": 5264 }
struct ____ { public uint32_t apiVersion; public uint32_t driverVersion; public uint32_t vendorID; public uint32_t deviceID; public VkPhysicalDeviceType deviceType; public fixed byte deviceName[256]; public fixed uint8_t pipelineCacheUUID[16]; public VkPhysicalDeviceLimits limits; public VkPhysicalDeviceSparseProperties sparseProperties; } unsafe
VkPhysicalDeviceProperties
csharp
dotnet__aspnetcore
src/ProjectTemplates/Web.ProjectTemplates/content/StarterWeb-CSharp/Program.Main.cs
{ "start": 959, "end": 5468 }
public class ____ { public static void Main(string[] args) { var builder = WebApplication.CreateBuilder(args); // Add services to the container. #if (IndividualLocalAuth) var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found."); builder.Services.AddDbContext<ApplicationDbContext>(options => #if (UseLocalDB) options.UseSqlServer(connectionString)); #else options.UseSqlite(connectionString)); #endif builder.Services.AddDatabaseDeveloperPageExceptionFilter(); builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true) .AddEntityFrameworkStores<ApplicationDbContext>(); #elif (OrganizationalAuth) #if (GenerateApiOrGraph) var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' '); #endif builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) #if (GenerateApiOrGraph) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")) .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) #if (GenerateApi) .AddDownstreamApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi")) #endif #if (GenerateGraph) .AddMicrosoftGraph(builder.Configuration.GetSection("DownstreamApi")) #endif .AddInMemoryTokenCaches(); #else .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd")); #endif #elif (IndividualB2CAuth) #if (GenerateApi) var initialScopes = builder.Configuration["DownstreamApi:Scopes"]?.Split(' '); #endif builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme) #if (GenerateApi) .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C")) .EnableTokenAcquisitionToCallDownstreamApi(initialScopes) .AddDownstreamApi("DownstreamApi", builder.Configuration.GetSection("DownstreamApi")) .AddInMemoryTokenCaches(); #else .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAdB2C")); #endif #endif #if (OrganizationalAuth) builder.Services.AddControllersWithViews(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); #else builder.Services.AddControllersWithViews(); #endif #if (OrganizationalAuth || IndividualB2CAuth) builder.Services.AddRazorPages() .AddMicrosoftIdentityUI(); #endif #if (WindowsAuth) builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme) .AddNegotiate(); builder.Services.AddAuthorization(options => { // By default, all incoming requests will be authorized according to the default policy. options.FallbackPolicy = options.DefaultPolicy; }); builder.Services.AddRazorPages(); #endif var app = builder.Build(); // Configure the HTTP request pipeline. #if (IndividualLocalAuth) if (app.Environment.IsDevelopment()) { app.UseMigrationsEndPoint(); } else #else if (!app.Environment.IsDevelopment()) #endif { app.UseExceptionHandler("/Home/Error"); #if (HasHttpsProfile) // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); #else } #endif app.UseRouting(); app.UseAuthorization(); app.MapStaticAssets(); app.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}") .WithStaticAssets(); #if (OrganizationalAuth || IndividualAuth) app.MapRazorPages() .WithStaticAssets(); #endif app.Run(); } }
Program
csharp
dotnet__extensions
test/Generators/Microsoft.Gen.Metrics/Unit/ParserTests.StrongTypes.cs
{ "start": 2816, "end": 3231 }
public class ____ { [TagName(""test2_FromAttribute"")] public string test2_WithAttribute { get; set; } public string test2 { get; set; } [TagName(""test1_FromAttribute_In_Child1"")] public string? test1 { get; set; } public ChildTagNames2? ChildTagNames2 { get; set;} }
ChildTagNames
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Linq/Observable/Sum.cs
{ "start": 4545, "end": 5287 }
internal sealed class ____ : IdentitySink<long> { private long _sum; public _(IObserver<long> observer) : base(observer) { } public override void OnNext(long value) { try { checked { _sum += value; } } catch (Exception exception) { ForwardOnError(exception); } } public override void OnCompleted() { ForwardOnNext(_sum); ForwardOnCompleted(); } } }
_
csharp
AvaloniaUI__Avalonia
src/Avalonia.Controls.ColorPicker/Converters/ColorToDisplayNameConverter.cs
{ "start": 274, "end": 1896 }
public class ____ : IValueConverter { /// <inheritdoc/> public object? Convert( object? value, Type targetType, object? parameter, CultureInfo culture) { Color color; if (value is Color valueColor) { color = valueColor; } else if (value is HslColor valueHslColor) { color = valueHslColor.ToRgb(); } else if (value is HsvColor valueHsvColor) { color = valueHsvColor.ToRgb(); } else if (value is SolidColorBrush valueBrush) { color = valueBrush.Color; } else { // Invalid color value provided return AvaloniaProperty.UnsetValue; } // ColorHelper.ToDisplayName ignores the alpha component // This means fully transparent colors will be named as a real color // That undesirable behavior is specially overridden here if (color.A == 0x00) { return AvaloniaProperty.UnsetValue; } else { return ColorHelper.ToDisplayName(color); } } /// <inheritdoc/> public object? ConvertBack( object? value, Type targetType, object? parameter, CultureInfo culture) { return AvaloniaProperty.UnsetValue; } } }
ColorToDisplayNameConverter
csharp
RicoSuter__NJsonSchema
src/NJsonSchema.Tests/Generation/IgnoredPropertyTests.cs
{ "start": 199, "end": 717 }
public class ____ { public string IncludeMe; [JsonIgnore] public string IgnoreMe; } [Fact] public async Task When_field_has_JsonIgnoreAttribute_then_it_is_ignored() { // Arrange var schema = NewtonsoftJsonSchemaGenerator.FromType<Mno>(); // Act var json = schema.ToJson(); // Assert Assert.DoesNotContain("IgnoreMe", json); } [DataContract]
Mno
csharp
LibreHardwareMonitor__LibreHardwareMonitor
LibreHardwareMonitor/UI/GadgetWindow.cs
{ "start": 12976, "end": 13209 }
private struct ____ { public byte BlendOp; public byte BlendFlags; public byte SourceConstantAlpha; public byte AlphaFormat; } [StructLayout(LayoutKind.Sequential, Pack = 1)]
BlendFunction
csharp
icsharpcode__SharpZipLib
test/ICSharpCode.SharpZipLib.Tests/Checksum/ChecksumTests.cs
{ "start": 196, "end": 5341 }
public class ____ { private readonly // Represents ASCII string of "123456789" byte[] check = { 49, 50, 51, 52, 53, 54, 55, 56, 57 }; // Represents string "123456789123456789123456789123456789" private readonly byte[] longCheck = { 49, 50, 51, 52, 53, 54, 55, 56, 57, 49, 50, 51, 52, 53, 54, 55, 56, 57, 49, 50, 51, 52, 53, 54, 55, 56, 57, 49, 50, 51, 52, 53, 54, 55, 56, 57 }; [Test] public void Adler_32() { var underTestAdler32 = new Adler32(); Assert.AreEqual(0x00000001, underTestAdler32.Value); underTestAdler32.Update(check); Assert.AreEqual(0x091E01DE, underTestAdler32.Value); underTestAdler32.Reset(); Assert.AreEqual(0x00000001, underTestAdler32.Value); exceptionTesting(underTestAdler32); } const long BufferSize = 256 * 1024 * 1024; [Test] public void Adler_32_Performance() { var rand = new Random(1); var buffer = new byte[BufferSize]; rand.NextBytes(buffer); var adler = new Adler32(); Assert.AreEqual(0x00000001, adler.Value); var sw = new Stopwatch(); sw.Start(); adler.Update(buffer); sw.Stop(); Console.WriteLine($"Adler32 Hashing of 256 MiB: {sw.Elapsed.TotalSeconds:f4} second(s)"); adler.Update(check); Assert.AreEqual(0xD4897DA3, adler.Value); exceptionTesting(adler); } [Test] public void CRC_32_BZip2() { var underTestBZip2Crc = new BZip2Crc(); Assert.AreEqual(0x0, underTestBZip2Crc.Value); underTestBZip2Crc.Update(check); Assert.AreEqual(0xFC891918, underTestBZip2Crc.Value); underTestBZip2Crc.Reset(); Assert.AreEqual(0x0, underTestBZip2Crc.Value); exceptionTesting(underTestBZip2Crc); } [Test] public void CRC_32_BZip2_Long() { var underTestCrc32 = new BZip2Crc(); underTestCrc32.Update(longCheck); Assert.AreEqual(0xEE53D2B2, underTestCrc32.Value); } [Test] public void CRC_32_BZip2_Unaligned() { // Extract "456" and CRC var underTestCrc32 = new BZip2Crc(); underTestCrc32.Update(new ArraySegment<byte>(check, 3, 3)); Assert.AreEqual(0x001D0511, underTestCrc32.Value); } [Test] public void CRC_32_BZip2_Long_Unaligned() { // Extract "789123456789123456" and CRC var underTestCrc32 = new BZip2Crc(); underTestCrc32.Update(new ArraySegment<byte>(longCheck, 15, 18)); Assert.AreEqual(0x025846E0, underTestCrc32.Value); } [Test] public void CRC_32() { var underTestCrc32 = new Crc32(); Assert.AreEqual(0x0, underTestCrc32.Value); underTestCrc32.Update(check); Assert.AreEqual(0xCBF43926, underTestCrc32.Value); underTestCrc32.Reset(); Assert.AreEqual(0x0, underTestCrc32.Value); exceptionTesting(underTestCrc32); } [Test] public void CRC_32_Long() { var underTestCrc32 = new Crc32(); underTestCrc32.Update(longCheck); Assert.AreEqual(0x3E29169C, underTestCrc32.Value); } [Test] public void CRC_32_Unaligned() { // Extract "456" and CRC var underTestCrc32 = new Crc32(); underTestCrc32.Update(new ArraySegment<byte>(check, 3, 3)); Assert.AreEqual(0xB1A8C371, underTestCrc32.Value); } [Test] public void CRC_32_Long_Unaligned() { // Extract "789123456789123456" and CRC var underTestCrc32 = new Crc32(); underTestCrc32.Update(new ArraySegment<byte>(longCheck, 15, 18)); Assert.AreEqual(0x31CA9A2E, underTestCrc32.Value); } private void exceptionTesting(IChecksum crcUnderTest) { bool exception = false; try { crcUnderTest.Update(null); } catch (ArgumentNullException) { exception = true; } Assert.IsTrue(exception, "Passing a null buffer should cause an ArgumentNullException"); // reset exception exception = false; try { crcUnderTest.Update(new ArraySegment<byte>(null, 0, 0)); } catch (ArgumentNullException) { exception = true; } Assert.IsTrue(exception, "Passing a null buffer should cause an ArgumentNullException"); // reset exception exception = false; try { crcUnderTest.Update(new ArraySegment<byte>(check, -1, 9)); } catch (ArgumentOutOfRangeException) { exception = true; } Assert.IsTrue(exception, "Passing a negative offset should cause an ArgumentOutOfRangeException"); // reset exception exception = false; try { crcUnderTest.Update(new ArraySegment<byte>(check, 10, 0)); } catch (ArgumentException) { exception = true; } Assert.IsTrue(exception, "Passing an offset greater than buffer.Length should cause an ArgumentException"); // reset exception exception = false; try { crcUnderTest.Update(new ArraySegment<byte>(check, 0, -1)); } catch (ArgumentOutOfRangeException) { exception = true; } Assert.IsTrue(exception, "Passing a negative count should cause an ArgumentOutOfRangeException"); // reset exception exception = false; try { crcUnderTest.Update(new ArraySegment<byte>(check, 0, 10)); } catch (ArgumentException) { exception = true; } Assert.IsTrue(exception, "Passing a count + offset greater than buffer.Length should cause an ArgumentException"); } } }
ChecksumTests
csharp
dotnet__aspnetcore
src/DataProtection/DataProtection/test/Microsoft.AspNetCore.DataProtection.TrimmingTests/TestEncryptedXmlDecryptor.cs
{ "start": 1233, "end": 1440 }
internal sealed class ____ : IDataProtectionBuilder { public DataProtectionBuilder(IServiceCollection services) => Services = services; public IServiceCollection Services { get; } }
DataProtectionBuilder
csharp
dotnet__machinelearning
docs/samples/Microsoft.ML.Samples/Dynamic/Transforms/NormalizeBinningMulticolumn.cs
{ "start": 243, "end": 2718 }
public class ____ { public static void Example() { // Create a new ML context, for ML.NET operations. It can be used for // exception tracking and logging, as well as the source of randomness. var mlContext = new MLContext(); var samples = new List<DataPoint>() { new DataPoint(){ Features = new float[4] { 8, 1, 3, 0}, Features2 = 1 }, new DataPoint(){ Features = new float[4] { 6, 2, 2, 0}, Features2 = 4 }, new DataPoint(){ Features = new float[4] { 4, 0, 1, 0}, Features2 = 1 }, new DataPoint(){ Features = new float[4] { 2,-1,-1, 1}, Features2 = 2 } }; // Convert training data to IDataView, the general data type used in // ML.NET. var data = mlContext.Data.LoadFromEnumerable(samples); // NormalizeBinning normalizes the data by constructing equidensity bins // and produce output based on to which bin the original value belongs. var normalize = mlContext.Transforms.NormalizeBinning(new[]{ new InputOutputColumnPair("Features"), new InputOutputColumnPair("Features2"), }, maximumBinCount: 4, fixZero: false); // Now we can transform the data and look at the output to confirm the // behavior of the estimator. This operation doesn't actually evaluate // data until we read the data below. var normalizeTransform = normalize.Fit(data); var transformedData = normalizeTransform.Transform(data); var column = transformedData.GetColumn<float[]>("Features").ToArray(); var column2 = transformedData.GetColumn<float>("Features2").ToArray(); for (int i = 0; i < column.Length; i++) Console.WriteLine(string.Join(", ", column[i].Select(x => x .ToString("f4"))) + "\t\t" + column2[i]); // Expected output: // // Features Feature2 // 1.0000, 0.6667, 1.0000, 0.0000 0 // 0.6667, 1.0000, 0.6667, 0.0000 1 // 0.3333, 0.3333, 0.3333, 0.0000 0 // 0.0000, 0.0000, 0.0000, 1.0000 0.5 }
NormalizeBinningMulticolumn
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Joins/ActivePlan.cs
{ "start": 39219, "end": 44691 }
internal sealed class ____<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> : ActivePlan { private readonly Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> _onNext; private readonly JoinObserver<T1> _first; private readonly JoinObserver<T2> _second; private readonly JoinObserver<T3> _third; private readonly JoinObserver<T4> _fourth; private readonly JoinObserver<T5> _fifth; private readonly JoinObserver<T6> _sixth; private readonly JoinObserver<T7> _seventh; private readonly JoinObserver<T8> _eighth; private readonly JoinObserver<T9> _ninth; private readonly JoinObserver<T10> _tenth; private readonly JoinObserver<T11> _eleventh; private readonly JoinObserver<T12> _twelfth; private readonly JoinObserver<T13> _thirteenth; private readonly JoinObserver<T14> _fourteenth; internal ActivePlan(JoinObserver<T1> first, JoinObserver<T2> second, JoinObserver<T3> third, JoinObserver<T4> fourth, JoinObserver<T5> fifth, JoinObserver<T6> sixth, JoinObserver<T7> seventh, JoinObserver<T8> eighth, JoinObserver<T9> ninth, JoinObserver<T10> tenth, JoinObserver<T11> eleventh, JoinObserver<T12> twelfth, JoinObserver<T13> thirteenth, JoinObserver<T14> fourteenth, Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> onNext, Action onCompleted) : base(onCompleted) { _onNext = onNext; _first = first; _second = second; _third = third; _fourth = fourth; _fifth = fifth; _sixth = sixth; _seventh = seventh; _eighth = eighth; _ninth = ninth; _tenth = tenth; _eleventh = eleventh; _twelfth = twelfth; _thirteenth = thirteenth; _fourteenth = fourteenth; AddJoinObserver(first); AddJoinObserver(second); AddJoinObserver(third); AddJoinObserver(fourth); AddJoinObserver(fifth); AddJoinObserver(sixth); AddJoinObserver(seventh); AddJoinObserver(eighth); AddJoinObserver(ninth); AddJoinObserver(tenth); AddJoinObserver(eleventh); AddJoinObserver(twelfth); AddJoinObserver(thirteenth); AddJoinObserver(fourteenth); } internal override void Match() { if (_first.Queue.Count > 0 && _second.Queue.Count > 0 && _third.Queue.Count > 0 && _fourth.Queue.Count > 0 && _fifth.Queue.Count > 0 && _sixth.Queue.Count > 0 && _seventh.Queue.Count > 0 && _eighth.Queue.Count > 0 && _ninth.Queue.Count > 0 && _tenth.Queue.Count > 0 && _eleventh.Queue.Count > 0 && _twelfth.Queue.Count > 0 && _thirteenth.Queue.Count > 0 && _fourteenth.Queue.Count > 0 ) { var n1 = _first.Queue.Peek(); var n2 = _second.Queue.Peek(); var n3 = _third.Queue.Peek(); var n4 = _fourth.Queue.Peek(); var n5 = _fifth.Queue.Peek(); var n6 = _sixth.Queue.Peek(); var n7 = _seventh.Queue.Peek(); var n8 = _eighth.Queue.Peek(); var n9 = _ninth.Queue.Peek(); var n10 = _tenth.Queue.Peek(); var n11 = _eleventh.Queue.Peek(); var n12 = _twelfth.Queue.Peek(); var n13 = _thirteenth.Queue.Peek(); var n14 = _fourteenth.Queue.Peek(); if (n1.Kind == NotificationKind.OnCompleted || n2.Kind == NotificationKind.OnCompleted || n3.Kind == NotificationKind.OnCompleted || n4.Kind == NotificationKind.OnCompleted || n5.Kind == NotificationKind.OnCompleted || n6.Kind == NotificationKind.OnCompleted || n7.Kind == NotificationKind.OnCompleted || n8.Kind == NotificationKind.OnCompleted || n9.Kind == NotificationKind.OnCompleted || n10.Kind == NotificationKind.OnCompleted || n11.Kind == NotificationKind.OnCompleted || n12.Kind == NotificationKind.OnCompleted || n13.Kind == NotificationKind.OnCompleted || n14.Kind == NotificationKind.OnCompleted ) { _onCompleted(); } else { Dequeue(); _onNext(n1.Value, n2.Value, n3.Value, n4.Value, n5.Value, n6.Value, n7.Value, n8.Value, n9.Value, n10.Value, n11.Value, n12.Value, n13.Value, n14.Value ); } } } }
ActivePlan
csharp
npgsql__npgsql
src/Npgsql.GeoJSON/CrsMap.WellKnown.cs
{ "start": 28, "end": 19833 }
public partial class ____ { /// <summary> /// These entries came from spatial_res_sys. They are used to elide memory allocations /// if they are identical to the entries for the current connection. Otherwise, /// memory allocated for overridden entries only (added, removed, or modified). /// </summary> internal static readonly CrsMapEntry[] WellKnown = [ new(2000, 2180, "EPSG"), new(2188, 2217, "EPSG"), new(2219, 2220, "EPSG"), new(2222, 2292, "EPSG"), new(2294, 2295, "EPSG"), new(2308, 2962, "EPSG"), new(2964, 2973, "EPSG"), new(2975, 2984, "EPSG"), new(2987, 3051, "EPSG"), new(3054, 3138, "EPSG"), new(3140, 3143, "EPSG"), new(3146, 3172, "EPSG"), new(3174, 3294, "EPSG"), new(3296, 3791, "EPSG"), new(3793, 3802, "EPSG"), new(3812, 3812, "EPSG"), new(3814, 3816, "EPSG"), new(3819, 3819, "EPSG"), new(3821, 3822, "EPSG"), new(3824, 3829, "EPSG"), new(3832, 3852, "EPSG"), new(3854, 3854, "EPSG"), new(3857, 3857, "EPSG"), new(3873, 3885, "EPSG"), new(3887, 3887, "EPSG"), new(3889, 3893, "EPSG"), new(3901, 3903, "EPSG"), new(3906, 3912, "EPSG"), new(3920, 3920, "EPSG"), new(3942, 3950, "EPSG"), new(3968, 3970, "EPSG"), new(3973, 3976, "EPSG"), new(3978, 3979, "EPSG"), new(3985, 3989, "EPSG"), new(3991, 3992, "EPSG"), new(3994, 3997, "EPSG"), new(4000, 4016, "EPSG"), new(4018, 4039, "EPSG"), new(4041, 4063, "EPSG"), new(4071, 4071, "EPSG"), new(4073, 4073, "EPSG"), new(4075, 4075, "EPSG"), new(4079, 4079, "EPSG"), new(4081, 4083, "EPSG"), new(4087, 4088, "EPSG"), new(4093, 4100, "EPSG"), new(4120, 4176, "EPSG"), new(4178, 4185, "EPSG"), new(4188, 4289, "EPSG"), new(4291, 4304, "EPSG"), new(4306, 4319, "EPSG"), new(4322, 4322, "EPSG"), new(4324, 4324, "EPSG"), new(4326, 4326, "EPSG"), new(4328, 4328, "EPSG"), new(4330, 4338, "EPSG"), new(4340, 4340, "EPSG"), new(4342, 4342, "EPSG"), new(4344, 4344, "EPSG"), new(4346, 4346, "EPSG"), new(4348, 4348, "EPSG"), new(4350, 4350, "EPSG"), new(4352, 4352, "EPSG"), new(4354, 4354, "EPSG"), new(4356, 4356, "EPSG"), new(4358, 4358, "EPSG"), new(4360, 4360, "EPSG"), new(4362, 4362, "EPSG"), new(4364, 4364, "EPSG"), new(4366, 4366, "EPSG"), new(4368, 4368, "EPSG"), new(4370, 4370, "EPSG"), new(4372, 4372, "EPSG"), new(4374, 4374, "EPSG"), new(4376, 4376, "EPSG"), new(4378, 4378, "EPSG"), new(4380, 4380, "EPSG"), new(4382, 4382, "EPSG"), new(4384, 4385, "EPSG"), new(4387, 4387, "EPSG"), new(4389, 4415, "EPSG"), new(4417, 4434, "EPSG"), new(4437, 4439, "EPSG"), new(4455, 4457, "EPSG"), new(4462, 4463, "EPSG"), new(4465, 4465, "EPSG"), new(4467, 4468, "EPSG"), new(4470, 4471, "EPSG"), new(4473, 4475, "EPSG"), new(4479, 4479, "EPSG"), new(4481, 4481, "EPSG"), new(4483, 4556, "EPSG"), new(4558, 4559, "EPSG"), new(4568, 4589, "EPSG"), new(4600, 4647, "EPSG"), new(4652, 4824, "EPSG"), new(4826, 4826, "EPSG"), new(4839, 4839, "EPSG"), new(4855, 4880, "EPSG"), new(4882, 4882, "EPSG"), new(4884, 4884, "EPSG"), new(4886, 4886, "EPSG"), new(4888, 4888, "EPSG"), new(4890, 4890, "EPSG"), new(4892, 4892, "EPSG"), new(4894, 4894, "EPSG"), new(4896, 4897, "EPSG"), new(4899, 4899, "EPSG"), new(4901, 4904, "EPSG"), new(4906, 4906, "EPSG"), new(4908, 4908, "EPSG"), new(4910, 4920, "EPSG"), new(4922, 4922, "EPSG"), new(4924, 4924, "EPSG"), new(4926, 4926, "EPSG"), new(4928, 4928, "EPSG"), new(4930, 4930, "EPSG"), new(4932, 4932, "EPSG"), new(4934, 4934, "EPSG"), new(4936, 4936, "EPSG"), new(4938, 4938, "EPSG"), new(4940, 4940, "EPSG"), new(4942, 4942, "EPSG"), new(4944, 4944, "EPSG"), new(4946, 4946, "EPSG"), new(4948, 4948, "EPSG"), new(4950, 4950, "EPSG"), new(4952, 4952, "EPSG"), new(4954, 4954, "EPSG"), new(4956, 4956, "EPSG"), new(4958, 4958, "EPSG"), new(4960, 4960, "EPSG"), new(4962, 4962, "EPSG"), new(4964, 4964, "EPSG"), new(4966, 4966, "EPSG"), new(4968, 4968, "EPSG"), new(4970, 4970, "EPSG"), new(4972, 4972, "EPSG"), new(4974, 4974, "EPSG"), new(4976, 4976, "EPSG"), new(4978, 4978, "EPSG"), new(4980, 4980, "EPSG"), new(4982, 4982, "EPSG"), new(4984, 4984, "EPSG"), new(4986, 4986, "EPSG"), new(4988, 4988, "EPSG"), new(4990, 4990, "EPSG"), new(4992, 4992, "EPSG"), new(4994, 4994, "EPSG"), new(4996, 4996, "EPSG"), new(4998, 4998, "EPSG"), new(5011, 5011, "EPSG"), new(5013, 5016, "EPSG"), new(5018, 5018, "EPSG"), new(5041, 5042, "EPSG"), new(5048, 5048, "EPSG"), new(5069, 5072, "EPSG"), new(5105, 5130, "EPSG"), new(5132, 5132, "EPSG"), new(5167, 5188, "EPSG"), new(5221, 5221, "EPSG"), new(5223, 5223, "EPSG"), new(5228, 5229, "EPSG"), new(5233, 5235, "EPSG"), new(5243, 5244, "EPSG"), new(5246, 5247, "EPSG"), new(5250, 5250, "EPSG"), new(5252, 5259, "EPSG"), new(5262, 5262, "EPSG"), new(5264, 5264, "EPSG"), new(5266, 5266, "EPSG"), new(5269, 5275, "EPSG"), new(5292, 5311, "EPSG"), new(5316, 5316, "EPSG"), new(5318, 5318, "EPSG"), new(5320, 5322, "EPSG"), new(5324, 5325, "EPSG"), new(5329, 5332, "EPSG"), new(5337, 5337, "EPSG"), new(5340, 5341, "EPSG"), new(5343, 5349, "EPSG"), new(5352, 5352, "EPSG"), new(5354, 5358, "EPSG"), new(5360, 5363, "EPSG"), new(5365, 5365, "EPSG"), new(5367, 5369, "EPSG"), new(5371, 5371, "EPSG"), new(5373, 5373, "EPSG"), new(5379, 5379, "EPSG"), new(5381, 5383, "EPSG"), new(5387, 5389, "EPSG"), new(5391, 5391, "EPSG"), new(5393, 5393, "EPSG"), new(5396, 5396, "EPSG"), new(5451, 5451, "EPSG"), new(5456, 5464, "EPSG"), new(5466, 5467, "EPSG"), new(5469, 5469, "EPSG"), new(5472, 5472, "EPSG"), new(5479, 5482, "EPSG"), new(5487, 5487, "EPSG"), new(5489, 5490, "EPSG"), new(5498, 5500, "EPSG"), new(5513, 5514, "EPSG"), new(5518, 5520, "EPSG"), new(5523, 5524, "EPSG"), new(5527, 5527, "EPSG"), new(5530, 5539, "EPSG"), new(5544, 5544, "EPSG"), new(5546, 5546, "EPSG"), new(5550, 5552, "EPSG"), new(5554, 5556, "EPSG"), new(5558, 5559, "EPSG"), new(5561, 5583, "EPSG"), new(5588, 5589, "EPSG"), new(5591, 5591, "EPSG"), new(5593, 5593, "EPSG"), new(5596, 5596, "EPSG"), new(5598, 5598, "EPSG"), new(5623, 5625, "EPSG"), new(5627, 5629, "EPSG"), new(5631, 5639, "EPSG"), new(5641, 5641, "EPSG"), new(5643, 5644, "EPSG"), new(5646, 5646, "EPSG"), new(5649, 5655, "EPSG"), new(5659, 5659, "EPSG"), new(5663, 5685, "EPSG"), new(5698, 5700, "EPSG"), new(5707, 5708, "EPSG"), new(5825, 5825, "EPSG"), new(5828, 5828, "EPSG"), new(5832, 5837, "EPSG"), new(5839, 5839, "EPSG"), new(5842, 5842, "EPSG"), new(5844, 5858, "EPSG"), new(5875, 5877, "EPSG"), new(5879, 5880, "EPSG"), new(5884, 5884, "EPSG"), new(5886, 5887, "EPSG"), new(5890, 5890, "EPSG"), new(5921, 5940, "EPSG"), new(5942, 5942, "EPSG"), new(5945, 5976, "EPSG"), new(6050, 6125, "EPSG"), new(6128, 6129, "EPSG"), new(6133, 6133, "EPSG"), new(6135, 6135, "EPSG"), new(6141, 6141, "EPSG"), new(6144, 6176, "EPSG"), new(6190, 6190, "EPSG"), new(6204, 6204, "EPSG"), new(6207, 6207, "EPSG"), new(6210, 6211, "EPSG"), new(6307, 6307, "EPSG"), new(6309, 6309, "EPSG"), new(6311, 6312, "EPSG"), new(6316, 6318, "EPSG"), new(6320, 6320, "EPSG"), new(6322, 6323, "EPSG"), new(6325, 6325, "EPSG"), new(6328, 6356, "EPSG"), new(6362, 6363, "EPSG"), new(6365, 6372, "EPSG"), new(6381, 6387, "EPSG"), new(6391, 6391, "EPSG"), new(6393, 6637, "EPSG"), new(6646, 6646, "EPSG"), new(6649, 6666, "EPSG"), new(6668, 6692, "EPSG"), new(6696, 6697, "EPSG"), new(6700, 6700, "EPSG"), new(6703, 6704, "EPSG"), new(6706, 6709, "EPSG"), new(6720, 6723, "EPSG"), new(6732, 6738, "EPSG"), new(6781, 6781, "EPSG"), new(6783, 6863, "EPSG"), new(6867, 6868, "EPSG"), new(6870, 6871, "EPSG"), new(6875, 6876, "EPSG"), new(6879, 6887, "EPSG"), new(6892, 6894, "EPSG"), new(6915, 6915, "EPSG"), new(6917, 6917, "EPSG"), new(6922, 6925, "EPSG"), new(6927, 6927, "EPSG"), new(6931, 6934, "EPSG"), new(6956, 6959, "EPSG"), new(6962, 6962, "EPSG"), new(6978, 6978, "EPSG"), new(6980, 6981, "EPSG"), new(6983, 6985, "EPSG"), new(6987, 6988, "EPSG"), new(6990, 6991, "EPSG"), new(6996, 6997, "EPSG"), new(7005, 7007, "EPSG"), new(7035, 7035, "EPSG"), new(7037, 7037, "EPSG"), new(7039, 7039, "EPSG"), new(7041, 7041, "EPSG"), new(7057, 7071, "EPSG"), new(7073, 7081, "EPSG"), new(7084, 7084, "EPSG"), new(7086, 7086, "EPSG"), new(7088, 7088, "EPSG"), new(7109, 7128, "EPSG"), new(7131, 7134, "EPSG"), new(7136, 7137, "EPSG"), new(7139, 7139, "EPSG"), new(7142, 7142, "EPSG"), new(7257, 7371, "EPSG"), new(7373, 7376, "EPSG"), new(7400, 7423, "EPSG"), new(7528, 7645, "EPSG"), new(7656, 7656, "EPSG"), new(7658, 7658, "EPSG"), new(7660, 7660, "EPSG"), new(7662, 7662, "EPSG"), new(7664, 7664, "EPSG"), new(7677, 7677, "EPSG"), new(7679, 7679, "EPSG"), new(7681, 7681, "EPSG"), new(7683, 7684, "EPSG"), new(7686, 7686, "EPSG"), new(7692, 7696, "EPSG"), new(7755, 7787, "EPSG"), new(7789, 7789, "EPSG"), new(7791, 7796, "EPSG"), new(7798, 7801, "EPSG"), new(7803, 7805, "EPSG"), new(7815, 7815, "EPSG"), new(7825, 7831, "EPSG"), new(7842, 7842, "EPSG"), new(7844, 7859, "EPSG"), new(7877, 7879, "EPSG"), new(7881, 7884, "EPSG"), new(7886, 7887, "EPSG"), new(7899, 7899, "EPSG"), new(7914, 7914, "EPSG"), new(7916, 7916, "EPSG"), new(7918, 7918, "EPSG"), new(7920, 7920, "EPSG"), new(7922, 7922, "EPSG"), new(7924, 7924, "EPSG"), new(7926, 7926, "EPSG"), new(7928, 7928, "EPSG"), new(7930, 7930, "EPSG"), new(7954, 7956, "EPSG"), new(7991, 7992, "EPSG"), new(8013, 8032, "EPSG"), new(8035, 8036, "EPSG"), new(8042, 8045, "EPSG"), new(8058, 8059, "EPSG"), new(8065, 8068, "EPSG"), new(8082, 8084, "EPSG"), new(8086, 8086, "EPSG"), new(8088, 8088, "EPSG"), new(8090, 8093, "EPSG"), new(8095, 8173, "EPSG"), new(8177, 8177, "EPSG"), new(8179, 8182, "EPSG"), new(8184, 8185, "EPSG"), new(8187, 8187, "EPSG"), new(8189, 8189, "EPSG"), new(8191, 8191, "EPSG"), new(8193, 8193, "EPSG"), new(8196, 8198, "EPSG"), new(8200, 8210, "EPSG"), new(8212, 8214, "EPSG"), new(8216, 8216, "EPSG"), new(8218, 8218, "EPSG"), new(8220, 8220, "EPSG"), new(8222, 8222, "EPSG"), new(8224, 8227, "EPSG"), new(8230, 8230, "EPSG"), new(8232, 8233, "EPSG"), new(8237, 8238, "EPSG"), new(8240, 8240, "EPSG"), new(8242, 8242, "EPSG"), new(8246, 8247, "EPSG"), new(8249, 8250, "EPSG"), new(8252, 8253, "EPSG"), new(8255, 8255, "EPSG"), new(8311, 8350, "EPSG"), new(20004, 20032, "EPSG"), new(20064, 20092, "EPSG"), new(20135, 20138, "EPSG"), new(20248, 20258, "EPSG"), new(20348, 20358, "EPSG"), new(20436, 20440, "EPSG"), new(20499, 20499, "EPSG"), new(20538, 20539, "EPSG"), new(20790, 20791, "EPSG"), new(20822, 20824, "EPSG"), new(20934, 20936, "EPSG"), new(21035, 21037, "EPSG"), new(21095, 21097, "EPSG"), new(21100, 21100, "EPSG"), new(21148, 21150, "EPSG"), new(21291, 21292, "EPSG"), new(21413, 21423, "EPSG"), new(21453, 21463, "EPSG"), new(21473, 21483, "EPSG"), new(21500, 21500, "EPSG"), new(21780, 21782, "EPSG"), new(21817, 21818, "EPSG"), new(21891, 21894, "EPSG"), new(21896, 21899, "EPSG"), new(22032, 22033, "EPSG"), new(22091, 22092, "EPSG"), new(22171, 22177, "EPSG"), new(22181, 22187, "EPSG"), new(22191, 22197, "EPSG"), new(22234, 22236, "EPSG"), new(22275, 22275, "EPSG"), new(22277, 22277, "EPSG"), new(22279, 22279, "EPSG"), new(22281, 22281, "EPSG"), new(22283, 22283, "EPSG"), new(22285, 22285, "EPSG"), new(22287, 22287, "EPSG"), new(22289, 22289, "EPSG"), new(22291, 22291, "EPSG"), new(22293, 22293, "EPSG"), new(22300, 22300, "EPSG"), new(22332, 22332, "EPSG"), new(22391, 22392, "EPSG"), new(22521, 22525, "EPSG"), new(22700, 22700, "EPSG"), new(22770, 22770, "EPSG"), new(22780, 22780, "EPSG"), new(22832, 22832, "EPSG"), new(22991, 22994, "EPSG"), new(23028, 23038, "EPSG"), new(23090, 23090, "EPSG"), new(23095, 23095, "EPSG"), new(23239, 23240, "EPSG"), new(23433, 23433, "EPSG"), new(23700, 23700, "EPSG"), new(23830, 23853, "EPSG"), new(23866, 23872, "EPSG"), new(23877, 23884, "EPSG"), new(23886, 23894, "EPSG"), new(23946, 23948, "EPSG"), new(24047, 24048, "EPSG"), new(24100, 24100, "EPSG"), new(24200, 24200, "EPSG"), new(24305, 24306, "EPSG"), new(24311, 24313, "EPSG"), new(24342, 24347, "EPSG"), new(24370, 24383, "EPSG"), new(24500, 24500, "EPSG"), new(24547, 24548, "EPSG"), new(24571, 24571, "EPSG"), new(24600, 24600, "EPSG"), new(24718, 24720, "EPSG"), new(24817, 24821, "EPSG"), new(24877, 24882, "EPSG"), new(24891, 24893, "EPSG"), new(25000, 25000, "EPSG"), new(25231, 25231, "EPSG"), new(25391, 25395, "EPSG"), new(25700, 25700, "EPSG"), new(25828, 25838, "EPSG"), new(25884, 25884, "EPSG"), new(25932, 25932, "EPSG"), new(26191, 26195, "EPSG"), new(26237, 26237, "EPSG"), new(26331, 26332, "EPSG"), new(26391, 26393, "EPSG"), new(26432, 26432, "EPSG"), new(26591, 26592, "EPSG"), new(26632, 26632, "EPSG"), new(26692, 26692, "EPSG"), new(26701, 26722, "EPSG"), new(26729, 26760, "EPSG"), new(26766, 26787, "EPSG"), new(26791, 26799, "EPSG"), new(26801, 26803, "EPSG"), new(26811, 26815, "EPSG"), new(26819, 26826, "EPSG"), new(26830, 26837, "EPSG"), new(26841, 26870, "EPSG"), new(26891, 26899, "EPSG"), new(26901, 26923, "EPSG"), new(26929, 26946, "EPSG"), new(26948, 26998, "EPSG"), new(27037, 27040, "EPSG"), new(27120, 27120, "EPSG"), new(27200, 27200, "EPSG"), new(27205, 27232, "EPSG"), new(27258, 27260, "EPSG"), new(27291, 27292, "EPSG"), new(27391, 27398, "EPSG"), new(27429, 27429, "EPSG"), new(27492, 27493, "EPSG"), new(27500, 27500, "EPSG"), new(27561, 27564, "EPSG"), new(27571, 27574, "EPSG"), new(27581, 27584, "EPSG"), new(27591, 27594, "EPSG"), new(27700, 27700, "EPSG"), new(28191, 28193, "EPSG"), new(28232, 28232, "EPSG"), new(28348, 28358, "EPSG"), new(28402, 28432, "EPSG"), new(28462, 28492, "EPSG"), new(28600, 28600, "EPSG"), new(28991, 28992, "EPSG"), new(29100, 29101, "EPSG"), new(29118, 29122, "EPSG"), new(29168, 29172, "EPSG"), new(29177, 29185, "EPSG"), new(29187, 29195, "EPSG"), new(29220, 29221, "EPSG"), new(29333, 29333, "EPSG"), new(29371, 29371, "EPSG"), new(29373, 29373, "EPSG"), new(29375, 29375, "EPSG"), new(29377, 29377, "EPSG"), new(29379, 29379, "EPSG"), new(29381, 29381, "EPSG"), new(29383, 29383, "EPSG"), new(29385, 29385, "EPSG"), new(29635, 29636, "EPSG"), new(29700, 29702, "EPSG"), new(29738, 29739, "EPSG"), new(29849, 29850, "EPSG"), new(29871, 29873, "EPSG"), new(29900, 29903, "EPSG"), new(30161, 30179, "EPSG"), new(30200, 30200, "EPSG"), new(30339, 30340, "EPSG"), new(30491, 30494, "EPSG"), new(30729, 30732, "EPSG"), new(30791, 30792, "EPSG"), new(30800, 30800, "EPSG"), new(31028, 31028, "EPSG"), new(31121, 31121, "EPSG"), new(31154, 31154, "EPSG"), new(31170, 31171, "EPSG"), new(31251, 31259, "EPSG"), new(31265, 31268, "EPSG"), new(31275, 31279, "EPSG"), new(31281, 31297, "EPSG"), new(31300, 31300, "EPSG"), new(31370, 31370, "EPSG"), new(31461, 31469, "EPSG"), new(31528, 31529, "EPSG"), new(31600, 31600, "EPSG"), new(31700, 31700, "EPSG"), new(31838, 31839, "EPSG"), new(31900, 31901, "EPSG"), new(31965, 32003, "EPSG"), new(32005, 32031, "EPSG"), new(32033, 32058, "EPSG"), new(32061, 32062, "EPSG"), new(32064, 32067, "EPSG"), new(32074, 32077, "EPSG"), new(32081, 32086, "EPSG"), new(32098, 32100, "EPSG"), new(32104, 32104, "EPSG"), new(32107, 32130, "EPSG"), new(32133, 32158, "EPSG"), new(32161, 32161, "EPSG"), new(32164, 32167, "EPSG"), new(32180, 32199, "EPSG"), new(32201, 32260, "EPSG"), new(32301, 32360, "EPSG"), new(32401, 32460, "EPSG"), new(32501, 32560, "EPSG"), new(32601, 32667, "EPSG"), new(32701, 32761, "EPSG"), new(32766, 32766, "EPSG"), new(900913, 900913, "spatialreferencing.org") ]; }
CrsMap
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 1426596, "end": 1429045 }
public partial class ____ : global::System.IEquatable<OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_SchemaDeployment>, IOnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_SchemaDeployment { public OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_SchemaDeployment(global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_2> errors) { Errors = errors; } public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.IOnClientVersionPublishUpdated_OnClientVersionPublishingUpdate_Deployment_Errors_2> Errors { get; } public virtual global::System.Boolean Equals(OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_SchemaDeployment? other) { if (ReferenceEquals(null, other)) { return false; } if (ReferenceEquals(this, other)) { return true; } if (other.GetType() != GetType()) { return false; } return (global::StrawberryShake.Internal.ComparisonHelper.SequenceEqual(Errors, other.Errors)); } public override global::System.Boolean Equals(global::System.Object? obj) { if (ReferenceEquals(null, obj)) { return false; } if (ReferenceEquals(this, obj)) { return true; } if (obj.GetType() != GetType()) { return false; } return Equals((OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_SchemaDeployment)obj); } public override global::System.Int32 GetHashCode() { unchecked { int hash = 5; foreach (var Errors_elm in Errors) { hash ^= 397 * Errors_elm.GetHashCode(); } return hash; } } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
OnSchemaVersionPublishUpdated_OnSchemaVersionPublishingUpdate_Deployment_SchemaDeployment
csharp
dotnet__aspnetcore
src/SignalR/common/SignalR.Common/test/Internal/Protocol/NewtonsoftJsonHubProtocolTests.cs
{ "start": 560, "end": 5118 }
public class ____ : JsonHubProtocolTestsBase { protected override IHubProtocol JsonHubProtocol => new NewtonsoftJsonHubProtocol(); protected override IHubProtocol GetProtocolWithOptions(bool useCamelCase, bool ignoreNullValues) { var protocolOptions = new NewtonsoftJsonHubProtocolOptions { PayloadSerializerSettings = new JsonSerializerSettings() { NullValueHandling = ignoreNullValues ? NullValueHandling.Ignore : NullValueHandling.Include, ContractResolver = useCamelCase ? new CamelCasePropertyNamesContractResolver() : new DefaultContractResolver() } }; return new NewtonsoftJsonHubProtocol(Options.Create(protocolOptions)); } [Theory] [InlineData("", "Unexpected end when reading JSON.")] [InlineData("42", "Unexpected JSON Token Type 'Integer'. Expected a JSON Object.")] [InlineData("{\"type\":\"foo\"}", "Expected 'type' to be of type Integer.")] [InlineData("{\"type\":3,\"invocationId\":\"42\",\"result\":true", "Unexpected end when reading JSON.")] [InlineData("{\"type\":8,\"sequenceId\":true}", "Expected 'sequenceId' to be of type Integer.")] [InlineData("{\"type\":9,\"sequenceId\":\"value\"}", "Expected 'sequenceId' to be of type Integer.")] public void CustomInvalidMessages(string input, string expectedMessage) { input = Frame(input); var binder = new TestBinder(Array.Empty<Type>(), typeof(object)); var data = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes(input)); var ex = Assert.Throws<InvalidDataException>(() => JsonHubProtocol.TryParseMessage(ref data, binder, out var _)); Assert.Equal(expectedMessage, ex.Message); } [Theory] [MemberData(nameof(CustomProtocolTestDataNames))] public void CustomWriteMessage(string protocolTestDataName) { var testData = CustomProtocolTestData[protocolTestDataName]; var expectedOutput = Frame(testData.Json); var protocol = GetProtocolWithOptions(testData.UseCamelCase, testData.IgnoreNullValues); var writer = MemoryBufferWriter.Get(); try { protocol.WriteMessage(testData.Message, writer); var json = Encoding.UTF8.GetString(writer.ToArray()); Assert.Equal(expectedOutput, json); } finally { MemoryBufferWriter.Return(writer); } } [Theory] [MemberData(nameof(CustomProtocolTestDataNames))] public void CustomParseMessage(string protocolTestDataName) { var testData = CustomProtocolTestData[protocolTestDataName]; var input = Frame(testData.Json); var binder = new TestBinder(testData.Message); var data = new ReadOnlySequence<byte>(Encoding.UTF8.GetBytes(input)); var protocol = GetProtocolWithOptions(testData.UseCamelCase, testData.IgnoreNullValues); protocol.TryParseMessage(ref data, binder, out var message); Assert.Equal(testData.Message, message, TestHubMessageEqualityComparer.Instance); } public static IDictionary<string, JsonProtocolTestData> CustomProtocolTestData => new[] { new JsonProtocolTestData("InvocationMessage_HasFloatArgument", new InvocationMessage(null, "Target", new object[] { 1, "Foo", 2.0f }), true, true, "{\"type\":1,\"target\":\"Target\",\"arguments\":[1,\"Foo\",2.0]}"), new JsonProtocolTestData("InvocationMessage_HasHeaders", AddHeaders(TestHeaders, new InvocationMessage("123", "Target", new object[] { 1, "Foo", 2.0f })), true, true, "{\"type\":1," + SerializedHeaders + ",\"invocationId\":\"123\",\"target\":\"Target\",\"arguments\":[1,\"Foo\",2.0]}"), new JsonProtocolTestData("StreamItemMessage_HasFloatItem", new StreamItemMessage("123", 2.0f), true, true, "{\"type\":2,\"invocationId\":\"123\",\"item\":2.0}"), new JsonProtocolTestData("CompletionMessage_HasFloatResult", CompletionMessage.WithResult("123", 2.0f), true, true, "{\"type\":3,\"invocationId\":\"123\",\"result\":2.0}"), new JsonProtocolTestData("StreamInvocationMessage_HasFloatArgument", new StreamInvocationMessage("123", "Target", new object[] { 1, "Foo", 2.0f }), true, true, "{\"type\":4,\"invocationId\":\"123\",\"target\":\"Target\",\"arguments\":[1,\"Foo\",2.0]}"), }.ToDictionary(t => t.Name); public static IEnumerable<object[]> CustomProtocolTestDataNames => CustomProtocolTestData.Keys.Select(name => new object[] { name }); }
NewtonsoftJsonHubProtocolTests
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler.Tests/TestCases/ILPretty/CS1xSwitch_Debug.cs
{ "start": 1558, "end": 9097 }
public enum ____ { False, True, Null } public static string SparseIntegerSwitch(int i) { Console.WriteLine("SparseIntegerSwitch: " + i); switch (i) { case -10000000: return "-10 mln"; case -100: return "-hundred"; case -1: return "-1"; case 0: return "0"; case 1: return "1"; case 2: return "2"; case 4: return "4"; case 100: return "hundred"; case 10000: return "ten thousand"; case 10001: return "ten thousand and one"; case int.MaxValue: return "int.MaxValue"; default: return "something else"; } } public static void SwitchOverInt(int i) { switch (i) { case 0: Console.WriteLine("zero"); break; case 5: Console.WriteLine("five"); break; case 10: Console.WriteLine("ten"); break; case 15: Console.WriteLine("fifteen"); break; case 20: Console.WriteLine("twenty"); break; case 25: Console.WriteLine("twenty-five"); break; case 30: Console.WriteLine("thirty"); break; } } public static string ShortSwitchOverString(string text) { Console.WriteLine("ShortSwitchOverString: " + text); switch (text) { case "First case": return "Text1"; case "Second case": return "Text2"; case "Third case": return "Text3"; default: return "Default"; } } public static string ShortSwitchOverStringWithNullCase(string text) { Console.WriteLine("ShortSwitchOverStringWithNullCase: " + text); switch (text) { case "First case": return "Text1"; case "Second case": return "Text2"; case null: return "null"; default: return "Default"; } } public static string SwitchOverString1(string text) { Console.WriteLine("SwitchOverString1: " + text); switch (text) { case "First case": return "Text1"; case "Second case": case "2nd case": return "Text2"; case "Third case": return "Text3"; case "Fourth case": return "Text4"; case "Fifth case": return "Text5"; case "Sixth case": return "Text6"; case null: return null; default: return "Default"; } } public static string SwitchOverString2() { Console.WriteLine("SwitchOverString2:"); switch (Environment.UserName) { case "First case": return "Text1"; case "Second case": return "Text2"; case "Third case": return "Text3"; case "Fourth case": return "Text4"; case "Fifth case": return "Text5"; case "Sixth case": return "Text6"; case "Seventh case": return "Text7"; case "Eighth case": return "Text8"; case "Ninth case": return "Text9"; case "Tenth case": return "Text10"; case "Eleventh case": return "Text11"; default: return "Default"; } } public static string TwoDifferentSwitchBlocksInTryFinally() { try { Console.WriteLine("TwoDifferentSwitchBlocks:"); switch (Environment.UserName) { case "First case": return "Text1"; case "Second case": return "Text2"; case "Third case": return "Text3"; case "Fourth case": return "Text4"; case "Fifth case": return "Text5"; case "Sixth case": return "Text6"; case "Seventh case": return "Text7"; case "Eighth case": return "Text8"; case "Ninth case": return "Text9"; case "Tenth case": return "Text10"; case "Eleventh case": return "Text11"; default: return "Default"; } } finally { Console.WriteLine("Second switch:"); switch (Console.ReadLine()) { case "12": Console.WriteLine("Te43234xt1"); break; case "13": Console.WriteLine("Te223443xt2"); break; case "14": Console.WriteLine("Te234xt3"); break; case "15": Console.WriteLine("Tex243t4"); break; case "16": Console.WriteLine("Tex243t5"); break; case "17": Console.WriteLine("Text2346"); break; case "18": Console.WriteLine("Text234234"); break; case "19 case": Console.WriteLine("Text8234"); break; case "20 case": Console.WriteLine("Text923423"); break; case "21 case": Console.WriteLine("Text10"); break; case "22 case": Console.WriteLine("Text1134123"); break; default: Console.WriteLine("Defa234234ult"); break; } } } public static string SwitchOverBool(bool b) { Console.WriteLine("SwitchOverBool: " + b); switch (b) { case true: return bool.TrueString; case false: return bool.FalseString; default: return null; } } public static void SwitchInLoop(int i) { Console.WriteLine("SwitchInLoop: " + i); while (true) { switch (i) { case 1: Console.WriteLine("one"); break; case 2: Console.WriteLine("two"); break; //case 3: // Console.WriteLine("three"); // continue; case 4: Console.WriteLine("four"); return; default: Console.WriteLine("default"); Console.WriteLine("more code"); return; } i++; } } public static void SwitchWithGoto(int i) { Console.WriteLine("SwitchWithGoto: " + i); switch (i) { case 1: Console.WriteLine("one"); goto default; case 2: Console.WriteLine("two"); goto case 3; case 3: Console.WriteLine("three"); break; case 4: Console.WriteLine("four"); return; default: Console.WriteLine("default"); break; } Console.WriteLine("End of method"); } private static SetProperty[] GetProperties() { return new SetProperty[0]; } public static void SwitchOnStringInForLoop() { ArrayList arrayList = new ArrayList(); ArrayList arrayList2 = new ArrayList(); SetProperty[] properties = GetProperties(); for (int i = 0; i < properties.Length; i++) { Console.WriteLine("In for-loop"); SetProperty setProperty = properties[i]; switch (setProperty.Property.Name) { case "Name1": setProperty.Set = 1; arrayList.Add(setProperty); break; case "Name2": setProperty.Set = 2; arrayList.Add(setProperty); break; case "Name3": setProperty.Set = 3; arrayList.Add(setProperty); break; case "Name4": setProperty.Set = 4; arrayList.Add(setProperty); break; case "Name5": case "Name6": arrayList.Add(setProperty); break; default: arrayList2.Add(setProperty); break; } } } public static void SwitchWithComplexCondition(string[] args) { switch ((args.Length == 0) ? "dummy" : args[0]) { case "a": Console.WriteLine("a"); break; case "b": Console.WriteLine("b"); break; case "c": Console.WriteLine("c"); break; case "d": Console.WriteLine("d"); break; } Console.WriteLine("end"); } public static void SwitchWithArray(string[] args) { switch (args[0]) { case "a": Console.WriteLine("a"); break; case "b": Console.WriteLine("b"); break; case "c": Console.WriteLine("c"); break; case "d": Console.WriteLine("d"); break; } Console.WriteLine("end"); } } }
State
csharp
dotnet__efcore
src/EFCore.Relational/Storage/TimeSpanTypeMapping.cs
{ "start": 784, "end": 2782 }
public class ____ : RelationalTypeMapping { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static TimeSpanTypeMapping Default { get; } = new("time"); /// <summary> /// Initializes a new instance of the <see cref="TimeSpanTypeMapping" /> class. /// </summary> /// <param name="storeType">The name of the database type.</param> /// <param name="dbType">The <see cref="DbType" /> to be used.</param> public TimeSpanTypeMapping( string storeType, DbType? dbType = System.Data.DbType.Time) : base(storeType, typeof(TimeSpan), dbType, jsonValueReaderWriter: JsonTimeSpanReaderWriter.Instance) { } /// <summary> /// Initializes a new instance of the <see cref="TimeSpanTypeMapping" /> class. /// </summary> /// <param name="parameters">Parameter object for <see cref="RelationalTypeMapping" />.</param> protected TimeSpanTypeMapping(RelationalTypeMappingParameters parameters) : base(parameters) { } /// <summary> /// Creates a copy of this mapping. /// </summary> /// <param name="parameters">The parameters for this mapping.</param> /// <returns>The newly created mapping.</returns> protected override RelationalTypeMapping Clone(RelationalTypeMappingParameters parameters) => new TimeSpanTypeMapping(parameters); /// <summary> /// Gets the string format to be used to generate SQL literals of this type. /// </summary> protected override string SqlLiteralFormatString => "'{0}'"; }
TimeSpanTypeMapping
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Threading/AsyncHelper.cs
{ "start": 223, "end": 1412 }
public static class ____ { /// <summary> /// Checks if given method is an async method. /// </summary> /// <param name="method">A method to check</param> public static bool IsAsync(this MethodInfo method) { return ( method.ReturnType == typeof(Task) || (method.ReturnType.GetTypeInfo().IsGenericType && method.ReturnType.GetGenericTypeDefinition() == typeof(Task<>)) ); } /// <summary> /// Runs a async method synchronously. /// </summary> /// <param name="func">A function that returns a result</param> /// <typeparam name="TResult">Result type</typeparam> /// <returns>Result of the async operation</returns> public static TResult RunSync<TResult>(Func<Task<TResult>> func) { return AsyncContext.Run(func); } /// <summary> /// Runs a async method synchronously. /// </summary> /// <param name="action">An async action</param> public static void RunSync(Func<Task> action) { AsyncContext.Run(action); } } }
AsyncHelper
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Ast/Expressions/AstComputedArrayExpression.cs
{ "start": 876, "end": 1875 }
internal sealed class ____ : AstExpression { private readonly IReadOnlyList<AstExpression> _items; public AstComputedArrayExpression(IEnumerable<AstExpression> items) { _items = Ensure.IsNotNull(items, nameof(items)).AsReadOnlyList(); } public IReadOnlyList<AstExpression> Items => _items; public override AstNodeType NodeType => AstNodeType.ComputedArrayExpression; public override AstNode Accept(AstNodeVisitor visitor) { return visitor.VisitComputedArrayExpression(this); } public override BsonValue Render() { return new BsonArray(_items.Select(item => item.Render())); } public AstComputedArrayExpression Update(IEnumerable<AstExpression> items) { if (items == _items) { return this; } return new AstComputedArrayExpression(items); } } }
AstComputedArrayExpression
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Core/Domain/Orders/OrderNote.cs
{ "start": 94, "end": 808 }
public partial class ____ : BaseEntity { /// <summary> /// Gets or sets the order identifier /// </summary> public int OrderId { get; set; } /// <summary> /// Gets or sets the note /// </summary> public string Note { get; set; } /// <summary> /// Gets or sets the attached file (download) identifier /// </summary> public int DownloadId { get; set; } /// <summary> /// Gets or sets a value indicating whether a customer can see a note /// </summary> public bool DisplayToCustomer { get; set; } /// <summary> /// Gets or sets the date and time of order note creation /// </summary> public DateTime CreatedOnUtc { get; set; } }
OrderNote
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/ContainerTests/Common_Tests/Common_Mediator.cs
{ "start": 6163, "end": 6360 }
public interface ____ { Guid OriginalConversationId { get; } Guid OriginalInitiatorId { get; } string Value { get; } } }
SubsequentResponse
csharp
nunit__nunit
src/NUnitFramework/nunitlite.tests/TeamCityEventListenerTests.cs
{ "start": 307, "end": 3541 }
public class ____ { private TeamCityEventListener _teamCity; private StringBuilder _output; private static readonly string NL = Environment.NewLine; [SetUp] public void CreateListener() { _output = new StringBuilder(); var outWriter = new StringWriter(_output); _teamCity = new TeamCityEventListener(outWriter); } [Test] public void TestSuiteStarted() { _teamCity.TestStarted(new TestSuite("dummy")); Assert.That(_output.ToString(), Is.EqualTo( "##teamcity[testSuiteStarted name='dummy']" + NL)); } [Test] public void TestSuiteFinished() { _teamCity.TestFinished(new TestSuite("dummy").MakeTestResult()); Assert.That(_output.ToString(), Is.EqualTo( "##teamcity[testSuiteFinished name='dummy']" + NL)); } [Test] public void TestStarted() { _teamCity.TestStarted(Fakes.GetTestMethod(this, "FakeTestMethod")); Assert.That(_output.ToString(), Is.EqualTo( "##teamcity[testStarted name='FakeTestMethod' captureStandardOutput='true']" + NL)); } [Test] public void TestFinished_Passed() { var result = Fakes.GetTestMethod(this, "FakeTestMethod").MakeTestResult(); result.SetResult(ResultState.Success); result.Duration = 1.234; _teamCity.TestFinished(result); Assert.That(_output.ToString(), Is.EqualTo( "##teamcity[testFinished name='FakeTestMethod' duration='1234']" + NL)); } [Test] public void TestFinished_Inconclusive() { var result = Fakes.GetTestMethod(this, "FakeTestMethod").MakeTestResult(); result.SetResult(ResultState.Inconclusive); _teamCity.TestFinished(result); Assert.That(_output.ToString(), Is.EqualTo( "##teamcity[testIgnored name='FakeTestMethod' message='Inconclusive']" + NL)); } [Test] public void TestFinished_Ignored() { var result = Fakes.GetTestMethod(this, "FakeTestMethod").MakeTestResult(); result.SetResult(ResultState.Ignored, "Just because"); _teamCity.TestFinished(result); Assert.That(_output.ToString(), Is.EqualTo( "##teamcity[testIgnored name='FakeTestMethod' message='Just because']" + NL)); } [Test] public void TestFinished_Failed() { var result = Fakes.GetTestMethod(this, "FakeTestMethod").MakeTestResult(); result.SetResult(ResultState.Failure, "Error message", "Stack trace"); result.Duration = 1.234; _teamCity.TestFinished(result); Assert.That(_output.ToString(), Is.EqualTo( "##teamcity[testFailed name='FakeTestMethod' message='Error message' details='Stack trace']" + NL + "##teamcity[testFinished name='FakeTestMethod' duration='1234']" + NL)); } private void FakeTestMethod() { } } }
TeamCityEventListenerTests
csharp
EventStore__EventStore
src/SchemaRegistry/KurrentDB.SchemaRegistry/Modules/Schemas/Domain/SchemaApplication.cs
{ "start": 1703, "end": 19816 }
public class ____ : EntityApplication<SchemaEntity> { protected override Func<dynamic, string> GetEntityId => cmd => cmd.SchemaName; protected override StreamTemplate StreamTemplate => SchemasStreamTemplate; public SchemaApplication(ISchemaCompatibilityManager compatibilityManager, LookupSchemaNameByVersionId lookupSchemaName, GetUtcNow getUtcNow, IEventStore store) : base(store) { OnAny<CreateSchemaRequest>((state, cmd) => { if (state.IsNew) { return [ new SchemaCreated { SchemaName = cmd.SchemaName, Description = cmd.Details.Description, DataFormat = cmd.Details.DataFormat, Compatibility = cmd.Details.Compatibility, Tags = { cmd.Details.Tags }, SchemaVersionId = Guid.NewGuid().ToString(), SchemaDefinition = cmd.SchemaDefinition, VersionNumber = 1, CreatedAt = getUtcNow().ToTimestamp() } ]; } throw new DomainExceptions.EntityAlreadyExists("Schema", cmd.SchemaName); }); OnExisting<RegisterSchemaVersionRequest>((state, cmd) => { state.EnsureNotDeleted(); var lastVersion = state.LatestVersion; if (lastVersion.IsSameDefinition(cmd.SchemaDefinition.Memory)) throw new DomainExceptions.EntityException("Schema definition has not changed"); // check last version because if it is the same we should throw an error // validate // if (cmd.Details.DataFormat == Protocol.V2.SchemaFormat.Json) { // var result = NJsonSchemaCompatibility.CheckCompatibility( // lastVersion.SchemaDefinition, // cmd.SchemaDefinition.ToStringUtf8(), // state.Compatibility // ).GetAwaiter().GetResult(); // // if (!result.IsCompatible) { // throw new DomainExceptions.EntityException($"Schema definition is not compatible with the last version. {result}"); // } // // // we first validate it // // then register if validation is successful // } return [ new SchemaVersionRegistered { SchemaVersionId = Guid.NewGuid().ToString(), SchemaDefinition = cmd.SchemaDefinition, DataFormat = (KurrentDB.Protocol.Registry.V2.SchemaDataFormat)state.DataFormat, VersionNumber = lastVersion.VersionNumber + 1, SchemaName = cmd.SchemaName, RegisteredAt = getUtcNow().ToTimestamp() } ]; }); OnExisting<UpdateSchemaRequest>((state, cmd) => { state.EnsureNotDeleted(); // Ensure at least one field is being updated if (cmd.UpdateMask.Paths.Count == 0) throw new DomainExceptions.EntityException("Update mask must contain at least one field"); var knownPaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Details.Description", "Details.Tags", "Details.Compatibility", "Details.DataFormat" }; var modifiablePaths = new HashSet<string>(StringComparer.OrdinalIgnoreCase) { "Details.Description", "Details.Tags" }; // Check for unknown fields first var unknownField = cmd.UpdateMask.Paths.FirstOrDefault(path => !knownPaths.Contains(path)); if (unknownField != null) throw new DomainExceptions.EntityException($"Unknown field {unknownField} in update mask"); // Check for non-modifiable fields var nonModifiableField = cmd.UpdateMask.Paths.FirstOrDefault(path => knownPaths.Contains(path) && !modifiablePaths.Contains(path)); if (nonModifiableField != null) { var fieldDisplayName = nonModifiableField switch { _ when nonModifiableField.Equals("Details.Compatibility", StringComparison.OrdinalIgnoreCase) => "Compatibility mode", _ when nonModifiableField.Equals("Details.DataFormat", StringComparison.OrdinalIgnoreCase) => "DataFormat", _ => nonModifiableField }; throw new DomainExceptions.EntityNotModified("Schema", state.SchemaName, $"{fieldDisplayName} is not modifiable"); } return cmd.UpdateMask.Paths.Aggregate(new List<object>(), (seed, path) => { if (path.Equals("Details.Description", StringComparison.OrdinalIgnoreCase)) { if (state.Description.Equals(cmd.Details.Description)) throw new DomainExceptions.EntityNotModified("Schema", state.SchemaName, "Description has not changed"); seed.Add(new SchemaDescriptionUpdated { SchemaName = cmd.SchemaName, Description = cmd.Details.Description, UpdatedAt = getUtcNow().ToTimestamp() }); } else if (path.Equals("Details.Tags", StringComparison.OrdinalIgnoreCase)) { if (state.Tags.DictionaryEquals(cmd.Details.Tags)) throw new DomainExceptions.EntityNotModified("Schema", state.SchemaName, "Tags have not changed"); seed.Add(new SchemaTagsUpdated { SchemaName = cmd.SchemaName, Tags = { cmd.Details.Tags }, UpdatedAt = getUtcNow().ToTimestamp() }); } // else if (path.Equals("Details.Compatibility", StringComparison.OrdinalIgnoreCase)) { // if (state.Compatibility.Equals(cmd.Details.Compatibility)) // throw new DomainExceptions.EntityNotModified("Schema", state.SchemaName, "Compatibility have not changed"); // // // Validate compatibility requirements based on the new mode // var newMode = (CompatibilityMode)cmd.Details.Compatibility; // // // Full compatibility mode validation // if (newMode == CompatibilityMode.Full) { // foreach (var olderVersion in state.Versions.Values) { // foreach (var newerVersion in state.Versions.Values.Where(v => v.VersionNumber > olderVersion.VersionNumber)) { // var olderDefinition = olderVersion.SchemaDefinition; // var newerDefinition = newerVersion.SchemaDefinition; // // // Check full compatibility (bidirectional) // var result = compatibilityManager.CheckCompatibility(olderDefinition, newerDefinition, SchemaCompatibilityMode.Full).AsTask().GetAwaiter().GetResult(); // // if (!result.IsCompatible) { // throw new DomainExceptions.EntityException( // $"Cannot change to Full compatibility mode - versions {olderVersion.VersionNumber} and {newerVersion.VersionNumber} " // + $"are not fully compatible with each other. {result.Errors.FirstOrDefault()?.Details}" // ); // } // } // } // } // // Forward compatibility mode validation // else if (newMode == CompatibilityMode.Forward) { // foreach (var olderVersion in state.Versions.Values) { // foreach (var newerVersion in state.Versions.Values.Where(v => v.VersionNumber > olderVersion.VersionNumber)) { // var olderDefinition = olderVersion.SchemaDefinition; // var newerDefinition = newerVersion.SchemaDefinition; // // // Check forward compatibility (older can read newer) // var result = compatibilityManager.CheckCompatibility(olderDefinition, newerDefinition, SchemaCompatibilityMode.Forward).AsTask().GetAwaiter().GetResult(); // // if (!result.IsCompatible) { // throw new DomainExceptions.EntityException( // $"Cannot change to Forward compatibility mode - version {olderVersion.VersionNumber} " // + $"cannot read data from version {newerVersion.VersionNumber}. {result.Errors.FirstOrDefault()?.Details}" // ); // } // } // } // } // // Backward compatibility mode validation // else if (newMode == CompatibilityMode.Backward) { // var latestVersion = state.LatestVersion; // // foreach (var olderVersion in state.Versions.Values.Where(v => v.VersionNumber < latestVersion.VersionNumber)) { // var olderDefinition = olderVersion.SchemaDefinition; // var latestDefinition = latestVersion.SchemaDefinition; // // // Check backward compatibility (newer can read older) // var result = compatibilityManager.CheckCompatibility(latestDefinition, olderDefinition, SchemaCompatibilityMode.Backward).AsTask().GetAwaiter().GetResult(); // // if (!result.IsCompatible) { // throw new DomainExceptions.EntityException( // $"Cannot change to Backward compatibility mode - latest version {latestVersion.VersionNumber} " // + $"cannot read data from version {olderVersion.VersionNumber}. {result.Errors.FirstOrDefault()?.Details}" // ); // } // } // } // // BackwardAll compatibility mode validation // else if (newMode == CompatibilityMode.BackwardAll) { // var versions = state.Versions.Values.ToList(); // foreach (var schema in versions) { // var olderVersions = versions // .Where(v => v.VersionNumber < schema.VersionNumber) // .Select(v => v.SchemaDefinition) // .ToList(); // // if (olderVersions.IsEmpty()) continue; // // var result = compatibilityManager // .CheckCompatibility(schema.SchemaDefinition, olderVersions, SchemaCompatibilityMode.BackwardAll).AsTask().GetAwaiter() // .GetResult(); // // if (!result.IsCompatible) { // throw new DomainExceptions.EntityException( // $"Cannot change to BackwardAll compatibility mode - version {schema.VersionNumber} " + // $"is not backward compatible with all previous versions. {result.Errors.FirstOrDefault()?.Details}" // ); // } // } // } // // ForwardAll compatibility mode validation // else if (newMode == CompatibilityMode.ForwardAll) { // var versions = state.Versions.Values.ToList(); // foreach (var schema in versions) { // var newerVersions = versions // .Where(v => v.VersionNumber > schema.VersionNumber) // .Select(v => v.SchemaDefinition) // .ToList(); // // if (newerVersions.IsEmpty()) continue; // // var result = compatibilityManager // .CheckCompatibility(schema.SchemaDefinition, newerVersions, SchemaCompatibilityMode.ForwardAll).AsTask().GetAwaiter() // .GetResult(); // // if (!result.IsCompatible) { // throw new DomainExceptions.EntityException( // $"Cannot change to ForwardAll compatibility mode - version {schema.VersionNumber} " + // $"is not forward compatible with all newer versions. {result.Errors.FirstOrDefault()?.Details}" // ); // } // } // } // // FullAll compatibility mode validation // else if (newMode == CompatibilityMode.FullAll) { // var versions = state.Versions.Values.ToList(); // foreach (var schema in versions) { // var otherVersions = versions // .Where(v => v.VersionNumber != schema.VersionNumber) // .Select(v => v.SchemaDefinition) // .ToList(); // // if (otherVersions.IsEmpty()) continue; // // var result = compatibilityManager.CheckCompatibility(schema.SchemaDefinition, otherVersions, SchemaCompatibilityMode.FullAll) // .AsTask().GetAwaiter().GetResult(); // // if (!result.IsCompatible) { // throw new DomainExceptions.EntityException( // $"Cannot change to FullAll compatibility mode - version {schema.VersionNumber} " + // $"is not fully compatible with all other versions. {result.Errors.FirstOrDefault()?.Details}" // ); // } // } // } // // seed.Add(new SchemaCompatibilityModeChanged { // SchemaName = cmd.SchemaName, // Compatibility = cmd.Details.Compatibility, // ChangedAt = getUtcNow().ToTimestamp() // }); // } return seed; }); }); OnExisting<DeleteSchemaVersionsRequest>( (state, cmd) => { state.EnsureNotDeleted(); // Check if any requested version doesn't exist var existingVersionNumbers = state.Versions.Values.Select(x => x.VersionNumber).ToHashSet(); var nonExistentVersions = cmd.Versions.Except(existingVersionNumbers).ToList(); if (nonExistentVersions.Any()) throw new DomainExceptions.EntityException($"Schema {state.SchemaName} does not have versions: {string.Join(", ", nonExistentVersions)}"); if (state.Versions.Count == cmd.Versions.Count) throw new DomainExceptions.EntityException($"Cannot delete all versions of schema {state.SchemaName}"); var versionsToDelete = state.Versions.Values .Where(x => cmd.Versions.Contains(x.VersionNumber)) .Select(x => x.SchemaVersionId) .ToList(); if (state.Compatibility is CompatibilityMode.Backward) { var latestVersionNumber = state.LatestVersion.VersionNumber; if (cmd.Versions.Contains(latestVersionNumber)) throw new DomainExceptions.EntityException($"Cannot delete the latest version of schema {state.SchemaName} in Backward compatibility mode"); } else if (state.Compatibility is CompatibilityMode.Forward or CompatibilityMode.Full) { // Prevent deletion of any versions in Forward or Full compatibility mode throw new DomainExceptions.EntityException($"Cannot delete versions of schema {state.SchemaName} in {state.Compatibility} compatibility mode"); } var latestVersion = state.LatestVersion; return [ new SchemaVersionsDeleted { Versions = { versionsToDelete }, SchemaName = state.SchemaName, LatestSchemaVersionId = latestVersion.SchemaVersionId, LatestSchemaVersionNumber = latestVersion.VersionNumber, DeletedAt = getUtcNow().ToTimestamp() } ]; } ); OnExisting<DeleteSchemaRequest>((state, cmd) => { state.EnsureNotDeleted(); return [ new SchemaDeleted { SchemaName = cmd.SchemaName, DeletedAt = getUtcNow().ToTimestamp() } ]; }); } }
SchemaApplication
csharp
smartstore__Smartstore
src/Smartstore.Core/Platform/Web/UserAgent/UaMatcher.cs
{ "start": 562, "end": 1536 }
internal class ____ : UaMatcher { public RegexMatcher(Regex rg) { Regex = Guard.NotNull(rg); } public Regex Regex { get; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public override bool Match(ReadOnlySpan<char> userAgent, [MaybeNullWhen(true)] out string? version) { version = null; var match = Regex.Match(userAgent.ToString()); if (match.Success) { if (match.Groups.ContainsKey("v")) { version = match.Groups["v"].Value.NullEmpty(); } else if (match.Groups.Count > 1) { version = match.Groups[1].Value.NullEmpty(); } return true; } return false; } } [DebuggerDisplay("Contains: {Contains}, Name: {Name}, Platform: {PlatformFamily}")]
RegexMatcher
csharp
ShareX__ShareX
ShareX.HelpersLib/Cryptographic/TranslatorHelper.cs
{ "start": 1177, "end": 5571 }
public static class ____ { #region Text to ... public static string[] TextToBinary(string text) { string[] result = new string[text.Length]; for (int i = 0; i < text.Length; i++) { result[i] = ByteToBinary((byte)text[i]); } return result; } public static string[] TextToHexadecimal(string text) { return BytesToHexadecimal(Encoding.UTF8.GetBytes(text)); } public static byte[] TextToASCII(string text) { return Encoding.ASCII.GetBytes(text); } public static string TextToBase64(string text) { byte[] bytes = Encoding.UTF8.GetBytes(text); return Convert.ToBase64String(bytes); } public static string TextToHash(string text, HashType hashType, bool uppercase = false) { using (HashAlgorithm hash = HashChecker.GetHashAlgorithm(hashType)) { byte[] bytes = hash.ComputeHash(Encoding.UTF8.GetBytes(text)); string[] hex = BytesToHexadecimal(bytes); string result = string.Concat(hex); if (uppercase) result = result.ToUpperInvariant(); return result; } } #endregion Text to ... #region Binary to ... public static byte BinaryToByte(string binary) { return Convert.ToByte(binary, 2); } public static string BinaryToText(string binary) { binary = Regex.Replace(binary, @"[^01]", ""); using (MemoryStream stream = new MemoryStream()) { for (int i = 0; i + 8 <= binary.Length; i += 8) { stream.WriteByte(BinaryToByte(binary.Substring(i, 8))); } return Encoding.UTF8.GetString(stream.ToArray()); } } #endregion Binary to ... #region Byte to ... public static string ByteToBinary(byte b) { char[] result = new char[8]; int pos = 7; for (int i = 0; i < 8; i++) { if ((b & (1 << i)) != 0) { result[pos] = '1'; } else { result[pos] = '0'; } pos--; } return new string(result); } public static string[] BytesToHexadecimal(byte[] bytes) { string[] result = new string[bytes.Length]; for (int i = 0; i < bytes.Length; i++) { result[i] = bytes[i].ToString("x2"); } return result; } #endregion Byte to ... #region Hexadecimal to ... public static byte HexadecimalToByte(string hex) { return Convert.ToByte(hex, 16); } public static string HexadecimalToText(string hex) { hex = Regex.Replace(hex, @"[^0-9a-fA-F]", ""); using (MemoryStream stream = new MemoryStream()) { for (int i = 0; i + 2 <= hex.Length; i += 2) { stream.WriteByte(HexadecimalToByte(hex.Substring(i, 2))); } return Encoding.UTF8.GetString(stream.ToArray()); } } #endregion Hexadecimal to ... #region Base64 to ... public static string Base64ToText(string base64) { byte[] bytes = Convert.FromBase64String(base64); return Encoding.UTF8.GetString(bytes); } #endregion Base64 to ... #region ASCII to ... public static string ASCIIToText(string ascii) { string[] numbers = Regex.Split(ascii, @"\D+"); using (MemoryStream stream = new MemoryStream()) { foreach (string number in numbers) { if (byte.TryParse(number, out byte b)) { stream.WriteByte(b); } } return Encoding.ASCII.GetString(stream.ToArray()); } } #endregion ASCII to ... } }
TranslatorHelper
csharp
dotnet__efcore
src/EFCore/Infrastructure/ModelCustomizerDependencies.cs
{ "start": 1573, "end": 2809 }
public sealed record ____ { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> /// <remarks> /// Do not call this constructor directly from either provider or application code as it may change /// as new dependencies are added. Instead, use this type in your constructor so that an instance /// will be created and injected automatically by the dependency injection container. To create /// an instance with some dependent services replaced, first resolve the object from the dependency /// injection container, then replace selected services using the C# 'with' operator. Do not call /// the constructor at any point in this process. /// </remarks> [EntityFrameworkInternal] public ModelCustomizerDependencies() { } }
ModelCustomizerDependencies
csharp
nunit__nunit
src/NUnitFramework/framework/Constraints/EqualConstraint{T}.cs
{ "start": 458, "end": 2323 }
public class ____<T> : EqualConstraint { #region Constructor /// <summary> /// Initializes a new instance of the <see cref="EqualConstraint"/> class. /// </summary> /// <param name="expected">The expected value.</param> public EqualConstraint(object? expected) : base(expected) { } #endregion #region Constraint Modifiers /// <summary> /// Enables comparing a subset of instance properties. /// </summary> /// <remarks> /// This allows comparing classes that don't implement <see cref="IEquatable{T}"/> /// without having to compare each property separately in own code. /// </remarks> /// <param name="configure">Function to configure the <see cref="PropertiesComparerConfiguration"/></param> public EqualConstraint UsingPropertiesComparer(Func<PropertiesComparerConfiguration<T>, PropertiesComparerConfiguration<T>> configure) { Comparer.CompareProperties = true; Comparer.ComparePropertiesConfiguration = configure(new PropertiesComparerConfiguration<T>()); return this; } /// <inheritdoc/> public override EqualConstraint UsingPropertiesComparer<TParam>(Func<PropertiesComparerConfiguration<TParam>, PropertiesComparerConfiguration<TParam>> configure) { if (typeof(TParam) != typeof(T)) throw new ArgumentException($"The type parameter {typeof(TParam).Name} does not match the type parameter {typeof(T).Name} of this constraint.", nameof(configure)); Comparer.CompareProperties = true; Comparer.ComparePropertiesConfiguration = configure(new PropertiesComparerConfiguration<TParam>()); return this; } #endregion } }
EqualConstraint
csharp
bitwarden__server
src/Core/Auth/UserFeatures/DeviceTrust/Interfaces/IUntrustDevicesCommand.cs
{ "start": 78, "end": 201 }
public interface ____ { public Task UntrustDevices(User user, IEnumerable<Guid> devicesToUntrust); }
IUntrustDevicesCommand
csharp
icsharpcode__ILSpy
ILSpy/Metadata/CorTables/StandAloneSigTableTreeNode.cs
{ "start": 1328, "end": 1908 }
class ____ : MetadataTableTreeNode<StandAloneSigTableTreeNode.StandAloneSigEntry> { public StandAloneSigTableTreeNode(MetadataFile metadataFile) : base(TableIndex.StandAloneSig, metadataFile) { } protected override IReadOnlyList<StandAloneSigEntry> LoadTable() { var list = new List<StandAloneSigEntry>(); for (int row = 1; row <= metadataFile.Metadata.GetTableRowCount(TableIndex.StandAloneSig); row++) { list.Add(new StandAloneSigEntry(metadataFile, MetadataTokens.StandaloneSignatureHandle(row))); } return list; }
StandAloneSigTableTreeNode
csharp
dotnet__maui
src/Compatibility/Core/src/Android/CollectionView/CarouselViewRenderer.cs
{ "start": 19593, "end": 21956 }
internal class ____ { public const int LoopScale = 16384; IItemsViewSource _itemsSource; readonly Queue<ScrollToRequestEventArgs> _pendingScrollTo = new Queue<ScrollToRequestEventArgs>(); public void CenterIfNeeded(RecyclerView recyclerView, bool isHorizontal) { if (!(recyclerView.GetLayoutManager() is LinearLayoutManager linearLayoutManager)) return; var itemSourceCount = _itemsSource.Count; var firstCompletelyItemVisible = linearLayoutManager.FindFirstCompletelyVisibleItemPosition(); var offSet = recyclerView.ComputeHorizontalScrollOffset(); if (!isHorizontal) offSet = recyclerView.ComputeVerticalScrollOffset(); if (firstCompletelyItemVisible == 0) linearLayoutManager.ScrollToPositionWithOffset(itemSourceCount, -offSet); } public void CheckPendingScrollToEvents(RecyclerView recyclerView) { if (!(recyclerView is CarouselViewRenderer carouselViewRenderer)) return; if (_pendingScrollTo.TryDequeue(out ScrollToRequestEventArgs scrollToRequestEventArgs)) carouselViewRenderer.ScrollTo(scrollToRequestEventArgs); } public void AddPendingScrollTo(ScrollToRequestEventArgs args) => _pendingScrollTo.Enqueue(args); public int GetGoToIndex(RecyclerView recyclerView, int carouselPosition, int newPosition) { if (!(recyclerView.GetLayoutManager() is LinearLayoutManager linearLayoutManager)) return -1; var currentCarouselPosition = carouselPosition; var itemSourceCount = _itemsSource.Count; var diffToStart = currentCarouselPosition + (itemSourceCount - newPosition); var diffToEnd = itemSourceCount - currentCarouselPosition + newPosition; var centerView = recyclerView.GetCenteredView(); if (centerView == null) return -1; var centerPosition = linearLayoutManager.GetPosition(centerView); var increment = currentCarouselPosition - newPosition; var incrementAbs = System.Math.Abs(increment); int goToPosition; if (diffToStart < incrementAbs) goToPosition = centerPosition - diffToStart; else if (diffToEnd < incrementAbs) goToPosition = centerPosition + diffToEnd; else goToPosition = centerPosition - increment; return goToPosition; } public void SetItemsSource(IItemsViewSource itemsSource) => _itemsSource = itemsSource; } } }
CarouselViewLoopManager
csharp
Testably__Testably.Abstractions
Tests/Testably.Abstractions.Testing.Tests/RandomProviderTests.cs
{ "start": 195, "end": 13577 }
public partial class ____ { [Fact] public async Task Default_ShouldReturnRandomGuid() { List<Guid> results = []; IRandomProvider randomProvider = RandomProvider.Default(); for (int i = 0; i < 100; i++) { results.Add(randomProvider.GetGuid()); } await That(results).AreAllUnique(); } [Fact] public async Task Default_ShouldReturnRandomNumbers() { List<int> results = []; IRandomProvider randomProvider = RandomProvider.Default(); for (int i = 0; i < 100; i++) { results.Add(randomProvider.GetRandom(i).Next()); } await That(results).AreAllUnique(); } [Theory] [AutoData] public async Task GenerateGuid_ShouldReturnSpecifiedGuid(Guid guid) { List<Guid> results = []; IRandomProvider randomProvider = RandomProvider.Generate(guidGenerator: guid); for (int i = 0; i < 100; i++) { results.Add(randomProvider.GetGuid()); } await That(results).All().AreEqualTo(guid); } [Theory] [AutoData] public async Task GenerateGuid_ShouldReturnSpecifiedGuids(Guid[] guids) { List<Guid> results = []; IRandomProvider randomProvider = RandomProvider.Generate(guidGenerator: guids); for (int i = 0; i < 100; i++) { results.Add(randomProvider.GetGuid()); } await That(results).Contains(guids).IgnoringInterspersedItems(); } [Theory] [AutoData] public async Task GenerateRandom_Next_ShouldReturnSpecifiedValue(int seed, int value) { List<int> results = []; IRandomProvider randomProvider = RandomProvider.Generate(seed, intGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.Next()); } await That(results).All().AreEqualTo(value); } [Theory] [AutoData] public async Task GenerateRandom_Next_ShouldReturnSpecifiedValues(int seed, int[] values) { List<int> results = []; IRandomProvider randomProvider = RandomProvider.Generate(intGenerator: values); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.Next()); } await That(results).Contains(values).IgnoringInterspersedItems(); } [Theory] [AutoData] public async Task GenerateRandom_Next_WithMaxValue_ShouldReturnSpecifiedValue( int seed, int value) { int maxValue = value - 1; List<int> results = []; IRandomProvider randomProvider = RandomProvider.Generate(intGenerator: value); int expectedValue = maxValue - 1; IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.Next(maxValue)); } await That(results).All().AreEqualTo(expectedValue); } [Theory] [AutoData] public async Task GenerateRandom_Next_WithMinAndMaxValue_Larger_ShouldReturnSpecifiedValue( int seed, int value) { int minValue = value - 10; int maxValue = value - 1; List<int> results = []; IRandomProvider randomProvider = RandomProvider.Generate(intGenerator: value); int expectedValue = maxValue - 1; IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.Next(minValue, maxValue)); } await That(results).All().AreEqualTo(expectedValue); } [Theory] [AutoData] public async Task GenerateRandom_Next_WithMinAndMaxValue_Smaller_ShouldReturnSpecifiedValue( int seed, int value) { int minValue = value + 1; int maxValue = minValue + 10; List<int> results = []; IRandomProvider randomProvider = RandomProvider.Generate(intGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.Next(minValue, maxValue)); } await That(results).All().AreEqualTo(minValue); } [Theory] [AutoData] public async Task GenerateRandom_Next_WithoutGenerator_ShouldReturnRandomValues(int seed) { List<int> results = []; IRandomProvider randomProvider = RandomProvider.Generate(); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 10; i++) { results.Add(random.Next()); } await That(results).AreAllUnique(); } [Theory] [AutoData] public async Task GenerateRandom_NextBytes_ShouldReturnSpecifiedValue( int seed, byte[] value) { List<byte[]> results = []; IRandomProvider randomProvider = RandomProvider.Generate(byteGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { byte[] buffer = new byte[value.Length]; random.NextBytes(buffer); results.Add(buffer); } await That(results).All().ComplyWith(v => v.IsEqualTo(value)); } #if FEATURE_SPAN [Theory] [AutoData] public async Task GenerateRandom_NextBytes_Span_ShouldReturnSpecifiedValue( int seed, byte[] value) { List<byte[]> results = []; IRandomProvider randomProvider = RandomProvider.Generate(byteGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { byte[] buffer = new byte[value.Length]; random.NextBytes(buffer.AsSpan()); results.Add(buffer); } await That(results).All().ComplyWith(v => v.IsEqualTo(value)); } #endif #if FEATURE_SPAN [Theory] [AutoData] public async Task GenerateRandom_NextBytes_Span_WithoutGenerator_ShouldReturnRandomValues( int seed) { List<byte[]> results = []; IRandomProvider randomProvider = RandomProvider.Generate(); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 10; i++) { byte[] buffer = new byte[10]; random.NextBytes(buffer.AsSpan()); results.Add(buffer); } await That(results).AreAllUnique(); } #endif #if FEATURE_SPAN [Theory] [AutoData] public async Task GenerateRandom_NextBytes_Span_WithSmallerBuffer_ShouldReturnPartlyInitializedBytes( int seed, byte[] value) { List<byte[]> results = []; IRandomProvider randomProvider = RandomProvider.Generate(byteGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { byte[] buffer = new byte[value.Length + 1]; random.NextBytes(buffer.AsSpan()); results.Add(buffer); } var expected = value.Concat(new[] { (byte)0, }).ToArray(); await That(results).All().ComplyWith(v => v.IsEqualTo(expected)); } #endif [Theory] [AutoData] public async Task GenerateRandom_NextBytes_WithoutGenerator_ShouldReturnRandomValues( int seed) { List<byte[]> results = []; IRandomProvider randomProvider = RandomProvider.Generate(); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 10; i++) { byte[] buffer = new byte[10]; random.NextBytes(buffer); results.Add(buffer); } await That(results).AreAllUnique(); } [Theory] [AutoData] public async Task GenerateRandom_NextBytes_WithSmallerBuffer_ShouldReturnPartlyInitializedBytes( int seed, byte[] value) { List<byte[]> results = []; IRandomProvider randomProvider = RandomProvider.Generate(byteGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { byte[] buffer = new byte[value.Length + 1]; random.NextBytes(buffer); results.Add(buffer); } byte[] expected = value.Concat(new[] { (byte)0, }).ToArray(); await That(results).All().ComplyWith(v => v.IsEqualTo(expected)); } [Theory] [AutoData] public async Task GenerateRandom_NextDouble_ShouldReturnSpecifiedValue( int seed, double value) { List<double> results = []; IRandomProvider randomProvider = RandomProvider.Generate(doubleGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.NextDouble()); } await That(results).All().AreEqualTo(value); } [Theory] [AutoData] public async Task GenerateRandom_NextDouble_WithoutGenerator_ShouldReturnRandomValues( int seed) { List<double> results = []; IRandomProvider randomProvider = RandomProvider.Generate(); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 10; i++) { results.Add(random.NextDouble()); } await That(results).AreAllUnique(); } #if FEATURE_RANDOM_ADVANCED [Theory] [AutoData] public async Task GenerateRandom_NextInt64_ShouldReturnSpecifiedValue(int seed, long value) { List<long> results = []; IRandomProvider randomProvider = RandomProvider.Generate(longGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.NextInt64()); } await That(results).All().AreEqualTo(value); } #endif #if FEATURE_RANDOM_ADVANCED [Theory] [AutoData] public async Task GenerateRandom_NextInt64_WithMaxValue_ShouldReturnSpecifiedValue( int seed, long value) { long maxValue = value - 1; List<long> results = []; IRandomProvider randomProvider = RandomProvider.Generate(longGenerator: value); long expectedValue = maxValue - 1; IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.NextInt64(maxValue)); } await That(results).All().AreEqualTo(expectedValue); } #endif #if FEATURE_RANDOM_ADVANCED [Theory] [AutoData] public async Task GenerateRandom_NextInt64_WithMinAndMaxValue_Larger_ShouldReturnSpecifiedValue( int seed, long value) { long minValue = value - 10; long maxValue = value - 1; List<long> results = []; IRandomProvider randomProvider = RandomProvider.Generate(longGenerator: value); long expectedValue = maxValue - 1; IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.NextInt64(minValue, maxValue)); } await That(results).All().AreEqualTo(expectedValue); } #endif #if FEATURE_RANDOM_ADVANCED [Theory] [AutoData] public async Task GenerateRandom_NextInt64_WithMinAndMaxValue_Smaller_ShouldReturnSpecifiedValue( int seed, long value) { long minValue = value + 1; long maxValue = minValue + 10; List<long> results = []; IRandomProvider randomProvider = RandomProvider.Generate(longGenerator: value); long expectedValue = minValue; IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.NextInt64(minValue, maxValue)); } await That(results).All().AreEqualTo(expectedValue); } #endif #if FEATURE_RANDOM_ADVANCED [Theory] [AutoData] public async Task GenerateRandom_NextInt64_WithoutGenerator_ShouldReturnRandomValues( int seed) { List<long> results = []; IRandomProvider randomProvider = RandomProvider.Generate(); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 10; i++) { results.Add(random.NextInt64()); } await That(results).AreAllUnique(); } #endif #if FEATURE_RANDOM_ADVANCED [Theory] [AutoData] public async Task GenerateRandom_NextSingle_ShouldReturnSpecifiedValue( int seed, float value) { List<float> results = []; IRandomProvider randomProvider = RandomProvider.Generate(singleGenerator: value); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 100; i++) { results.Add(random.NextSingle()); } await That(results).All().AreEqualTo(value); } #endif #if FEATURE_RANDOM_ADVANCED [Theory] [AutoData] public async Task GenerateRandom_NextSingle_WithoutGenerator_ShouldReturnRandomValues( int seed) { List<float> results = []; IRandomProvider randomProvider = RandomProvider.Generate(); IRandom random = randomProvider.GetRandom(seed); for (int i = 0; i < 10; i++) { results.Add(random.NextSingle()); } await That(results).AreAllUnique(); } #endif [Fact] public async Task GetRandom_DefaultValue_ShouldReturnSharedRandom() { RandomProviderMock randomProvider = new(); IRandom random1 = randomProvider.GetRandom(); IRandom random2 = randomProvider.GetRandom(); int[] result1 = Enumerable.Range(0, 100) .Select(_ => random1.Next()) .ToArray(); int[] result2 = Enumerable.Range(0, 100) .Select(_ => random2.Next()) .ToArray(); await That(result1).IsNotEqualTo(result2).InAnyOrder(); } [Theory] [AutoData] public async Task GetRandom_FixedSeed_ShouldReturnSeparateRandomInstances(int seed) { RandomProviderMock randomProvider = new(); IRandom random1 = randomProvider.GetRandom(seed); IRandom random2 = randomProvider.GetRandom(seed); int[] result1 = Enumerable.Range(0, 100) .Select(_ => random1.Next()) .ToArray(); int[] result2 = Enumerable.Range(0, 100) .Select(_ => random2.Next()) .ToArray(); await That(result1).IsEqualTo(result2).InAnyOrder(); } #if FEATURE_SPAN [Theory] [AutoData] public async Task NextBytes_Span_WithoutByteGenerator_ShouldUseRealRandomValuesFromSeed( int seed) { Span<byte> result = new byte[100]; Random random = new(seed); byte[] expectedBytes = new byte[result.Length]; random.NextBytes(expectedBytes); IRandomProvider sut = RandomProvider.Generate(seed); sut.GetRandom().NextBytes(result); await That(result.ToArray()).IsEqualTo(expectedBytes); } #endif [Theory] [AutoData] public async Task NextBytes_WithoutByteGenerator_ShouldUseRealRandomValuesFromSeed( int seed) { byte[] result = new byte[100]; Random random = new(seed); byte[] expectedBytes = new byte[result.Length]; random.NextBytes(expectedBytes); IRandomProvider sut = RandomProvider.Generate(seed); sut.GetRandom().NextBytes(result); await That(result).IsEqualTo(expectedBytes).InAnyOrder(); } }
RandomProviderTests
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/Html/MarkdownDeep/TableSpec.cs
{ "start": 793, "end": 863 }
internal enum ____ { NA, Left, Right, Center, }
ColumnAlignment
csharp
smartstore__Smartstore
src/Smartstore.Core/Content/Media/Handlers/ImageHandlerBase.cs
{ "start": 157, "end": 5034 }
public abstract class ____ : IMediaHandler { protected ImageHandlerBase(IImageCache imageCache, MediaExceptionFactory exceptionFactory) { ImageCache = imageCache; ExceptionFactory = exceptionFactory; } public ILogger Logger { get; set; } = NullLogger.Instance; public IImageCache ImageCache { get; set; } public MediaExceptionFactory ExceptionFactory { get; set; } public Localizer T { get; set; } = NullLocalizer.Instance; public virtual int Order => -100; public async Task ExecuteAsync(MediaHandlerContext context) { if (!IsProcessable(context)) { return; } var query = context.ImageQuery; var pathData = context.PathData; var cachedImage = await ImageCache.GetAsync(context.MediaFileId, pathData, query); if (!pathData.Extension.EqualsNoCase(cachedImage.Extension)) { // The query requests another format. // Adjust extension and mime type fo proper ETag creation. pathData.Extension = cachedImage.Extension; pathData.MimeType = cachedImage.MimeType; } var exists = cachedImage.Exists; if (exists && cachedImage.FileSize == 0) { // Empty file means: thumb extraction failed before and will most likely fail again. // Don't bother proceeding. context.Exception = ExceptionFactory.ExtractThumbnail(cachedImage.FileName); context.Executed = true; return; } if (!exists) { // Lock concurrent requests to same resource using (await AsyncLock.KeyedAsync("ImageHandlerBase.Execute." + cachedImage.Path)) { await ImageCache.RefreshInfoAsync(cachedImage); // File could have been processed by another request in the meantime, check again. if (!cachedImage.Exists) { // Call inner function var sourceFile = await context.GetSourceFileAsync(); if (sourceFile == null || sourceFile.Length == 0) { context.Executed = true; return; } var inputStream = await sourceFile.OpenReadAsync(); if (inputStream == null) { context.Exception = ExceptionFactory.ExtractThumbnail(sourceFile.SubPath, T("Admin.Media.Exception.NullInputStream")); context.Executed = true; return; } try { await ProcessImageAsync(context, cachedImage, inputStream); } catch (Exception ex) { Logger.Error(ex); if (ex is ExtractThumbnailException) { // Thumbnail extraction failed and we must assume that it always will fail. // Therefore we create an empty file to prevent repetitive processing. using (var memStream = new MemoryStream()) { await ImageCache.PutAsync(cachedImage, memStream); } } context.Exception = ex; context.Executed = true; return; } if (context.ResultImage != null) { await ImageCache.PutAsync(cachedImage, context.ResultImage); context.ResultFile = cachedImage.File; } context.Executed = true; return; } } } // Cached image existed already context.ResultFile = cachedImage.File; context.Executed = true; } protected abstract bool IsProcessable(MediaHandlerContext context); /// <summary> /// The handler implementation. <paramref name="inputStream"/> should be closed by implementor. /// </summary> protected abstract Task ProcessImageAsync( MediaHandlerContext context, CachedImage cachedImage, Stream inputStream); } }
ImageHandlerBase
csharp
getsentry__sentry-dotnet
test/Sentry.Maui.Tests/MauiEventsBinderTests.Shell.cs
{ "start": 59, "end": 4081 }
public partial class ____ { [Fact] public void Shell_Navigating_AddsBreadcrumb() { // Arrange var shell = new Shell { StyleId = "shell" }; _fixture.Binder.HandleShellEvents(shell); var current = new ShellNavigationState("foo"); var target = new ShellNavigationState("bar"); const ShellNavigationSource source = ShellNavigationSource.Push; // Act shell.RaiseEvent(nameof(Shell.Navigating), new ShellNavigatingEventArgs(current, target, source, false)); // Assert var crumb = Assert.Single(_fixture.Scope.Breadcrumbs); Assert.Equal($"{nameof(Shell)}.{nameof(Shell.Navigating)}", crumb.Message); Assert.Equal(BreadcrumbLevel.Info, crumb.Level); Assert.Equal(MauiEventsBinder.NavigationType, crumb.Type); Assert.Equal(MauiEventsBinder.NavigationCategory, crumb.Category); crumb.Data.Should().Contain($"{nameof(Shell)}.Name", "shell"); crumb.Data.Should().Contain($"from", "foo"); crumb.Data.Should().Contain($"to", "bar"); crumb.Data.Should().Contain($"Source", "Push"); } [Fact] public void Shell_UnbindNavigating_DoesNotAddBreadcrumb() { // Arrange var shell = new Shell { StyleId = "shell" }; _fixture.Binder.HandleShellEvents(shell); var current = new ShellNavigationState("foo"); var target = new ShellNavigationState("bar"); const ShellNavigationSource source = ShellNavigationSource.Push; shell.RaiseEvent(nameof(Shell.Navigating), new ShellNavigatingEventArgs(current, target, source, false)); Assert.Single(_fixture.Scope.Breadcrumbs); // Sanity check _fixture.Binder.HandleShellEvents(shell, bind: false); // Act shell.RaiseEvent(nameof(Shell.Navigating), new ShellNavigatingEventArgs(target, current, source, false)); // Assert Assert.Single(_fixture.Scope.Breadcrumbs); } [Fact] public void Shell_Navigated_AddsBreadcrumb() { // Arrange var shell = new Shell { StyleId = "shell" }; _fixture.Binder.HandleShellEvents(shell); var previous = new ShellNavigationState("foo"); var current = new ShellNavigationState("bar"); const ShellNavigationSource source = ShellNavigationSource.Push; // Act shell.RaiseEvent(nameof(Shell.Navigated), new ShellNavigatedEventArgs(previous, current, source)); // Assert var crumb = Assert.Single(_fixture.Scope.Breadcrumbs); Assert.Equal($"{nameof(Shell)}.{nameof(Shell.Navigated)}", crumb.Message); Assert.Equal(BreadcrumbLevel.Info, crumb.Level); Assert.Equal(MauiEventsBinder.NavigationType, crumb.Type); Assert.Equal(MauiEventsBinder.NavigationCategory, crumb.Category); crumb.Data.Should().Contain($"{nameof(Shell)}.Name", "shell"); crumb.Data.Should().Contain($"from", "foo"); crumb.Data.Should().Contain($"to", "bar"); crumb.Data.Should().Contain($"Source", "Push"); } [Fact] public void Shell_UnbindNavigated_DoesNotAddBreadcrumb() { // Arrange var shell = new Shell { StyleId = "shell" }; _fixture.Binder.HandleShellEvents(shell); var previous = new ShellNavigationState("foo"); var current = new ShellNavigationState("bar"); const ShellNavigationSource source = ShellNavigationSource.Push; shell.RaiseEvent(nameof(Shell.Navigated), new ShellNavigatedEventArgs(previous, current, source)); Assert.Single(_fixture.Scope.Breadcrumbs); // Sanity check _fixture.Binder.HandleShellEvents(shell, bind: false); // Act shell.RaiseEvent(nameof(Shell.Navigated), new ShellNavigatedEventArgs(current, previous, source)); // Assert Assert.Single(_fixture.Scope.Breadcrumbs); } }
MauiEventsBinderTests
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/src/Formatters/FormatterMappings.cs
{ "start": 396, "end": 3824 }
public class ____ { private readonly Dictionary<string, string> _map = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase); /// <summary> /// Sets mapping for the format to specified media type. /// If the format already exists, the media type will be overwritten with the new value. /// </summary> /// <param name="format">The format value.</param> /// <param name="contentType">The media type for the format value.</param> public void SetMediaTypeMappingForFormat(string format, string contentType) { ArgumentNullException.ThrowIfNull(format); ArgumentNullException.ThrowIfNull(contentType); SetMediaTypeMappingForFormat(format, MediaTypeHeaderValue.Parse(contentType)); } /// <summary> /// Sets mapping for the format to specified media type. /// If the format already exists, the media type will be overwritten with the new value. /// </summary> /// <param name="format">The format value.</param> /// <param name="contentType">The media type for the format value.</param> public void SetMediaTypeMappingForFormat(string format, MediaTypeHeaderValue contentType) { ArgumentNullException.ThrowIfNull(format); ArgumentNullException.ThrowIfNull(contentType); ValidateContentType(contentType); format = RemovePeriodIfPresent(format); _map[format] = contentType.ToString(); } /// <summary> /// Gets the media type for the specified format. /// </summary> /// <param name="format">The format value.</param> /// <returns>The media type for input format.</returns> public string? GetMediaTypeMappingForFormat(string format) { if (string.IsNullOrEmpty(format)) { var message = Resources.FormatFormatFormatterMappings_GetMediaTypeMappingForFormat_InvalidFormat( nameof(format)); throw new ArgumentException(message, nameof(format)); } format = RemovePeriodIfPresent(format); _map.TryGetValue(format, out var value); return value; } /// <summary> /// Clears the media type mapping for the format. /// </summary> /// <param name="format">The format value.</param> /// <returns><c>true</c> if the format is successfully found and cleared; otherwise, <c>false</c>.</returns> public bool ClearMediaTypeMappingForFormat(string format) { ArgumentNullException.ThrowIfNull(format); format = RemovePeriodIfPresent(format); return _map.Remove(format); } private static void ValidateContentType(MediaTypeHeaderValue contentType) { if (contentType.Type == "*" || contentType.SubType == "*") { throw new ArgumentException( string.Format(CultureInfo.CurrentCulture, Resources.FormatterMappings_NotValidMediaType, contentType), nameof(contentType)); } } private static string RemovePeriodIfPresent(string format) { ArgumentException.ThrowIfNullOrEmpty(format); if (format.StartsWith('.')) { if (format == ".") { throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Format_NotValid, format), nameof(format)); } format = format.Substring(1); } return format; } }
FormatterMappings
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Options/BaseSchemaFileOption.cs
{ "start": 55, "end": 337 }
internal class ____ : Option<FileInfo> { public BaseSchemaFileOption() : base("--schema") { Description = "The path to the graphql file with the schema"; IsRequired = true; this.DefaultFileFromEnvironmentValue("SCHEMA_FILE"); } }
BaseSchemaFileOption
csharp
dotnet__aspnetcore
src/DataProtection/Cryptography.Internal/src/SafeHandles/BCryptHandle.cs
{ "start": 256, "end": 996 }
class ____ : SafeHandleZeroOrMinusOneIsInvalid { protected BCryptHandle() : base(ownsHandle: true) { } protected uint GetProperty(string pszProperty, void* pbOutput, uint cbOutput) { uint retVal; int ntstatus = UnsafeNativeMethods.BCryptGetProperty(this, pszProperty, pbOutput, cbOutput, out retVal, dwFlags: 0); UnsafeNativeMethods.ThrowExceptionForBCryptStatus(ntstatus); return retVal; } protected void SetProperty(string pszProperty, void* pbInput, uint cbInput) { int ntstatus = UnsafeNativeMethods.BCryptSetProperty(this, pszProperty, pbInput, cbInput, dwFlags: 0); UnsafeNativeMethods.ThrowExceptionForBCryptStatus(ntstatus); } }
BCryptHandle
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Documentation/TraceWriterTests.cs
{ "start": 2119, "end": 2344 }
public class ____ { public static LogLevel Info; public static LogLevel Trace; public static LogLevel Error; public static LogLevel Warn; public static LogLevel Off; }
LogLevel
csharp
nunit__nunit
src/NUnitFramework/framework/Internal/ValueGenerator.cs
{ "start": 3039, "end": 5239 }
public sealed class ____<TStep> : Step where TStep : IComparable<TStep> { private readonly TStep _step; private readonly Func<T, TStep, T> _apply; /// <summary> /// Initializes a new instance of the <see cref="ComparableStep{TStep}"/> class. /// </summary> /// <param name="value">The amount by which to increment each time this step is applied.</param> /// <param name="apply"> /// Must increment the given value and return the result. /// If the result is outside the range representable by <typeparamref name="T"/>, /// must throw <see cref="OverflowException"/>. If the result does not change due to lack /// of precision representable by <typeparamref name="T"/>, must throw <see cref="ArithmeticException"/>. /// </param> public ComparableStep(TStep value, Func<T, TStep, T> apply) { if (apply is null) throw new ArgumentNullException(nameof(apply)); _step = value; _apply = apply; } public override bool IsPositive => Comparer<TStep>.Default.Compare(default, _step) < 0; public override bool IsNegative => Comparer<TStep>.Default.Compare(_step, default) < 0; /// <summary> /// Increments the given value and returns the result. /// If the result is outside the range representable by <typeparamref name="T"/>, /// throws <see cref="OverflowException"/>. If the result does not change due to lack /// of precision representable by <typeparamref name="T"/>, throws <see cref="ArithmeticException"/>. /// </summary> /// <exception cref="OverflowException"/> /// <exception cref="ArithmeticException"/> public override T Apply(T value) => _apply.Invoke(value, _step); } /// <summary> /// Encapsulates the ability to increment a <typeparamref name="T"/> value by an amount /// which may be of a different type. /// </summary> public new
ComparableStep
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue3089.cs
{ "start": 2366, "end": 2658 }
public class ____ : ContentPage { public ListPageCode() { IconImageSource = "coffee.png"; ListView view = new ListView(ListViewCachingStrategy.RecycleElement); Content = view; view.SetBinding(ListView.ItemsSourceProperty, "Items"); } } } } }
ListPageCode
csharp
AvaloniaUI__Avalonia
src/Linux/Avalonia.LinuxFramebuffer/EpollDispatcherImpl.cs
{ "start": 2458, "end": 6770 }
private enum ____ { Timer = 1, Signal = 2 } private int _sigread, _sigwrite; private int _timerfd; private object _lock = new(); private bool _signaled; private bool _wakeupRequested; private TimeSpan? _nextTimer; private int _epoll; private Stopwatch _clock = Stopwatch.StartNew(); public EpollDispatcherImpl(ManagedDispatcherImpl.IManagedDispatcherInputProvider inputProvider) { _inputProvider = inputProvider; _mainThread = Thread.CurrentThread; _epoll = epoll_create1(EPOLL_CLOEXEC); if (_epoll == -1) throw new Win32Exception("epoll_create1 failed"); var fds = stackalloc int[2]; pipe2(fds, O_NONBLOCK | O_CLOEXEC); _sigread = fds[0]; _sigwrite = fds[1]; var ev = new epoll_event { events = EPOLLIN, data = { u32 = (int)EventCodes.Signal } }; if (epoll_ctl(_epoll, EPOLL_CTL_ADD, _sigread, ref ev) == -1) throw new Win32Exception("Unable to attach signal pipe to epoll"); _timerfd = timerfd_create(CLOCK_MONOTONIC, O_NONBLOCK | O_CLOEXEC); ev.data.u32 = (int)EventCodes.Timer; if (epoll_ctl(_epoll, EPOLL_CTL_ADD, _timerfd, ref ev) == -1) throw new Win32Exception("Unable to attach timer fd to epoll"); } private bool CheckSignaled() { lock (_lock) { if (!_signaled) return false; _signaled = false; } Signaled?.Invoke(); return true; } public void RunLoop(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested) { var now = _clock.Elapsed; if (_nextTimer.HasValue && now > _nextTimer.Value) { Timer?.Invoke(); continue; } if (CheckSignaled()) continue; if (_inputProvider.HasInput) { _inputProvider.DispatchNextInputEvent(); continue; } epoll_event ev; if (_nextTimer != null) { var waitFor = _nextTimer.Value - now; if (waitFor.Ticks < 0) continue; itimerspec timer = new() { it_interval = default, it_value = new() { tv_sec = new IntPtr(Math.Min((int)waitFor.TotalSeconds, 100)), tv_nsec = new IntPtr((waitFor.Ticks % 10000000) * 100) } }; timerfd_settime(_timerfd, 0, &timer, null); } else { itimerspec none = default; timerfd_settime(_timerfd, 0, &none, null); } epoll_wait(_epoll, &ev, 1, (int)-1); // Drain the signaled pipe long buf = 0; while (read(_sigread, &buf, new IntPtr(8)).ToInt64() > 0) { } // Drain timer fd while (read(_timerfd, &buf, new IntPtr(8)).ToInt64() > 0) { } lock (_lock) _wakeupRequested = false; } } private void Wakeup() { lock (_lock) { if (_wakeupRequested) return; _wakeupRequested = true; int buf = 0; write(_sigwrite, &buf, new IntPtr(1)); } } public void Signal() { lock (_lock) { if (_signaled) return; _signaled = true; Wakeup(); } } public bool CurrentThreadIsLoopThread => Thread.CurrentThread == _mainThread; public event Action? Signaled; public event Action? Timer; public void UpdateTimer(long? dueTimeInMs) { _nextTimer = dueTimeInMs == null ? null : TimeSpan.FromMilliseconds(dueTimeInMs.Value); if (_nextTimer != null) Wakeup(); } public long Now => _clock.ElapsedMilliseconds; public bool CanQueryPendingInput => true; public bool HasPendingInput => _inputProvider.HasInput; }
EventCodes
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.CursorPagination.Tests/CustomConnectionTest.cs
{ "start": 1670, "end": 1708 }
public record ____(string Name); }
Product
csharp
DuendeSoftware__IdentityServer
identity-server/src/IdentityServer/Stores/Empty/EmptyResourceStore.cs
{ "start": 201, "end": 1014 }
internal class ____ : IResourceStore { public Task<IEnumerable<ApiResource>> FindApiResourcesByNameAsync(IEnumerable<string> apiResourceNames) => Task.FromResult(Enumerable.Empty<ApiResource>()); public Task<IEnumerable<ApiResource>> FindApiResourcesByScopeNameAsync(IEnumerable<string> scopeNames) => Task.FromResult(Enumerable.Empty<ApiResource>()); public Task<IEnumerable<ApiScope>> FindApiScopesByNameAsync(IEnumerable<string> scopeNames) => Task.FromResult(Enumerable.Empty<ApiScope>()); public Task<IEnumerable<IdentityResource>> FindIdentityResourcesByScopeNameAsync(IEnumerable<string> scopeNames) => Task.FromResult(Enumerable.Empty<IdentityResource>()); public Task<Resources> GetAllResourcesAsync() => Task.FromResult(new Resources() { OfflineAccess = true }); }
EmptyResourceStore
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Issue8715.xaml.cs
{ "start": 247, "end": 395 }
public partial class ____ : TestShell { public Issue8715() { InitializeComponent(); } protected override void Init() { } }
Issue8715
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Specs/ReturnExtensionSpec.cs
{ "start": 1773, "end": 2253 }
public class ____ : When_setting_return_value { [Test] public void Should_not_match_last_calls_arguments() { _substitutionContext.received(x => x.LastCallShouldReturn(_returnValueSet, MatchArgs.Any)); } public override void Because() { new object().ReturnsForAnyArgs(_value); } } } }
When_setting_a_return_value_for_the_previous_call_with_any_args
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/XFIssue/Issue7240.cs
{ "start": 159, "end": 932 }
public class ____ : TestShell { const string Success = "Page Count:3"; const string ClickMe = "ClickMe"; int pageCount = 1; protected override void Init() { Func<ContentPage> createNewPage = null; createNewPage = () => new ContentPage() { Content = new StackLayout() { new Button() { Text = "Click me and you should see a new page with this same button in the same place", AutomationId = ClickMe, Command = new Command(() => { pageCount++; Navigation.PushAsync(createNewPage()); }) }, new Label() { Text = $"Page Count:{pageCount}", AutomationId=$"Page Count:{pageCount}" } } }; AddContentPage(createNewPage()); } }
Issue7240
csharp
fluentassertions__fluentassertions
Tests/FluentAssertions.Specs/Streams/StreamAssertionSpecs.cs
{ "start": 6160, "end": 7641 }
public class ____ { [Fact] public void When_having_a_readable_stream_be_readable_should_succeed() { // Arrange using var stream = new TestStream { Readable = true }; // Act Action act = () => stream.Should().BeReadable(); // Assert act.Should().NotThrow(); } [Fact] public void When_having_a_non_readable_stream_be_readable_should_fail() { // Arrange using var stream = new TestStream { Readable = false }; // Act Action act = () => stream.Should().BeReadable("we want to test the failure {0}", "message"); // Assert act.Should().Throw<XunitException>() .WithMessage("Expected stream to be readable *failure message*, but it was not."); } [Fact] public void When_null_be_readable_should_fail() { // Arrange TestStream stream = null; // Act Action act = () => { using var _ = new AssertionScope(); stream.Should().BeReadable("we want to test the failure {0}", "message"); }; // Assert act.Should().Throw<XunitException>() .WithMessage("Expected stream to be readable *failure message*, but found a <null> reference."); } }
BeReadable
csharp
dotnet__efcore
src/EFCore.Relational/Update/ReaderModificationCommandBatch.cs
{ "start": 746, "end": 17305 }
public abstract class ____ : ModificationCommandBatch { private readonly List<IReadOnlyModificationCommand> _modificationCommands = []; private readonly int _batchHeaderLength; private bool _requiresTransaction = true; private bool _areMoreBatchesExpected; private int _sqlBuilderPosition, _commandResultSetCount; private int _pendingParameters; /// <summary> /// Creates a new <see cref="ReaderModificationCommandBatch" /> instance. /// </summary> /// <param name="dependencies">Service dependencies.</param> /// <param name="maxBatchSize">The maximum batch size. Defaults to 1000.</param> protected ReaderModificationCommandBatch(ModificationCommandBatchFactoryDependencies dependencies, int? maxBatchSize = null) { Dependencies = dependencies; RelationalCommandBuilder = dependencies.CommandBuilderFactory.Create(); UpdateSqlGenerator = dependencies.UpdateSqlGenerator; UpdateSqlGenerator.AppendBatchHeader(SqlBuilder); _batchHeaderLength = SqlBuilder.Length; MaxBatchSize = maxBatchSize ?? 1000; } /// <summary> /// Relational provider-specific dependencies for this service. /// </summary> protected virtual ModificationCommandBatchFactoryDependencies Dependencies { get; } /// <summary> /// The update SQL generator. /// </summary> protected virtual IUpdateSqlGenerator UpdateSqlGenerator { get; } /// <summary> /// Gets the relational command builder for the commands in the batch. /// </summary> protected virtual IRelationalCommandBuilder RelationalCommandBuilder { get; } /// <summary> /// The maximum number of <see cref="ModificationCommand" /> instances that can be added to a single batch. /// </summary> protected virtual int MaxBatchSize { get; } /// <summary> /// Gets the command text builder for the commands in the batch. /// </summary> protected virtual StringBuilder SqlBuilder { get; } = new(); /// <summary> /// Gets the parameter values for the commands in the batch. /// </summary> protected virtual Dictionary<string, object?> ParameterValues { get; } = new(); /// <summary> /// The list of conceptual insert/update/delete <see cref="ModificationCommands" />s in the batch. /// </summary> public override IReadOnlyList<IReadOnlyModificationCommand> ModificationCommands => _modificationCommands; /// <summary> /// The <see cref="ResultSetMapping" />s for each command in <see cref="ModificationCommands" />. /// </summary> protected virtual IList<ResultSetMapping> ResultSetMappings { get; } = new List<ResultSetMapping>(); /// <summary> /// The store command generated from this batch when <see cref="Complete" /> is called. /// </summary> protected virtual RawSqlCommand? StoreCommand { get; set; } /// <inheritdoc /> public override bool TryAddCommand(IReadOnlyModificationCommand modificationCommand) { if (StoreCommand is not null) { throw new InvalidOperationException(RelationalStrings.ModificationCommandBatchAlreadyComplete); } if (_modificationCommands.Count >= MaxBatchSize) { return false; } _sqlBuilderPosition = SqlBuilder.Length; _commandResultSetCount = ResultSetMappings.Count; _pendingParameters = 0; AddCommand(modificationCommand); _modificationCommands.Add(modificationCommand); // Check if the batch is still valid after having added the command (e.g. have we bypassed a maximum CommandText size?) // A batch with only one command is always considered valid (otherwise we'd get an endless loop); allow the batch to fail // server-side. if (IsValid() || _modificationCommands.Count == 1) { return true; } Check.DebugAssert( ReferenceEquals(modificationCommand, _modificationCommands[^1])); RollbackLastCommand(modificationCommand); return false; } /// <summary> /// Rolls back the last command added. Used when adding a command caused the batch to become invalid (e.g. CommandText too long). /// </summary> protected virtual void RollbackLastCommand(IReadOnlyModificationCommand modificationCommand) { _modificationCommands.RemoveAt(_modificationCommands.Count - 1); SqlBuilder.Length = _sqlBuilderPosition; while (ResultSetMappings.Count > _commandResultSetCount) { ResultSetMappings.RemoveAt(ResultSetMappings.Count - 1); } for (var i = 0; i < _pendingParameters; i++) { var parameterIndex = RelationalCommandBuilder.Parameters.Count - 1; var parameter = RelationalCommandBuilder.Parameters[parameterIndex]; RelationalCommandBuilder.RemoveParameterAt(parameterIndex); ParameterValues.Remove(parameter.InvariantName); } // The command's column modifications had their parameter names generated, that needs to be rolled back as well. foreach (var columnModification in modificationCommand.ColumnModifications) { columnModification.ResetParameterNames(); } } /// <summary> /// Whether any SQL has already been added to the batch command text. /// </summary> protected virtual bool IsCommandTextEmpty => SqlBuilder.Length == _batchHeaderLength; /// <inheritdoc /> public override bool RequiresTransaction => _requiresTransaction; /// <inheritdoc /> public override bool AreMoreBatchesExpected => _areMoreBatchesExpected; /// <summary> /// Sets whether the batch requires a transaction in order to execute correctly. /// </summary> /// <param name="requiresTransaction">Whether the batch requires a transaction in order to execute correctly.</param> protected virtual void SetRequiresTransaction(bool requiresTransaction) => _requiresTransaction = requiresTransaction; /// <summary> /// Checks whether the command text is valid. /// </summary> /// <returns><see langword="true" /> if the command text is valid; <see langword="false" /> otherwise.</returns> protected virtual bool IsValid() => true; /// <summary> /// Adds Updates the command text for the command at the given position in the <see cref="ModificationCommands" /> list. /// </summary> /// <param name="modificationCommand">The command to add.</param> protected virtual void AddCommand(IReadOnlyModificationCommand modificationCommand) { bool requiresTransaction; var commandPosition = ResultSetMappings.Count; if (modificationCommand.StoreStoredProcedure is not null) { ResultSetMappings.Add( UpdateSqlGenerator.AppendStoredProcedureCall( SqlBuilder, modificationCommand, commandPosition, out requiresTransaction)); } else { switch (modificationCommand.EntityState) { case EntityState.Added: ResultSetMappings.Add( UpdateSqlGenerator.AppendInsertOperation( SqlBuilder, modificationCommand, commandPosition, out requiresTransaction)); break; case EntityState.Modified: ResultSetMappings.Add( UpdateSqlGenerator.AppendUpdateOperation( SqlBuilder, modificationCommand, commandPosition, out requiresTransaction)); break; case EntityState.Deleted: ResultSetMappings.Add( UpdateSqlGenerator.AppendDeleteOperation( SqlBuilder, modificationCommand, commandPosition, out requiresTransaction)); break; default: throw new InvalidOperationException( RelationalStrings.ModificationCommandInvalidEntityState( modificationCommand.Entries[0].EntityType, modificationCommand.EntityState)); } } AddParameters(modificationCommand); _requiresTransaction = commandPosition > 0 || requiresTransaction; } /// <inheritdoc /> public override void Complete(bool moreBatchesExpected) { if (StoreCommand is not null) { throw new InvalidOperationException(RelationalStrings.ModificationCommandBatchAlreadyComplete); } _areMoreBatchesExpected = moreBatchesExpected; // Some database have a mode where autocommit is off, and so executing a command outside of an explicit transaction implicitly // creates a new transaction (which needs to be explicitly committed). // The below is a hook for allowing providers to turn autocommit on, in case it's off. if (!RequiresTransaction) { UpdateSqlGenerator.PrependEnsureAutocommit(SqlBuilder); } RelationalCommandBuilder.Append(SqlBuilder.ToString()); StoreCommand = new RawSqlCommand(RelationalCommandBuilder.Build(), ParameterValues); } /// <summary> /// Adds parameters for all column modifications in the given <paramref name="modificationCommand" /> to the relational command /// being built for this batch. /// </summary> /// <param name="modificationCommand">The modification command for which to add parameters.</param> protected virtual void AddParameters(IReadOnlyModificationCommand modificationCommand) { Check.DebugAssert( !modificationCommand.ColumnModifications.Any(m => m.Column is IStoreStoredProcedureReturnValue) || modificationCommand.ColumnModifications[0].Column is IStoreStoredProcedureReturnValue, "ResultValue column modification in non-first position"); var modifications = modificationCommand.StoreStoredProcedure is null ? modificationCommand.ColumnModifications : modificationCommand.ColumnModifications.Where(c => c.Column is IStoreStoredProcedureParameter or IStoreStoredProcedureReturnValue); foreach (var columnModification in modifications) { AddParameter(columnModification); } } /// <summary> /// Adds a parameter for the given <paramref name="columnModification" /> to the relational command being built for this batch. /// </summary> /// <param name="columnModification">The column modification for which to add parameters.</param> protected virtual void AddParameter(IColumnModification columnModification) { var direction = columnModification.Column switch { IStoreStoredProcedureParameter storedProcedureParameter => storedProcedureParameter.Direction, IStoreStoredProcedureReturnValue => ParameterDirection.Output, _ => ParameterDirection.Input }; // For the case where the same modification has both current and original value parameters, and corresponds to an in/out parameter, // we only want to add a single parameter. This will happen below. if (columnModification.UseCurrentValueParameter && !(columnModification.UseOriginalValueParameter && direction == ParameterDirection.InputOutput)) { AddParameterCore( columnModification.ParameterName, columnModification.UseCurrentValue ? columnModification.Value : direction == ParameterDirection.InputOutput ? DBNull.Value : null); } if (columnModification.UseOriginalValueParameter) { Check.DebugAssert(direction.HasFlag(ParameterDirection.Input)); AddParameterCore(columnModification.OriginalParameterName, columnModification.OriginalValue); } void AddParameterCore(string name, object? value) { RelationalCommandBuilder.AddParameter( name, Dependencies.SqlGenerationHelper.GenerateParameterName(name), columnModification.TypeMapping!, columnModification.IsNullable, direction); ParameterValues.Add(name, value); _pendingParameters++; } } /// <summary> /// Executes the command generated by this batch against a database using the given connection. /// </summary> /// <param name="connection">The connection to the database to update.</param> public override void Execute(IRelationalConnection connection) { if (StoreCommand is null) { throw new InvalidOperationException(RelationalStrings.ModificationCommandBatchNotComplete); } try { using var dataReader = StoreCommand.RelationalCommand.ExecuteReader( new RelationalCommandParameterObject( connection, StoreCommand.ParameterValues, null, Dependencies.CurrentContext.Context, Dependencies.Logger, CommandSource.SaveChanges)); Consume(dataReader); } catch (Exception ex) when (ex is not DbUpdateException and not OperationCanceledException) { throw new DbUpdateException( RelationalStrings.UpdateStoreException, ex, ModificationCommands.SelectMany(c => c.Entries).ToList()); } } /// <summary> /// Executes the command generated by this batch against a database using the given connection. /// </summary> /// <param name="connection">The connection to the database to update.</param> /// <param name="cancellationToken">A <see cref="CancellationToken" /> to observe while waiting for the task to complete.</param> /// <returns>A task that represents the asynchronous operation.</returns> /// <exception cref="OperationCanceledException">If the <see cref="CancellationToken" /> is canceled.</exception> public override async Task ExecuteAsync( IRelationalConnection connection, CancellationToken cancellationToken = default) { if (StoreCommand is null) { throw new InvalidOperationException(RelationalStrings.ModificationCommandBatchNotComplete); } try { var dataReader = await StoreCommand.RelationalCommand.ExecuteReaderAsync( new RelationalCommandParameterObject( connection, StoreCommand.ParameterValues, null, Dependencies.CurrentContext.Context, Dependencies.Logger, CommandSource.SaveChanges), cancellationToken).ConfigureAwait(false); await using var _ = dataReader.ConfigureAwait(false); await ConsumeAsync(dataReader, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not DbUpdateException and not OperationCanceledException and not UnreachableException) { throw new DbUpdateException( RelationalStrings.UpdateStoreException, ex, ModificationCommands.SelectMany(c => c.Entries).ToList()); } } /// <summary> /// Consumes the data reader created by <see cref="Execute" />. /// </summary> /// <param name="reader">The data reader.</param> protected abstract void Consume(RelationalDataReader reader); /// <summary> /// Consumes the data reader created by <see cref="ExecuteAsync" />. /// </summary> /// <param name="reader">The data reader.</param> /// <param name="cancellationToken">A <see cref="CancellationToken" /> to observe while waiting for the task to complete.</param> /// <returns>A task that represents the asynchronous operation.</returns> /// <exception cref="OperationCanceledException">If the <see cref="CancellationToken" /> is canceled.</exception> protected abstract Task ConsumeAsync( RelationalDataReader reader, CancellationToken cancellationToken = default); }
ReaderModificationCommandBatch
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Workflows/Trimming/Drivers/WorkflowTrimmingDisplayDriver.cs
{ "start": 413, "end": 3032 }
public sealed class ____ : SiteDisplayDriver<WorkflowTrimmingSettings> { public const string GroupId = "WorkflowTrimmingSettings"; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IAuthorizationService _authorizationService; private readonly IDocumentManager<WorkflowTrimmingState> _workflowTrimmingStateDocumentManager; public WorkflowTrimmingDisplayDriver( IAuthorizationService authorizationService, IHttpContextAccessor httpContextAccessor, IDocumentManager<WorkflowTrimmingState> workflowTrimmingStateDocumentManager) { _authorizationService = authorizationService; _httpContextAccessor = httpContextAccessor; _workflowTrimmingStateDocumentManager = workflowTrimmingStateDocumentManager; } protected override string SettingsGroupId => GroupId; public override async Task<IDisplayResult> EditAsync(ISite model, WorkflowTrimmingSettings settings, BuildEditorContext context) { if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, WorkflowsPermissions.ManageWorkflowSettings)) { return null; } return Initialize<WorkflowTrimmingViewModel>("WorkflowTrimming_Fields_Edit", async model => { model.RetentionDays = settings.RetentionDays; model.LastRunUtc = (await _workflowTrimmingStateDocumentManager.GetOrCreateImmutableAsync()).LastRunUtc; model.Disabled = settings.Disabled; foreach (var status in settings.Statuses ?? []) { model.Statuses.Single(statusItem => statusItem.Status == status).IsSelected = true; } }).Location("Content:5") .OnGroup(GroupId); } public override async Task<IDisplayResult> UpdateAsync(ISite site, WorkflowTrimmingSettings settings, UpdateEditorContext context) { if (!await _authorizationService.AuthorizeAsync(_httpContextAccessor.HttpContext?.User, WorkflowsPermissions.ManageWorkflowSettings)) { return null; } var viewModel = new WorkflowTrimmingViewModel(); await context.Updater.TryUpdateModelAsync(viewModel, Prefix); settings.RetentionDays = viewModel.RetentionDays; settings.Disabled = viewModel.Disabled; settings.Statuses = viewModel.Statuses .Where(statusItem => statusItem.IsSelected) .Select(statusItem => statusItem.Status) .ToArray(); return await EditAsync(site, settings, context); } }
WorkflowTrimmingDisplayDriver
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Media/DrawingBrush.cs
{ "start": 398, "end": 3267 }
public sealed class ____ : TileBrush, ISceneBrush { /// <summary> /// Defines the <see cref="Drawing"/> property. /// </summary> public static readonly StyledProperty<Drawing?> DrawingProperty = AvaloniaProperty.Register<DrawingBrush, Drawing?>(nameof(Drawing)); /// <summary> /// Initializes a new instance of the <see cref="DrawingBrush"/> class. /// </summary> public DrawingBrush() { } /// <summary> /// Initializes a new instance of the <see cref="DrawingBrush"/> class. /// </summary> /// <param name="visual">The visual to draw.</param> public DrawingBrush(Drawing visual) { Drawing = visual; } /// <summary> /// Gets or sets the visual to draw. /// </summary> public Drawing? Drawing { get { return GetValue(DrawingProperty); } set { SetValue(DrawingProperty, value); } } ISceneBrushContent? ISceneBrush.CreateContent() { if (Drawing == null) return null; using var recorder = new RenderDataDrawingContext(null); Drawing?.Draw(recorder); return recorder.GetImmediateSceneBrushContent(this, null, true); } internal override Func<Compositor, ServerCompositionSimpleBrush> Factory => static c => new ServerCompositionSimpleContentBrush(c.Server); private InlineDictionary<Compositor, CompositionRenderData?> _renderDataDictionary; private protected override void OnReferencedFromCompositor(Compositor c) { _renderDataDictionary.Add(c, CreateServerContent(c)); base.OnReferencedFromCompositor(c); } protected override void OnUnreferencedFromCompositor(Compositor c) { if (_renderDataDictionary.TryGetAndRemoveValue(c, out var content)) content?.Dispose(); base.OnUnreferencedFromCompositor(c); } private protected override void SerializeChanges(Compositor c, BatchStreamWriter writer) { base.SerializeChanges(c, writer); if (_renderDataDictionary.TryGetValue(c, out var content) && content != null) writer.WriteObject(new CompositionRenderDataSceneBrushContent.Properties(content.Server, null, true)); else writer.WriteObject(null); } CompositionRenderData? CreateServerContent(Compositor c) { if (Drawing == null) return null; using var recorder = new RenderDataDrawingContext(c); Drawing?.Draw(recorder); return recorder.GetRenderResults(); } } }
DrawingBrush
csharp
microsoft__PowerToys
src/modules/launcher/Plugins/Microsoft.Plugin.Indexer/SearchHelper/OleDBResult.cs
{ "start": 274, "end": 467 }
public class ____ { public List<object> FieldData { get; } public OleDBResult(List<object> fieldData) { FieldData = fieldData; } } }
OleDBResult
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/Automatonymous/Combine_Assigned_Specs.cs
{ "start": 3799, "end": 7020 }
public class ____ { [Test] public async Task Should_have_called_combined_event() { _machine = new TestStateMachine(); _instance = new Instance(); await _machine.RaiseEvent(_instance, _machine.Start); Assert.That(_instance.Called, Is.False); await _machine.RaiseEvent(_instance, _machine.First); await _machine.RaiseEvent(_instance, _machine.Second); Assert.Multiple(() => { Assert.That(_instance.Called, Is.True); Assert.That(_instance.CurrentState, Is.EqualTo(2)); Assert.That(_machine.NextEvents(_machine.GetState("Final")), Is.Empty); }); } [Test] public async Task Should_have_correct_events() { _machine = new TestStateMachine(); _instance = new Instance(); Assert.Multiple(() => { Assert.That(_machine.NextEvents(_machine.Initial).Count(), Is.EqualTo(1)); Assert.That(_machine.NextEvents(_machine.GetState("Initial")).Count(), Is.EqualTo(1)); Assert.That(_machine.NextEvents(_machine.Waiting).Count(), Is.EqualTo(3)); Assert.That(_machine.NextEvents(_machine.GetState("Waiting")).Count(), Is.EqualTo(3)); Assert.That(_machine.NextEvents(_machine.Final).Count(), Is.EqualTo(0)); Assert.That(_machine.NextEvents(_machine.GetState("Final")).Count(), Is.EqualTo(0)); }); } [Test] public async Task Should_have_initial_state_with_zero() { _machine = new TestStateMachine(); _instance = new Instance(); await _machine.RaiseEvent(_instance, _machine.Start); Assert.Multiple(() => { Assert.That(_instance.CurrentState, Is.EqualTo(3)); Assert.That(_machine.NextEvents(_machine.GetState("Final")), Is.Empty); }); } [Test] public async Task Should_not_call_for_one_event() { _machine = new TestStateMachine(); _instance = new Instance(); await _machine.RaiseEvent(_instance, _machine.Start); await _machine.RaiseEvent(_instance, _machine.First); Assert.Multiple(() => { Assert.That(_instance.Called, Is.False); Assert.That(_machine.NextEvents(_machine.GetState("Final")), Is.Empty); }); } [Test] public async Task Should_not_call_for_one_other_event() { _machine = new TestStateMachine(); _instance = new Instance(); await _machine.RaiseEvent(_instance, _machine.Start); await _machine.RaiseEvent(_instance, _machine.Second); Assert.Multiple(() => { Assert.That(_instance.Called, Is.False); Assert.That(_machine.NextEvents(_machine.GetState("Final")), Is.Empty); }); } TestStateMachine _machine; Instance _instance;
When_combining_events_with_an_int_for_state_assigned_to_state
csharp
dotnet__aspnetcore
src/Security/Authentication/OpenIdConnect/src/UniqueJsonKeyClaimAction.cs
{ "start": 659, "end": 2414 }
public class ____ : JsonKeyClaimAction { /// <summary> /// Creates a new UniqueJsonKeyClaimAction. /// </summary> /// <param name="claimType">The value to use for Claim.Type when creating a Claim.</param> /// <param name="valueType">The value to use for Claim.ValueType when creating a Claim.</param> /// <param name="jsonKey">The top level key to look for in the json user data.</param> public UniqueJsonKeyClaimAction(string claimType, string valueType, string jsonKey) : base(claimType, valueType, jsonKey) { } /// <inheritdoc /> public override void Run(JsonElement userData, ClaimsIdentity identity, string issuer) { var value = userData.GetString(JsonKey); if (string.IsNullOrEmpty(value)) { // Not found return; } var claim = identity.FindFirst(c => string.Equals(c.Type, ClaimType, StringComparison.OrdinalIgnoreCase)); if (claim != null && string.Equals(claim.Value, value, StringComparison.Ordinal)) { // Duplicate return; } claim = identity.FindFirst(c => { // If this claimType is mapped by the JwtSeurityTokenHandler, then this property will be set return c.Properties.TryGetValue(JwtSecurityTokenHandler.ShortClaimTypeProperty, out var shortType) && string.Equals(shortType, ClaimType, StringComparison.OrdinalIgnoreCase); }); if (claim != null && string.Equals(claim.Value, value, StringComparison.Ordinal)) { // Duplicate with an alternate name. return; } identity.AddClaim(new Claim(ClaimType, value, ValueType, issuer)); } }
UniqueJsonKeyClaimAction
csharp
microsoft__PowerToys
src/common/UITestAutomation/UITestBase.cs
{ "start": 35171, "end": 41374 }
public struct ____ { [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DmDeviceName; public short DmSpecVersion; public short DmDriverVersion; public short DmSize; public short DmDriverExtra; public int DmFields; public int DmPositionX; public int DmPositionY; public int DmDisplayOrientation; public int DmDisplayFixedOutput; public short DmColor; public short DmDuplex; public short DmYResolution; public short DmTTOption; public short DmCollate; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 32)] public string DmFormName; public short DmLogPixels; public int DmBitsPerPel; public int DmPelsWidth; public int DmPelsHeight; public int DmDisplayFlags; public int DmDisplayFrequency; public int DmICMMethod; public int DmICMIntent; public int DmMediaType; public int DmDitherType; public int DmReserved1; public int DmReserved2; public int DmPanningWidth; public int DmPanningHeight; } public static void GetMonitorInfo() { int deviceIndex = 0; DISPLAY_DEVICE d = default(DISPLAY_DEVICE); d.cb = Marshal.SizeOf(d); Console.WriteLine("monitor list :"); while (EnumDisplayDevices(IntPtr.Zero, deviceIndex, ref d, 0)) { Console.WriteLine($"monitor {deviceIndex + 1}:"); Console.WriteLine($" name: {d.DeviceName}"); Console.WriteLine($"  string: {d.DeviceString}"); Console.WriteLine($"  ID: {d.DeviceID}"); Console.WriteLine($"  key: {d.DeviceKey}"); Console.WriteLine(); DEVMODE dm = default(DEVMODE); dm.DmSize = (short)Marshal.SizeOf<DEVMODE>(); int modeNum = 0; while (EnumDisplaySettings(d.DeviceName, modeNum, ref dm) > 0) { MonitorInfoData.Monitors.Add(new MonitorInfoData.MonitorInfoDataWrapper() { DeviceName = d.DeviceName, DeviceString = d.DeviceString, DeviceID = d.DeviceID, DeviceKey = d.DeviceKey, PelsWidth = dm.DmPelsWidth, PelsHeight = dm.DmPelsHeight, DisplayFrequency = dm.DmDisplayFrequency, }); Console.WriteLine($"  mode {modeNum}: {dm.DmPelsWidth}x{dm.DmPelsHeight} @ {dm.DmDisplayFrequency}Hz"); modeNum++; } deviceIndex++; d.cb = Marshal.SizeOf(d); // Reset the size for the next device } } public static void ChangeDisplayResolution(int PelsWidth, int PelsHeight) { Screen screen = Screen.PrimaryScreen!; if (screen.Bounds.Width == PelsWidth && screen.Bounds.Height == PelsHeight) { return; } DEVMODE devMode = default(DEVMODE); devMode.DmDeviceName = new string(new char[32]); devMode.DmFormName = new string(new char[32]); devMode.DmSize = (short)Marshal.SizeOf<DEVMODE>(); int modeNum = 0; while (EnumDisplaySettings(IntPtr.Zero, modeNum, ref devMode) > 0) { Console.WriteLine($"Mode {modeNum}: {devMode.DmPelsWidth}x{devMode.DmPelsHeight} @ {devMode.DmDisplayFrequency}Hz"); modeNum++; } devMode.DmPelsWidth = PelsWidth; devMode.DmPelsHeight = PelsHeight; int result = NativeMethods.ChangeDisplaySettings(ref devMode, NativeMethods.CDS_TEST); if (result == DISP_CHANGE_SUCCESSFUL) { result = ChangeDisplaySettings(ref devMode, CDS_UPDATEREGISTRY); if (result == DISP_CHANGE_SUCCESSFUL) { Console.WriteLine($"Changing display resolution to {devMode.DmPelsWidth}x{devMode.DmPelsHeight}"); } else { Console.WriteLine($"Failed to change display resolution. Error code: {result}"); } } else if (result == DISP_CHANGE_RESTART) { Console.WriteLine($"Changing display resolution to {devMode.DmPelsWidth}x{devMode.DmPelsHeight} requires a restart"); } else { Console.WriteLine($"Failed to change display resolution. Error code: {result}"); } } // Windows API for moving windows [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy, uint uFlags); private const uint SWPNOSIZE = 0x0001; private const uint SWPNOZORDER = 0x0004; public static void MoveWindow(Element window, int x, int y) { var windowHandle = IntPtr.Parse(window.GetAttribute("NativeWindowHandle") ?? "0", System.Globalization.CultureInfo.InvariantCulture); if (windowHandle != IntPtr.Zero) { SetWindowPos(windowHandle, IntPtr.Zero, x, y, 0, 0, SWPNOSIZE | SWPNOZORDER); Task.Delay(500).Wait(); } } } } }
DEVMODE
csharp
ardalis__GuardClauses
src/GuardClauses/Exceptions/NotFoundException.cs
{ "start": 294, "end": 745 }
class ____ a specified name of the queried object and its key. /// </summary> /// <param name="objectName">Name of the queried object.</param> /// <param name="key">The value by which the object is queried.</param> public NotFoundException(string key, string objectName) : base($"Queried object {objectName} was not found, Key: {key}") { } /// <summary> /// Initializes a new instance of the NotFoundException
with
csharp
dotnet__reactive
Ix.NET/Source/System.Interactive.Tests/System/Linq/Operators/DistinctUntilChanged.cs
{ "start": 309, "end": 1918 }
public class ____ : Tests { [Fact] public void DistinctUntilChanged_Arguments() { AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int>(null)); AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int>(null, EqualityComparer<int>.Default)); AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int>([1], null)); AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int, int>(null, _ => _)); AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int, int>([1], null)); AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int, int>(null, _ => _, EqualityComparer<int>.Default)); AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int, int>([1], null, EqualityComparer<int>.Default)); AssertThrows<ArgumentNullException>(() => EnumerableEx.DistinctUntilChanged<int, int>([1], _ => _, null)); } [Fact] public void DistinctUntilChanged1() { var res = new[] { 1, 2, 2, 3, 3, 3, 2, 2, 1 }.DistinctUntilChanged().ToList(); Assert.True(Enumerable.SequenceEqual(res, [1, 2, 3, 2, 1])); } [Fact] public void DistinctUntilChanged2() { var res = new[] { 1, 1, 2, 3, 4, 5, 5, 6, 7 }.DistinctUntilChanged(x => x / 2).ToList(); Assert.True(Enumerable.SequenceEqual(res, [1, 2, 4, 6])); } } }
DistinctUntilChanged
csharp
bitwarden__server
util/PostgresMigrations/Migrations/20250717164620_20250717_AddingProjectIdToEvent.cs
{ "start": 134, "end": 662 }
public partial class ____ : Migration { /// <inheritdoc /> protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<Guid>( name: "ProjectId", table: "Event", type: "uuid", nullable: true); } /// <inheritdoc /> protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "ProjectId", table: "Event"); } }
_20250717_AddingProjectIdToEvent
csharp
bitwarden__server
src/Core/AdminConsole/OrganizationFeatures/OrganizationApiKeys/Interfaces/IGetOrganizationApiKeyQuery.cs
{ "start": 135, "end": 309 }
public interface ____ { Task<OrganizationApiKey> GetOrganizationApiKeyAsync(Guid organizationId, OrganizationApiKeyType organizationApiKeyType); }
IGetOrganizationApiKeyQuery
csharp
bitwarden__server
src/Core/SecretsManager/Repositories/Noop/NoopProjectRepository.cs
{ "start": 254, "end": 2588 }
public class ____ : IProjectRepository { public Task<IEnumerable<ProjectPermissionDetails>> GetManyByOrganizationIdAsync(Guid organizationId, Guid userId, AccessClientType accessType) { return Task.FromResult(null as IEnumerable<ProjectPermissionDetails>); } public Task<IEnumerable<Project>> GetManyByOrganizationIdWriteAccessAsync(Guid organizationId, Guid userId, AccessClientType accessType) { return Task.FromResult(null as IEnumerable<Project>); } public Task<IEnumerable<Project>> GetManyWithSecretsByIds(IEnumerable<Guid> ids) { return Task.FromResult(null as IEnumerable<Project>); } public Task<Project> GetByIdAsync(Guid id) { return Task.FromResult(null as Project); } public Task<Project> CreateAsync(Project project) { return Task.FromResult(null as Project); } public Task ReplaceAsync(Project project) { return Task.FromResult(0); } public Task DeleteManyByIdAsync(IEnumerable<Guid> ids) { return Task.FromResult(0); } public Task<IEnumerable<Project>> ImportAsync(IEnumerable<Project> projects) { return Task.FromResult(null as IEnumerable<Project>); } public Task<(bool Read, bool Write)> AccessToProjectAsync(Guid id, Guid userId, AccessClientType accessType) { return Task.FromResult((false, false)); } public Task<bool> ProjectsAreInOrganization(List<Guid> projectIds, Guid organizationId) { return Task.FromResult(false); } public Task<int> GetProjectCountByOrganizationIdAsync(Guid organizationId) { return Task.FromResult(0); } public Task<int> GetProjectCountByOrganizationIdAsync(Guid organizationId, Guid userId, AccessClientType accessType) { return Task.FromResult(0); } public Task<ProjectCounts> GetProjectCountsByIdAsync(Guid projectId, Guid userId, AccessClientType accessType) { return Task.FromResult(null as ProjectCounts); } public Task<Dictionary<Guid, (bool Read, bool Write)>> AccessToProjectsAsync(IEnumerable<Guid> projectIds, Guid userId, AccessClientType accessType) { return Task.FromResult(null as Dictionary<Guid, (bool Read, bool Write)>); } }
NoopProjectRepository
csharp
SixLabors__ImageSharp
src/ImageSharp/Processing/Processors/Convolution/Convolution2DState.cs
{ "start": 371, "end": 1786 }
struct ____ { private readonly Span<int> rowOffsetMap; private readonly Span<int> columnOffsetMap; private readonly uint kernelHeight; private readonly uint kernelWidth; public Convolution2DState( in DenseMatrix<float> kernelY, in DenseMatrix<float> kernelX, KernelSamplingMap map) { // We check the kernels are the same size upstream. this.KernelY = new ReadOnlyKernel(kernelY); this.KernelX = new ReadOnlyKernel(kernelX); this.kernelHeight = (uint)kernelY.Rows; this.kernelWidth = (uint)kernelY.Columns; this.rowOffsetMap = map.GetRowOffsetSpan(); this.columnOffsetMap = map.GetColumnOffsetSpan(); } public readonly ReadOnlyKernel KernelY { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; } public readonly ReadOnlyKernel KernelX { [MethodImpl(MethodImplOptions.AggressiveInlining)] get; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ref int GetSampleRow(uint row) => ref Unsafe.Add(ref MemoryMarshal.GetReference(this.rowOffsetMap), row * this.kernelHeight); [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly ref int GetSampleColumn(uint column) => ref Unsafe.Add(ref MemoryMarshal.GetReference(this.columnOffsetMap), column * this.kernelWidth); }
Convolution2DState