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 | mongodb__mongo-csharp-driver | src/MongoDB.Driver/FieldDefinition.cs | {
"start": 4640,
"end": 4761
} | class ____ field names.
/// </summary>
/// <typeparam name="TDocument">The type of the document.</typeparam>
| for |
csharp | nunit__nunit | src/NUnitFramework/tests/Internal/Filters/TestFilterXmlTests.cs | {
"start": 1160,
"end": 1624
} | class ____='1'>Dummy</class></filter>");
Assert.That(filter, Is.TypeOf<ClassNameFilter>());
Assert.That(filter.Match(DummyFixtureSuite));
Assert.That(filter.Match(AnotherFixtureSuite), Is.False);
}
[Test]
public void ClassNameFilter_ToXml_Regex()
{
TestFilter filter = new ClassNameFilter("FULLNAME", isRegex: true);
Assert.That(filter.ToXml(false).OuterXml, Is.EqualTo("< | re |
csharp | dotnet__efcore | test/EFCore.Design.Tests/Query/LinqToCSharpSyntaxTranslatorTest.cs | {
"start": 61606,
"end": 62060
} | public enum ____
{
One = 1,
Two = 2
}
// ReSharper restore UnusedMember.Local
// ReSharper restore AutoPropertyCanBeMadeGetOnly.Local
// ReSharper restore UnusedParameter.Local
// ReSharper restore UnusedAutoPropertyAccessor.Local
// ReSharper restore MemberCanBePrivate.Local
private readonly ExpressionPrinter _expressionPrinter = new();
private readonly bool _outputExpressionTrees = true;
}
| SomeEnum |
csharp | CommunityToolkit__dotnet | src/CommunityToolkit.Mvvm/Messaging/IMessengerExtensions.cs | {
"start": 1267,
"end": 1782
} | private static class ____
{
/// <summary>
/// The <see cref="MethodInfo"/> instance associated with <see cref="Register{TMessage,TToken}(IMessenger,IRecipient{TMessage},TToken)"/>.
/// </summary>
public static readonly MethodInfo RegisterIRecipient = new Action<IMessenger, IRecipient<object>, Unit>(Register).Method.GetGenericMethodDefinition();
}
/// <summary>
/// A non-generic version of <see cref="DiscoveredRecipients{TToken}"/>.
/// </summary>
| MethodInfos |
csharp | SixLabors__ImageSharp | tests/ImageSharp.Tests/Image/ImageTests.cs | {
"start": 3483,
"end": 7598
} | public class ____
{
private readonly Configuration configuration = Configuration.CreateDefaultInstance();
private void LimitBufferCapacity(int bufferCapacityInBytes) =>
this.configuration.MemoryAllocator = new TestMemoryAllocator { BufferCapacityInBytes = bufferCapacityInBytes };
[Theory]
[InlineData(false)]
[InlineData(true)]
public void GetSet(bool enforceDisco)
{
if (enforceDisco)
{
this.LimitBufferCapacity(100);
}
using Image<Rgba32> image = new(this.configuration, 10, 10);
Rgba32 val = image[3, 4];
Assert.Equal(default(Rgba32), val);
image[3, 4] = Color.Red.ToPixel<Rgba32>();
val = image[3, 4];
Assert.Equal(Color.Red.ToPixel<Rgba32>(), val);
}
public static TheoryData<bool, int> OutOfRangeData = new()
{
{ false, -1 },
{ false, 10 },
{ true, -1 },
{ true, 10 },
};
[Theory]
[MemberData(nameof(OutOfRangeData))]
public void Get_OutOfRangeX(bool enforceDisco, int x)
{
if (enforceDisco)
{
this.LimitBufferCapacity(100);
}
using Image<Rgba32> image = new(this.configuration, 10, 10);
ArgumentOutOfRangeException ex = Assert.Throws<ArgumentOutOfRangeException>(() => _ = image[x, 3]);
Assert.Equal("x", ex.ParamName);
}
[Theory]
[MemberData(nameof(OutOfRangeData))]
public void Set_OutOfRangeX(bool enforceDisco, int x)
{
if (enforceDisco)
{
this.LimitBufferCapacity(100);
}
using Image<Rgba32> image = new(this.configuration, 10, 10);
ArgumentOutOfRangeException ex = Assert.Throws<ArgumentOutOfRangeException>(() => image[x, 3] = default);
Assert.Equal("x", ex.ParamName);
}
[Theory]
[MemberData(nameof(OutOfRangeData))]
public void Set_OutOfRangeY(bool enforceDisco, int y)
{
if (enforceDisco)
{
this.LimitBufferCapacity(100);
}
using Image<Rgba32> image = new(this.configuration, 10, 10);
ArgumentOutOfRangeException ex = Assert.Throws<ArgumentOutOfRangeException>(() => image[3, y] = default);
Assert.Equal("y", ex.ParamName);
}
[Theory]
[InlineData(false, false)]
[InlineData(false, true)]
[InlineData(true, false)]
[InlineData(true, true)]
public void CopyPixelDataTo_Success(bool disco, bool byteSpan)
{
if (disco)
{
this.LimitBufferCapacity(20);
}
using Image<La16> image = new(this.configuration, 10, 10);
if (disco)
{
Assert.True(image.GetPixelMemoryGroup().Count > 1);
}
byte[] expected = TestUtils.FillImageWithRandomBytes(image);
Span<byte> actual = new byte[expected.Length];
if (byteSpan)
{
image.CopyPixelDataTo(actual);
}
else
{
Span<La16> destination = MemoryMarshal.Cast<byte, La16>(actual);
image.CopyPixelDataTo(destination);
}
Assert.True(expected.AsSpan().SequenceEqual(actual));
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public void CopyPixelDataTo_DestinationTooShort_Throws(bool byteSpan)
{
using Image<La16> image = new(this.configuration, 10, 10);
Assert.ThrowsAny<ArgumentOutOfRangeException>(() =>
{
if (byteSpan)
{
image.CopyPixelDataTo(new byte[199]);
}
else
{
image.CopyPixelDataTo(new La16[99]);
}
});
}
}
| Indexer |
csharp | icsharpcode__SharpZipLib | src/ICSharpCode.SharpZipLib/Zip/Compression/Streams/StreamManipulator.cs | {
"start": 780,
"end": 7910
} | public class ____
{
/// <summary>
/// Get the next sequence of bits but don't increase input pointer. bitCount must be
/// less or equal 16 and if this call succeeds, you must drop
/// at least n - 8 bits in the next call.
/// </summary>
/// <param name="bitCount">The number of bits to peek.</param>
/// <returns>
/// the value of the bits, or -1 if not enough bits available. */
/// </returns>
public int PeekBits(int bitCount)
{
if (bitsInBuffer_ < bitCount)
{
if (windowStart_ == windowEnd_)
{
return -1; // ok
}
buffer_ |= (uint)((window_[windowStart_++] & 0xff |
(window_[windowStart_++] & 0xff) << 8) << bitsInBuffer_);
bitsInBuffer_ += 16;
}
return (int)(buffer_ & ((1 << bitCount) - 1));
}
/// <summary>
/// Tries to grab the next <paramref name="bitCount"/> bits from the input and
/// sets <paramref name="output"/> to the value, adding <paramref name="outputOffset"/>.
/// </summary>
/// <returns>true if enough bits could be read, otherwise false</returns>
public bool TryGetBits(int bitCount, ref int output, int outputOffset = 0)
{
var bits = PeekBits(bitCount);
if (bits < 0)
{
return false;
}
output = bits + outputOffset;
DropBits(bitCount);
return true;
}
/// <summary>
/// Tries to grab the next <paramref name="bitCount"/> bits from the input and
/// sets <paramref name="index"/> of <paramref name="array"/> to the value.
/// </summary>
/// <returns>true if enough bits could be read, otherwise false</returns>
public bool TryGetBits(int bitCount, ref byte[] array, int index)
{
var bits = PeekBits(bitCount);
if (bits < 0)
{
return false;
}
array[index] = (byte)bits;
DropBits(bitCount);
return true;
}
/// <summary>
/// Drops the next n bits from the input. You should have called PeekBits
/// with a bigger or equal n before, to make sure that enough bits are in
/// the bit buffer.
/// </summary>
/// <param name="bitCount">The number of bits to drop.</param>
public void DropBits(int bitCount)
{
buffer_ >>= bitCount;
bitsInBuffer_ -= bitCount;
}
/// <summary>
/// Gets the next n bits and increases input pointer. This is equivalent
/// to <see cref="PeekBits"/> followed by <see cref="DropBits"/>, except for correct error handling.
/// </summary>
/// <param name="bitCount">The number of bits to retrieve.</param>
/// <returns>
/// the value of the bits, or -1 if not enough bits available.
/// </returns>
public int GetBits(int bitCount)
{
int bits = PeekBits(bitCount);
if (bits >= 0)
{
DropBits(bitCount);
}
return bits;
}
/// <summary>
/// Gets the number of bits available in the bit buffer. This must be
/// only called when a previous PeekBits() returned -1.
/// </summary>
/// <returns>
/// the number of bits available.
/// </returns>
public int AvailableBits
{
get
{
return bitsInBuffer_;
}
}
/// <summary>
/// Gets the number of bytes available.
/// </summary>
/// <returns>
/// The number of bytes available.
/// </returns>
public int AvailableBytes
{
get
{
return windowEnd_ - windowStart_ + (bitsInBuffer_ >> 3);
}
}
/// <summary>
/// Skips to the next byte boundary.
/// </summary>
public void SkipToByteBoundary()
{
buffer_ >>= (bitsInBuffer_ & 7);
bitsInBuffer_ &= ~7;
}
/// <summary>
/// Returns true when SetInput can be called
/// </summary>
public bool IsNeedingInput
{
get
{
return windowStart_ == windowEnd_;
}
}
/// <summary>
/// Copies bytes from input buffer to output buffer starting
/// at output[offset]. You have to make sure, that the buffer is
/// byte aligned. If not enough bytes are available, copies fewer
/// bytes.
/// </summary>
/// <param name="output">
/// The buffer to copy bytes to.
/// </param>
/// <param name="offset">
/// The offset in the buffer at which copying starts
/// </param>
/// <param name="length">
/// The length to copy, 0 is allowed.
/// </param>
/// <returns>
/// The number of bytes copied, 0 if no bytes were available.
/// </returns>
/// <exception cref="ArgumentOutOfRangeException">
/// Length is less than zero
/// </exception>
/// <exception cref="InvalidOperationException">
/// Bit buffer isnt byte aligned
/// </exception>
public int CopyBytes(byte[] output, int offset, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if ((bitsInBuffer_ & 7) != 0)
{
// bits_in_buffer may only be 0 or a multiple of 8
throw new InvalidOperationException("Bit buffer is not byte aligned!");
}
int count = 0;
while ((bitsInBuffer_ > 0) && (length > 0))
{
output[offset++] = (byte)buffer_;
buffer_ >>= 8;
bitsInBuffer_ -= 8;
length--;
count++;
}
if (length == 0)
{
return count;
}
int avail = windowEnd_ - windowStart_;
if (length > avail)
{
length = avail;
}
System.Array.Copy(window_, windowStart_, output, offset, length);
windowStart_ += length;
if (((windowStart_ - windowEnd_) & 1) != 0)
{
// We always want an even number of bytes in input, see peekBits
buffer_ = (uint)(window_[windowStart_++] & 0xff);
bitsInBuffer_ = 8;
}
return count + length;
}
/// <summary>
/// Resets state and empties internal buffers
/// </summary>
public void Reset()
{
buffer_ = 0;
windowStart_ = windowEnd_ = bitsInBuffer_ = 0;
}
/// <summary>
/// Add more input for consumption.
/// Only call when IsNeedingInput returns true
/// </summary>
/// <param name="buffer">data to be input</param>
/// <param name="offset">offset of first byte of input</param>
/// <param name="count">number of bytes of input to add.</param>
public void SetInput(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (offset < 0)
{
throw new ArgumentOutOfRangeException(nameof(offset), "Cannot be negative");
}
if (count < 0)
{
throw new ArgumentOutOfRangeException(nameof(count), "Cannot be negative");
}
if (windowStart_ < windowEnd_)
{
throw new InvalidOperationException("Old input was not completely processed");
}
int end = offset + count;
// We want to throw an ArrayIndexOutOfBoundsException early.
// Note the check also handles integer wrap around.
if ((offset > end) || (end > buffer.Length))
{
throw new ArgumentOutOfRangeException(nameof(count));
}
if ((count & 1) != 0)
{
// We always want an even number of bytes in input, see PeekBits
buffer_ |= (uint)((buffer[offset++] & 0xff) << bitsInBuffer_);
bitsInBuffer_ += 8;
}
window_ = buffer;
windowStart_ = offset;
windowEnd_ = end;
}
#region Instance Fields
private byte[] window_;
private int windowStart_;
private int windowEnd_;
private uint buffer_;
private int bitsInBuffer_;
#endregion Instance Fields
}
}
| StreamManipulator |
csharp | dotnet__maui | src/Compatibility/Material/src/Android/MaterialPickerTextInputLayout.cs | {
"start": 198,
"end": 808
} | public class ____ : MaterialFormsTextInputLayoutBase, IPopupTrigger
{
public bool ShowPopupOnFocus { get; set; }
public MaterialPickerTextInputLayout(Context context) : base(context)
{
}
public MaterialPickerTextInputLayout(Context context, IAttributeSet attrs) : base(context, attrs)
{
}
public MaterialPickerTextInputLayout(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr)
{
}
protected MaterialPickerTextInputLayout(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer)
{
}
}
} | MaterialPickerTextInputLayout |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Input/Internal/IFocusable.cs | {
"start": 228,
"end": 941
} | internal interface ____
{
bool IsFocusable();
int GetTabIndex();
DependencyProperty GetXYFocusDownPropertyIndex();
DependencyProperty GetXYFocusDownNavigationStrategyPropertyIndex();
DependencyProperty GetXYFocusLeftPropertyIndex();
DependencyProperty GetXYFocusLeftNavigationStrategyPropertyIndex();
DependencyProperty GetXYFocusRightPropertyIndex();
DependencyProperty GetXYFocusRightNavigationStrategyPropertyIndex();
DependencyProperty GetXYFocusUpPropertyIndex();
DependencyProperty GetXYFocusUpNavigationStrategyPropertyIndex();
DependencyProperty GetFocusStatePropertyIndex();
void OnGotFocus(RoutedEventArgs args);
void OnLostFocus(RoutedEventArgs args);
}
}
| IFocusable |
csharp | dotnet__aspnetcore | src/Identity/test/Identity.FunctionalTests/Pages/Index.cs | {
"start": 308,
"end": 2724
} | public class ____ : DefaultUIPage
{
private readonly IHtmlAnchorElement _registerLink;
private readonly IHtmlAnchorElement _loginLink;
private readonly IHtmlAnchorElement _manageLink;
public static readonly string Path = "/";
public Index(
HttpClient client,
IHtmlDocument index,
DefaultUIContext context)
: base(client, index, context)
{
if (!Context.UserAuthenticated)
{
_registerLink = HtmlAssert.HasLink("#register", Document);
_loginLink = HtmlAssert.HasLink("#login", Document);
}
else
{
_manageLink = HtmlAssert.HasLink("#manage", Document);
}
}
public static async Task<Index> CreateAsync(HttpClient client, DefaultUIContext context = null)
{
var goToIndex = await client.GetAsync("/");
var index = await ResponseAssert.IsHtmlDocumentAsync(goToIndex);
return new Index(client, index, context ?? new DefaultUIContext());
}
public async Task<Register> ClickRegisterLinkAsync()
{
Assert.False(Context.UserAuthenticated);
var goToRegister = await Client.GetAsync(_registerLink.Href);
var register = await ResponseAssert.IsHtmlDocumentAsync(goToRegister);
return new Register(Client, register, Context);
}
public async Task<Login> ClickLoginLinkAsync()
{
Assert.False(Context.UserAuthenticated);
var goToLogin = await Client.GetAsync(_loginLink.Href);
var login = await ResponseAssert.IsHtmlDocumentAsync(goToLogin);
return new Login(Client, login, Context);
}
internal async Task<Account.Manage.Index> ClickManageLinkAsync()
{
Assert.True(Context.UserAuthenticated);
var goToManage = await Client.GetAsync(_manageLink.Href);
var manage = await ResponseAssert.IsHtmlDocumentAsync(goToManage);
return new Account.Manage.Index(Client, manage, Context);
}
internal async Task<Account.Manage.Index> ClickManageLinkWithExternalLoginAsync()
{
Assert.True(Context.UserAuthenticated);
var goToManage = await Client.GetAsync(_manageLink.Href);
var manage = await ResponseAssert.IsHtmlDocumentAsync(goToManage);
return new Account.Manage.Index(Client, manage, Context
.WithSocialLoginEnabled()
.WithSocialLoginProvider());
}
}
| Index |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/Issues/Gh4319.xaml.cs | {
"start": 255,
"end": 851
} | class ____
{
MockDeviceInfo mockDeviceInfo;
[SetUp] public void Setup() => DeviceInfo.SetCurrent(mockDeviceInfo = new MockDeviceInfo());
[TearDown] public void TearDown() => DeviceInfo.SetCurrent(null);
[Test]
public void OnPlatformMarkupAndNamedSizes([Values] XamlInflator inflator)
{
mockDeviceInfo.Platform = DevicePlatform.iOS;
var layout = new Gh4319(inflator);
Assert.That(layout.label.FontSize, Is.EqualTo(4d));
mockDeviceInfo.Platform = DevicePlatform.Android;
layout = new Gh4319(inflator);
Assert.That(layout.label.FontSize, Is.EqualTo(8d));
}
}
} | Tests |
csharp | duplicati__duplicati | Duplicati/Library/Interface/IPowerModeProvider.cs | {
"start": 1331,
"end": 1666
} | public interface ____ : IDisposable
{
/// <summary>
/// Event that is triggered when the system is resuming from suspend
/// </summary>
Action? OnResume { get; set; }
/// <summary>
/// Event that is triggered when the system is suspending
/// </summary>
Action? OnSuspend { get; set; }
}
| IPowerModeProvider |
csharp | dotnet__maui | src/TestUtils/src/Microsoft.Maui.IntegrationTests/SampleTests.cs | {
"start": 1559,
"end": 1666
} | public class ____
{
public SolutionElement solution { get; set; } = new SolutionElement();
}
| SolutionFile |
csharp | pythonnet__pythonnet | tests/domain_tests/TestRunner.cs | {
"start": 23492,
"end": 24188
} | public class ____ { }
}",
PythonCode = @"
import clr
import sys
clr.AddReference('DomainTests')
import TestNamespace
def before_reload():
sys.my_cls = TestNamespace.Before
def after_reload():
try:
bar = sys.my_cls()
except TypeError:
print('Caught expected exception')
else:
raise AssertionError('Failed to throw exception')
",
},
new TestCase
{
Name = "out_to_ref_param",
DotNetBefore = @"
namespace TestNamespace
{
[System.Serializable]
| After |
csharp | domaindrivendev__Swashbuckle.AspNetCore | test/Swashbuckle.AspNetCore.TestSupport/Fixtures/ContainingType.cs | {
"start": 48,
"end": 129
} | public class ____
{
public NestedType Property1 { get; set; }
| ContainingType |
csharp | icsharpcode__ILSpy | ICSharpCode.BamlDecompiler/Baml/BamlRecords.cs | {
"start": 28690,
"end": 29036
} | internal class ____ : BamlRecord
{
public override BamlRecordType Type => BamlRecordType.LinePosition;
public uint LinePosition { get; set; }
public override void Read(BamlBinaryReader reader) => LinePosition = reader.ReadUInt32();
public override void Write(BamlBinaryWriter writer) => writer.Write(LinePosition);
}
| LinePositionRecord |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.ZeroCore.EntityFramework/Zero/EntityFramework/AbpZeroDbMigrator.cs | {
"start": 275,
"end": 2604
} | public abstract class ____<TDbContext, TConfiguration> : IAbpZeroDbMigrator, ITransientDependency
where TDbContext : DbContext
where TConfiguration : DbMigrationsConfiguration<TDbContext>, IMultiTenantSeed, new()
{
private readonly IUnitOfWorkManager _unitOfWorkManager;
private readonly IDbPerTenantConnectionStringResolver _connectionStringResolver;
private readonly IIocResolver _iocResolver;
protected AbpZeroDbMigrator(
IUnitOfWorkManager unitOfWorkManager,
IDbPerTenantConnectionStringResolver connectionStringResolver,
IIocResolver iocResolver)
{
_unitOfWorkManager = unitOfWorkManager;
_connectionStringResolver = connectionStringResolver;
_iocResolver = iocResolver;
}
public virtual void CreateOrMigrateForHost()
{
CreateOrMigrate(null);
}
public virtual void CreateOrMigrateForTenant(AbpTenantBase tenant)
{
if (tenant.ConnectionString.IsNullOrEmpty())
{
return;
}
CreateOrMigrate(tenant);
}
protected virtual void CreateOrMigrate(AbpTenantBase tenant)
{
var args = new DbPerTenantConnectionStringResolveArgs(
tenant == null ? (int?)null : (int?)tenant.Id,
tenant == null ? MultiTenancySides.Host : MultiTenancySides.Tenant
);
args["DbContextType"] = typeof(TDbContext);
args["DbContextConcreteType"] = typeof(TDbContext);
var nameOrConnectionString = ConnectionStringHelper.GetConnectionString(
_connectionStringResolver.GetNameOrConnectionString(args)
);
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.Suppress))
{
using (var dbContext = _iocResolver.ResolveAsDisposable<TDbContext>(new { nameOrConnectionString = nameOrConnectionString }))
{
var dbInitializer = new MigrateDatabaseToLatestVersion<TDbContext, TConfiguration>(
true,
new TConfiguration
{
Tenant = tenant
});
dbInitializer.InitializeDatabase(dbContext.Object);
_unitOfWorkManager.Current.SaveChanges();
uow.Complete();
}
}
}
} | AbpZeroDbMigrator |
csharp | dotnet__aspire | src/Tools/ConfigurationSchemaGenerator/RuntimeSource/SourceGenerators/CSharpSyntaxUtilities.cs | {
"start": 277,
"end": 2366
} | internal static class ____
{
// Standard format for double and single on non-inbox frameworks to ensure value is round-trippable.
public const string DoubleFormatString = "G17";
public const string SingleFormatString = "G9";
// Format a literal in C# format -- works around https://github.com/dotnet/roslyn/issues/58705
public static string FormatLiteral(object? value, TypeRef type)
{
if (value == null)
{
return $"default({type.FullyQualifiedName})";
}
switch (value)
{
case string @string:
return SymbolDisplay.FormatLiteral(@string, quote: true);
case char @char:
return SymbolDisplay.FormatLiteral(@char, quote: true);
case double.NegativeInfinity:
return "double.NegativeInfinity";
case double.PositiveInfinity:
return "double.PositiveInfinity";
case double.NaN:
return "double.NaN";
case double @double:
return $"{@double.ToString(DoubleFormatString, CultureInfo.InvariantCulture)}D";
case float.NegativeInfinity:
return "float.NegativeInfinity";
case float.PositiveInfinity:
return "float.PositiveInfinity";
case float.NaN:
return "float.NaN";
case float @float:
return $"{@float.ToString(SingleFormatString, CultureInfo.InvariantCulture)}F";
case decimal @decimal:
// we do not need to specify a format string for decimal as it's default is round-trippable on all frameworks.
return $"{@decimal.ToString(CultureInfo.InvariantCulture)}M";
case bool @bool:
return @bool ? "true" : "false";
default:
// Assume this is a number.
return FormatNumber();
}
string FormatNumber() => $"({type.FullyQualifiedName})({Convert.ToString(value, CultureInfo.InvariantCulture)})";
}
}
| CSharpSyntaxUtilities |
csharp | getsentry__sentry-dotnet | test/Sentry.Serilog.Tests/SerilogAspNetSentrySdkTestFixture.cs | {
"start": 91,
"end": 1285
} | public class ____ : AspNetSentrySdkTestFixture
{
protected List<SentryEvent> Events;
protected List<SentryLog> Logs;
protected bool EnableLogs { get; set; }
protected override void ConfigureBuilder(WebHostBuilder builder)
{
Events = new List<SentryEvent>();
Logs = new List<SentryLog>();
Configure = options =>
{
options.SetBeforeSend((@event, _) => { Events.Add(@event); return @event; });
options.EnableLogs = EnableLogs;
options.SetBeforeSendLog(log => { Logs.Add(log); return log; });
};
ConfigureApp = app =>
{
app.UseExceptionHandler(new ExceptionHandlerOptions
{
AllowStatusCode404Response = true,
ExceptionHandlingPath = "/error"
});
};
builder.ConfigureLogging(loggingBuilder =>
{
var logger = new LoggerConfiguration()
.WriteTo.Sentry(ValidDsn, enableLogs: EnableLogs)
.CreateLogger();
loggingBuilder.AddSerilog(logger);
});
base.ConfigureBuilder(builder);
}
}
#endif
| SerilogAspNetSentrySdkTestFixture |
csharp | MassTransit__MassTransit | tests/MassTransit.RabbitMqTransport.Tests/PublishTopology_Specs.cs | {
"start": 1135,
"end": 1619
} | public class ____ :
RabbitMqTestFixture
{
[Test]
[Explicit]
public void Should_create_the_exchanges()
{
}
protected override void ConfigureRabbitMqBus(IRabbitMqBusFactoryConfigurator configurator)
{
configurator.DeployPublishTopology = true;
configurator.AddPublishMessageTypesFromNamespaceContaining<OrderSubmitted>();
}
}
}
| Configuring_the_publish_topology_at_startup_by_namespace |
csharp | dotnetcore__FreeSql | FreeSql.Tests/FreeSql.Tests/SqlServer/SqlServerCodeFirstTest.cs | {
"start": 7464,
"end": 9060
} | class ____
{
public Guid id { get; set; }
public string name { get; set; }
[Column(IsVersion = true)]
public int version { get; set; }
}
[Fact]
public void VersionBytes()
{
bool LocalEqualsVersion(byte[] v1, byte[] v2)
{
if (v1.Length == v2.Length)
{
for (var y = 0; y < v2.Length; y++)
if (v1[y] != v2[y]) return false;
return true;
}
return false;
}
var fsql = g.sqlserver;
fsql.Delete<VersionBytes01>().Where("1=1").ExecuteAffrows();
var item = new VersionBytes01 { name = "name01" };
fsql.Insert(item).ExecuteAffrows();
var itemVersion = item.version;
Assert.NotNull(itemVersion);
item = fsql.Select<VersionBytes01>().Where(a => a.id == item.id).First();
Assert.NotNull(item);
Assert.True(LocalEqualsVersion(itemVersion, item.version));
item.name = "name02";
var sql = fsql.Update<VersionBytes01>().SetSource(item).ToSql();
Assert.Equal(1, fsql.Update<VersionBytes01>().SetSource(item).ExecuteAffrows());
item.name = "name03";
Assert.Equal(1, fsql.Update<VersionBytes01>().SetSource(item).ExecuteAffrows());
Assert.Equal(1, fsql.Update<VersionBytes01>().Set(a => a.name, "name04").Where(a => a.id == item.id).ExecuteAffrows());
}
| VersionInt01 |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 282277,
"end": 282497
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1297 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1299> ChildEntities { get; set; }
}
| RelatedEntity1298 |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/Topology/Configuration/TopologyPublishPipeSpecificationObserver.cs | {
"start": 43,
"end": 781
} | public class ____ :
IPublishPipeSpecificationObserver
{
readonly IPublishTopology _topology;
public TopologyPublishPipeSpecificationObserver(IPublishTopology topology)
{
_topology = topology;
}
void IPublishPipeSpecificationObserver.MessageSpecificationCreated<T>(IMessagePublishPipeSpecification<T> specification)
{
IMessagePublishTopology<T> messagePublishTopology = _topology.GetMessageTopology<T>();
var topologySpecification = new MessagePublishTopologyPipeSpecification<T>(messagePublishTopology);
specification.AddParentMessageSpecification(topologySpecification);
}
}
}
| TopologyPublishPipeSpecificationObserver |
csharp | ShareX__ShareX | ShareX.UploadersLib/TextUploaders/Pastebin.cs | {
"start": 2054,
"end": 11724
} | public sealed class ____ : TextUploader
{
private string APIKey;
public PastebinSettings Settings { get; private set; }
public Pastebin(string apiKey)
{
APIKey = apiKey;
Settings = new PastebinSettings();
}
public Pastebin(string apiKey, PastebinSettings settings)
{
APIKey = apiKey;
Settings = settings;
}
public bool Login()
{
if (!string.IsNullOrEmpty(Settings.Username) && !string.IsNullOrEmpty(Settings.Password))
{
Dictionary<string, string> loginArgs = new Dictionary<string, string>();
loginArgs.Add("api_dev_key", APIKey);
loginArgs.Add("api_user_name", Settings.Username);
loginArgs.Add("api_user_password", Settings.Password);
string loginResponse = SendRequestMultiPart("https://pastebin.com/api/api_login.php", loginArgs);
if (!string.IsNullOrEmpty(loginResponse) && !loginResponse.StartsWith("Bad API request"))
{
Settings.UserKey = loginResponse;
return true;
}
}
Settings.UserKey = null;
Errors.Add("Pastebin login failed.");
return false;
}
public override UploadResult UploadText(string text, string fileName)
{
UploadResult ur = new UploadResult();
if (!string.IsNullOrEmpty(text) && Settings != null)
{
Dictionary<string, string> args = new Dictionary<string, string>();
args.Add("api_dev_key", APIKey); // which is your unique API Developers Key
args.Add("api_option", "paste"); // set as 'paste', this will indicate you want to create a new paste
args.Add("api_paste_code", text); // this is the text that will be written inside your paste
// Optional args
args.Add("api_paste_name", Settings.Title); // this will be the name / title of your paste
args.Add("api_paste_format", Settings.TextFormat); // this will be the syntax highlighting value
args.Add("api_paste_private", GetPrivacy(Settings.Exposure)); // this makes a paste public or private, public = 0, private = 1
args.Add("api_paste_expire_date", GetExpiration(Settings.Expiration)); // this sets the expiration date of your paste
if (!string.IsNullOrEmpty(Settings.UserKey))
{
args.Add("api_user_key", Settings.UserKey); // this paramater is part of the login system
}
ur.Response = SendRequestMultiPart("https://pastebin.com/api/api_post.php", args);
if (URLHelpers.IsValidURL(ur.Response))
{
if (Settings.RawURL)
{
string id = URLHelpers.GetFileName(ur.Response);
ur.URL = "https://pastebin.com/raw/" + id;
}
else
{
ur.URL = ur.Response;
}
}
else
{
Errors.Add(ur.Response);
}
}
return ur;
}
private string GetPrivacy(PastebinPrivacy privacy)
{
switch (privacy)
{
case PastebinPrivacy.Public:
return "0";
default:
case PastebinPrivacy.Unlisted:
return "1";
case PastebinPrivacy.Private:
return "2";
}
}
private string GetExpiration(PastebinExpiration expiration)
{
switch (expiration)
{
default:
case PastebinExpiration.N:
return "N";
case PastebinExpiration.M10:
return "10M";
case PastebinExpiration.H1:
return "1H";
case PastebinExpiration.D1:
return "1D";
case PastebinExpiration.W1:
return "1W";
case PastebinExpiration.W2:
return "2W";
case PastebinExpiration.M1:
return "1M";
}
}
public static List<PastebinSyntaxInfo> GetSyntaxList()
{
string syntaxList = @"4cs = 4CS
6502acme = 6502 ACME Cross Assembler
6502kickass = 6502 Kick Assembler
6502tasm = 6502 TASM/64TASS
abap = ABAP
actionscript = ActionScript
actionscript3 = ActionScript 3
ada = Ada
aimms = AIMMS
algol68 = ALGOL 68
apache = Apache Log
applescript = AppleScript
apt_sources = APT Sources
arm = ARM
asm = ASM (NASM)
asp = ASP
asymptote = Asymptote
autoconf = autoconf
autohotkey = Autohotkey
autoit = AutoIt
avisynth = Avisynth
awk = Awk
bascomavr = BASCOM AVR
bash = Bash
basic4gl = Basic4GL
dos = Batch
bibtex = BibTeX
blitzbasic = Blitz Basic
b3d = Blitz3D
bmx = BlitzMax
bnf = BNF
boo = BOO
bf = BrainFuck
c = C
c_winapi = C (WinAPI)
c_mac = C for Macs
cil = C Intermediate Language
csharp = C#
cpp = C++
cpp-winapi = C++ (WinAPI)
cpp-qt = C++ (with Qt extensions)
c_loadrunner = C: Loadrunner
caddcl = CAD DCL
cadlisp = CAD Lisp
ceylon = Ceylon
cfdg = CFDG
chaiscript = ChaiScript
chapel = Chapel
clojure = Clojure
klonec = Clone C
klonecpp = Clone C++
cmake = CMake
cobol = COBOL
coffeescript = CoffeeScript
cfm = ColdFusion
css = CSS
cuesheet = Cuesheet
d = D
dart = Dart
dcl = DCL
dcpu16 = DCPU-16
dcs = DCS
delphi = Delphi
oxygene = Delphi Prism (Oxygene)
diff = Diff
div = DIV
dot = DOT
e = E
ezt = Easytrieve
ecmascript = ECMAScript
eiffel = Eiffel
email = Email
epc = EPC
erlang = Erlang
euphoria = Euphoria
fsharp = F#
falcon = Falcon
filemaker = Filemaker
fo = FO Language
f1 = Formula One
fortran = Fortran
freebasic = FreeBasic
freeswitch = FreeSWITCH
gambas = GAMBAS
gml = Game Maker
gdb = GDB
genero = Genero
genie = Genie
gettext = GetText
go = Go
groovy = Groovy
gwbasic = GwBasic
haskell = Haskell
haxe = Haxe
hicest = HicEst
hq9plus = HQ9 Plus
html4strict = HTML
html5 = HTML 5
icon = Icon
idl = IDL
ini = INI file
inno = Inno Script
intercal = INTERCAL
io = IO
ispfpanel = ISPF Panel Definition
j = J
java = Java
java5 = Java 5
javascript = JavaScript
jcl = JCL
jquery = jQuery
json = JSON
julia = Julia
kixtart = KiXtart
kotlin = Kotlin
latex = Latex
ldif = LDIF
lb = Liberty BASIC
lsl2 = Linden Scripting
lisp = Lisp
llvm = LLVM
locobasic = Loco Basic
logtalk = Logtalk
lolcode = LOL Code
lotusformulas = Lotus Formulas
lotusscript = Lotus Script
lscript = LScript
lua = Lua
m68k = M68000 Assembler
magiksf = MagikSF
make = Make
mapbasic = MapBasic
markdown = Markdown
matlab = MatLab
mirc = mIRC
mmix = MIX Assembler
modula2 = Modula 2
modula3 = Modula 3
68000devpac = Motorola 68000 HiSoft Dev
mpasm = MPASM
mxml = MXML
mysql = MySQL
nagios = Nagios
netrexx = NetRexx
newlisp = newLISP
nginx = Nginx
nimrod = Nimrod
nsis = NullSoft Installer
oberon2 = Oberon 2
objeck = Objeck Programming Langua
objc = Objective C
ocaml-brief = OCalm Brief
ocaml = OCaml
octave = Octave
oorexx = Open Object Rexx
pf = OpenBSD PACKET FILTER
glsl = OpenGL Shading
oobas = Openoffice BASIC
oracle11 = Oracle 11
oracle8 = Oracle 8
oz = Oz
parasail = ParaSail
parigp = PARI/GP
pascal = Pascal
pawn = Pawn
pcre = PCRE
per = Per
perl = Perl
perl6 = Perl 6
php = PHP
php-brief = PHP Brief
pic16 = Pic 16
pike = Pike
pixelbender = Pixel Bender
pli = PL/I
plsql = PL/SQL
postgresql = PostgreSQL
postscript = PostScript
povray = POV-Ray
powershell = Power Shell
powerbuilder = PowerBuilder
proftpd = ProFTPd
progress = Progress
prolog = Prolog
properties = Properties
providex = ProvideX
puppet = Puppet
purebasic = PureBasic
pycon = PyCon
python = Python
pys60 = Python for S60
q = q/kdb+
qbasic = QBasic
qml = QML
rsplus = R
racket = Racket
rails = Rails
rbs = RBScript
rebol = REBOL
reg = REG
rexx = Rexx
robots = Robots
rpmspec = RPM Spec
ruby = Ruby
gnuplot = Ruby Gnuplot
rust = Rust
sas = SAS
scala = Scala
scheme = Scheme
scilab = Scilab
scl = SCL
sdlbasic = SdlBasic
smalltalk = Smalltalk
smarty = Smarty
spark = SPARK
sparql = SPARQL
sqf = SQF
sql = SQL
standardml = StandardML
stonescript = StoneScript
sclang = SuperCollider
swift = Swift
systemverilog = SystemVerilog
tsql = T-SQL
tcl = TCL
teraterm = Tera Term
thinbasic = thinBasic
typoscript = TypoScript
unicon = Unicon
uscript = UnrealScript
upc = UPC
urbi = Urbi
vala = Vala
vbnet = VB.NET
vbscript = VBScript
vedit = Vedit
verilog = VeriLog
vhdl = VHDL
vim = VIM
visualprolog = Visual Pro Log
vb = VisualBasic
visualfoxpro = VisualFoxPro
whitespace = WhiteSpace
whois = WHOIS
winbatch = Winbatch
xbasic = XBasic
xml = XML
xorg_conf = Xorg Config
xpp = XPP
yaml = YAML
z80 = Z80 Assembler
zxbasic = ZXBasic";
List<PastebinSyntaxInfo> result = new List<PastebinSyntaxInfo>();
result.Add(new PastebinSyntaxInfo("None", "text"));
foreach (string line in syntaxList.Lines().Select(x => x.Trim()))
{
int index = line.IndexOf('=');
if (index > 0)
{
PastebinSyntaxInfo syntaxInfo = new PastebinSyntaxInfo();
syntaxInfo.Value = line.Remove(index).Trim();
syntaxInfo.Name = line.Substring(index + 1).Trim();
result.Add(syntaxInfo);
}
}
return result;
}
}
| Pastebin |
csharp | dotnet__aspire | src/Aspire.Hosting.Kubernetes/Resources/HostAliasV1.cs | {
"start": 441,
"end": 1130
} | public sealed class ____
{
/// <summary>
/// Gets or sets the IP address associated with the HostAlias in the Kubernetes resource definition.
/// </summary>
/// <remarks>
/// This property represents the IP address that will be mapped to the specified hostnames in the resource.
/// </remarks>
[YamlMember(Alias = "ip")]
public string Ip { get; set; } = null!;
/// <summary>
/// Represents a collection of hostnames associated with a specific IP address.
/// This property contains a list of hostnames used for defining aliases.
/// </summary>
[YamlMember(Alias = "hostnames")]
public List<string> Hostnames { get; } = [];
}
| HostAliasV1 |
csharp | EventStore__EventStore | src/KurrentDB.Projections.Core/Services/Management/ManagedProjectionStates/ManagedProjectionStateBase.cs | {
"start": 309,
"end": 1256
} | internal abstract class ____ {
protected readonly ManagedProjection _managedProjection;
protected ManagedProjectionStateBase(ManagedProjection managedProjection) {
_managedProjection = managedProjection;
}
private void Unexpected(string message) {
_managedProjection.Fault(message + " in " + this.GetType().Name);
}
protected void SetFaulted(string reason) {
_managedProjection.Fault(reason);
}
protected internal virtual void Started() {
Unexpected("Unexpected 'STARTED' message");
}
protected internal virtual void Stopped(CoreProjectionStatusMessage.Stopped message) {
Unexpected("Unexpected 'STOPPED' message");
}
protected internal virtual void Faulted(CoreProjectionStatusMessage.Faulted message) {
Unexpected("Unexpected 'FAULTED' message");
}
protected internal virtual void Prepared(CoreProjectionStatusMessage.Prepared message) {
Unexpected("Unexpected 'PREPARED' message");
}
}
| ManagedProjectionStateBase |
csharp | FluentValidation__FluentValidation | src/FluentValidation/Resources/Languages/KhmerLanguage.cs | {
"start": 811,
"end": 3725
} | internal class ____ {
public const string Culture = "km";
public static string GetTranslation(string key) => key switch {
"EmailValidator" => "'{PropertyName}'មិនមែនជាអ៊ីមែលត្រឹមត្រូវទេ។",
"GreaterThanOrEqualValidator" => "'{PropertyName}'ត្រូវតែធំជាង ឬស្មើ'{ComparisonValue}។'",
"GreaterThanValidator" => "'{PropertyName}'ត្រូវតែធំជាង'{ComparisonValue}'។",
"LengthValidator" => "'{PropertyName}'ត្រូវតែនៅចន្លោះពី{MinLength}ទៅ{MaxLength}តួអក្សរ។ អ្នកបានបញ្ចូល{TotalLength}តួអក្សរ។",
"MinimumLengthValidator" => "ប្រវែង'{PropertyName}'ត្រូវតែមានយ៉ាងហោចណាស់{MinLength}តួអក្សរ។ អ្នកបានបញ្ចូល{TotalLength}តួអក្សរ។",
"MaximumLengthValidator" => "ប្រវែង'{PropertyName}'ត្រូវតែមាន{MaxLength}តួអក្សរ ឬតិចជាងនេះ។ អ្នកបានបញ្ចូល{TotalLength}តួអក្សរ។",
"LessThanOrEqualValidator" => "'{PropertyName}'ត្រូវតែតិចជាង ឬស្មើនឹង'{ComparisonValue}'។",
"LessThanValidator" => "'{PropertyName}'ត្រូវតែតិចជាង'{ComparisonValue}'។",
"NotEmptyValidator" => "'{PropertyName}'មិនត្រូវទទេទេ។",
"NotEqualValidator" => "'{PropertyName}'មិនត្រូវស្មើនឹង'{ComparisonValue}'ទេ។",
"NotNullValidator" => "'{PropertyName}'មិនត្រូវទទេទេ។",
"PredicateValidator" => "លក្ខខណ្ឌដែលបានបញ្ជាក់មិនត្រូវបានបំពេញសម្រាប់'{PropertyName}'ទេ។",
"AsyncPredicateValidator" => "លក្ខខណ្ឌដែលបានបញ្ជាក់មិនត្រូវបានបំពេញសម្រាប់'{PropertyName}'ទេ។",
"RegularExpressionValidator" => "'{PropertyName}'មិនមានទម្រង់ត្រឹមត្រូវទេ។",
"EqualValidator" => "'{PropertyName}'ត្រូវតែស្មើនឹង'{ComparisonValue}'។",
"ExactLengthValidator" => "'{PropertyName}'ត្រូវតែមាន{MaxLength}តួអក្សរ។ អ្នកបានបញ្ចូល{TotalLength}តួអក្សរ។",
"InclusiveBetweenValidator" => "'{PropertyName}'ត្រូវតែស្ថិតនៅចន្លោះ{From}និង{To}។ អ្នកបានបញ្ចូល{PropertyValue}។",
"ExclusiveBetweenValidator" => "'{PropertyName}'ត្រូវតែស្ថិតនៅចន្លោះ{From}និង {To}(ដាច់ខាត)។ អ្នកបានបញ្ចូល{PropertyValue}។",
"CreditCardValidator" => "'{PropertyName}'មិនមែនជាលេខកាតឥណទានត្រឹមត្រូវទេ។",
"ScalePrecisionValidator" => "'{PropertyName}'មិនត្រូវលើសពី{ExpectedPrecision}ខ្ទង់ជាសរុប ដោយមានការអនុញ្ញាតសម្រាប់ទសភាគ{ExpectedScale}។ ទសភាគ{Digits}ខ្ទង់និង {ActualScale}ត្រូវបានរកឃើញ។",
"EmptyValidator" => "លក្ខខណ្ឌដែលបានបញ្ជាក់មិនត្រូវបានបំពេញសម្រាប់'{PropertyName}'ទេ។",
"NullValidator" => "លក្ខខណ្ឌដែលបានបញ្ជាក់មិនត្រូវបានបំពេញសម្រាប់'{PropertyName}'ទេ។",
"EnumValidator" => "'{PropertyName}'មានជួរតម្លៃដែលមិនរួមបញ្ចូល'{PropertyValue}'។",
// Additional fallback messages used by clientside validation integration.
"Length_Simple" => "'{PropertyName}'ត្រូវតែស្ថិតនៅចន្លោះតួអក្សរ{MinLength}ទៅ {MaxLength}តួអក្សរ។",
"MinimumLength_Simple" => "ប្រវែង'{PropertyName}'ត្រូវតែមានយ៉ាងហោចណាស់{MinLength}តួអក្សរ។",
"MaximumLength_Simple" => "ប្រវែង'{PropertyName}'ត្រូវតែមាន{MaxLength}តួអក្សរ ឬតិចជាងនេះ។",
"ExactLength_Simple" => "'{PropertyName}'ត្រូវតែមាន{MaxLength}តួអក្សរ។",
"InclusiveBetween_Simple" => "'{PropertyName}'ត្រូវតែស្ថិតនៅចន្លោះ{From}និង{To}។",
_ => null,
};
}
| KhmerLanguage |
csharp | microsoft__semantic-kernel | dotnet/samples/Concepts/Functions/Arguments.cs | {
"start": 238,
"end": 1598
} | public class ____(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Arguments ========");
Kernel kernel = new();
var textPlugin = kernel.ImportPluginFromType<StaticTextPlugin>();
var arguments = new KernelArguments()
{
["input"] = "Today is: ",
["day"] = DateTimeOffset.Now.ToString("dddd", CultureInfo.CurrentCulture)
};
// ** Different ways of executing functions with arguments **
// Specify and get the value type as generic parameter
string? resultValue = await kernel.InvokeAsync<string>(textPlugin["AppendDay"], arguments);
Console.WriteLine($"string -> {resultValue}");
// If you need to access the result metadata, you can use the non-generic version to get the FunctionResult
FunctionResult functionResult = await kernel.InvokeAsync(textPlugin["AppendDay"], arguments);
var metadata = functionResult.Metadata;
// Specify the type from the FunctionResult
Console.WriteLine($"FunctionResult.GetValue<string>() -> {functionResult.GetValue<string>()}");
// FunctionResult.ToString() automatically converts the result to string
Console.WriteLine($"FunctionResult.ToString() -> {functionResult}");
}
| Arguments |
csharp | dotnet__maui | src/Core/tests/Benchmarks/Benchmarks/PropertyMapperBenchmarker.cs | {
"start": 174,
"end": 1054
} | class ____ : ButtonHandler
{
protected override object CreatePlatformView()
{
return new object();
}
}
readonly Registrar<IView, IViewHandler> _registrar;
readonly IViewHandler _handler;
readonly Button _button;
public PropertyMapperBenchmarker()
{
_button = new Button();
_registrar = new Registrar<IView, IViewHandler>();
_registrar.Register<IButton, TestButtonHandler>();
_handler = _registrar.GetHandler<IButton>();
_handler.SetVirtualView(new Button());
}
[Benchmark]
public void BenchmarkUpdateProperties()
{
var button = new Button();
for (int i = 0; i < 100_000; i++)
{
var handler = _registrar.GetHandler<IButton>();
handler.SetVirtualView(button);
}
}
[Benchmark]
public void BenchmarkUpdateProperty()
{
for (int i = 0; i < 1_000_000; i++)
{
_handler.UpdateValue(nameof(IView.Opacity));
}
}
} | TestButtonHandler |
csharp | SixLabors__ImageSharp | src/ImageSharp/Formats/Jpeg/Components/ColorConverters/JpegColorConverterScalar.cs | {
"start": 152,
"end": 350
} | partial class ____
{
/// <summary>
/// <see cref="JpegColorConverterBase"/> abstract base for implementations
/// based on scalar instructions.
/// </summary>
| JpegColorConverterBase |
csharp | MassTransit__MassTransit | src/MassTransit.Abstractions/IConsumer.cs | {
"start": 189,
"end": 365
} | interface ____ allow access to details surrounding the inbound message, including headers.
/// </summary>
/// <typeparam name="TMessage">The message type</typeparam>
| to |
csharp | JoshClose__CsvHelper | tests/CsvHelper.Tests/TypeConversion/TypeConverterOptionsTests.cs | {
"start": 2593,
"end": 2919
} | private sealed class ____ : ClassMap<Test>
{
public TestMap()
{
Map(m => m.Id);
Map(m => m.Name).TypeConverterOption.NullValues(string.Empty);
}
}
// auto map options have defaults
// map options could be default or custom if set
// global has defaults or custom
// merge global with map
}
}
| TestMap |
csharp | dotnet__maui | src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Issue13126_2.cs | {
"start": 116,
"end": 568
} | public class ____ : _IssuesUITest
{
const string Success = "Success";
public Issue13126_2(TestDevice testDevice) : base(testDevice)
{
}
public override string Issue => "[Bug] Regression: 5.0.0-pre5 often fails to draw dynamically loaded collection view content";
[Test]
[Category(UITestCategories.CollectionView)]
public void CollectionViewShouldSourceShouldResetWhileInvisible()
{
App.WaitForElement(Success);
}
}
} | Issue13126_2 |
csharp | protobuf-net__protobuf-net | src/protobuf-net.Test/NullMaps.cs | {
"start": 25347,
"end": 25597
} | public class ____ : ITestScenario
{
[ProtoMember(4), NullWrappedCollection(AsGroup = true), NullWrappedValue]
public Dictionary<int, Foo?>? Foos { get; set; }
}
| WithNullWrappedGroupCollection_WrappedValues |
csharp | AvaloniaUI__Avalonia | src/Avalonia.Base/Input/TextInput/InputMethodManager.cs | {
"start": 111,
"end": 5387
} | internal class ____
{
private ITextInputMethodImpl? _im;
private IInputElement? _focusedElement;
private Interactive? _visualRoot;
private TextInputMethodClient? _client;
private readonly TransformTrackingHelper _transformTracker = new TransformTrackingHelper();
public TextInputMethodManager()
{
_transformTracker.MatrixChanged += UpdateCursorRect;
InputMethod.IsInputMethodEnabledProperty.Changed.Subscribe(OnIsInputMethodEnabledChanged);
}
private TextInputMethodClient? Client
{
get => _client;
set
{
if(_client == value)
{
return;
}
if (_client != null)
{
_client.CursorRectangleChanged -= OnCursorRectangleChanged;
_client.TextViewVisualChanged -= OnTextViewVisualChanged;
_client.ResetRequested -= OnResetRequested;
_client = null;
_im?.Reset();
}
_client = value;
if (_client != null)
{
_client.CursorRectangleChanged += OnCursorRectangleChanged;
_client.TextViewVisualChanged += OnTextViewVisualChanged;
_client.ResetRequested += OnResetRequested;
PopulateImWithInitialValues();
}
else
{
_im?.SetClient(null);
_transformTracker.SetVisual(null);
}
}
}
void PopulateImWithInitialValues()
{
if (_focusedElement is StyledElement target)
{
_im?.SetOptions(TextInputOptions.FromStyledElement(target));
}
else
{
_im?.SetOptions(TextInputOptions.Default);
}
_transformTracker.SetVisual(_client?.TextViewVisual);
_im?.SetClient(_client);
UpdateCursorRect();
}
private void OnResetRequested(object? sender, EventArgs args)
{
if (_im != null && sender == _client)
{
_im.Reset();
PopulateImWithInitialValues();
}
}
private void OnIsInputMethodEnabledChanged(AvaloniaPropertyChangedEventArgs<bool> obj)
{
if (ReferenceEquals(obj.Sender, _focusedElement))
{
TryFindAndApplyClient();
}
}
private void OnTextViewVisualChanged(object? sender, EventArgs e)
=> _transformTracker.SetVisual(_client?.TextViewVisual);
private void UpdateCursorRect()
{
if (_im == null ||
_client == null ||
_focusedElement is not Visual v ||
v.VisualRoot is not Visual root)
return;
var transform = v.TransformToVisual(root);
if (transform == null)
_im.SetCursorRect(default);
else
_im.SetCursorRect(_client.CursorRectangle.TransformToAABB(transform.Value));
}
private void OnCursorRectangleChanged(object? sender, EventArgs e)
{
if (sender == _client)
UpdateCursorRect();
}
public void SetFocusedElement(IInputElement? element)
{
if(_focusedElement == element)
return;
if (_visualRoot != null)
InputMethod.RemoveTextInputMethodClientRequeryRequestedHandler(_visualRoot,
TextInputMethodClientRequeryRequested);
_focusedElement = element;
_visualRoot = (element as Visual)?.VisualRoot as Interactive;
if (_visualRoot != null)
InputMethod.AddTextInputMethodClientRequeryRequestedHandler(_visualRoot,
TextInputMethodClientRequeryRequested);
var inputMethod = ((element as Visual)?.VisualRoot as ITextInputMethodRoot)?.InputMethod;
if (_im != inputMethod)
{
_im?.SetClient(null);
}
_im = inputMethod;
TryFindAndApplyClient();
}
private void TextInputMethodClientRequeryRequested(object? sender, RoutedEventArgs e)
{
if (_im != null)
TryFindAndApplyClient();
}
private void TryFindAndApplyClient()
{
if (_focusedElement is not InputElement focused ||
_im == null ||
!InputMethod.GetIsInputMethodEnabled(focused))
{
Client = null;
return;
}
var clientQuery = new TextInputMethodClientRequestedEventArgs
{
RoutedEvent = InputElement.TextInputMethodClientRequestedEvent
};
_focusedElement.RaiseEvent(clientQuery);
Client = clientQuery.Client;
}
}
}
| TextInputMethodManager |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Adapters/src/Adapters.OpenApi.Core/Execution/DynamicEndpointMiddleware.cs | {
"start": 304,
"end": 10665
} | internal sealed class ____(
string schemaName,
OpenApiEndpointDescriptor endpointDescriptor)
{
// TODO: This needs to raise diagnostic events (httprequest, startsingle and httprequesterror
public async Task InvokeAsync(HttpContext context)
{
var cancellationToken = context.RequestAborted;
try
{
if (endpointDescriptor.VariableFilledThroughBody is not null)
{
if (context.Request.ContentType?.StartsWith("application/json", StringComparison.OrdinalIgnoreCase) != true)
{
await Results.Problem(
detail: "Content-Type must be application/json",
statusCode: StatusCodes.Status415UnsupportedMediaType).ExecuteAsync(context);
return;
}
if (context.Request.ContentLength < 1)
{
await Results.Problem(
detail: "Request body is required",
statusCode: StatusCodes.Status400BadRequest).ExecuteAsync(context);
return;
}
}
var proxy = context.RequestServices.GetRequiredKeyedService<HttpRequestExecutorProxy>(schemaName);
var session = await proxy.GetOrCreateSessionAsync(context.RequestAborted);
using var variableBuffer = new PooledArrayWriter();
var variables = await BuildVariablesAsync(
endpointDescriptor,
context,
variableBuffer,
cancellationToken);
var requestBuilder = OperationRequestBuilder.New()
.SetDocument(endpointDescriptor.Document)
.SetErrorHandlingMode(ErrorHandlingMode.Halt)
.SetVariableValues(variables);
await session.OnCreateAsync(context, requestBuilder, cancellationToken);
var executionResult = await session.ExecuteAsync(
requestBuilder.Build(),
cancellationToken).ConfigureAwait(false);
// If the request was cancelled, we do not attempt to write a response.
if (cancellationToken.IsCancellationRequested)
{
return;
}
// If we do not have an operation result, something went wrong and we return HTTP 500.
if (executionResult is not IOperationResult operationResult)
{
await Results.InternalServerError().ExecuteAsync(context);
return;
}
// If the request had validation errors or execution didn't start, we return HTTP 400.
if (operationResult.ContextData?.ContainsKey(ExecutionContextData.ValidationErrors) == true
|| operationResult is OperationResult { IsDataSet: false })
{
await Results.BadRequest().ExecuteAsync(context);
return;
}
// If execution started, and we produced GraphQL errors,
// we return HTTP 500 or 401/403 for authorization errors.
if (operationResult.Errors is not null)
{
var result = GetResultFromErrors(operationResult.Errors);
await result.ExecuteAsync(context);
return;
}
var formatter = session.Schema.Services.GetRequiredService<IOpenApiResultFormatter>();
await formatter.FormatResultAsync(operationResult, context, endpointDescriptor, cancellationToken);
}
catch (InvalidFormatException)
{
await Results.BadRequest().ExecuteAsync(context);
}
catch
{
await Results.InternalServerError().ExecuteAsync(context);
}
}
private static async Task<IReadOnlyDictionary<string, object?>> BuildVariablesAsync(
OpenApiEndpointDescriptor endpointDescriptor,
HttpContext httpContext,
PooledArrayWriter variableBuffer,
CancellationToken cancellationToken)
{
var variables = new Dictionary<string, object?>();
if (endpointDescriptor.VariableFilledThroughBody is { } bodyVariable)
{
const int chunkSize = 256;
using var writer = new PooledArrayWriter();
var body = httpContext.Request.Body;
int read;
do
{
var memory = writer.GetMemory(chunkSize);
read = await body.ReadAsync(memory, cancellationToken).ConfigureAwait(false);
writer.Advance(read);
// if (_maxRequestSize < writer.Length)
// {
// throw DefaultHttpRequestParser_MaxRequestSizeExceeded();
// }
} while (read == chunkSize);
if (read == 0)
{
throw new InvalidOperationException("Expected to have a body");
}
var jsonValueParser = new JsonValueParser(buffer: variableBuffer);
var bodyValue = jsonValueParser.Parse(writer.WrittenSpan);
variables[bodyVariable] = bodyValue;
}
InsertParametersIntoVariables(variables, endpointDescriptor, httpContext);
return variables;
}
private static void InsertParametersIntoVariables(
Dictionary<string, object?> variables,
OpenApiEndpointDescriptor endpointDescriptor,
HttpContext httpContext)
{
var routeData = httpContext.GetRouteData();
var query = httpContext.Request.Query;
foreach (var (variableName, segment) in endpointDescriptor.ParameterTrie)
{
if (segment is VariableValueInsertionTrieLeaf leaf)
{
variables[variableName] = GetValueForParameter(leaf, routeData, query);
}
else if (segment is VariableValueInsertionTrie trie
&& variables[variableName] is ObjectValueNode objectValue)
{
variables[variableName] = RewriteObjectValueNode(
objectValue,
trie,
routeData,
query);
}
else
{
throw new InvalidOperationException();
}
}
}
private static IValueNode RewriteObjectValueNode(
ObjectValueNode objectValueNode,
VariableValueInsertionTrie trie,
RouteData routeData,
IQueryCollection query)
{
var newFields = new List<ObjectFieldNode>();
var processedFields = new HashSet<string>(objectValueNode.Fields.Count);
foreach (var field in objectValueNode.Fields)
{
var fieldName = field.Name.Value;
if (trie.TryGetValue(fieldName, out var segment))
{
if (segment is not VariableValueInsertionTrie trieSegment)
{
throw new InvalidOperationException(
"Did not expect to have a value for a field supposed to be filled by a parameter");
}
if (field.Value is not ObjectValueNode fieldObject)
{
throw new InvalidOperationException($"Expected field '{fieldName}' to be an object");
}
var newFieldValue = RewriteObjectValueNode(fieldObject, trieSegment, routeData, query);
newFields.Add(field.WithValue(newFieldValue));
}
else
{
newFields.Add(field);
}
processedFields.Add(fieldName);
}
if (trie.Keys.Count != processedFields.Count)
{
foreach (var (fieldName, segment) in trie)
{
if (processedFields.Contains(fieldName))
{
continue;
}
IValueNode newValue;
if (segment is VariableValueInsertionTrieLeaf leaf)
{
newValue = GetValueForParameter(leaf, routeData, query);
}
else if (segment is VariableValueInsertionTrie trieSegment)
{
newValue = RewriteObjectValueNode(
new ObjectValueNode(),
trieSegment,
routeData,
query);
}
else
{
throw new NotSupportedException();
}
newFields.Add(new ObjectFieldNode(fieldName, newValue));
}
}
return objectValueNode.WithFields(newFields);
}
private static readonly NullValueNode s_nullValueNode = new(null);
private static IValueNode GetValueForParameter(
VariableValueInsertionTrieLeaf leaf,
RouteData routeData,
IQueryCollection query)
{
if (leaf.ParameterType is OpenApiEndpointParameterType.Route)
{
if (!routeData.Values.TryGetValue(leaf.ParameterKey, out var value))
{
return s_nullValueNode;
}
return ParseValueNode(value, leaf.Type);
}
if (leaf.ParameterType is OpenApiEndpointParameterType.Query)
{
if (!query.TryGetValue(leaf.ParameterKey, out var values)
|| values is not [{ } value])
{
return s_nullValueNode;
}
return ParseValueNode(value, leaf.Type);
}
throw new NotSupportedException();
}
// TODO: Maybe we can optimize this further, so we don't have to perform a lot of checks at runtime
private static IValueNode ParseValueNode(object? value, ITypeDefinition type)
{
if (value is null)
{
return s_nullValueNode;
}
if (type is IEnumTypeDefinition enumType)
{
if (value is not string s)
{
throw new InvalidFormatException("Expected a string value");
}
var matchingValue = enumType.Values.FirstOrDefault(v => v.Name == s);
if (matchingValue is null)
{
throw new InvalidFormatException("Expected to find a matching | DynamicEndpointMiddleware |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Media/Imaging/Svg/ISvgProvider.cs | {
"start": 289,
"end": 358
} | interface ____, as its signature
/// may change.
/// </summary>
| directly |
csharp | NLog__NLog | src/NLog/SetupLoadConfigurationExtensions.cs | {
"start": 15536,
"end": 16219
} | interface ____ configuring targets for the new LoggingRule.</returns>
public static ISetupConfigurationTargetBuilder WriteTo(this ISetupConfigurationTargetBuilder configBuilder, params Target[] targets)
{
if (targets?.Length > 0)
{
for (int i = 0; i < targets.Length; ++i)
{
configBuilder.WriteTo(targets[i]);
}
}
return configBuilder;
}
/// <summary>
/// Redirect output from matching <see cref="Logger"/> to the provided <paramref name="targetBuilder"/>
/// </summary>
/// <param name="configBuilder">Fluent | for |
csharp | grandnode__grandnode2 | src/Core/Grand.Domain/Permissions/IGroupLinkEntity.cs | {
"start": 122,
"end": 366
} | public interface ____
{
/// <summary>
/// Gets or sets a value indicating whether the entity is subject to group
/// </summary>
bool LimitedToGroups { get; set; }
IList<string> CustomerGroups { get; set; }
} | IGroupLinkEntity |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Controllers/AffiliateController.cs | {
"start": 510,
"end": 7234
} | public class ____ : BaseAdminController
{
#region Constructors
public AffiliateController(ITranslationService translationService,
IAffiliateService affiliateService, IAffiliateViewModelService affiliateViewModelService,
IPermissionService permissionService)
{
_translationService = translationService;
_affiliateService = affiliateService;
_affiliateViewModelService = affiliateViewModelService;
_permissionService = permissionService;
}
#endregion
#region Fields
private readonly ITranslationService _translationService;
private readonly IAffiliateService _affiliateService;
private readonly IAffiliateViewModelService _affiliateViewModelService;
private readonly IPermissionService _permissionService;
#endregion
#region Methods
//list
public IActionResult Index()
{
return RedirectToAction("List");
}
public IActionResult List()
{
var model = new AffiliateListModel();
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.List)]
[HttpPost]
public async Task<IActionResult> List(DataSourceRequest command, AffiliateListModel model)
{
var affiliatesModel =
await _affiliateViewModelService.PrepareAffiliateModelList(model, command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = affiliatesModel.affiliateModels,
Total = affiliatesModel.totalCount
};
return Json(gridModel);
}
//create
[PermissionAuthorizeAction(PermissionActionName.Create)]
public async Task<IActionResult> Create()
{
var model = new AffiliateModel();
await _affiliateViewModelService.PrepareAffiliateModel(model, null, false);
return View(model);
}
[PermissionAuthorizeAction(PermissionActionName.Edit)]
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
public async Task<IActionResult> Create(AffiliateModel model, bool continueEditing)
{
if (ModelState.IsValid)
{
var affiliate = await _affiliateViewModelService.InsertAffiliateModel(model);
Success(_translationService.GetResource("Admin.Affiliates.Added"));
return continueEditing ? RedirectToAction("Edit", new { id = affiliate.Id }) : RedirectToAction("List");
}
//If we got this far, something failed, redisplay form
await _affiliateViewModelService.PrepareAffiliateModel(model, null, true);
return View(model);
}
//edit
[PermissionAuthorizeAction(PermissionActionName.Preview)]
public async Task<IActionResult> Edit(string id)
{
var affiliate = await _affiliateService.GetAffiliateById(id);
if (affiliate == null)
//No affiliate found with the specified id
return RedirectToAction("List");
var model = new AffiliateModel();
await _affiliateViewModelService.PrepareAffiliateModel(model, affiliate, false);
return View(model);
}
[HttpPost]
[ArgumentNameFilter(KeyName = "save-continue", Argument = "continueEditing")]
[PermissionAuthorizeAction(PermissionActionName.Edit)]
public async Task<IActionResult> Edit(AffiliateModel model, bool continueEditing)
{
var affiliate = await _affiliateService.GetAffiliateById(model.Id);
if (affiliate == null)
//No affiliate found with the specified id
return RedirectToAction("List");
if (ModelState.IsValid)
{
affiliate = await _affiliateViewModelService.UpdateAffiliateModel(model, affiliate);
Success(_translationService.GetResource("Admin.Affiliates.Updated"));
if (continueEditing)
{
//selected tab
await SaveSelectedTabIndex();
return RedirectToAction("Edit", new { id = affiliate.Id });
}
return RedirectToAction("List");
}
//If we got this far, something failed, redisplay form
await _affiliateViewModelService.PrepareAffiliateModel(model, affiliate, true);
return View(model);
}
//delete
[PermissionAuthorizeAction(PermissionActionName.Delete)]
[HttpPost]
public async Task<IActionResult> Delete(AffiliateDeleteModel model)
{
var affiliate = await _affiliateService.GetAffiliateById(model.Id);
if (affiliate == null)
//No affiliate found with the specified id
return RedirectToAction("List");
if (ModelState.IsValid)
{
await _affiliateService.DeleteAffiliate(affiliate);
Success(_translationService.GetResource("Admin.Affiliates.Deleted"));
return RedirectToAction("List");
}
Error(ModelState);
return RedirectToAction("Edit", new { model.Id });
}
[PermissionAuthorizeAction(PermissionActionName.Preview)]
[HttpPost]
public async Task<IActionResult> AffiliatedOrderList(DataSourceRequest command, AffiliatedOrderListModel model)
{
if (!await _permissionService.Authorize(StandardPermission.ManageOrders))
return Json(new DataSourceResult {
Data = null,
Total = 0
});
var affiliate = await _affiliateService.GetAffiliateById(model.AffliateId);
if (affiliate == null)
throw new ArgumentException("No affiliate found with the specified id");
var affiliateOrders =
await _affiliateViewModelService.PrepareAffiliatedOrderList(affiliate, model, command.Page,
command.PageSize);
var gridModel = new DataSourceResult {
Data = affiliateOrders.affiliateOrderModels,
Total = affiliateOrders.totalCount
};
return Json(gridModel);
}
[PermissionAuthorizeAction(PermissionActionName.Preview)]
[HttpPost]
public async Task<IActionResult> AffiliatedCustomerList(string affiliateId, DataSourceRequest command)
{
var affiliate = await _affiliateService.GetAffiliateById(affiliateId);
if (affiliate == null)
throw new ArgumentException("No affiliate found with the specified id");
var affiliateCustomers =
await _affiliateViewModelService.PrepareAffiliatedCustomerList(affiliate, command.Page, command.PageSize);
var gridModel = new DataSourceResult {
Data = affiliateCustomers.affiliateCustomerModels,
Total = affiliateCustomers.totalCount
};
return Json(gridModel);
}
#endregion
} | AffiliateController |
csharp | microsoft__garnet | modules/GarnetJSON/JSONPath/JsonPath.cs | {
"start": 2054,
"end": 42727
} | class ____ the specified expression.
/// </summary>
/// <param name="expression">The JSON Path expression.</param>
/// <exception cref="ArgumentNullException">Thrown when the expression is null.</exception>
public JsonPath(string expression)
{
ArgumentNullException.ThrowIfNull(expression);
_expression = expression;
Filters = new List<PathFilter>();
ParseMain();
}
/// <summary>
/// Determines whether the current JPath is a static path.
/// A static path is guaranteed to return at most one result.
/// </summary>
/// <returns>true if the path is static; otherwise, false.</returns>
internal bool IsStaticPath()
{
return Filters.All(filter => filter switch
{
FieldFilter fieldFilter => fieldFilter.Name is not null,
ArrayIndexFilter arrayFilter => arrayFilter.Index.HasValue,
RootFilter => true,
_ => false
});
}
/// <summary>
/// Evaluates the JSON Path expression against the provided JSON nodes.
/// </summary>
/// <param name="root">The root JSON node.</param>
/// <param name="t">The current JSON node.</param>
/// <param name="settings">The settings used for JSON selection.</param>
/// <returns>An enumerable of JSON nodes that match the JSON Path expression.</returns>
internal IEnumerable<JsonNode?> Evaluate(JsonNode root, JsonNode? t, JsonSelectSettings? settings)
{
return Evaluate(Filters, root, t, settings);
}
/// <summary>
/// Evaluates the JSON Path expression against the provided JSON nodes using the specified filters.
/// </summary>
/// <param name="filters">The list of path filters to apply.</param>
/// <param name="root">The root JSON node.</param>
/// <param name="t">The current JSON node.</param>
/// <param name="settings">The settings used for JSON selection.</param>
/// <returns>An enumerable of JSON nodes that match the JSON Path expression.</returns>
internal static IEnumerable<JsonNode?> Evaluate(List<PathFilter> filters, JsonNode root, JsonNode? t,
JsonSelectSettings? settings)
{
if (filters.Count >= 1)
{
var firstFilter = filters[0];
var current = firstFilter.ExecuteFilter(root, t, settings);
for (int i = 1; i < filters.Count; i++)
{
current = filters[i].ExecuteFilter(root, current, settings);
}
return current;
}
else
{
return new List<JsonNode?> { t };
}
}
/// <summary>
/// Parses the main JSON Path expression and builds the filter list.
/// </summary>
private void ParseMain()
{
int currentPartStartIndex = _currentIndex;
EatWhitespace();
if (_expression.Length == _currentIndex)
{
return;
}
if (_expression[_currentIndex] == '$')
{
if (_expression.Length == 1)
{
return;
}
// only increment position for "$." or "$["
// otherwise assume property that starts with $
char c = _expression[_currentIndex + 1];
if (c == '.' || c == '[')
{
_currentIndex++;
currentPartStartIndex = _currentIndex;
}
}
if (!ParsePath(Filters, currentPartStartIndex, false))
{
int lastCharacterIndex = _currentIndex;
EatWhitespace();
if (_currentIndex < _expression.Length)
{
throw new JsonException("Unexpected character while parsing path: " +
_expression[lastCharacterIndex]);
}
}
}
/// <summary>
/// Parses a path segment and adds appropriate filters to the filter list.
/// </summary>
/// <param name="filters">The list to add parsed filters to.</param>
/// <param name="currentPartStartIndex">The starting index of the current path segment.</param>
/// <param name="query">Indicates if parsing within a query context.</param>
/// <returns>True if parsing reached the end of the expression; otherwise, false.</returns>
private bool ParsePath(List<PathFilter> filters, int currentPartStartIndex, bool query)
{
bool scan = false;
bool followingIndexer = false;
bool followingDot = false;
bool ended = false;
while (_currentIndex < _expression.Length && !ended)
{
char currentChar = _expression[_currentIndex];
switch (currentChar)
{
case '[':
case '(':
if (_currentIndex > currentPartStartIndex)
{
string? member = _expression.Substring(currentPartStartIndex,
_currentIndex - currentPartStartIndex);
if (member == "*")
{
member = null;
}
filters.Add(CreatePathFilter(member, scan));
scan = false;
}
filters.Add(ParseIndexer(currentChar, scan, query));
scan = false;
if (_currentIndex < _expression.Length &&
((_expression[_currentIndex] == ']' && currentChar is '[') ||
(_expression[_currentIndex] is ')' && currentChar is '(')))
{
_currentIndex++;
}
currentPartStartIndex = _currentIndex;
followingIndexer = true;
followingDot = false;
break;
case ']':
case ')':
ended = true;
break;
case ' ':
if (_currentIndex < _expression.Length)
{
ended = true;
}
break;
case '.':
if (_currentIndex > currentPartStartIndex)
{
string? member = _expression.Substring(currentPartStartIndex,
_currentIndex - currentPartStartIndex);
if (member == "*")
{
member = null;
}
filters.Add(CreatePathFilter(member, scan));
scan = false;
}
if (_currentIndex + 1 < _expression.Length && _expression[_currentIndex + 1] == '.')
{
scan = true;
_currentIndex++;
}
_currentIndex++;
currentPartStartIndex = _currentIndex;
followingIndexer = false;
followingDot = true;
break;
default:
if (query && (currentChar == '=' || currentChar == '<' || currentChar == '!' ||
currentChar == '>' || currentChar == '|' || currentChar == '&'))
{
ended = true;
}
else
{
if (followingIndexer)
{
throw new JsonException("Unexpected character following indexer: " + currentChar);
}
_currentIndex++;
}
break;
}
}
bool atPathEnd = (_currentIndex == _expression.Length);
if (_currentIndex > currentPartStartIndex)
{
// TODO: Check performance of using AsSpan and TrimEnd then convert to string for the critical path
string? member = _expression.Substring(currentPartStartIndex, _currentIndex - currentPartStartIndex)
.TrimEnd();
if (member == "*")
{
member = null;
}
filters.Add(CreatePathFilter(member, scan));
}
else
{
// no field name following dot in path and at end of base path/query
if (followingDot && (atPathEnd || query))
{
throw new JsonException("Unexpected end while parsing path.");
}
}
return atPathEnd;
}
/// <summary>
/// Creates a path filter based on the member name and scan flag.
/// </summary>
/// <param name="member">The member name for the filter.</param>
/// <param name="scan">Indicates if this is a scan operation.</param>
/// <returns>A new PathFilter instance.</returns>
private static PathFilter CreatePathFilter(string? member, bool scan)
{
PathFilter filter = scan ? new ScanFilter(member) : new FieldFilter(member);
return filter;
}
/// <summary>
/// Parses an indexer expression starting with '[' or '('.
/// </summary>
/// <param name="indexerOpenChar">The opening character of the indexer.</param>
/// <param name="scan">Indicates if this is a scan operation.</param>
/// <param name="query">Indicates if this is within the context of a query parser.</param>
/// <returns>A PathFilter representing the parsed indexer.</returns>
private PathFilter ParseIndexer(char indexerOpenChar, bool scan, bool query)
{
_currentIndex++;
char indexerCloseChar = indexerOpenChar is '[' ? ']' : ')';
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] is '\'' or '\"')
{
return ParseQuotedField(indexerCloseChar, scan);
}
// either it's a filter like [?( OR we're within a query context and we're parsing a parens grouping
if ((query && indexerOpenChar is '(') || _expression[_currentIndex] == '?')
{
return ParseQuery(indexerCloseChar, scan);
}
return ParseArrayIndexer(indexerCloseChar, scan);
}
/// <summary>
/// Parses an array indexer expression, supporting single index, multiple indexes, or slice notation.
/// </summary>
/// <param name="indexerCloseChar">The closing character of the indexer.</param>
/// <param name="scan">Indicates if this is a scan operation.</param>
/// <returns>A PathFilter representing the array indexer.</returns>
private PathFilter ParseArrayIndexer(char indexerCloseChar, bool scan)
{
int start = _currentIndex;
int? end = null;
List<int>? indexes = null;
int colonCount = 0;
int? startIndex = null;
int? endIndex = null;
int? step = null;
while (_currentIndex < _expression.Length)
{
char currentCharacter = _expression[_currentIndex];
if (currentCharacter == ' ')
{
end = _currentIndex;
EatWhitespace();
continue;
}
if (currentCharacter == indexerCloseChar)
{
int length = (end ?? _currentIndex) - start;
if (indexes != null)
{
if (length == 0)
{
throw new JsonException("Array index expected.");
}
var indexer = _expression.AsSpan(start, length);
if (!TryParseIndex(indexer, out int index))
{
throw new JsonException($"Invalid Array index: {indexer}");
}
indexes.Add(index);
return scan ? new ScanArrayMultipleIndexFilter(indexes) : new ArrayMultipleIndexFilter(indexes);
}
else if (colonCount > 0)
{
if (length > 0)
{
var indexer = _expression.AsSpan(start, length);
if (!TryParseIndex(indexer, out int index))
{
throw new JsonException($"Invalid Array index: {indexer}");
}
if (colonCount == 1)
{
endIndex = index;
}
else
{
step = index;
}
}
return scan
? new ScanArraySliceFilter { Start = startIndex, End = endIndex, Step = step }
: new ArraySliceFilter { Start = startIndex, End = endIndex, Step = step };
}
else
{
if (length == 0)
{
throw new JsonException("Array index expected.");
}
var indexer = _expression.AsSpan(start, length);
if (!TryParseIndex(indexer, out int index))
{
throw new JsonException($"Invalid Array index: {indexer}");
}
return scan
? new ScanArrayIndexFilter() { Index = index }
: new ArrayIndexFilter { Index = index };
}
}
else if (currentCharacter == ',')
{
int length = (end ?? _currentIndex) - start;
if (length == 0)
{
throw new JsonException("Array index expected.");
}
indexes ??= [];
var indexer = _expression.AsSpan(start, length);
indexes.Add(int.Parse(indexer, CultureInfo.InvariantCulture));
_currentIndex++;
EatWhitespace();
start = _currentIndex;
end = null;
}
else if (currentCharacter == '*')
{
_currentIndex++;
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex] != indexerCloseChar)
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
return scan ? new ScanArrayIndexFilter() : new ArrayIndexFilter();
}
else if (currentCharacter == ':')
{
int length = (end ?? _currentIndex) - start;
if (length > 0)
{
var indexer = _expression.AsSpan(start, length);
if (!TryParseIndex(indexer, out int index))
{
throw new JsonException($"Invalid Array index: {indexer}");
}
if (colonCount == 0)
{
startIndex = index;
}
else if (colonCount == 1)
{
endIndex = index;
}
else
{
step = index;
}
}
colonCount++;
_currentIndex++;
EatWhitespace();
start = _currentIndex;
end = null;
}
else if (!char.IsDigit(currentCharacter) && currentCharacter != '-')
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
else
{
if (end != null)
{
throw new JsonException("Unexpected character while parsing path indexer: " + currentCharacter);
}
_currentIndex++;
}
}
throw new JsonException("Path ended with open indexer.");
}
/// <summary>
/// Advances the current index past any whitespace characters.
/// </summary>
private void EatWhitespace()
{
while (_currentIndex < _expression.Length)
{
if (_expression[_currentIndex] != ' ')
{
break;
}
_currentIndex++;
}
}
/// <summary>
/// Try and parse a span to a properly clamped array index
/// </summary>
/// <param name="expression">The expression to be parsed</param>
/// <param name="index">When successful, contains the int clamped Index, otherwise -1.</param>
/// <returns>Whether the expression was parsed successfully.</returns>
private static bool TryParseIndex(ReadOnlySpan<char> expression, out int index)
{
if (long.TryParse(expression, CultureInfo.InvariantCulture, out var longIndex))
{
if (Math.Abs(longIndex) > Array.MaxLength)
{
index = longIndex < 0 ? -Array.MaxLength : Array.MaxLength;
}
else
{
index = (int)longIndex;
}
return true;
}
index = -1;
return false;
}
/// <summary>
/// Parses a query expression within an indexer.
/// </summary>
/// <param name="indexerCloseChar">The closing character of the indexer.</param>
/// <param name="scan">Indicates if this is a scan operation.</param>
/// <returns>A QueryFilter or QueryScanFilter based on the parsed expression.</returns>
private PathFilter ParseQuery(char indexerCloseChar, bool scan)
{
_currentIndex++;
EnsureLength("Path ended with open indexer.");
if (indexerCloseChar is ']')
{
if (_expression[_currentIndex] != '(')
{
throw new JsonException("Unexpected character while parsing path indexer: " +
_expression[_currentIndex]);
}
_currentIndex++;
}
QueryExpression expression = ParseExpression();
if (indexerCloseChar is ']')
{
_currentIndex++;
}
EnsureLength("Path ended with open indexer.");
EatWhitespace();
if (_expression[_currentIndex++] != indexerCloseChar)
{
throw new JsonException(
"Unexpected character while parsing path indexer: " + _expression[_currentIndex]);
}
if (!scan)
{
return new QueryFilter(expression);
}
else
{
return new QueryScanFilter(expression);
}
}
/// <summary>
/// Attempts to parse an expression starting with '$' or '@'.
/// </summary>
/// <param name="expressionPath">When successful, contains the list of filters for the expression.</param>
/// <returns>True if successfully parsed an expression; otherwise, false.</returns>
private bool TryParseExpression(out List<PathFilter>? expressionPath)
{
if (_expression[_currentIndex] == '$')
{
expressionPath = new List<PathFilter> { RootFilter.Instance };
}
else if (_expression[_currentIndex] == '@')
{
expressionPath = new List<PathFilter>();
}
else if (_expression[_currentIndex] == '(')
{
var query = ParseQuery(')', false);
expressionPath = [query];
return true;
}
else
{
expressionPath = null;
return false;
}
_currentIndex++;
if (ParsePath(expressionPath, _currentIndex, true))
{
throw new JsonException("Path ended with open query.");
}
return true;
}
/// <summary>
/// Creates a JsonException for unexpected characters encountered during parsing.
/// </summary>
/// <returns>A new JsonException with details about the unexpected character.</returns>
private JsonException CreateUnexpectedCharacterException()
{
return new JsonException("Unexpected character while parsing path query: " + _expression[_currentIndex]);
}
/// <summary>
/// Parses one side of a query expression.
/// </summary>
/// <returns>An object representing either a path filter list or a value.</returns>
private object? ParseSide()
{
EatWhitespace();
if (TryParseExpression(out List<PathFilter>? expressionPath))
{
EatWhitespace();
EnsureLength("Path ended with open query.");
return expressionPath;
}
if (TryParseValue(out var value))
{
EatWhitespace();
EnsureLength("Path ended with open query.");
return value;
}
if (TryParseArrayLiteral(out var arrayValue))
{
EatWhitespace();
EnsureLength("Path ended with open query.");
return arrayValue;
}
throw CreateUnexpectedCharacterException();
}
/// <summary>
/// Parses a complete query expression, including boolean operations.
/// </summary>
/// <returns>A QueryExpression representing the parsed expression.</returns>
private QueryExpression ParseExpression()
{
QueryExpression? rootExpression = null;
CompositeExpression? parentExpression = null;
while (_currentIndex < _expression.Length)
{
bool isNot = _expression[_currentIndex] == '!';
if (isNot)
{
_currentIndex++;
}
object? left = ParseSide();
object? right = null;
QueryOperator op;
if (_expression[_currentIndex] == ')'
|| _expression[_currentIndex] == '|'
|| _expression[_currentIndex] == '&')
{
op = QueryOperator.Exists;
}
else
{
op = ParseOperator();
right = ParseSide();
}
QueryExpression thisExpression;
// If this expression was a grouping ( @.a || @.b), it will return as a QueryFilter, so we need to pull the expression out
if (op is QueryOperator.Exists && left is List<PathFilter> leftPathFilters &&
leftPathFilters.Count == 1 && leftPathFilters[0] is QueryFilter qf)
{
thisExpression = qf.Expression;
}
else
{
thisExpression = new BooleanQueryExpression(op, left, right);
}
if (isNot)
{
var notExpression = new CompositeExpression(QueryOperator.Not);
notExpression.Expressions.Add(thisExpression);
thisExpression = notExpression;
}
if (_expression[_currentIndex] == ')')
{
if (parentExpression != null)
{
parentExpression.Expressions.Add(thisExpression);
return rootExpression!;
}
return thisExpression;
}
if (_expression[_currentIndex] == '&')
{
if (!Match("&&"))
{
throw CreateUnexpectedCharacterException();
}
if (parentExpression == null || parentExpression.Operator != QueryOperator.And)
{
CompositeExpression andExpression = new CompositeExpression(QueryOperator.And);
parentExpression?.Expressions.Add(andExpression);
parentExpression = andExpression;
rootExpression ??= parentExpression;
}
parentExpression.Expressions.Add(thisExpression);
}
if (_expression[_currentIndex] == '|')
{
if (!Match("||"))
{
throw CreateUnexpectedCharacterException();
}
if (parentExpression == null || parentExpression.Operator != QueryOperator.Or)
{
CompositeExpression orExpression = new CompositeExpression(QueryOperator.Or);
parentExpression?.Expressions.Add(orExpression);
parentExpression = orExpression;
rootExpression ??= parentExpression;
}
parentExpression.Expressions.Add(thisExpression);
}
}
throw new JsonException("Path ended with open query.");
}
/// <summary>
/// Attempts to parse a JSON value (string, number, boolean, or null).
/// </summary>
/// <param name="value">When successful, contains the parsed JsonValue.</param>
/// <returns>True if successfully parsed a value; otherwise, false.</returns>
private bool TryParseValue(out JsonValue? value)
{
char currentChar = _expression[_currentIndex];
if (currentChar is '\'' or '"')
{
value = JsonValue.Create(ReadQuotedString());
return true;
}
else if (char.IsDigit(currentChar) || currentChar == '-')
{
var start = _currentIndex;
_currentIndex++;
bool decimalSeen = false;
while (_currentIndex < _expression.Length)
{
currentChar = _expression[_currentIndex];
var isNegativeSign = _currentIndex == start && currentChar == '-';
var isDecimal = currentChar is '.' or 'e' or 'E';
if (isDecimal)
{
decimalSeen = true;
}
// account for + in scientific notation
if (decimalSeen && currentChar is '+' && _expression[_currentIndex - 1] is 'e' or 'E')
{
isDecimal = true;
}
if (!char.IsDigit(currentChar) && !isNegativeSign && !isDecimal)
{
var numberChars = _expression.AsSpan(start.._currentIndex);
if (decimalSeen && double.TryParse(numberChars, out double dbl))
{
value = JsonValue.Create(dbl);
return true;
}
if (!decimalSeen && long.TryParse(numberChars, out long long_val))
{
value = JsonValue.Create(long_val);
return true;
}
value = null;
return false;
}
_currentIndex++;
}
}
else if (currentChar == 't')
{
if (Match("true"))
{
value = TrueJsonValue;
return true;
}
}
else if (currentChar == 'f')
{
if (Match("false"))
{
value = FalseJsonValue;
return true;
}
}
else if (currentChar == 'n')
{
if (Match("null"))
{
value = null;
return true;
}
}
else if (currentChar == '/')
{
value = JsonValue.Create(ReadRegexString());
return true;
}
value = null;
return false;
}
private bool TryParseArrayLiteral(out JsonArray? value)
{
if (_expression[_currentIndex] == '[')
{
int innerIndex = _currentIndex;
int arrayDepth = 0;
bool inQuotes = false;
bool isEscaped = false;
bool done = false;
while (innerIndex < _expression.Length && !done)
{
char currChar = _expression[innerIndex++];
if (inQuotes && currChar == '\\' && !isEscaped)
{
isEscaped = true;
continue;
}
if (currChar == '[' && !inQuotes)
{
arrayDepth++;
}
else if (currChar == ']' && !inQuotes)
{
arrayDepth--;
if (arrayDepth == 0)
{
done = true;
break;
}
}
else if (currChar == '"' && !isEscaped)
{
inQuotes = !inQuotes;
}
isEscaped = false;
}
if (!done)
{
throw new JsonException("Incomplete Array Literal");
}
var possibleJsonArray = _expression.AsSpan(_currentIndex..innerIndex);
_currentIndex = innerIndex;
var maxByteCount = Encoding.UTF8.GetMaxByteCount(possibleJsonArray.Length);
if (maxByteCount > 256)
{
var thisJsonBytes = ArrayPool<byte>.Shared.Rent(maxByteCount);
var thisJsonByteLen = Encoding.UTF8.GetBytes(possibleJsonArray, thisJsonBytes);
var arr = JsonNode.Parse(thisJsonBytes.AsSpan(..thisJsonByteLen));
ArrayPool<byte>.Shared.Return(thisJsonBytes);
value = arr?.AsArray();
}
else
{
Span<byte> thisJsonBytes = stackalloc byte[maxByteCount];
var thisJsonByteLen = Encoding.UTF8.GetBytes(possibleJsonArray, thisJsonBytes);
var arr = JsonNode.Parse(thisJsonBytes[..thisJsonByteLen]);
value = arr?.AsArray();
}
return true;
}
value = null;
return false;
}
/// <summary>
/// Reads a quoted string value, handling escape sequences.
/// </summary>
/// <returns>The parsed string value.</returns>
private string ReadQuotedString()
{
StringBuilder sb = new StringBuilder();
char quoteChar = _expression[_currentIndex];
_currentIndex++;
while (_currentIndex < _expression.Length)
{
char currentChar = _expression[_currentIndex];
if (currentChar != '\\')
{
if (currentChar == quoteChar)
{
_currentIndex++;
return sb.ToString();
}
sb.Append(currentChar);
_currentIndex++;
continue;
}
if (_currentIndex + 1 >= _expression.Length)
{
throw new JsonException("Path ended with an open string.");
}
//Get past the '\'
_currentIndex++;
currentChar = _expression[_currentIndex++];
switch (currentChar)
{
case 'b':
sb.Append('\b');
break;
case 't':
sb.Append('\t');
break;
case 'n':
sb.Append('\n');
break;
case 'f':
sb.Append('\f');
break;
case 'r':
sb.Append('\r');
break;
case '\\':
case '"':
case '\'':
case '/':
sb.Append(currentChar);
break;
case 'u':
case 'U':
TryParseEscapedCodepoint(sb, currentChar);
break;
default:
throw new JsonException($"Unknown Unknown escape character: \\{currentChar}");
}
}
throw new JsonException("Path ended with an open string.");
}
private void TryParseEscapedCodepoint(StringBuilder sb, char currentChar)
{
var length = 4;
if (_currentIndex + length >= _expression.Length)
{
throw new JsonException(
$"Invalid escape sequence: '\\{currentChar}{_expression.AsSpan()[_currentIndex..]}'");
}
if (!IsValidHex(_currentIndex, 4) ||
!int.TryParse(_expression.AsSpan(_currentIndex, 4), NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out var hex))
{
throw new JsonException(
$"Invalid escape sequence: '\\{currentChar}{_expression.AsSpan().Slice(_currentIndex, length)}'");
}
if (_currentIndex + length + 2 < _expression.Length && _expression[_currentIndex + length] == '\\' &&
_expression[_currentIndex + length + 1] == 'u')
{
// +2 from \u
// +4 from the next four hex chars
length += 6;
if (_currentIndex + length >= _expression.Length)
{
throw new JsonException(
$"Invalid escape sequence: '\\{currentChar}{_expression.AsSpan()[_currentIndex..]}'");
}
if (!IsValidHex(_currentIndex + 6, 4) ||
!int.TryParse(_expression.AsSpan(_currentIndex + 6, 4), NumberStyles.HexNumber,
CultureInfo.InvariantCulture, out int hex2))
{
throw new JsonException(
$"Invalid escape sequence: '\\{currentChar}{_expression.AsSpan().Slice(_currentIndex, length)}'");
}
hex = ((hex - 0xD800) * 0x400) + ((hex2 - 0xDC00) % 0x400) + 0x10000;
}
if (0 <= hex && hex <= 0x10FFFF && !(0xD800 <= hex && hex <= 0xDFFF))
{
sb.Append(char.ConvertFromUtf32(hex));
}
else
{
throw new JsonException($"Invalid UTF-32 code point: '{hex}'");
}
_currentIndex += length;
}
private bool IsValidHex(int index, int count)
{
for (int i = index; i < index + count; ++i)
{
// if not a hex digit
if ((_expression[i] < '0' || _expression[i] > '9') &&
(_expression[i] < 'A' || _expression[i] > 'F') &&
(_expression[i] < 'a' || _expression[i] > 'f'))
return false;
}
return true;
}
/// <summary>
/// Reads a regular expression string, including any flags.
/// </summary>
/// <returns>The complete regular expression string including delimiters and flags.</returns>
private string ReadRegexString()
{
int startIndex = _currentIndex;
_currentIndex++;
while (_currentIndex < _expression.Length)
{
char currentChar = _expression[_currentIndex];
// handle escaped / character
if (currentChar == '\\' && _currentIndex + 1 < _expression.Length)
{
_currentIndex += 2;
}
else if (currentChar == '/')
{
_currentIndex++;
while (_currentIndex < _expression.Length)
{
currentChar = _expression[_currentIndex];
if (char.IsLetter(currentChar))
{
_currentIndex++;
}
else
{
break;
}
}
return _expression.Substring(startIndex, _currentIndex - startIndex);
}
else
{
_currentIndex++;
}
}
throw new JsonException("Path ended with an open regex.");
}
/// <summary>
/// Attempts to match a specific string at the current position.
/// </summary>
/// <param name="s">The string to match.</param>
/// <returns>True if the string matches at the current position; otherwise, false.</returns>
private bool Match(string s)
{
if (_currentIndex + s.Length >= _expression.Length)
{
return false;
}
if (_expression.AsSpan(_currentIndex, s.Length).Equals(s, StringComparison.OrdinalIgnoreCase))
{
_currentIndex += s.Length;
return true;
}
return false;
}
/// <summary>
/// Parses a comparison operator in a query expression.
/// </summary>
/// <returns>The QueryOperator | with |
csharp | ShareX__ShareX | ShareX.UploadersLib/Forms/CustomUploaderSyntaxTestForm.cs | {
"start": 1144,
"end": 6038
} | public partial class ____ : Form
{
private ResponseInfo testResponseInfo;
public CustomUploaderSyntaxTestForm() : this(null, null)
{
}
public CustomUploaderSyntaxTestForm(ResponseInfo responseInfo, string urlSyntax)
{
InitializeComponent();
testResponseInfo = responseInfo;
if (testResponseInfo == null)
{
testResponseInfo = new ResponseInfo()
{
ResponseText = "{\r\n \"status\": 200,\r\n \"data\": {\r\n \"link\": \"https:\\/\\/example.com\\/image.png\"\r\n }\r\n}",
ResponseURL = "https://example.com/upload"
};
}
if (string.IsNullOrEmpty(urlSyntax))
{
urlSyntax = "{json:data.link}";
}
rtbResponseText.Text = testResponseInfo.ResponseText;
rtbURLSyntax.Text = urlSyntax;
rtbURLSyntax.Select(rtbURLSyntax.TextLength, 0);
CodeMenuItem[] outputCodeMenuItems = new CodeMenuItem[]
{
new CodeMenuItem("{response}", "Response text"),
new CodeMenuItem("{responseurl}", "Response/Redirection URL"),
new CodeMenuItem("{header:header_name}", "Response header"),
new CodeMenuItem("{json:path}", "Parse JSON response using JSONPath"),
new CodeMenuItem("{xml:path}", "Parse XML response using XPath"),
new CodeMenuItem("{regex:pattern|group}", "Parse response using Regex"),
new CodeMenuItem("{filename}", "File name used when uploading"),
new CodeMenuItem("{random:input1|input2}", "Random selection from list"),
new CodeMenuItem("{select:input1|input2}", "Lets user to select one input from list"),
new CodeMenuItem("{prompt:title|default_value}", "Lets user to input text"),
new CodeMenuItem("{base64:input}", "Base64 encode input")
};
new CodeMenu(rtbURLSyntax, outputCodeMenuItems)
{
MenuLocationOffset = new Point(5, -3)
};
rtbURLSyntax.AddContextMenu();
ShareXResources.ApplyTheme(this, true);
CustomUploaderSyntaxHighlight(rtbURLSyntax);
UpdatePreview();
}
private void CustomUploaderSyntaxHighlight(RichTextBox rtb)
{
string text = rtb.Text;
if (!string.IsNullOrEmpty(text))
{
int start = rtb.SelectionStart;
int length = rtb.SelectionLength;
rtb.BeginUpdate();
rtb.SelectionStart = 0;
rtb.SelectionLength = rtb.TextLength;
rtb.SelectionColor = rtb.ForeColor;
ShareXCustomUploaderSyntaxParser parser = new ShareXCustomUploaderSyntaxParser();
for (int i = 0; i < text.Length; i++)
{
char c = text[i];
if (c == parser.SyntaxStart || c == parser.SyntaxEnd || c == parser.SyntaxParameterStart ||
c == parser.SyntaxParameterDelimiter || c == parser.SyntaxEscape)
{
rtb.SelectionStart = i;
rtb.SelectionLength = 1;
rtb.SelectionColor = Color.Lime;
}
}
rtb.SelectionStart = start;
rtb.SelectionLength = length;
rtb.EndUpdate();
}
}
private string ParseSyntax(ResponseInfo responseInfo, string urlSyntax)
{
if (responseInfo == null || string.IsNullOrEmpty(urlSyntax))
{
return null;
}
ShareXCustomUploaderSyntaxParser parser = new ShareXCustomUploaderSyntaxParser()
{
FileName = "example.png",
ResponseInfo = responseInfo,
URLEncode = true
};
return parser.Parse(urlSyntax);
}
private void UpdatePreview()
{
try
{
testResponseInfo.ResponseText = rtbResponseText.Text;
string result = ParseSyntax(testResponseInfo, rtbURLSyntax.Text);
txtResult.Text = result;
}
catch (Exception ex)
{
txtResult.Text = "Error\r\n" + ex.Message;
}
}
private void txtResponseText_TextChanged(object sender, EventArgs e)
{
UpdatePreview();
}
private void rtbURLSyntax_TextChanged(object sender, EventArgs e)
{
CustomUploaderSyntaxHighlight(rtbURLSyntax);
UpdatePreview();
}
}
} | CustomUploaderSyntaxTestForm |
csharp | nuke-build__nuke | source/Nuke.Utilities/Text/String.Quoting.cs | {
"start": 246,
"end": 3055
} | partial class ____
{
/// <summary>
/// Double-quotes a given string if it contains spaces. Empty and already quoted strings remain unchanged.
/// </summary>
[Pure]
public static string DoubleQuoteIfNeeded([CanBeNull] this string str)
{
return str.DoubleQuoteIfNeeded(' ');
}
/// <summary>
/// Double-quotes a given string if it contains disallowed characters. Empty and already quoted strings remain unchanged.
/// </summary>
[Pure]
public static string DoubleQuoteIfNeeded([CanBeNull] this string str, params char?[] disallowed)
{
if (string.IsNullOrWhiteSpace(str))
return string.Empty;
if (str.IsDoubleQuoted())
return str;
if (!str.Contains(disallowed))
return str;
return str.DoubleQuote();
}
/// <summary>
/// Double-quotes a given string in double-quotes with existing double-quotes escaped.
/// </summary>
[Pure]
public static string DoubleQuote([CanBeNull] this string str)
{
return $"\"{str?.Replace("\"", "\\\"")}\"";
}
/// <summary>
/// Single-quotes a given string if it contains spaces. Empty and already quoted strings remain unchanged.
/// </summary>
[Pure]
public static string SingleQuoteIfNeeded([CanBeNull] this string str)
{
return str.SingleQuoteIfNeeded(' ');
}
/// <summary>
/// Single-quotes a given string if it contains disallowed characters. Empty and already quoted strings remain unchanged.
/// </summary>
[Pure]
public static string SingleQuoteIfNeeded([CanBeNull] this string str, params char?[] disallowed)
{
if (string.IsNullOrWhiteSpace(str))
return string.Empty;
if (str.IsSingleQuoted())
return str;
if (!str.Contains(disallowed))
return str;
return str.SingleQuote();
}
/// <summary>
/// Single-quotes a given string with existing single-quotes escaped.
/// </summary>
[Pure]
public static string SingleQuote([CanBeNull] this string str)
{
return $"'{str?.Replace("'", "\\'")}'";
}
/// <summary>
/// Indicates whether a given string is double-quoted.
/// </summary>
[Pure]
public static bool IsDoubleQuoted(this string str)
{
return str.StartsWith("\"") && str.EndsWith("\"");
}
/// <summary>
/// Indicates whether a given string is single-quoted.
/// </summary>
[Pure]
public static bool IsSingleQuoted(this string str)
{
return str.StartsWith("'") && str.EndsWith("'");
}
[Pure]
private static bool Contains(this string str, char?[] chars)
{
return chars.Any(x => x.HasValue && str.IndexOf(x.Value) != -1);
}
} | StringExtensions |
csharp | atata-framework__atata | src/Atata/DataProvision/IObjectProviderEnumerableExtensions.cs | {
"start": 193,
"end": 15488
} | public static class ____
{
/// <inheritdoc cref="Contains{TSource}(IObjectProvider{IEnumerable{TSource}}, IEnumerable{TSource})"/>
public static bool Contains<TSource>(
this IObjectProvider<IEnumerable<TSource>> source,
params TSource[] items) =>
source.Contains(items.AsEnumerable());
/// <summary>
/// Determines whether the source sequence contains all of the specified items by using the default equality comparer.
/// </summary>
/// <typeparam name="TSource">The type of the source item.</typeparam>
/// <param name="source">The source.</param>
/// <param name="items">The items to locate.</param>
/// <returns>
/// <see langword="true"/> if the source sequence contains all; otherwise, <see langword="false"/>.
/// </returns>
public static bool Contains<TSource>(
this IObjectProvider<IEnumerable<TSource>> source,
IEnumerable<TSource> items)
{
Guard.ThrowIfNull(source);
Guard.ThrowIfNullOrEmpty(items);
return source.Object.Intersect(items).Count() == items.Distinct().Count();
}
/// <inheritdoc cref="ContainsAny{TSource}(IObjectProvider{IEnumerable{TSource}}, IEnumerable{TSource})"/>
public static bool ContainsAny<TSource>(
this IObjectProvider<IEnumerable<TSource>> source,
params TSource[] items) =>
source.ContainsAny(items.AsEnumerable());
/// <summary>
/// Determines whether the source sequence contains any of the specified items by using the default equality comparer.
/// </summary>
/// <typeparam name="TSource">The type of the source item.</typeparam>
/// <param name="source">The source.</param>
/// <param name="items">The items to locate.</param>
/// <returns>
/// <see langword="true"/> if the source sequence contains any; otherwise, <see langword="false"/>.
/// </returns>
public static bool ContainsAny<TSource>(
this IObjectProvider<IEnumerable<TSource>> source,
IEnumerable<TSource> items)
{
Guard.ThrowIfNull(source);
Guard.ThrowIfNullOrEmpty(items);
return source.Object.Intersect(items).Any();
}
/// <summary>
/// Executes a foreach operation on source elements.
/// </summary>
/// <typeparam name="TSource">The type of the source item.</typeparam>
/// <typeparam name="TOwner">The type of the owner.</typeparam>
/// <param name="source">The source.</param>
/// <param name="action">The action to invoke once per iteration.</param>
/// <returns>An owner instance.</returns>
public static TOwner ForEach<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Action<TSource> action)
{
Guard.ThrowIfNull(source);
Guard.ThrowIfNull(action);
foreach (TSource item in source.Object)
action.Invoke(item);
return source.Owner;
}
public static ValueProvider<int, TOwner> Count<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.Count(), "Count()");
public static ValueProvider<int, TOwner> Count<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.Count(predicateFunction),
$"Count({ConvertToString(predicate)})");
}
public static ValueProvider<IEnumerable<TSource>, TOwner> Distinct<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(
x => x.Distinct(),
"Distinct()");
public static ValueProvider<IEnumerable<TSource>, TOwner> Distinct<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
IEqualityComparer<TSource> comparer)
=>
source.ValueOf(
x => x.Distinct(comparer),
$"Distinct({comparer})");
public static ValueProvider<TSource, TOwner> ElementAt<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
int index)
=>
source.ValueOf(
x => x.ElementAt(index),
$"ElementAt({index})");
public static ValueProvider<TSource, TOwner> ElementAtOrDefault<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
int index)
=>
source.ValueOf(
x => x.ElementAtOrDefault(index),
$"ElementAtOrDefault({index})");
public static ValueProvider<TSource, TOwner> First<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.First(), "First()");
public static ValueProvider<TSource, TOwner> First<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.First(predicateFunction),
$"First({ConvertToString(predicate)})");
}
public static ValueProvider<TSource, TOwner> FirstOrDefault<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.FirstOrDefault(), "FirstOrDefault()");
public static ValueProvider<TSource, TOwner> FirstOrDefault<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.FirstOrDefault(predicateFunction),
$"FirstOrDefault({ConvertToString(predicate)})");
}
public static ValueProvider<TSource, TOwner> Last<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.Last(), "Last()");
public static ValueProvider<TSource, TOwner> Last<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.Last(predicateFunction),
$"Last({ConvertToString(predicate)})");
}
public static ValueProvider<TSource, TOwner> LastOrDefault<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.LastOrDefault(), "LastOrDefault()");
public static ValueProvider<TSource, TOwner> LastOrDefault<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.LastOrDefault(predicateFunction),
$"LastOrDefault({ConvertToString(predicate)})");
}
public static ValueProvider<long, TOwner> LongCount<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.LongCount(), "LongCount()");
public static ValueProvider<long, TOwner> LongCount<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.LongCount(predicateFunction),
$"LongCount({ConvertToString(predicate)})");
}
public static ValueProvider<TResult, TOwner> Max<TSource, TResult, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, TResult>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.Max(predicateFunction),
$"Max({ConvertToString(predicate)})");
}
public static ValueProvider<TSource, TOwner> Max<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(
x => x.Max(),
"Max()");
public static ValueProvider<TResult, TOwner> Min<TSource, TResult, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, TResult>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.Min(predicateFunction),
$"Min({ConvertToString(predicate)})");
}
public static ValueProvider<TSource, TOwner> Min<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(
x => x.Min(),
"Min()");
public static ValueProvider<IEnumerable<TResult>, TOwner> Select<TSource, TResult, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, TResult>> selector)
{
Guard.ThrowIfNull(selector);
var selectorFunction = selector.Compile();
return source.ValueOf(
x => x.Select(selectorFunction),
$"Select({ConvertToString(selector)})");
}
public static ValueProvider<IEnumerable<TResult>, TOwner> Select<TSource, TResult, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, int, TResult>> selector)
{
Guard.ThrowIfNull(selector);
var selectorFunction = selector.Compile();
return source.ValueOf(
x => x.Select(selectorFunction),
$"Select({ConvertToString(selector)})");
}
public static ValueProvider<TSource, TOwner> Single<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.Single(), "Single()");
public static ValueProvider<TSource, TOwner> Single<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.Single(predicateFunction),
$"Single({ConvertToString(predicate)})");
}
public static ValueProvider<TSource, TOwner> SingleOrDefault<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
=>
source.ValueOf(x => x.SingleOrDefault(), "SingleOrDefault()");
public static ValueProvider<TSource, TOwner> SingleOrDefault<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.SingleOrDefault(predicateFunction),
$"SingleOrDefault({ConvertToString(predicate)})");
}
public static ValueProvider<IEnumerable<TSource>, TOwner> Skip<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
int count)
=>
source.ValueOf(
x => x.Skip(count),
$"Skip({count})");
public static ValueProvider<IEnumerable<TSource>, TOwner> SkipWhile<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.SkipWhile(predicateFunction),
$"SkipWhile({ConvertToString(predicate)})");
}
public static ValueProvider<IEnumerable<TSource>, TOwner> SkipWhile<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, int, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.SkipWhile(predicateFunction),
$"SkipWhile({ConvertToString(predicate)})");
}
public static ValueProvider<IEnumerable<TSource>, TOwner> Take<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
int count)
=>
source.ValueOf(
x => x.Take(count),
$"Take({count})");
public static ValueProvider<IEnumerable<TSource>, TOwner> TakeWhile<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.TakeWhile(predicateFunction),
$"TakeWhile({ConvertToString(predicate)})");
}
public static ValueProvider<IEnumerable<TSource>, TOwner> TakeWhile<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, int, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.TakeWhile(predicateFunction),
$"TakeWhile({ConvertToString(predicate)})");
}
public static TSource[] ToArray<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
{
Guard.ThrowIfNull(source);
return [.. source.Object];
}
public static List<TSource> ToList<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source)
{
Guard.ThrowIfNull(source);
return [.. source.Object];
}
public static ValueProvider<IEnumerable<TSource>, TOwner> Where<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, int, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.Where(predicateFunction),
$"Where({ConvertToString(predicate)})");
}
public static ValueProvider<IEnumerable<TSource>, TOwner> Where<TSource, TOwner>(
this IObjectProvider<IEnumerable<TSource>, TOwner> source,
Expression<Func<TSource, bool>> predicate)
{
Guard.ThrowIfNull(predicate);
var predicateFunction = predicate.Compile();
return source.ValueOf(
x => x.Where(predicateFunction),
$"Where({ConvertToString(predicate)})");
}
private static string ConvertToString(Expression expression) =>
ImprovedExpressionStringBuilder.ExpressionToString(expression);
}
| IObjectProviderEnumerableExtensions |
csharp | DuendeSoftware__IdentityServer | identity-server/src/IdentityServer/Validation/Contexts/IntrospectionRequestValidationContext.cs | {
"start": 338,
"end": 785
} | public class ____
{
/// <summary>
/// The request parameters
/// </summary>
public NameValueCollection Parameters { get; set; } = default!;
/// <summary>
/// The ApiResource that is making the request
/// </summary>
public ApiResource? Api { get; set; }
/// <summary>
/// The Client that is making the request
/// </summary>
public Client? Client { get; set; }
}
| IntrospectionRequestValidationContext |
csharp | CommunityToolkit__dotnet | src/CommunityToolkit.HighPerformance/Memory/Span2D{T}.cs | {
"start": 14920,
"end": 16340
} | struct ____ a layer in a 3D array.
/// </summary>
/// <param name="array">The given 3D array to wrap.</param>
/// <param name="depth">The target layer to map within <paramref name="array"/>.</param>
/// <exception cref="ArrayTypeMismatchException">
/// Thrown when <paramref name="array"/> doesn't match <typeparamref name="T"/>.
/// </exception>
/// <exception cref="ArgumentOutOfRangeException">Thrown when a parameter is invalid.</exception>
public Span2D(T[,,] array, int depth)
{
if (array.IsCovariant())
{
ThrowHelper.ThrowArrayTypeMismatchException();
}
if ((uint)depth >= (uint)array.GetLength(0))
{
ThrowHelper.ThrowArgumentOutOfRangeExceptionForDepth();
}
#if NET8_0_OR_GREATER
this.reference = ref array.DangerousGetReferenceAt(depth, 0, 0);
this.height = array.GetLength(1);
#elif NETSTANDARD2_1_OR_GREATER
this.span = MemoryMarshal.CreateSpan(ref array.DangerousGetReferenceAt(depth, 0, 0), array.GetLength(1));
#else
this.Instance = array;
this.Offset = ObjectMarshal.DangerousGetObjectDataByteOffset(array, ref array.DangerousGetReferenceAt(depth, 0, 0));
this.height = array.GetLength(1);
#endif
this.width = this.Stride = array.GetLength(2);
}
/// <summary>
/// Initializes a new instance of the <see cref="Span2D{T}"/> | wrapping |
csharp | dotnet__efcore | src/EFCore/Metadata/Conventions/IModelInitializedConvention.cs | {
"start": 476,
"end": 936
} | public interface ____ : IConvention
{
/// <summary>
/// Called after a model is initialized.
/// </summary>
/// <param name="modelBuilder">The builder for the model.</param>
/// <param name="context">Additional information associated with convention execution.</param>
void ProcessModelInitialized(
IConventionModelBuilder modelBuilder,
IConventionContext<IConventionModelBuilder> context);
}
| IModelInitializedConvention |
csharp | xunit__xunit | src/xunit.v3.core/Utility/DisplayNameFormatter.cs | {
"start": 301,
"end": 2297
} | public class ____
{
readonly CharacterRule rule;
/// <summary>
/// Initializes a new instance of the <see cref="DisplayNameFormatter"/> class.
/// </summary>
public DisplayNameFormatter() =>
rule = new CharacterRule();
/// <summary>
/// Initializes a new instance of the <see cref="DisplayNameFormatter"/> class.
/// </summary>
/// <param name="display">The <see cref="TestMethodDisplay"/> used by the formatter.</param>
/// <param name="displayOptions">The <see cref="TestMethodDisplayOptions"/> used by the formatter.</param>
public DisplayNameFormatter(
TestMethodDisplay display,
TestMethodDisplayOptions displayOptions)
{
rule = new CharacterRule();
if ((displayOptions & TestMethodDisplayOptions.UseEscapeSequences) == TestMethodDisplayOptions.UseEscapeSequences)
rule = new ReplaceEscapeSequenceRule() { Next = rule };
if ((displayOptions & TestMethodDisplayOptions.ReplaceUnderscoreWithSpace) == TestMethodDisplayOptions.ReplaceUnderscoreWithSpace)
rule = new ReplaceUnderscoreRule() { Next = rule };
if ((displayOptions & TestMethodDisplayOptions.UseOperatorMonikers) == TestMethodDisplayOptions.UseOperatorMonikers)
rule = new ReplaceOperatorMonikerRule() { Next = rule };
if (display == TestMethodDisplay.ClassAndMethod)
rule =
(displayOptions & TestMethodDisplayOptions.ReplacePeriodWithComma) == TestMethodDisplayOptions.ReplacePeriodWithComma
? new ReplacePeriodRule() { Next = rule }
: new KeepPeriodRule() { Next = rule };
}
/// <summary>
/// Formats the specified display name.
/// </summary>
/// <param name="displayName">The display name to format.</param>
/// <returns>The formatted display name.</returns>
public string Format(string displayName)
{
Guard.ArgumentNotNull(displayName);
var context = new FormatContext(displayName);
while (context.HasMoreText)
rule.Evaluate(context, context.ReadNext());
context.Flush();
return context.FormattedDisplayName.ToString();
}
| DisplayNameFormatter |
csharp | nunit__nunit | src/NUnitFramework/benchmarks/nunit.framework.benchmarks/ByteAllocationBenchmark.cs | {
"start": 11729,
"end": 12504
} | public enum ____
{
/// <summary>
/// Method does not support the instances being compared.
/// </summary>
TypesNotSupported,
/// <summary>
/// Method is appropriate for the data types, but doesn't support the specified tolerance.
/// </summary>
ToleranceNotSupported,
/// <summary>
/// Method is appropriate and the items are considered equal.
/// </summary>
ComparedEqual,
/// <summary>
/// Method is appropriate and the items are considered different.
/// </summary>
ComparedNotEqual,
/// <summary>
/// Method is appropriate but the | EqualMethodResult |
csharp | microsoft__PowerToys | src/common/UITestAutomation/KeyboardHelper.cs | {
"start": 454,
"end": 1476
} | public enum ____
{
Ctrl,
LCtrl,
RCtrl,
Alt,
Shift,
Tab,
Esc,
Enter,
Win,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
Num0,
Num1,
Num2,
Num3,
Num4,
Num5,
Num6,
Num7,
Num8,
Num9,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
Space,
Backspace,
Delete,
Insert,
Home,
End,
PageUp,
PageDown,
Up,
Down,
Left,
Right,
Other,
}
/// <summary>
/// Provides methods for simulating keyboard input.
/// </summary>
| Key |
csharp | abpframework__abp | modules/cms-kit/src/Volo.CmsKit.Public.Web/Security/Captcha/CaptchaOutput.cs | {
"start": 68,
"end": 249
} | public class ____
{
public Guid Id { get; set; }
public string Text { get; set; }
public byte[] ImageBytes { get; set; }
public int Result { get; set; }
}
| CaptchaOutput |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI.Controls.Layout/OrbitView/OrbitViewDataItem.cs | {
"start": 516,
"end": 3652
} | public partial class ____ : DependencyObject
{
/// <summary>
/// Gets or sets a value indicating the distance from the center.
/// Expected value between 0 and 1
/// </summary>
public double Distance
{
get { return (double)GetValue(DistanceProperty); }
set { SetValue(DistanceProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Distance"/> property
/// </summary>
public static readonly DependencyProperty DistanceProperty =
DependencyProperty.Register(nameof(Distance), typeof(double), typeof(OrbitViewDataItem), new PropertyMetadata(0.5));
/// <summary>
/// Gets or sets a value indicating the name of the item.
/// Used for <see cref="AutomationProperties"/>
/// </summary>
public string Label
{
get { return (string)GetValue(LabelProperty); }
set { SetValue(LabelProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Label"/> property
/// </summary>
public static readonly DependencyProperty LabelProperty =
DependencyProperty.Register(nameof(Label), typeof(string), typeof(OrbitViewDataItem), new PropertyMetadata("OrbitViewDataItem"));
/// <summary>
/// Gets or sets a value indicating the diameter of the item.
/// Expected value between 0 and 1
/// </summary>
public double Diameter
{
get { return (double)GetValue(DiameterProperty); }
set { SetValue(DiameterProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Diameter"/> property
/// </summary>
public static readonly DependencyProperty DiameterProperty =
DependencyProperty.Register(nameof(Diameter), typeof(double), typeof(OrbitViewDataItem), new PropertyMetadata(-1d));
/// <summary>
/// Gets or sets a value indicating the image of the item.
/// </summary>
public ImageSource Image
{
get { return (ImageSource)GetValue(ImageProperty); }
set { SetValue(ImageProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Image"/> property
/// </summary>
public static readonly DependencyProperty ImageProperty =
DependencyProperty.Register(nameof(Image), typeof(ImageSource), typeof(OrbitViewDataItem), new PropertyMetadata(null));
/// <summary>
/// Gets or sets a value of an object that can be used to store model data.
/// </summary>
public object Item
{
get { return (object)GetValue(ItemProperty); }
set { SetValue(ItemProperty, value); }
}
/// <summary>
/// Identifies the <see cref="Item"/> property
/// </summary>
public static readonly DependencyProperty ItemProperty =
DependencyProperty.Register(nameof(Item), typeof(object), typeof(OrbitViewDataItem), new PropertyMetadata(null));
}
} | OrbitViewDataItem |
csharp | dotnet__efcore | src/EFCore.Relational/Metadata/Internal/ViewColumn.cs | {
"start": 647,
"end": 2883
} | public class ____ : ColumnBase<ViewColumnMapping>, IViewColumn
{
/// <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 ViewColumn(
string name,
string type,
View view,
RelationalTypeMapping? storeTypeMapping = null,
ValueComparer? providerValueComparer = null)
: base(name, type, view, storeTypeMapping, providerValueComparer)
{
}
/// <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 virtual View View
=> (View)Table;
/// <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 override string ToString()
=> ((IViewColumn)this).ToDebugString(MetadataDebugStringOptions.SingleLineDefault);
/// <inheritdoc />
IView IViewColumn.View
{
[DebuggerStepThrough]
get => View;
}
/// <inheritdoc />
IReadOnlyList<IViewColumnMapping> IViewColumn.PropertyMappings
{
[DebuggerStepThrough]
get => PropertyMappings;
}
}
| ViewColumn |
csharp | MassTransit__MassTransit | tests/MassTransit.Tests/ContainerTests/ExcludeTypeFromFilter_Specs.cs | {
"start": 1731,
"end": 2675
} | class ____<T> :
IFilter<PublishContext<T>>
where T : class
{
readonly ILogger<PublishTenantHeaderFilter<T>> _logger;
public PublishTenantHeaderFilter(ILogger<PublishTenantHeaderFilter<T>> logger)
{
_logger = logger;
}
public void Probe(ProbeContext context)
{
context.CreateFilterScope("PublishTenantHeaderFilter");
}
public Task Send(PublishContext<T> context, IPipe<PublishContext<T>> next)
{
var headerValue = context.TryGetHeader("X-FilterCount", out int? value) ? value + 1 : 1;
context.Headers.Set("X-FilterCount", headerValue);
_logger.LogInformation($"Set filter count to {headerValue}");
return next.Send(context);
}
}
[Serializable]
| PublishTenantHeaderFilter |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 317917,
"end": 318137
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1459 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1461> ChildEntities { get; set; }
}
| RelatedEntity1460 |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/CommandBarFlyout/CommandBarFlyoutCommandBar.h.mux.cs | {
"start": 690,
"end": 764
} | internal enum ____
{
Opacity,
Clip
}
| CommandBarFlyoutOpenCloseAnimationKind |
csharp | dotnet__maui | src/Controls/tests/ManualTests/Tests/Editor/D14.xaml.cs | {
"start": 190,
"end": 278
} | public partial class ____ : ContentPage
{
public D14()
{
InitializeComponent();
}
}
| D14 |
csharp | ChilliCream__graphql-platform | src/GreenDonut/src/GreenDonut.Abstractions/Batch.cs | {
"start": 460,
"end": 2466
} | public abstract class ____
{
/// <summary>
/// <para>
/// Gets the number of items currently contained in this batch.
/// </para>
/// <para>
/// This reflects the current size of the batch and can be used
/// to decide whether to dispatch early (e.g., when reaching a
/// maximum size threshold).
/// </para>
/// </summary>
public abstract int Size { get; }
/// <summary>
/// <para>
/// Gets the current status of this batch.
/// </para>
/// <para>
/// The status indicates whether the batch is newly created, has
/// been observed ("touched") by the scheduler in the current
/// turn/epoch, or is ready for dispatch.
/// </para>
/// </summary>
public abstract BatchStatus Status { get; }
/// <summary>
/// Gets a high-resolution timestamp representing when this batch was first created.
/// This value is used to enforce maximum batch age timeouts to prevent starvation.
/// </summary>
public abstract long CreatedTimestamp { get; }
/// <summary>
/// Gets a high-resolution timestamp from representing the last time an item was added to this batch.
/// This value is used for recency checks in scheduling decisions.
/// </summary>
public abstract long ModifiedTimestamp { get; }
/// <summary>
/// <para>
/// Marks the batch as "touched" by the scheduler.
/// </para>
/// <para>
/// This is typically called when the scheduler observes the batch
/// during a scheduling turn, indicating that it has been considered
/// for dispatch. A touched batch may be given a short grace period
/// or additional turn to gather more items before being dispatched.
/// </para>
/// </summary>
/// <returns>
/// <c>true</c> if it did not change since it last was touched.
/// </returns>
public abstract bool Touch();
/// <summary>
/// Dispatch this batch.
/// </summary>
public abstract Task DispatchAsync();
}
| Batch |
csharp | unoplatform__uno | src/Uno.UI.Composition/Composition/CompositionColorBrush.cs | {
"start": 149,
"end": 1158
} | public partial class ____ : CompositionBrush
{
private Color _color;
internal CompositionColorBrush(Compositor compositor) : base(compositor)
{
}
public Color Color
{
get { return _color; }
set { SetProperty(ref _color, value); }
}
internal override object GetAnimatableProperty(string propertyName, string subPropertyName)
{
if (propertyName.Equals(nameof(Color), StringComparison.OrdinalIgnoreCase))
{
return GetColor(subPropertyName, Color);
}
else
{
return base.GetAnimatableProperty(propertyName, subPropertyName);
}
}
private protected override void SetAnimatableProperty(ReadOnlySpan<char> propertyName, ReadOnlySpan<char> subPropertyName, object? propertyValue)
{
if (propertyName.Equals(nameof(Color), StringComparison.OrdinalIgnoreCase))
{
Color = UpdateColor(subPropertyName, Color, propertyValue);
}
else
{
base.SetAnimatableProperty(propertyName, subPropertyName, propertyValue);
}
}
}
}
| CompositionColorBrush |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Execution/UnionInterfaceTests.cs | {
"start": 7697,
"end": 7733
} | public interface ____ : INamed
{
}
| IPet |
csharp | EventStore__EventStore | src/KurrentDB.Core/Services/Transport/Enumerators/Enumerator.ReadAllForwardsFiltered.cs | {
"start": 679,
"end": 4607
} | public class ____ : IAsyncEnumerator<ReadResponse> {
private readonly IPublisher _bus;
private readonly ulong _maxCount;
private readonly bool _resolveLinks;
private readonly IEventFilter _eventFilter;
private readonly ClaimsPrincipal _user;
private readonly bool _requiresLeader;
private readonly IExpiryStrategy _expiryStrategy;
private readonly uint _maxSearchWindow;
private readonly CancellationToken _cancellationToken;
private readonly SemaphoreSlim _semaphore = new(1, 1);
private readonly Channel<ReadResponse> _channel = Channel.CreateBounded<ReadResponse>(DefaultCatchUpChannelOptions);
private ReadResponse _current;
public ReadResponse Current => _current;
public ReadAllForwardsFiltered(IPublisher bus,
Position position,
ulong maxCount,
bool resolveLinks,
IEventFilter eventFilter,
ClaimsPrincipal user,
bool requiresLeader,
uint? maxSearchWindow,
IExpiryStrategy expiryStrategy,
CancellationToken cancellationToken) {
_bus = Ensure.NotNull(bus);
_maxCount = maxCount;
_resolveLinks = resolveLinks;
_eventFilter = Ensure.NotNull(eventFilter);
_user = user;
_requiresLeader = requiresLeader;
_maxSearchWindow = maxSearchWindow ?? DefaultReadBatchSize;
_expiryStrategy = expiryStrategy;
_cancellationToken = cancellationToken;
ReadPage(position);
}
public ValueTask DisposeAsync() {
_channel.Writer.TryComplete();
return new ValueTask(Task.CompletedTask);
}
public async ValueTask<bool> MoveNextAsync() {
if (!await _channel.Reader.WaitToReadAsync(_cancellationToken)) {
return false;
}
_current = await _channel.Reader.ReadAsync(_cancellationToken);
return true;
}
private void ReadPage(Position startPosition, ulong readCount = 0) {
var correlationId = Guid.NewGuid();
var (commitPosition, preparePosition) = startPosition.ToInt64();
_bus.Publish(new ClientMessage.FilteredReadAllEventsForward(
correlationId, correlationId, new ContinuationEnvelope(OnMessage, _semaphore, _cancellationToken),
commitPosition, preparePosition, (int)Math.Min(DefaultReadBatchSize, _maxCount), _resolveLinks,
_requiresLeader, (int)_maxSearchWindow, null, _eventFilter, _user,
replyOnExpired: true,
expires: _expiryStrategy.GetExpiry() ?? ClientMessage.ReadRequestMessage.NeverExpires,
cancellationToken: _cancellationToken)
);
async Task OnMessage(Message message, CancellationToken ct) {
if (message is ClientMessage.NotHandled notHandled && TryHandleNotHandled(notHandled, out var ex)) {
_channel.Writer.TryComplete(ex);
return;
}
if (message is not ClientMessage.FilteredReadAllEventsForwardCompleted completed) {
_channel.Writer.TryComplete(ReadResponseException.UnknownMessage.Create<ClientMessage.FilteredReadAllEventsForwardCompleted>(message));
return;
}
switch (completed.Result) {
case FilteredReadAllResult.Success:
foreach (var @event in completed.Events) {
if (readCount >= _maxCount) {
_channel.Writer.TryComplete();
return;
}
await _channel.Writer.WriteAsync(new ReadResponse.EventReceived(@event), ct);
readCount++;
}
if (completed.IsEndOfStream) {
_channel.Writer.TryComplete();
return;
}
ReadPage(Position.FromInt64(completed.NextPos.CommitPosition, completed.NextPos.PreparePosition), readCount);
return;
case FilteredReadAllResult.Expired:
ReadPage(Position.FromInt64(completed.CurrentPos.CommitPosition, completed.CurrentPos.PreparePosition), readCount);
return;
case FilteredReadAllResult.AccessDenied:
_channel.Writer.TryComplete(new ReadResponseException.AccessDenied());
return;
default:
_channel.Writer.TryComplete(ReadResponseException.UnknownError.Create(completed.Result, completed.Error));
return;
}
}
}
}
}
| ReadAllForwardsFiltered |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.System.Preview/TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs.cs | {
"start": 356,
"end": 1493
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.System.Preview.TwoPanelHingedDevicePosturePreviewReading Reading
{
get
{
throw new global::System.NotImplementedException("The member TwoPanelHingedDevicePosturePreviewReading TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs.Reading is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=TwoPanelHingedDevicePosturePreviewReading%20TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs.Reading");
}
}
#endif
// Forced skipping of method Windows.System.Preview.TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs.Reading.get
}
}
| TwoPanelHingedDevicePosturePreviewReadingChangedEventArgs |
csharp | Humanizr__Humanizer | src/Benchmarks/TimeOnlyToClockNotationConverterBenchmarks.cs | {
"start": 25,
"end": 1664
} | public class ____
{
static readonly TimeOnly time = new(13, 6, 2, 88, 987);
static readonly EsTimeOnlyToClockNotationConverter esConverter = new();
[Benchmark]
public void EsClockNotationConverter()
{
esConverter.Convert(time, ClockNotationRounding.None);
esConverter.Convert(time, ClockNotationRounding.NearestFiveMinutes);
}
static readonly BrazilianPortugueseTimeOnlyToClockNotationConverter brazilianConverter = new();
[Benchmark]
public void BrazilianPortugueseClockNotationConverter()
{
brazilianConverter.Convert(time, ClockNotationRounding.None);
brazilianConverter.Convert(time, ClockNotationRounding.NearestFiveMinutes);
}
static readonly FrTimeOnlyToClockNotationConverter frConverter = new();
[Benchmark]
public void FrClockNotationConverter()
{
frConverter.Convert(time, ClockNotationRounding.None);
frConverter.Convert(time, ClockNotationRounding.NearestFiveMinutes);
}
static readonly LbTimeOnlyToClockNotationConverter lbConverter = new();
[Benchmark]
public void LbClockNotationConverter()
{
lbConverter.Convert(time, ClockNotationRounding.None);
lbConverter.Convert(time, ClockNotationRounding.NearestFiveMinutes);
}
static readonly DefaultTimeOnlyToClockNotationConverter defaultConverter = new();
[Benchmark]
public void DefaultClockNotationConverter()
{
defaultConverter.Convert(time, ClockNotationRounding.None);
defaultConverter.Convert(time, ClockNotationRounding.NearestFiveMinutes);
}
} | TimeOnlyToClockNotationConverterBenchmarks |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Security.Authentication.Web.Core/WebAccountEventArgs.cs | {
"start": 315,
"end": 1193
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal WebAccountEventArgs()
{
}
#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.Security.Credentials.WebAccount Account
{
get
{
throw new global::System.NotImplementedException("The member WebAccount WebAccountEventArgs.Account is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=WebAccount%20WebAccountEventArgs.Account");
}
}
#endif
// Forced skipping of method Windows.Security.Authentication.Web.Core.WebAccountEventArgs.Account.get
}
}
| WebAccountEventArgs |
csharp | JamesNK__Newtonsoft.Json | Src/Newtonsoft.Json.Tests/TestObjects/Binding.cs | {
"start": 1202,
"end": 1341
} | public class ____
{
[JsonProperty(Required = Required.Always)]
public Binding RequiredProperty { get; set; }
}
} | Binding |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/EntryPoints/CommonOutputs.cs | {
"start": 5521,
"end": 5712
} | public interface ____
{
}
/// <summary>
/// Interface that all API trainer output classes will implement.
/// </summary>
| ISequencePredictionOutput |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Controls/Panel/Panel.unittests.cs | {
"start": 386,
"end": 503
} | partial class ____
{
public override IEnumerable<View> GetChildren() => Children.OfType<View>().ToArray<View>();
}
| Panel |
csharp | AutoMapper__AutoMapper | src/IntegrationTests/CustomMapFrom/MapObjectPropertyFromSubQuery.cs | {
"start": 9313,
"end": 11035
} | public partial class ____
{
public int Id { get; set; }
public string Name { get; set; }
public bool ECommercePublished { get; set; }
public virtual ICollection<Article> Articles { get; set; }
public int Value { get; }
[NotMapped]
public int NotMappedValue { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName1 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName2 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName3 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName4 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName5 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName6 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName7 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName8 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName9 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName10 { get; set; }
public int VeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnNameVeryLongColumnName11 { get; set; }
}
| Product |
csharp | App-vNext__Polly | test/Polly.TestUtils/BinarySerializationUtil.cs | {
"start": 345,
"end": 776
} | public static class ____
{
public static T SerializeAndDeserializeException<T>(T exception)
where T : Exception
{
using var stream = new MemoryStream();
var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize(stream, exception);
stream.Position = 0;
return (T)formatter.Deserialize(stream);
}
}
#endif
| BinarySerializationUtil |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.DisplayManagement/Shapes/ShapeDebugView.cs | {
"start": 959,
"end": 1685
} | public class ____
{
public KeyValuePairs(string key, object value)
{
if (_value is IShape)
{
_shapeType = ((IShape)_value).Metadata.Type;
}
_value = value;
_key = key;
}
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
#pragma warning disable IDE0052 // Remove unread private members
private readonly string _key;
#pragma warning restore IDE0052 // Remove unread private members
[DebuggerBrowsable(DebuggerBrowsableState.Never)]
private readonly object _shapeType;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
private readonly object _value;
}
}
| KeyValuePairs |
csharp | dotnet__tye | src/tye/StandardOptions.cs | {
"start": 380,
"end": 8817
} | public static class ____
{
private static readonly string[] AllOutputs = new string[] { "container", "chart", };
public static Option Environment
{
get
{
return new Option(new[] { "-e", "--environment" }, "Environment")
{
Argument = new Argument<string>("environment", () => "production")
{
Arity = ArgumentArity.ExactlyOne,
},
Required = false,
};
}
}
public static Option Tags
{
get
{
return new Option("--tags", "--filter")
{
Argument = new Argument<List<string>>("tags")
{
Arity = ArgumentArity.OneOrMore
},
Description = "Filter the group of running services by tag.",
Required = false
};
}
}
public static Option Framework =>
new Option(new string[] { "-f", "--framework" })
{
Description = "The target framework hint to use for all cross-targeting projects with multiple TFMs. " +
"This value must be a valid target framework for each individual cross-targeting project. " +
"Non-crosstargeting projects will ignore this hint and the value TFM configured in tye.yaml will override this hint. ",
Argument = new Argument<string>("framework")
{
Arity = ArgumentArity.ExactlyOne
},
Required = false
};
public static Option Interactive
{
get
{
return new Option(new[] { "-i", "--interactive", }, "Interactive mode")
{
Argument = new Argument<bool>(),
};
}
}
public static Option Outputs
{
get
{
var argument = new Argument<List<string>>(TryConvert)
{
Arity = ArgumentArity.ZeroOrMore,
};
argument.AddSuggestions(AllOutputs);
argument.SetDefaultValue(new List<string>(AllOutputs));
return new Option(new[] { "-o", "--outputs" }, "Outputs to generate")
{
Argument = argument,
};
static bool TryConvert(SymbolResult symbol, out List<string> outputs)
{
outputs = new List<string>();
foreach (var token in symbol.Tokens)
{
if (!AllOutputs.Any(item => string.Equals(item, token.Value, StringComparison.OrdinalIgnoreCase)))
{
symbol.ErrorMessage = $"output '{token.Value}' is not recognized";
outputs = default!;
return false;
}
outputs.Add(token.Value.ToLowerInvariant());
}
return true;
}
}
}
public static Option Project
{
get
{
var argument = new Argument<FileInfo>(TryParse, isDefault: true)
{
Arity = ArgumentArity.ZeroOrOne,
Name = "project-file or solution-file or directory",
};
return new Option(new[] { "-p", "--project", }, "Project file, Solution file or directory")
{
Argument = argument,
};
static bool TryFindProjectFile(string directoryPath, out string? projectFilePath, out string? errorMessage)
{
var matches = new List<string>();
foreach (var candidate in Directory.EnumerateFiles(directoryPath))
{
if (Path.GetExtension(candidate).EndsWith(".sln"))
{
matches.Add(candidate);
}
if (Path.GetExtension(candidate).EndsWith(".csproj"))
{
matches.Add(candidate);
}
}
// Prefer solution if both are in the same directory. This helps
// avoid some conflicts.
if (matches.Any(m => m.EndsWith(".sln")))
{
matches.RemoveAll(m => m.EndsWith(".csproj"));
}
if (matches.Count == 0)
{
errorMessage = $"No project file or solution file was found in directory '{directoryPath}'.";
projectFilePath = default;
return false;
}
else if (matches.Count == 1)
{
errorMessage = null;
projectFilePath = matches[0];
return true;
}
else
{
errorMessage = $"More than one project file or solution file was found in directory '{directoryPath}'.";
projectFilePath = default;
return false;
}
}
static FileInfo TryParse(ArgumentResult result)
{
var token = result.Tokens.Count switch
{
0 => ".",
1 => result.Tokens[0].Value,
_ => throw new InvalidOperationException("Unexpected token count."),
};
if (File.Exists(token))
{
return new FileInfo(token);
}
if (Directory.Exists(token))
{
if (TryFindProjectFile(token, out var filePath, out var errorMessage))
{
return new FileInfo(filePath!);
}
else
{
result.ErrorMessage = errorMessage;
return default!;
}
}
result.ErrorMessage = $"The file '{token}' could not be found.";
return default!;
}
}
}
public static Option Verbosity
{
get
{
return new Option(new[] { "-v", "--verbosity" }, "Output verbosity")
{
Argument = new Argument<Verbosity>("one of: quiet|info|debug", () => Tye.Verbosity.Info)
{
Arity = ArgumentArity.ExactlyOne,
},
Required = false,
};
}
}
public static Option Namespace
{
get
{
return new Option(new[] { "-n", "--namespace" })
{
Description = "Specify the namespace for the deployment",
Required = false,
Argument = new Argument<string>(),
};
}
}
public static Option NoDefaultOptions
{
get
{
return new Option(new[] { "--no-default" })
{
Description = "Disable default options from environment variables",
Required = false,
Argument = new Argument<bool>(),
};
}
}
public static Option CreateForce(string descriptions) =>
new Option(new[] { "--force" })
{
Argument = new Argument<bool>(),
Description = descriptions,
Required = false
};
}
}
| StandardOptions |
csharp | Cysharp__UniTask | src/UniTask.NetCoreSandbox/Program.cs | {
"start": 439,
"end": 898
} | public class ____
{
static async Task Main(string[] args)
{
var cts = new CancellationTokenSource();
// OK.
await FooAsync(10, cts.Token);
// NG(Compiler Error)
// await FooAsync(10);
}
static async UniTask FooAsync(int x, CancellationToken cancellationToken = default)
{
await UniTask.Yield();
}
}
}
| Program |
csharp | xunit__xunit | src/xunit.v3.core.tests/Acceptance/FixtureAcceptanceTests.cs | {
"start": 23628,
"end": 23782
} | public class ____ : ICollectionFixture<MessageSinkFixture> { }
[Collection("collection with message sink fixture")]
| ClassWithMessageSinkFixtureCollection |
csharp | dotnet__orleans | test/TesterInternal/ActivationRepartitioningTests/CustomToleranceTests.cs | {
"start": 6868,
"end": 8062
} | public class ____ : Grain, IF
{
public Task Ping() => Task.CompletedTask;
public Task<SiloAddress> GetAddress() => Task.FromResult(GrainContext.Address.SiloAddress);
public override Task OnActivateAsync(CancellationToken cancellationToken)
{
ServiceProvider.GetRequiredService<ILogger<F>>().LogInformation("Activating {GrainId} on silo {SiloAddress}", this.GrainId, this.Runtime.SiloAddress);
return base.OnActivateAsync(cancellationToken);
}
public override Task OnDeactivateAsync(DeactivationReason reason, CancellationToken cancellationToken)
{
ServiceProvider.GetRequiredService<ILogger<F>>().LogInformation("Deactivating {GrainId} on silo {SiloAddress}. Reason: {Reason}", this.GrainId, this.Runtime.SiloAddress, reason);
return base.OnDeactivateAsync(reason, cancellationToken);
}
}
/// <summary>
/// This is simply to achieve initial balance between the 2 silos, as by default the primary
/// will have 1 more activation than the secondary. That activations is 'sys.svc.clustering.dev'
/// </summary>
[Immovable(ImmovableKind.Repartitioner)]
| F |
csharp | bitwarden__server | bitwarden_license/src/Scim/Users/Interfaces/IPatchUserCommand.cs | {
"start": 63,
"end": 179
} | public interface ____
{
Task PatchUserAsync(Guid organizationId, Guid id, ScimPatchModel model);
}
| IPatchUserCommand |
csharp | icsharpcode__ILSpy | ILSpy/AppEnv/SingleInstance.cs | {
"start": 7121,
"end": 8400
} | public sealed class ____ : EventArgs
{
/// <summary>
/// Creates new instance.
/// </summary>
/// <param name="commandLine">Command line.</param>
/// <param name="commandLineArgs">String array containing the command line arguments in the same format as Environment.GetCommandLineArgs.</param>
internal NewInstanceEventArgs(string commandLine, string[] commandLineArgs)
{
CommandLine = commandLine;
_commandLineArgs = new string[commandLineArgs.Length];
Array.Copy(commandLineArgs, _commandLineArgs, _commandLineArgs.Length);
}
/// <summary>
/// Gets the command line.
/// </summary>
public string CommandLine { get; }
private readonly string[] _commandLineArgs;
/// <summary>
/// Returns a string array containing the command line arguments.
/// </summary>
public string[] GetCommandLineArgs()
{
var argCopy = new string[_commandLineArgs.Length];
Array.Copy(_commandLineArgs, argCopy, argCopy.Length);
return argCopy;
}
/// <summary>
/// Gets a string array containing the command line arguments without the name of exectuable.
/// </summary>
public string[] Args {
get {
var argCopy = new string[_commandLineArgs.Length - 1];
Array.Copy(_commandLineArgs, 1, argCopy, 0, argCopy.Length);
return argCopy;
}
}
}
| NewInstanceEventArgs |
csharp | dotnet__maui | src/Compatibility/Core/src/iOS/Renderers/IndicatorViewRenderer.cs | {
"start": 5889,
"end": 6439
} | class ____ : UIPageControl
{
const int DefaultIndicatorSize = 7;
public bool IsSquare { get; set; }
public double IndicatorSize { get; set; }
public override void LayoutSubviews()
{
base.LayoutSubviews();
float scale = (float)IndicatorSize / DefaultIndicatorSize;
var newTransform = CGAffineTransform.MakeScale(scale, scale);
Transform = newTransform;
if (Subviews.Length == 0)
return;
foreach (var view in Subviews)
{
if (IsSquare)
{
view.Layer.CornerRadius = 0;
}
}
}
}
} | FormsPageControl |
csharp | OrchardCMS__OrchardCore | src/OrchardCore.Modules/OrchardCore.Contents/AuditTrail/ViewModels/AuditTrailPartSettingsViewModel.cs | {
"start": 55,
"end": 151
} | public class ____
{
public bool ShowCommentInput { get; set; }
}
| AuditTrailPartSettingsViewModel |
csharp | dotnet__efcore | test/EFCore.SqlServer.FunctionalTests/TestUtilities/SqlServerCondition.cs | {
"start": 202,
"end": 815
} | public enum ____
{
IsAzureSql = 1 << 0,
IsNotAzureSql = 1 << 1,
SupportsMemoryOptimized = 1 << 2,
SupportsAttach = 1 << 3,
SupportsHiddenColumns = 1 << 4,
IsNotCI = 1 << 5,
SupportsFullTextSearch = 1 << 6,
SupportsOnlineIndexes = 1 << 7,
SupportsTemporalTablesCascadeDelete = 1 << 8,
SupportsUtf8 = 1 << 9,
SupportsJsonPathExpressions = 1 << 10,
SupportsSqlClr = 1 << 11,
SupportsFunctions2017 = 1 << 12,
SupportsFunctions2019 = 1 << 13,
SupportsFunctions2022 = 1 << 14,
SupportsJsonType = 1 << 15,
SupportsVectorType = 1 << 16,
}
| SqlServerCondition |
csharp | grpc__grpc-dotnet | src/Grpc.Net.Client/Internal/Configuration/ConvertHelpers.cs | {
"start": 742,
"end": 5068
} | internal static class ____
{
public static string ConvertStatusCode(StatusCode statusCode)
{
return statusCode switch
{
StatusCode.OK => "OK",
StatusCode.Cancelled => "CANCELLED",
StatusCode.Unknown => "UNKNOWN",
StatusCode.InvalidArgument => "INVALID_ARGUMENT",
StatusCode.DeadlineExceeded => "DEADLINE_EXCEEDED",
StatusCode.NotFound => "NOT_FOUND",
StatusCode.AlreadyExists => "ALREADY_EXISTS",
StatusCode.PermissionDenied => "PERMISSION_DENIED",
StatusCode.Unauthenticated => "UNAUTHENTICATED",
StatusCode.ResourceExhausted => "RESOURCE_EXHAUSTED",
StatusCode.FailedPrecondition => "FAILED_PRECONDITION",
StatusCode.Aborted => "ABORTED",
StatusCode.OutOfRange => "OUT_OF_RANGE",
StatusCode.Unimplemented => "UNIMPLEMENTED",
StatusCode.Internal => "INTERNAL",
StatusCode.Unavailable => "UNAVAILABLE",
StatusCode.DataLoss => "DATA_LOSS",
_ => throw new InvalidOperationException($"Unexpected status code: {statusCode}")
};
}
public static StatusCode ConvertStatusCode(string statusCode)
{
return statusCode.ToUpperInvariant() switch
{
"OK" => StatusCode.OK,
"CANCELLED" => StatusCode.Cancelled,
"UNKNOWN" => StatusCode.Unknown,
"INVALID_ARGUMENT" => StatusCode.InvalidArgument,
"DEADLINE_EXCEEDED" => StatusCode.DeadlineExceeded,
"NOT_FOUND" => StatusCode.NotFound,
"ALREADY_EXISTS" => StatusCode.AlreadyExists,
"PERMISSION_DENIED" => StatusCode.PermissionDenied,
"UNAUTHENTICATED" => StatusCode.Unauthenticated,
"RESOURCE_EXHAUSTED" => StatusCode.ResourceExhausted,
"FAILED_PRECONDITION" => StatusCode.FailedPrecondition,
"ABORTED" => StatusCode.Aborted,
"OUT_OF_RANGE" => StatusCode.OutOfRange,
"UNIMPLEMENTED" => StatusCode.Unimplemented,
"INTERNAL" => StatusCode.Internal,
"UNAVAILABLE" => StatusCode.Unavailable,
"DATA_LOSS" => StatusCode.DataLoss,
_ => int.TryParse(statusCode, out var number)
? (StatusCode)number
: throw new InvalidOperationException($"Unexpected status code: {statusCode}")
};
}
public static TimeSpan? ConvertDurationText(string? text)
{
if (text == null)
{
return null;
}
// This format is based on the Protobuf duration's JSON mapping.
// https://github.com/protocolbuffers/protobuf/blob/35bdcabdd6a05ce9ee738ad7df8c1299d9c7fc4b/src/google/protobuf/duration.proto#L92
//
// Note that this is precise down to ticks. Fractions that are smaller than ticks will be lost.
// This shouldn't matter because timers on Windows and Linux only have millisecond precision.
if (text.Length > 0 && text[text.Length - 1] == 's')
{
#if NET5_0_OR_GREATER
var decimalText = text.AsSpan(0, text.Length - 1);
#else
var decimalText = text.Substring(0, text.Length - 1);
#endif
if (decimal.TryParse(decimalText, NumberStyles.AllowDecimalPoint | NumberStyles.AllowLeadingSign, CultureInfo.InvariantCulture, out var seconds))
{
try
{
var ticks = (long)(seconds * TimeSpan.TicksPerSecond);
return TimeSpan.FromTicks(ticks);
}
catch (Exception ex)
{
throw new FormatException($"'{text}' isn't a valid duration.", ex);
}
}
}
throw new FormatException($"'{text}' isn't a valid duration.");
}
public static string? ToDurationText(TimeSpan? value)
{
if (value == null)
{
return null;
}
// This format is based on the Protobuf duration's JSON mapping.
// https://github.com/protocolbuffers/protobuf/blob/35bdcabdd6a05ce9ee738ad7df8c1299d9c7fc4b/src/google/protobuf/duration.proto#L92
return value.Value.TotalSeconds.ToString(CultureInfo.InvariantCulture) + "s";
}
}
| ConvertHelpers |
csharp | dotnet__machinelearning | src/Microsoft.ML.CodeGenerator/CodeGenerator/CSharp/TrainerGenerators.cs | {
"start": 13462,
"end": 14924
} | internal class ____ : TrainerGeneratorBase
{
//ClassName of the trainer
internal override string MethodName => "LbfgsPoissonRegression";
//ClassName of the options to trainer
internal override string OptionsName => "LbfgsPoissonRegressionTrainer.Options";
//The named parameters to the trainer.
internal override IDictionary<string, string> NamedParameters
{
get
{
return
new Dictionary<string, string>()
{
{"ExampleWeightColumnName","exampleWeightColumnName" },
{"LabelColumnName","labelColumnName" },
{"FeatureColumnName","featureColumnName" },
{"L1Regularization","l1Regularization" },
{"L2Regularization","l2Regularization" },
{"OptimizationTolerance","optimizationTolerance" },
{"HistorySize","historySize" },
{"EnforceNonNegativity","enforceNonNegativity" },
};
}
}
internal override string[] Usings => new string[] { "using Microsoft.ML.Trainers;\r\n" };
public LbfgsPoissonRegression(PipelineNode node) : base(node)
{
}
}
#region SDCA
| LbfgsPoissonRegression |
csharp | MahApps__MahApps.Metro | src/MahApps.Metro/Controls/Helper/ControlsHelper.cs | {
"start": 521,
"end": 12849
} | public static class ____
{
public static readonly DependencyProperty DisabledVisualElementVisibilityProperty
= DependencyProperty.RegisterAttached(
"DisabledVisualElementVisibility",
typeof(Visibility),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(Visibility.Visible, FrameworkPropertyMetadataOptions.Inherits | FrameworkPropertyMetadataOptions.AffectsMeasure));
/// <summary>
/// Gets the value to handle the visibility of the DisabledVisualElement in the template.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBoxBase))]
[AttachedPropertyBrowsableForType(typeof(PasswordBox))]
[AttachedPropertyBrowsableForType(typeof(NumericUpDown))]
[AttachedPropertyBrowsableForType(typeof(MultiSelectionComboBox))]
public static Visibility GetDisabledVisualElementVisibility(UIElement element)
{
return (Visibility)element.GetValue(DisabledVisualElementVisibilityProperty);
}
/// <summary>
/// Sets the value to handle the visibility of the DisabledVisualElement in the template.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBoxBase))]
[AttachedPropertyBrowsableForType(typeof(PasswordBox))]
[AttachedPropertyBrowsableForType(typeof(NumericUpDown))]
[AttachedPropertyBrowsableForType(typeof(MultiSelectionComboBox))]
public static void SetDisabledVisualElementVisibility(UIElement element, Visibility value)
{
element.SetValue(DisabledVisualElementVisibilityProperty, value);
}
/// <summary>
/// The DependencyProperty for the CharacterCasing property.
/// The Controls content will be converted to upper or lower case if it is a string.
/// </summary>
public static readonly DependencyProperty ContentCharacterCasingProperty =
DependencyProperty.RegisterAttached(
"ContentCharacterCasing",
typeof(CharacterCasing),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(CharacterCasing.Normal, FrameworkPropertyMetadataOptions.AffectsMeasure),
value => CharacterCasing.Normal <= (CharacterCasing)value && (CharacterCasing)value <= CharacterCasing.Upper);
/// <summary>
/// Gets the character casing of the control
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(ContentControl))]
[AttachedPropertyBrowsableForType(typeof(DropDownButton))]
[AttachedPropertyBrowsableForType(typeof(SplitButton))]
[AttachedPropertyBrowsableForType(typeof(WindowCommands))]
[AttachedPropertyBrowsableForType(typeof(ColorPalette))]
public static CharacterCasing GetContentCharacterCasing(UIElement element)
{
return (CharacterCasing)element.GetValue(ContentCharacterCasingProperty);
}
/// <summary>
/// Sets the character casing of the control
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(ContentControl))]
[AttachedPropertyBrowsableForType(typeof(DropDownButton))]
[AttachedPropertyBrowsableForType(typeof(SplitButton))]
[AttachedPropertyBrowsableForType(typeof(WindowCommands))]
[AttachedPropertyBrowsableForType(typeof(ColorPalette))]
public static void SetContentCharacterCasing(UIElement element, CharacterCasing value)
{
element.SetValue(ContentCharacterCasingProperty, value);
}
public static readonly DependencyProperty RecognizesAccessKeyProperty
= DependencyProperty.RegisterAttached(
"RecognizesAccessKey",
typeof(bool),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(BooleanBoxes.TrueBox));
/// <summary>
/// Gets the value if the inner ContentPresenter use AccessText in its style.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(ContentControl))]
[AttachedPropertyBrowsableForType(typeof(DropDownButton))]
[AttachedPropertyBrowsableForType(typeof(SplitButton))]
public static bool GetRecognizesAccessKey(UIElement element)
{
return (bool)element.GetValue(RecognizesAccessKeyProperty);
}
/// <summary>
/// Sets the value if the inner ContentPresenter should use AccessText in its style.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(ContentControl))]
[AttachedPropertyBrowsableForType(typeof(DropDownButton))]
[AttachedPropertyBrowsableForType(typeof(SplitButton))]
public static void SetRecognizesAccessKey(UIElement element, bool value)
{
element.SetValue(RecognizesAccessKeyProperty, BooleanBoxes.Box(value));
}
public static readonly DependencyProperty FocusBorderBrushProperty
= DependencyProperty.RegisterAttached(
"FocusBorderBrush",
typeof(Brush),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits));
/// <summary>
/// Gets the brush used to draw the focus border.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
[AttachedPropertyBrowsableForType(typeof(DatePicker))]
[AttachedPropertyBrowsableForType(typeof(ComboBox))]
[AttachedPropertyBrowsableForType(typeof(ButtonBase))]
public static Brush GetFocusBorderBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(FocusBorderBrushProperty);
}
/// <summary>
/// Sets the brush used to draw the focus border.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
[AttachedPropertyBrowsableForType(typeof(DatePicker))]
[AttachedPropertyBrowsableForType(typeof(ComboBox))]
[AttachedPropertyBrowsableForType(typeof(ButtonBase))]
public static void SetFocusBorderBrush(DependencyObject obj, Brush value)
{
obj.SetValue(FocusBorderBrushProperty, value);
}
public static readonly DependencyProperty FocusBorderThicknessProperty
= DependencyProperty.RegisterAttached(
"FocusBorderThickness",
typeof(Thickness),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(default(Thickness), FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits));
/// <summary>
/// Gets the brush used to draw the focus border.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
[AttachedPropertyBrowsableForType(typeof(DatePicker))]
[AttachedPropertyBrowsableForType(typeof(ComboBox))]
[AttachedPropertyBrowsableForType(typeof(ButtonBase))]
public static Thickness GetFocusBorderThickness(DependencyObject obj)
{
return (Thickness)obj.GetValue(FocusBorderThicknessProperty);
}
/// <summary>
/// Sets the brush used to draw the focus border.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
[AttachedPropertyBrowsableForType(typeof(DatePicker))]
[AttachedPropertyBrowsableForType(typeof(ComboBox))]
[AttachedPropertyBrowsableForType(typeof(ButtonBase))]
public static void SetFocusBorderThickness(DependencyObject obj, Thickness value)
{
obj.SetValue(FocusBorderThicknessProperty, value);
}
public static readonly DependencyProperty MouseOverBorderBrushProperty
= DependencyProperty.RegisterAttached(
"MouseOverBorderBrush",
typeof(Brush),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(Brushes.Transparent, FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.Inherits));
/// <summary>
/// Gets the brush used to draw the mouse over brush.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
[AttachedPropertyBrowsableForType(typeof(CheckBox))]
[AttachedPropertyBrowsableForType(typeof(RadioButton))]
[AttachedPropertyBrowsableForType(typeof(DatePicker))]
[AttachedPropertyBrowsableForType(typeof(ComboBox))]
[AttachedPropertyBrowsableForType(typeof(Tile))]
public static Brush GetMouseOverBorderBrush(DependencyObject obj)
{
return (Brush)obj.GetValue(MouseOverBorderBrushProperty);
}
/// <summary>
/// Sets the brush used to draw the mouse over brush.
/// </summary>
[Category(AppName.MahApps)]
[AttachedPropertyBrowsableForType(typeof(TextBox))]
[AttachedPropertyBrowsableForType(typeof(CheckBox))]
[AttachedPropertyBrowsableForType(typeof(RadioButton))]
[AttachedPropertyBrowsableForType(typeof(DatePicker))]
[AttachedPropertyBrowsableForType(typeof(ComboBox))]
[AttachedPropertyBrowsableForType(typeof(Tile))]
public static void SetMouseOverBorderBrush(DependencyObject obj, Brush value)
{
obj.SetValue(MouseOverBorderBrushProperty, value);
}
/// <summary>
/// DependencyProperty for <see cref="CornerRadius" /> property.
/// </summary>
public static readonly DependencyProperty CornerRadiusProperty
= DependencyProperty.RegisterAttached(
"CornerRadius",
typeof(CornerRadius),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(new CornerRadius(), FrameworkPropertyMetadataOptions.AffectsMeasure | FrameworkPropertyMetadataOptions.AffectsRender));
/// <summary>
/// The CornerRadius property allows users to control the roundness of the button corners independently by
/// setting a radius value for each corner. Radius values that are too large are scaled so that they
/// smoothly blend from corner to corner. (Can be used e.g. at MetroButton style)
/// Description taken from original Microsoft description :-D
/// </summary>
[Category(AppName.MahApps)]
public static CornerRadius GetCornerRadius(UIElement element)
{
return (CornerRadius)element.GetValue(CornerRadiusProperty);
}
[Category(AppName.MahApps)]
public static void SetCornerRadius(UIElement element, CornerRadius value)
{
element.SetValue(CornerRadiusProperty, value);
}
/// <summary>
/// Gets or sets a value indicating whether the child contents of the control are not editable.
/// </summary>
public static readonly DependencyProperty IsReadOnlyProperty
= DependencyProperty.RegisterAttached(
"IsReadOnly",
typeof(bool),
typeof(ControlsHelper),
new FrameworkPropertyMetadata(BooleanBoxes.FalseBox));
/// <summary>
/// Gets a value indicating whether the child contents of the control are not editable.
/// </summary>
public static bool GetIsReadOnly(UIElement element)
{
return (bool)element.GetValue(IsReadOnlyProperty);
}
/// <summary>
/// Sets a value indicating whether the child contents of the control are not editable.
/// </summary>
public static void SetIsReadOnly(UIElement element, bool value)
{
element.SetValue(IsReadOnlyProperty, BooleanBoxes.Box(value));
}
}
} | ControlsHelper |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Media/Animation/PanelTransitionHelper.cs | {
"start": 5927,
"end": 6109
} | private class ____
{
public View Element
{
get; set;
}
public int OffsetX
{
get; set;
}
public int OffsetY
{
get; set;
}
}
}
}
| ChildWithOffset |
csharp | AutoFixture__AutoFixture | Src/AutoFixtureUnitTest/FixtureTest.cs | {
"start": 194085,
"end": 194304
} | private class ____
{
public RecursionTestObjectWithReferenceOutA ReferenceToA
{
get;
set;
}
}
| RecursionTestObjectWithReferenceOutB |
csharp | dotnet__machinelearning | src/Microsoft.ML.Data/DataLoadSave/Text/TextLoaderCursor.cs | {
"start": 36874,
"end": 44309
} | private sealed class ____ : IDisposable
{
private readonly Cursor _curs;
private readonly LineReader _reader;
private readonly RowSet _rows;
// Number of blocks in this RowSet.
private readonly int _blockCount;
// Size of blocks in this RowSet.
private const int BlockSize = BatchSize;
// Ordered waiters on block numbers.
// _waiterWorking orders reading from _reader.
// _waiterPublish orders publishing to _queue.
private readonly OrderedWaiter _waiterReading;
private readonly OrderedWaiter _waiterPublish;
// A small capacity blocking collection that the main cursor thread consumes.
private readonly BlockingQueue<RowBatch> _queue;
private readonly Task[] _threads;
// Number of threads still running.
private int _threadsRunning;
// Signals threads to shut down.
private volatile bool _done;
// Exception during parsing.
public volatile Exception ParsingException;
public ParallelState(Cursor curs, out RowSet rows, int cthd)
{
Contracts.AssertValue(curs);
Contracts.Assert(cthd > 0);
_curs = curs;
_reader = _curs._reader;
// Why cthd + 3? We need two blocks for the blocking collection, and one
// more for the block currently being dished out by the cursor.
_blockCount = cthd + 3;
// Why cthd + 3? We need two blocks for the blocking collection, and one
// more for the block currently being dished out by the cursor.
_rows = rows = _curs._parser.CreateRowSet(_curs._stats,
checked(_blockCount * BlockSize), _curs._active);
_waiterReading = new OrderedWaiter(firstCleared: false);
_waiterPublish = new OrderedWaiter(firstCleared: false);
// The size limit here ensures that worker threads are never writing to
// a range that is being served up by the cursor.
_queue = new BlockingQueue<RowBatch>(2);
_threads = new Task[cthd];
_threadsRunning = cthd;
for (int tid = 0; tid < _threads.Length; tid++)
{
_threads[tid] = Utils.RunOnBackgroundThreadAsync(ThreadProc, tid);
}
}
public void Dispose()
{
// Signal all the threads to shut down and wait for them.
Quit();
Task.WaitAll(_threads);
}
private void Quit()
{
// Signal that we're done and wake up all the threads.
_done = true;
_waiterReading.IncrementAll();
_waiterPublish.IncrementAll();
}
public IEnumerable<RowBatch> GetBatches()
{
_waiterReading.Increment();
_waiterPublish.Increment();
return _queue.GetConsumingEnumerable();
}
private void ThreadProc(object obj)
{
// The object is the thread index, or "id".
int tid = (int)obj;
Contracts.Assert(0 <= tid && tid < _threads.Length);
try
{
Parse(tid);
}
catch (Exception ex)
{
// Record the exception and tell everyone to shut down.
ParsingException = ex;
Quit();
}
finally
{
// If this is the last thread to shut down, close the queue.
if (Interlocked.Decrement(ref _threadsRunning) <= 0)
_queue.CompleteAdding();
}
}
private void Parse(int tid)
{
long blk = tid;
int iblk = tid;
Contracts.Assert(iblk < _blockCount - 3);
var helper = _curs._parser.CreateHelper(_rows.Stats, _curs._srcNeeded);
while (!_done)
{
// Algorithm:
// * When it is our turn, grab a block of lines.
// * Parse rows.
// * When it is our turn, enqueue the batch.
// When it is our turn, read the lines and signal the next worker that it is ok to read.
LineBatch lines;
_waiterReading.Wait(blk);
if (_done)
return;
try
{
lines = _reader.GetBatch();
}
finally
{
_waiterReading.Increment();
}
Contracts.Assert(lines.Exception == null);
if (lines.Infos == null || _done)
return;
// Parse the lines into rows.
Contracts.Assert(lines.Infos.Length <= BlockSize);
var batch = new RowBatch(iblk * BlockSize, iblk * BlockSize + lines.Infos.Length, lines.Total);
int irow = batch.IrowMin;
foreach (var info in lines.Infos)
{
Contracts.Assert(info.Line > 0);
Contracts.AssertNonEmpty(info.Text);
if (_done)
return;
_curs._parser.ParseRow(_rows, irow, helper, _curs._active, lines.Path, info.Line, info.Text);
irow++;
}
Contracts.Assert(irow == batch.IrowLim);
if (_done)
return;
// When it is our turn, publish the rows and signal the next worker that it is ok to publish.
_waiterPublish.Wait(blk);
if (_done)
return;
while (!_queue.TryAdd(batch, TimeOut))
{
if (_done)
return;
}
_waiterPublish.Increment();
blk += _threads.Length;
iblk += _threads.Length;
if (iblk >= _blockCount)
iblk -= _blockCount;
Contracts.Assert(0 <= iblk && iblk < _blockCount);
}
}
}
}
}
}
| ParallelState |
csharp | bitwarden__server | src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/InviteUsers/IResendOrganizationInviteCommand.cs | {
"start": 86,
"end": 807
} | public interface ____
{
/// <summary>
/// Resend an invite to an organization user.
/// </summary>
/// <param name="organizationId">The ID of the organization.</param>
/// <param name="invitingUserId">The ID of the user who is inviting the organization user.</param>
/// <param name="organizationUserId">The ID of the organization user to resend the invite to.</param>
/// <param name="initOrganization">Whether to initialize the organization.
/// This is should only be true when inviting the owner of a new organization.</param>
Task ResendInviteAsync(Guid organizationId, Guid? invitingUserId, Guid organizationUserId, bool initOrganization = false);
}
| IResendOrganizationInviteCommand |
csharp | bitwarden__server | src/Core/AdminConsole/OrganizationFeatures/OrganizationUsers/InviteUsers/Errors/NoUsersToInviteError.cs | {
"start": 227,
"end": 418
} | public record ____(InviteOrganizationUsersResponse Response) : Error<InviteOrganizationUsersResponse>(Code, Response)
{
public const string Code = "No users to invite";
}
| NoUsersToInviteError |
csharp | ServiceStack__ServiceStack | ServiceStack.OrmLite/src/ServiceStack.OrmLite.MySqlConnector/MySqlConnectorConfiguration.cs | {
"start": 100,
"end": 1378
} | public static class ____
{
public static MySqlConnectorDialectProvider Configure(MySqlConnectorDialectProvider dialect)
{
dialect.UseJson = true;
return dialect;
}
public static MySqlConnectorDialectProvider UseMySqlConnector(this OrmLiteConfigOptions config, string? connectionString, Action<MySqlConnectorDialectProvider>? configure=null)
{
if (connectionString == null)
throw new ArgumentNullException(nameof(connectionString));
var dialect = Configure(new MySqlConnectorDialectProvider());
configure?.Invoke(dialect);
config.Init(connectionString, dialect);
return dialect;
}
public static OrmLiteConfigurationBuilder AddMySqlConnector(this OrmLiteConfigurationBuilder builder,
string namedConnection, string? connectionString, Action<MySqlConnectorDialectProvider>? configure=null)
{
if (connectionString == null)
throw new ArgumentNullException(nameof(connectionString));
var dialect = Configure(new MySqlConnectorDialectProvider());
configure?.Invoke(dialect);
builder.DbFactory.RegisterConnection(namedConnection, connectionString, dialect);
return builder;
}
}
| MySqlConnectorConfiguration |
csharp | MonoGame__MonoGame | MonoGame.Framework/Ray.cs | {
"start": 471,
"end": 13308
} | public struct ____ : IEquatable<Ray>
{
#region Public Fields
/// <summary>
/// The direction of this <see cref="Ray"/>.
/// </summary>
[DataMember]
public Vector3 Direction;
/// <summary>
/// The origin of this <see cref="Ray"/>.
/// </summary>
[DataMember]
public Vector3 Position;
#endregion
#region Public Constructors
/// <summary>
/// Create a <see cref="Ray"/>.
/// </summary>
/// <param name="position">The origin of the <see cref="Ray"/>.</param>
/// <param name="direction">The direction of the <see cref="Ray"/>.</param>
public Ray(Vector3 position, Vector3 direction)
{
this.Position = position;
this.Direction = direction;
}
#endregion
#region Public Methods
/// <summary>
/// Check if the specified <see cref="Object"/> is equal to this <see cref="Ray"/>.
/// </summary>
/// <param name="obj">The <see cref="Object"/> to test for equality with this <see cref="Ray"/>.</param>
/// <returns>
/// <code>true</code> if the specified <see cref="Object"/> is equal to this <see cref="Ray"/>,
/// <code>false</code> if it is not.
/// </returns>
public override bool Equals(object obj)
{
return (obj is Ray) && this.Equals((Ray)obj);
}
/// <summary>
/// Check if the specified <see cref="Ray"/> is equal to this <see cref="Ray"/>.
/// </summary>
/// <param name="other">The <see cref="Ray"/> to test for equality with this <see cref="Ray"/>.</param>
/// <returns>
/// <code>true</code> if the specified <see cref="Ray"/> is equal to this <see cref="Ray"/>,
/// <code>false</code> if it is not.
/// </returns>
public bool Equals(Ray other)
{
return this.Position.Equals(other.Position) && this.Direction.Equals(other.Direction);
}
/// <summary>
/// Get a hash code for this <see cref="Ray"/>.
/// </summary>
/// <returns>A hash code for this <see cref="Ray"/>.</returns>
public override int GetHashCode()
{
return Position.GetHashCode() ^ Direction.GetHashCode();
}
// adapted from http://www.scratchapixel.com/lessons/3d-basic-lessons/lesson-7-intersecting-simple-shapes/ray-box-intersection/
/// <summary>
/// Check if this <see cref="Ray"/> intersects the specified <see cref="BoundingBox"/>.
/// </summary>
/// <param name="box">The <see cref="BoundingBox"/> to test for intersection.</param>
/// <returns>
/// The distance along the ray of the intersection or <code>null</code> if this
/// <see cref="Ray"/> does not intersect the <see cref="BoundingBox"/>.
/// </returns>
public float? Intersects(BoundingBox box)
{
const float Epsilon = 1e-6f;
float? tMin = null, tMax = null;
if (Math.Abs(Direction.X) < Epsilon)
{
if (Position.X < box.Min.X || Position.X > box.Max.X)
return null;
}
else
{
tMin = (box.Min.X - Position.X) / Direction.X;
tMax = (box.Max.X - Position.X) / Direction.X;
if (tMin > tMax)
{
var temp = tMin;
tMin = tMax;
tMax = temp;
}
}
if (Math.Abs(Direction.Y) < Epsilon)
{
if (Position.Y < box.Min.Y || Position.Y > box.Max.Y)
return null;
}
else
{
var tMinY = (box.Min.Y - Position.Y) / Direction.Y;
var tMaxY = (box.Max.Y - Position.Y) / Direction.Y;
if (tMinY > tMaxY)
{
var temp = tMinY;
tMinY = tMaxY;
tMaxY = temp;
}
if ((tMin.HasValue && tMin > tMaxY) || (tMax.HasValue && tMinY > tMax))
return null;
if (!tMin.HasValue || tMinY > tMin) tMin = tMinY;
if (!tMax.HasValue || tMaxY < tMax) tMax = tMaxY;
}
if (Math.Abs(Direction.Z) < Epsilon)
{
if (Position.Z < box.Min.Z || Position.Z > box.Max.Z)
return null;
}
else
{
var tMinZ = (box.Min.Z - Position.Z) / Direction.Z;
var tMaxZ = (box.Max.Z - Position.Z) / Direction.Z;
if (tMinZ > tMaxZ)
{
var temp = tMinZ;
tMinZ = tMaxZ;
tMaxZ = temp;
}
if ((tMin.HasValue && tMin > tMaxZ) || (tMax.HasValue && tMinZ > tMax))
return null;
if (!tMin.HasValue || tMinZ > tMin) tMin = tMinZ;
if (!tMax.HasValue || tMaxZ < tMax) tMax = tMaxZ;
}
// having a positive tMax and a negative tMin means the ray is inside the box
// we expect the intesection distance to be 0 in that case
if ((tMin.HasValue && tMin < 0) && tMax > 0) return 0;
// a negative tMin means that the intersection point is behind the ray's origin
// we discard these as not hitting the AABB
if (tMin < 0) return null;
return tMin;
}
/// <summary>
/// Check if this <see cref="Ray"/> intersects the specified <see cref="BoundingBox"/>.
/// </summary>
/// <param name="box">The <see cref="BoundingBox"/> to test for intersection.</param>
/// <param name="result">
/// The distance along the ray of the intersection or <code>null</code> if this
/// <see cref="Ray"/> does not intersect the <see cref="BoundingBox"/>.
/// </param>
public void Intersects(ref BoundingBox box, out float? result)
{
result = Intersects(box);
}
/*
public float? Intersects(BoundingFrustum frustum)
{
if (frustum == null)
{
throw new ArgumentNullException("frustum");
}
return frustum.Intersects(this);
}
*/
/// <summary>
/// Check if this <see cref="Ray"/> intersects the specified <see cref="BoundingSphere"/>.
/// </summary>
/// <param name="sphere">The <see cref="BoundingBox"/> to test for intersection.</param>
/// <returns>
/// The distance along the ray of the intersection or <code>null</code> if this
/// <see cref="Ray"/> does not intersect the <see cref="BoundingSphere"/>.
/// </returns>
public float? Intersects(BoundingSphere sphere)
{
float? result;
Intersects(ref sphere, out result);
return result;
}
/// <summary>
/// Check if this <see cref="Ray"/> intersects the specified <see cref="Plane"/>.
/// </summary>
/// <param name="plane">The <see cref="Plane"/> to test for intersection.</param>
/// <returns>
/// The distance along the ray of the intersection or <code>null</code> if this
/// <see cref="Ray"/> does not intersect the <see cref="Plane"/>.
/// </returns>
public float? Intersects(Plane plane)
{
float? result;
Intersects(ref plane, out result);
return result;
}
/// <summary>
/// Check if this <see cref="Ray"/> intersects the specified <see cref="Plane"/>.
/// </summary>
/// <param name="plane">The <see cref="Plane"/> to test for intersection.</param>
/// <param name="result">
/// The distance along the ray of the intersection or <code>null</code> if this
/// <see cref="Ray"/> does not intersect the <see cref="Plane"/>.
/// </param>
public void Intersects(ref Plane plane, out float? result)
{
var den = Vector3.Dot(Direction, plane.Normal);
if (Math.Abs(den) < 0.00001f)
{
result = null;
return;
}
result = (-plane.D - Vector3.Dot(plane.Normal, Position)) / den;
if (result < 0.0f)
{
if (result < -0.00001f)
{
result = null;
return;
}
result = 0.0f;
}
}
/// <summary>
/// Check if this <see cref="Ray"/> intersects the specified <see cref="BoundingSphere"/>.
/// </summary>
/// <param name="sphere">The <see cref="BoundingBox"/> to test for intersection.</param>
/// <param name="result">
/// The distance along the ray of the intersection or <code>null</code> if this
/// <see cref="Ray"/> does not intersect the <see cref="BoundingSphere"/>.
/// </param>
public void Intersects(ref BoundingSphere sphere, out float? result)
{
// Find the vector between where the ray starts the the sphere's centre
Vector3 difference = sphere.Center - this.Position;
float differenceLengthSquared = difference.LengthSquared();
float sphereRadiusSquared = sphere.Radius * sphere.Radius;
float distanceAlongRay;
// If the distance between the ray start and the sphere's centre is less than
// the radius of the sphere, it means we've intersected. N.B. checking the LengthSquared is faster.
if (differenceLengthSquared < sphereRadiusSquared)
{
result = 0.0f;
return;
}
Vector3.Dot(ref this.Direction, ref difference, out distanceAlongRay);
// If the ray is pointing away from the sphere then we don't ever intersect
if (distanceAlongRay < 0)
{
result = null;
return;
}
// Next we kinda use Pythagoras to check if we are within the bounds of the sphere
// if x = radius of sphere
// if y = distance between ray position and sphere centre
// if z = the distance we've travelled along the ray
// if x^2 + z^2 - y^2 < 0, we do not intersect
float dist = sphereRadiusSquared + distanceAlongRay * distanceAlongRay - differenceLengthSquared;
result = (dist < 0) ? null : distanceAlongRay - (float?)MathF.Sqrt(dist);
}
/// <summary>
/// Check if two rays are not equal.
/// </summary>
/// <param name="a">A ray to check for inequality.</param>
/// <param name="b">A ray to check for inequality.</param>
/// <returns><code>true</code> if the two rays are not equal, <code>false</code> if they are.</returns>
public static bool operator !=(Ray a, Ray b)
{
return !a.Equals(b);
}
/// <summary>
/// Check if two rays are equal.
/// </summary>
/// <param name="a">A ray to check for equality.</param>
/// <param name="b">A ray to check for equality.</param>
/// <returns><code>true</code> if the two rays are equals, <code>false</code> if they are not.</returns>
public static bool operator ==(Ray a, Ray b)
{
return a.Equals(b);
}
internal string DebugDisplayString
{
get
{
return string.Concat(
"Pos( ", this.Position.DebugDisplayString, " ) \r\n",
"Dir( ", this.Direction.DebugDisplayString, " )"
);
}
}
/// <summary>
/// Get a <see cref="String"/> representation of this <see cref="Ray"/>.
/// </summary>
/// <returns>A <see cref="String"/> representation of this <see cref="Ray"/>.</returns>
public override string ToString()
{
return "{{Position:" + Position.ToString() + " Direction:" + Direction.ToString() + "}}";
}
/// <summary>
/// Deconstruction method for <see cref="Ray"/>.
/// </summary>
/// <param name="position">Receives the start position of the ray.</param>
/// <param name="direction">Receives the direction of the ray.</param>
public void Deconstruct(out Vector3 position, out Vector3 direction)
{
position = Position;
direction = Direction;
}
#endregion
}
}
| Ray |
csharp | cake-build__cake | src/Cake.Common/Tools/DotNet/Package/Search/DotNetPackageSearcher.cs | {
"start": 500,
"end": 4819
} | public sealed class ____ : DotNetTool<DotNetPackageSearchSettings>
{
private static readonly JsonSerializerOptions _jsonSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web);
private readonly ICakeEnvironment _environment;
/// <summary>
/// Initializes a new instance of the <see cref="DotNetPackageSearcher" /> class.
/// </summary>
/// <param name="fileSystem">The file system.</param>
/// <param name="environment">The environment.</param>
/// <param name="processRunner">The process runner.</param>
/// <param name="tools">The tool locator.</param>
public DotNetPackageSearcher(
IFileSystem fileSystem,
ICakeEnvironment environment,
IProcessRunner processRunner,
IToolLocator tools) : base(fileSystem, environment, processRunner, tools)
{
_environment = environment;
}
/// <summary>
/// Searches for packages.
/// </summary>
/// <param name="searchTerm">The search term.</param>
/// <param name="settings">The search settings.</param>
/// <returns>A collection of <see cref="DotNetPackageSearchItem"/>.</returns>
public IEnumerable<DotNetPackageSearchItem> Search(string searchTerm, DotNetPackageSearchSettings settings)
{
ArgumentNullException.ThrowIfNull(settings);
var processSettings = new ProcessSettings
{
RedirectStandardOutput = true
};
using var ms = new MemoryStream();
RunCommand(
settings,
GetArguments(searchTerm, settings),
processSettings,
process =>
{
using var sr = new StreamWriter(ms, leaveOpen: true);
foreach (var line in process.GetStandardOutput())
{
sr.WriteLine(line);
}
});
return Parse(ms.GetBuffer().AsMemory(0, (int)ms.Length)).ToList();
}
private ProcessArgumentBuilder GetArguments(string searchTerm, DotNetPackageSearchSettings settings)
{
var builder = new ProcessArgumentBuilder();
builder.Append("package search");
if (!string.IsNullOrEmpty(searchTerm))
{
builder.AppendQuoted(searchTerm);
}
if (settings.Prerelease)
{
builder.Append("--prerelease");
}
if (settings.ExactMatch)
{
builder.Append("--exact-match");
}
if (settings.Sources != null && settings.Sources.Count > 0)
{
foreach (var source in settings.Sources)
{
builder.Append("--source");
builder.AppendQuoted(source);
}
}
if (settings.ConfigFile != null)
{
builder.Append("--configfile");
builder.AppendQuoted(settings.ConfigFile.MakeAbsolute(_environment).FullPath);
}
if (settings.Take is { } take)
{
builder.Append("--take");
builder.Append(take.ToString());
}
if (settings.Skip is { } skip)
{
builder.Append("--skip");
builder.Append(skip.ToString());
}
builder.Append("--verbosity normal");
builder.Append("--format json");
return builder;
}
private static IEnumerable<DotNetPackageSearchItem> Parse(ReadOnlyMemory<byte> json)
{
var result = JsonSerializer.Deserialize<Result>(json.Span, _jsonSerializerOptions);
if (result is not null)
{
foreach (var searchResult in result.SearchResult)
{
foreach (var package in searchResult.Packages)
{
yield return new DotNetPackageSearchItem { Name = package.Id, Version = package.LatestVersion };
}
}
}
}
| DotNetPackageSearcher |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Graphics.Printing.Workflow/PrintWorkflowBackgroundSession.cs | {
"start": 309,
"end": 4961
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal PrintWorkflowBackgroundSession()
{
}
#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.Graphics.Printing.Workflow.PrintWorkflowSessionStatus Status
{
get
{
throw new global::System.NotImplementedException("The member PrintWorkflowSessionStatus PrintWorkflowBackgroundSession.Status is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=PrintWorkflowSessionStatus%20PrintWorkflowBackgroundSession.Status");
}
}
#endif
// Forced skipping of method Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession.SetupRequested.add
// Forced skipping of method Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession.SetupRequested.remove
// Forced skipping of method Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession.Submitted.add
// Forced skipping of method Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession.Submitted.remove
// Forced skipping of method Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession.Status.get
#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 void Start()
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession", "void PrintWorkflowBackgroundSession.Start()");
}
#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 event global::Windows.Foundation.TypedEventHandler<global::Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession, global::Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSetupRequestedEventArgs> SetupRequested
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession", "event TypedEventHandler<PrintWorkflowBackgroundSession, PrintWorkflowBackgroundSetupRequestedEventArgs> PrintWorkflowBackgroundSession.SetupRequested");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession", "event TypedEventHandler<PrintWorkflowBackgroundSession, PrintWorkflowBackgroundSetupRequestedEventArgs> PrintWorkflowBackgroundSession.SetupRequested");
}
}
#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 event global::Windows.Foundation.TypedEventHandler<global::Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession, global::Windows.Graphics.Printing.Workflow.PrintWorkflowSubmittedEventArgs> Submitted
{
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
add
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession", "event TypedEventHandler<PrintWorkflowBackgroundSession, PrintWorkflowSubmittedEventArgs> PrintWorkflowBackgroundSession.Submitted");
}
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
remove
{
global::Windows.Foundation.Metadata.ApiInformation.TryRaiseNotImplemented("Windows.Graphics.Printing.Workflow.PrintWorkflowBackgroundSession", "event TypedEventHandler<PrintWorkflowBackgroundSession, PrintWorkflowSubmittedEventArgs> PrintWorkflowBackgroundSession.Submitted");
}
}
#endif
}
}
| PrintWorkflowBackgroundSession |
csharp | dotnet__reactive | Rx.NET/Source/tests/Tests.System.Reactive/Tests/Linq/Observable/ObserveOnTest.cs | {
"start": 730,
"end": 7812
} | public class ____ : TestBase
{
#region + TestBase +
[TestMethod]
public void ObserveOn_ArgumentChecking()
{
var someObservable = Observable.Empty<int>();
#if HAS_WINFORMS
#pragma warning disable IDE0034 // (Simplify 'default'.) Want to be explicit about overloads being tested.
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.ObserveOn<int>(default(IObservable<int>), new ControlScheduler(new Label())));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.ObserveOn<int>(someObservable, default(ControlScheduler)));
ReactiveAssert.Throws<ArgumentNullException>(() => ControlObservable.ObserveOn<int>(default(IObservable<int>), new Label()));
ReactiveAssert.Throws<ArgumentNullException>(() => ControlObservable.ObserveOn<int>(someObservable, default(Label)));
#pragma warning restore IDE0034
#endif
#if HAS_WPF
#pragma warning disable IDE0034 // (Simplify 'default'.) Want to be explicit about overloads being tested.
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.ObserveOn<int>(default(IObservable<int>), new DispatcherScheduler(Dispatcher.CurrentDispatcher)));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.ObserveOn<int>(someObservable, default(DispatcherScheduler)));
ReactiveAssert.Throws<ArgumentNullException>(() => DispatcherObservable.ObserveOn<int>(default(IObservable<int>), Dispatcher.CurrentDispatcher));
ReactiveAssert.Throws<ArgumentNullException>(() => DispatcherObservable.ObserveOn<int>(someObservable, default(Dispatcher)));
ReactiveAssert.Throws<ArgumentNullException>(() => DispatcherObservable.ObserveOnDispatcher<int>(default(IObservable<int>)));
#pragma warning restore IDE0034
#endif
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.ObserveOn<int>(default, new SynchronizationContext()));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.ObserveOn(someObservable, default(SynchronizationContext)));
}
#if HAS_WINFORMS
[TestMethod]
public void ObserveOn_Control()
{
var okay = true;
using (WinFormsTestUtils.RunTest(out var lbl))
{
var evt = new ManualResetEvent(false);
Observable.Range(0, 10, NewThreadScheduler.Default).ObserveOn(lbl).Subscribe(x =>
{
lbl.Text = x.ToString();
okay &= (SynchronizationContext.Current is System.Windows.Forms.WindowsFormsSynchronizationContext);
}, () => evt.Set());
evt.WaitOne();
}
Assert.True(okay);
}
[TestMethod]
public void ObserveOn_ControlScheduler()
{
var okay = true;
using (WinFormsTestUtils.RunTest(out var lbl))
{
var evt = new ManualResetEvent(false);
Observable.Range(0, 10, NewThreadScheduler.Default).ObserveOn(new ControlScheduler(lbl)).Subscribe(x =>
{
lbl.Text = x.ToString();
okay &= (SynchronizationContext.Current is System.Windows.Forms.WindowsFormsSynchronizationContext);
}, () => evt.Set());
evt.WaitOne();
}
Assert.True(okay);
}
#endif
#if HAS_WPF
[TestMethod]
[Asynchronous]
public void ObserveOn_Dispatcher()
{
using (DispatcherHelpers.RunTest(out var dispatcher))
{
RunAsync(evt =>
{
var okay = true;
Observable.Range(0, 10, NewThreadScheduler.Default).ObserveOn(dispatcher).Subscribe(x =>
{
okay &= (SynchronizationContext.Current is System.Windows.Threading.DispatcherSynchronizationContext);
}, () =>
{
Assert.True(okay);
evt.Set();
});
});
}
}
[TestMethod]
[Asynchronous]
public void ObserveOn_DispatcherScheduler()
{
using (DispatcherHelpers.RunTest(out var dispatcher))
{
RunAsync(evt =>
{
var okay = true;
Observable.Range(0, 10, NewThreadScheduler.Default).ObserveOn(new DispatcherScheduler(dispatcher)).Subscribe(x =>
{
okay &= (SynchronizationContext.Current is System.Windows.Threading.DispatcherSynchronizationContext);
}, () =>
{
Assert.True(okay);
evt.Set();
});
});
}
}
[TestMethod]
[Asynchronous]
public void ObserveOn_CurrentDispatcher()
{
using (DispatcherHelpers.RunTest(out var dispatcher))
{
RunAsync(evt =>
{
var okay = true;
dispatcher.BeginInvoke(new Action(() =>
{
Observable.Range(0, 10, NewThreadScheduler.Default).ObserveOnDispatcher().Subscribe(x =>
{
okay &= (SynchronizationContext.Current is System.Windows.Threading.DispatcherSynchronizationContext);
}, () =>
{
Assert.True(okay);
evt.Set();
});
}));
});
}
}
[TestMethod]
[Asynchronous]
public void ObserveOn_Error()
{
using (DispatcherHelpers.RunTest(out var dispatcher))
{
RunAsync(evt =>
{
var ex = new Exception();
var okay = true;
dispatcher.BeginInvoke(new Action(() =>
{
Observable.Throw<int>(ex).ObserveOnDispatcher().Subscribe(x =>
{
okay &= (SynchronizationContext.Current is System.Windows.Threading.DispatcherSynchronizationContext);
},
e =>
{
Assert.True(okay);
Assert.Same(ex, e);
evt.Set();
},
() =>
{
Assert.True(false);
evt.Set();
});
}));
});
}
}
#endif
#endregion + TestBase +
}
[TestClass]
[DoNotParallelize] // We've observed hangs since enabling concurrent test execution.
| ObserveOnTest |
csharp | dotnet__machinelearning | test/Microsoft.ML.IntegrationTests/Debugging.cs | {
"start": 8446,
"end": 8879
} | internal class ____
{
public readonly ConcurrentDictionary<string, int> Lines;
public LogWatcher()
{
Lines = new ConcurrentDictionary<string, int>();
}
public void ObserveEvent(object sender, LoggingEventArgs e)
{
Lines.AddOrUpdate(e.Message, 1, (key, oldValue) => oldValue + 1);
}
}
}
}
| LogWatcher |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Midi/MidiNoteOnMessage.cs | {
"start": 255,
"end": 1390
} | public partial class ____ : global::Windows.Devices.Midi.IMidiMessage
{
// Skipping already declared property RawData
// Skipping already declared property Timestamp
// Skipping already declared property Type
// Skipping already declared property Channel
// Skipping already declared property Note
// Skipping already declared property Velocity
// Skipping already declared method Windows.Devices.Midi.MidiNoteOnMessage.MidiNoteOnMessage(byte, byte, byte)
// Forced skipping of method Windows.Devices.Midi.MidiNoteOnMessage.MidiNoteOnMessage(byte, byte, byte)
// Forced skipping of method Windows.Devices.Midi.MidiNoteOnMessage.Channel.get
// Forced skipping of method Windows.Devices.Midi.MidiNoteOnMessage.Note.get
// Forced skipping of method Windows.Devices.Midi.MidiNoteOnMessage.Velocity.get
// Forced skipping of method Windows.Devices.Midi.MidiNoteOnMessage.Timestamp.get
// Forced skipping of method Windows.Devices.Midi.MidiNoteOnMessage.RawData.get
// Forced skipping of method Windows.Devices.Midi.MidiNoteOnMessage.Type.get
// Processing: Windows.Devices.Midi.IMidiMessage
}
}
| MidiNoteOnMessage |
csharp | CommunityToolkit__dotnet | tests/CommunityToolkit.Mvvm.SourceGenerators.Roslyn4120.UnitTests/Test_UsePartialPropertyForObservablePropertyCodeFixer.cs | {
"start": 27873,
"end": 29659
} | partial class ____ : ObservableObject
{
[ObservableProperty]
public partial int I { get; set; }
public void M()
{
I = 42;
I = 42;
}
public int N() => I;
public int P() => I + Q(I) + Q(I);
private int Q(int i) => I + i;
}
""";
CSharpCodeFixTest test = new(LanguageVersion.Preview)
{
TestCode = original,
FixedCode = @fixed,
ReferenceAssemblies = ReferenceAssemblies.Net.Net80,
};
test.TestState.AdditionalReferences.Add(typeof(ObservableObject).Assembly);
test.ExpectedDiagnostics.AddRange(new[]
{
// /0/Test0.cs(6,17): info MVVMTK0042: The field C.i using [ObservableProperty] can be converted to a partial property instead, which is recommended (doing so improves the developer experience and allows other generators and analyzers to correctly see the generated property as well)
CSharpCodeFixVerifier.Diagnostic().WithSpan(6, 17, 6, 18).WithArguments("C", "i"),
});
test.FixedState.ExpectedDiagnostics.AddRange(new[]
{
// /0/Test0.cs(6,24): error CS9248: Partial property 'C.I' must have an implementation part.
DiagnosticResult.CompilerError("CS9248").WithSpan(6, 24, 6, 25).WithArguments("C.I"),
});
await test.RunAsync();
}
[TestMethod]
public async Task SimpleFields_WithMultipleAttributes_SingleProperty()
{
string original = """
using System;
using CommunityToolkit.Mvvm.ComponentModel;
| C |
csharp | abpframework__abp | framework/src/Volo.Abp.AspNetCore.Mvc.UI.Theme.Shared/Toolbars/ToolbarConfigurationContext.cs | {
"start": 345,
"end": 1722
} | public class ____ : IToolbarConfigurationContext
{
public IServiceProvider ServiceProvider { get; }
private readonly IAbpLazyServiceProvider _lazyServiceProvider;
public IAuthorizationService AuthorizationService => _lazyServiceProvider.LazyGetRequiredService<IAuthorizationService>();
public IStringLocalizerFactory StringLocalizerFactory => _lazyServiceProvider.LazyGetRequiredService<IStringLocalizerFactory>();
public ITheme Theme { get; }
public Toolbar Toolbar { get; }
public ToolbarConfigurationContext(ITheme currentTheme, Toolbar toolbar, IServiceProvider serviceProvider)
{
Theme = currentTheme;
Toolbar = toolbar;
ServiceProvider = serviceProvider;
_lazyServiceProvider = ServiceProvider.GetRequiredService<IAbpLazyServiceProvider>();
}
public Task<bool> IsGrantedAsync(string policyName)
{
return AuthorizationService.IsGrantedAsync(policyName);
}
public IStringLocalizer? GetDefaultLocalizer()
{
return StringLocalizerFactory.CreateDefaultOrNull();
}
[NotNull]
public IStringLocalizer GetLocalizer<T>()
{
return StringLocalizerFactory.Create<T>();
}
[NotNull]
public IStringLocalizer GetLocalizer(Type resourceType)
{
return StringLocalizerFactory.Create(resourceType);
}
}
| ToolbarConfigurationContext |
csharp | neuecc__MessagePack-CSharp | src/MessagePack/Formatters/PrimitiveFormatter.cs | {
"start": 19253,
"end": 20133
} | public sealed class ____ : IMessagePackFormatter<UInt32?>
{
public static readonly NullableUInt32Formatter Instance = new NullableUInt32Formatter();
private NullableUInt32Formatter()
{
}
public void Serialize(ref MessagePackWriter writer, UInt32? value, MessagePackSerializerOptions options)
{
if (value == null)
{
writer.WriteNil();
}
else
{
writer.Write(value.Value);
}
}
public UInt32? Deserialize(ref MessagePackReader reader, MessagePackSerializerOptions options)
{
if (reader.TryReadNil())
{
return default;
}
else
{
return reader.ReadUInt32();
}
}
}
| NullableUInt32Formatter |
csharp | dotnet__efcore | test/EFCore.InMemory.FunctionalTests/DatabaseErrorLogStateTest.cs | {
"start": 5950,
"end": 6268
} | private class ____ : ILoggerFactory
{
public readonly TestLogger Logger = new();
public void AddProvider(ILoggerProvider provider)
{
}
public ILogger CreateLogger(string name)
=> Logger;
public void Dispose()
{
}
| TestLoggerFactory |
csharp | MonoGame__MonoGame | MonoGame.Framework/Audio/Xact/MiniFormatTag.cs | {
"start": 229,
"end": 442
} | enum ____
{
Pcm = 0x0,
Xma = 0x1,
Adpcm = 0x2,
Wma = 0x3,
// We allow XMA to be reused for a platform specific format.
PlatformSpecific = Xma,
}
} | MiniFormatTag |
csharp | dotnet__machinelearning | src/Microsoft.ML.AutoML/SweepableEstimator/Estimators/FastForest.cs | {
"start": 1174,
"end": 1965
} | internal partial class ____
{
public override IEstimator<ITransformer> BuildFromOption(MLContext context, FastForestOption param)
{
var option = new FastForestRegressionTrainer.Options()
{
NumberOfTrees = param.NumberOfTrees,
NumberOfLeaves = param.NumberOfLeaves,
FeatureFraction = param.FeatureFraction,
LabelColumnName = param.LabelColumnName,
FeatureColumnName = param.FeatureColumnName,
ExampleWeightColumnName = param.ExampleWeightColumnName,
NumberOfThreads = AutoMlUtils.GetNumberOfThreadFromEnvrionment(),
};
return context.Regression.Trainers.FastForest(option);
}
}
| FastForestRegression |
csharp | dotnet__aspnetcore | src/Framework/AspNetCoreAnalyzers/test/RouteHandlers/DisallowReturningActionResultsFromMapMethodsTest.cs | {
"start": 1239,
"end": 2449
} | class ____ : IResult
{
public Task ExecuteAsync(HttpContext context) => Task.CompletedTask;
}
";
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source);
// Assert
Assert.Empty(diagnostics);
}
[Fact]
public async Task MinimalAction_ReturningIResultConditionallyWorks()
{
// Arrange
var source = @"
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
var webApp = WebApplication.Create();
webApp.MapGet(""/"", (int id) =>
{
if (id == 0)
{
return Results.NotFound();
}
return Results.Ok(""Here you go"");
});
";
// Act
var diagnostics = await Runner.GetDiagnosticsAsync(source);
// Assert
Assert.Empty(diagnostics);
}
[Fact]
public async Task MinimalAction_ReturningTypeThatImplementsIResultAndActionResultDoesNotProduceDiagnostics()
{
// Arrange
var source = @"
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
var webApp = WebApplication.Create();
webApp.MapGet(""/"", () => new CustomResult());
| CustomResult |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.