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
dotnetcore__WTM
src/WalkingTec.Mvvm.Core/Json/StringConverter.cs
{ "start": 227, "end": 1018 }
public class ____ : JsonConverter<string> { public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.Null) { return null; } if (reader.TokenType == JsonTokenType.String) { return reader.GetString(); } return null; } public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) { if (value == null) { writer.WriteNullValue(); } else { writer.WriteStringValue(value); } } } }
JsonStringConverter
csharp
HangfireIO__Hangfire
tests/Hangfire.Core.Tests/Utils/PlatformHelper.cs
{ "start": 116, "end": 412 }
internal static class ____ { public static bool IsRunningOnWindows() { #if !NETCOREAPP1_0 return Environment.OSVersion.Platform == PlatformID.Win32NT; #else return RuntimeInformation.IsOSPlatform(OSPlatform.Windows); #endif } } }
PlatformHelper
csharp
mysql-net__MySqlConnector
src/MySqlConnector.Authentication.Ed25519/Chaos.NaCl/Internal/Ed25519Ref10/fe_sq.cs
{ "start": 75, "end": 4971 }
partial class ____ { /* h = f * f Can overlap h with f. Preconditions: |f| bounded by 1.65*2^26,1.65*2^25,1.65*2^26,1.65*2^25,etc. Postconditions: |h| bounded by 1.01*2^25,1.01*2^24,1.01*2^25,1.01*2^24,etc. */ /* See fe_mul.c for discussion of implementation strategy. */ internal static void fe_sq(out FieldElement h, ref FieldElement f) { Int32 f0 = f.x0; Int32 f1 = f.x1; Int32 f2 = f.x2; Int32 f3 = f.x3; Int32 f4 = f.x4; Int32 f5 = f.x5; Int32 f6 = f.x6; Int32 f7 = f.x7; Int32 f8 = f.x8; Int32 f9 = f.x9; Int32 f0_2 = 2 * f0; Int32 f1_2 = 2 * f1; Int32 f2_2 = 2 * f2; Int32 f3_2 = 2 * f3; Int32 f4_2 = 2 * f4; Int32 f5_2 = 2 * f5; Int32 f6_2 = 2 * f6; Int32 f7_2 = 2 * f7; Int32 f5_38 = 38 * f5; /* 1.959375*2^30 */ Int32 f6_19 = 19 * f6; /* 1.959375*2^30 */ Int32 f7_38 = 38 * f7; /* 1.959375*2^30 */ Int32 f8_19 = 19 * f8; /* 1.959375*2^30 */ Int32 f9_38 = 38 * f9; /* 1.959375*2^30 */ Int64 f0f0 = f0 * (Int64)f0; Int64 f0f1_2 = f0_2 * (Int64)f1; Int64 f0f2_2 = f0_2 * (Int64)f2; Int64 f0f3_2 = f0_2 * (Int64)f3; Int64 f0f4_2 = f0_2 * (Int64)f4; Int64 f0f5_2 = f0_2 * (Int64)f5; Int64 f0f6_2 = f0_2 * (Int64)f6; Int64 f0f7_2 = f0_2 * (Int64)f7; Int64 f0f8_2 = f0_2 * (Int64)f8; Int64 f0f9_2 = f0_2 * (Int64)f9; Int64 f1f1_2 = f1_2 * (Int64)f1; Int64 f1f2_2 = f1_2 * (Int64)f2; Int64 f1f3_4 = f1_2 * (Int64)f3_2; Int64 f1f4_2 = f1_2 * (Int64)f4; Int64 f1f5_4 = f1_2 * (Int64)f5_2; Int64 f1f6_2 = f1_2 * (Int64)f6; Int64 f1f7_4 = f1_2 * (Int64)f7_2; Int64 f1f8_2 = f1_2 * (Int64)f8; Int64 f1f9_76 = f1_2 * (Int64)f9_38; Int64 f2f2 = f2 * (Int64)f2; Int64 f2f3_2 = f2_2 * (Int64)f3; Int64 f2f4_2 = f2_2 * (Int64)f4; Int64 f2f5_2 = f2_2 * (Int64)f5; Int64 f2f6_2 = f2_2 * (Int64)f6; Int64 f2f7_2 = f2_2 * (Int64)f7; Int64 f2f8_38 = f2_2 * (Int64)f8_19; Int64 f2f9_38 = f2 * (Int64)f9_38; Int64 f3f3_2 = f3_2 * (Int64)f3; Int64 f3f4_2 = f3_2 * (Int64)f4; Int64 f3f5_4 = f3_2 * (Int64)f5_2; Int64 f3f6_2 = f3_2 * (Int64)f6; Int64 f3f7_76 = f3_2 * (Int64)f7_38; Int64 f3f8_38 = f3_2 * (Int64)f8_19; Int64 f3f9_76 = f3_2 * (Int64)f9_38; Int64 f4f4 = f4 * (Int64)f4; Int64 f4f5_2 = f4_2 * (Int64)f5; Int64 f4f6_38 = f4_2 * (Int64)f6_19; Int64 f4f7_38 = f4 * (Int64)f7_38; Int64 f4f8_38 = f4_2 * (Int64)f8_19; Int64 f4f9_38 = f4 * (Int64)f9_38; Int64 f5f5_38 = f5 * (Int64)f5_38; Int64 f5f6_38 = f5_2 * (Int64)f6_19; Int64 f5f7_76 = f5_2 * (Int64)f7_38; Int64 f5f8_38 = f5_2 * (Int64)f8_19; Int64 f5f9_76 = f5_2 * (Int64)f9_38; Int64 f6f6_19 = f6 * (Int64)f6_19; Int64 f6f7_38 = f6 * (Int64)f7_38; Int64 f6f8_38 = f6_2 * (Int64)f8_19; Int64 f6f9_38 = f6 * (Int64)f9_38; Int64 f7f7_38 = f7 * (Int64)f7_38; Int64 f7f8_38 = f7_2 * (Int64)f8_19; Int64 f7f9_76 = f7_2 * (Int64)f9_38; Int64 f8f8_19 = f8 * (Int64)f8_19; Int64 f8f9_38 = f8 * (Int64)f9_38; Int64 f9f9_38 = f9 * (Int64)f9_38; Int64 h0 = f0f0 + f1f9_76 + f2f8_38 + f3f7_76 + f4f6_38 + f5f5_38; Int64 h1 = f0f1_2 + f2f9_38 + f3f8_38 + f4f7_38 + f5f6_38; Int64 h2 = f0f2_2 + f1f1_2 + f3f9_76 + f4f8_38 + f5f7_76 + f6f6_19; Int64 h3 = f0f3_2 + f1f2_2 + f4f9_38 + f5f8_38 + f6f7_38; Int64 h4 = f0f4_2 + f1f3_4 + f2f2 + f5f9_76 + f6f8_38 + f7f7_38; Int64 h5 = f0f5_2 + f1f4_2 + f2f3_2 + f6f9_38 + f7f8_38; Int64 h6 = f0f6_2 + f1f5_4 + f2f4_2 + f3f3_2 + f7f9_76 + f8f8_19; Int64 h7 = f0f7_2 + f1f6_2 + f2f5_2 + f3f4_2 + f8f9_38; Int64 h8 = f0f8_2 + f1f7_4 + f2f6_2 + f3f5_4 + f4f4 + f9f9_38; Int64 h9 = f0f9_2 + f1f8_2 + f2f7_2 + f3f6_2 + f4f5_2; Int64 carry0; Int64 carry1; Int64 carry2; Int64 carry3; Int64 carry4; Int64 carry5; Int64 carry6; Int64 carry7; Int64 carry8; Int64 carry9; carry0 = (h0 + (Int64)(1 << 25)) >> 26; h1 += carry0; h0 -= carry0 << 26; carry4 = (h4 + (Int64)(1 << 25)) >> 26; h5 += carry4; h4 -= carry4 << 26; carry1 = (h1 + (Int64)(1 << 24)) >> 25; h2 += carry1; h1 -= carry1 << 25; carry5 = (h5 + (Int64)(1 << 24)) >> 25; h6 += carry5; h5 -= carry5 << 25; carry2 = (h2 + (Int64)(1 << 25)) >> 26; h3 += carry2; h2 -= carry2 << 26; carry6 = (h6 + (Int64)(1 << 25)) >> 26; h7 += carry6; h6 -= carry6 << 26; carry3 = (h3 + (Int64)(1 << 24)) >> 25; h4 += carry3; h3 -= carry3 << 25; carry7 = (h7 + (Int64)(1 << 24)) >> 25; h8 += carry7; h7 -= carry7 << 25; carry4 = (h4 + (Int64)(1 << 25)) >> 26; h5 += carry4; h4 -= carry4 << 26; carry8 = (h8 + (Int64)(1 << 25)) >> 26; h9 += carry8; h8 -= carry8 << 26; carry9 = (h9 + (Int64)(1 << 24)) >> 25; h0 += carry9 * 19; h9 -= carry9 << 25; carry0 = (h0 + (Int64)(1 << 25)) >> 26; h1 += carry0; h0 -= carry0 << 26; h.x0 = (Int32)h0; h.x1 = (Int32)h1; h.x2 = (Int32)h2; h.x3 = (Int32)h3; h.x4 = (Int32)h4; h.x5 = (Int32)h5; h.x6 = (Int32)h6; h.x7 = (Int32)h7; h.x8 = (Int32)h8; h.x9 = (Int32)h9; } }
FieldOperations
csharp
Testably__Testably.Abstractions
Tests/Testably.Abstractions.Testing.Tests/Statistics/FileSystem/FileStreamFactoryStatisticsTests.cs
{ "start": 304, "end": 7127 }
public class ____ { #if NET6_0_OR_GREATER [Fact] public async Task Method_New_SafeFileHandle_FileAccess_Int_Bool_ShouldRegisterCall() { MockFileSystem sut = new(); sut.WithSafeFileHandleStrategy( new DefaultSafeFileHandleStrategy(_ => new SafeFileHandleMock("foo"))) .Initialize().WithFile("foo"); SafeFileHandle handle = new(); FileAccess access = FileAccess.ReadWrite; int bufferSize = 42; bool isAsync = true; using FileSystemStream result = sut.FileStream.New(handle, access, bufferSize, isAsync); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), handle, access, bufferSize, isAsync); } #endif #if NET6_0_OR_GREATER [Fact] public async Task Method_New_SafeFileHandle_FileAccess_Int_ShouldRegisterCall() { MockFileSystem sut = new(); sut.WithSafeFileHandleStrategy( new DefaultSafeFileHandleStrategy(_ => new SafeFileHandleMock("foo"))) .Initialize().WithFile("foo"); SafeFileHandle handle = new(); FileAccess access = FileAccess.ReadWrite; int bufferSize = 42; using FileSystemStream result = sut.FileStream.New(handle, access, bufferSize); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), handle, access, bufferSize); } #endif #if NET6_0_OR_GREATER [Fact] public async Task Method_New_SafeFileHandle_FileAccess_ShouldRegisterCall() { MockFileSystem sut = new(); sut.WithSafeFileHandleStrategy( new DefaultSafeFileHandleStrategy(_ => new SafeFileHandleMock("foo"))) .Initialize().WithFile("foo"); SafeFileHandle handle = new(); FileAccess access = FileAccess.ReadWrite; using FileSystemStream result = sut.FileStream.New(handle, access); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), handle, access); } #endif [Fact] public async Task Method_New_String_FileMode_FileAccess_FileShare_Int_Bool_ShouldRegisterCall() { MockFileSystem sut = new(); string path = "foo"; FileMode mode = FileMode.OpenOrCreate; FileAccess access = FileAccess.ReadWrite; FileShare share = FileShare.ReadWrite; int bufferSize = 42; bool useAsync = true; using FileSystemStream result = sut.FileStream.New(path, mode, access, share, bufferSize, useAsync); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), path, mode, access, share, bufferSize, useAsync); } [Fact] public async Task Method_New_String_FileMode_FileAccess_FileShare_Int_FileOptions_ShouldRegisterCall() { MockFileSystem sut = new(); string path = "foo"; FileMode mode = FileMode.OpenOrCreate; FileAccess access = FileAccess.ReadWrite; FileShare share = FileShare.ReadWrite; int bufferSize = 42; FileOptions options = new(); using FileSystemStream result = sut.FileStream.New(path, mode, access, share, bufferSize, options); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), path, mode, access, share, bufferSize, options); } [Fact] public async Task Method_New_String_FileMode_FileAccess_FileShare_Int_ShouldRegisterCall() { MockFileSystem sut = new(); string path = "foo"; FileMode mode = FileMode.OpenOrCreate; FileAccess access = FileAccess.ReadWrite; FileShare share = FileShare.ReadWrite; int bufferSize = 42; using FileSystemStream result = sut.FileStream.New(path, mode, access, share, bufferSize); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), path, mode, access, share, bufferSize); } [Fact] public async Task Method_New_String_FileMode_FileAccess_FileShare_ShouldRegisterCall() { MockFileSystem sut = new(); string path = "foo"; FileMode mode = FileMode.OpenOrCreate; FileAccess access = FileAccess.ReadWrite; FileShare share = FileShare.ReadWrite; using FileSystemStream result = sut.FileStream.New(path, mode, access, share); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), path, mode, access, share); } [Fact] public async Task Method_New_String_FileMode_FileAccess_ShouldRegisterCall() { MockFileSystem sut = new(); string path = "foo"; FileMode mode = FileMode.OpenOrCreate; FileAccess access = FileAccess.ReadWrite; using FileSystemStream result = sut.FileStream.New(path, mode, access); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), path, mode, access); } [Fact] public async Task Method_New_String_FileMode_ShouldRegisterCall() { MockFileSystem sut = new(); string path = "foo"; FileMode mode = FileMode.OpenOrCreate; using FileSystemStream result = sut.FileStream.New(path, mode); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), path, mode); } #if FEATURE_FILESYSTEM_STREAM_OPTIONS [Fact] public async Task Method_New_String_FileStreamOptions_ShouldRegisterCall() { MockFileSystem sut = new(); sut.Initialize().WithFile("foo"); string path = "foo"; FileStreamOptions options = new(); using FileSystemStream result = sut.FileStream.New(path, options); await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall(nameof(IFileStreamFactory.New), path, options); } #endif [Fact] public async Task Method_Wrap_FileStream_ShouldRegisterCall() { string path = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); MockFileSystem sut = new(); try { using FileStream fileStream = new(path, FileMode.OpenOrCreate); try { using FileSystemStream result = sut.FileStream.Wrap(fileStream); } catch (NotSupportedException) { // Wrap is not possible on the MockFileSystem, but should still be registered! } await That(sut.Statistics.TotalCount).IsEqualTo(1); await That(sut.Statistics.FileStream).OnlyContainsMethodCall( nameof(IFileStreamFactory.Wrap), fileStream); } finally { File.Delete(path); } } [Fact] public async Task ToString_ShouldBeFileStream() { IPathStatistics<IFileStreamFactory, FileSystemStream> sut = new MockFileSystem().Statistics.FileStream; string? result = sut.ToString(); await That(result).IsEqualTo("FileStream"); } }
FileStreamFactoryStatisticsTests
csharp
Testably__Testably.Abstractions
Tests/Testably.Abstractions.Tests/FileSystem/DirectoryInfo/GetFilesTests.cs
{ "start": 203, "end": 5069 }
public partial class ____ { [Theory] [AutoData] public async Task GetFiles_SearchOptionAllFiles_ShouldReturnAllFiles( string path) { IFileSystemDirectoryInitializer<IFileSystem> initialized = FileSystem.Initialize() .WithSubdirectory(path).Initialized(s => s .WithASubdirectory().Initialized(d => d .WithAFile() .WithAFile()) .WithASubdirectory() .WithAFile()); IDirectoryInfo baseDirectory = (IDirectoryInfo)initialized[0]; IFileInfo[] result = baseDirectory .GetFiles("*", SearchOption.AllDirectories); await That(result.Length).IsEqualTo(3); await That(result).Contains(d => string.Equals(d.Name, initialized[2].Name, StringComparison.Ordinal)); await That(result).Contains(d => string.Equals(d.Name, initialized[3].Name, StringComparison.Ordinal)); await That(result).Contains(d => string.Equals(d.Name, initialized[5].Name, StringComparison.Ordinal)); } [Theory] #if NETFRAMEWORK [InlineAutoData(false, "")] #else [InlineAutoData(true, "")] #endif [InlineAutoData(true, "*")] [InlineAutoData(true, ".")] [InlineAutoData(true, "*.*")] [InlineData(true, "a*c", "abc")] [InlineData(true, "ab*c", "abc")] [InlineData(true, "abc?", "abc")] [InlineData(false, "ab?c", "abc")] [InlineData(false, "ac", "abc")] public async Task GetFiles_SearchPattern_ShouldReturnExpectedValue( bool expectToBeFound, string searchPattern, string fileName) { IDirectoryInfo baseDirectory = FileSystem.Initialize() .WithFile(fileName) .BaseDirectory; IFileInfo[] result = baseDirectory .GetFiles(searchPattern); if (expectToBeFound) { await That(result).HasSingle() .Matching(d => string.Equals(d.Name, fileName, StringComparison.Ordinal)) .Because($"it should match '{searchPattern}'"); } else { await That(result).IsEmpty().Because($"{fileName} should not match '{searchPattern}'"); } } #if FEATURE_FILESYSTEM_ENUMERATION_OPTIONS [Fact] public async Task GetFiles_WithEnumerationOptions_ShouldConsiderSetOptions() { IDirectoryInfo baseDirectory = FileSystem.Initialize() .WithASubdirectory().Initialized(s => s .WithFile("xyz")) .WithAFile() .BaseDirectory; IFileInfo[] result = baseDirectory .GetFiles("XYZ", new EnumerationOptions { MatchCasing = MatchCasing.CaseInsensitive, RecurseSubdirectories = true, // Filename could start with a leading '.' indicating it as Hidden in Linux AttributesToSkip = FileAttributes.System, }); await That(result.Length).IsEqualTo(1); await That(result).DoesNotContain(d => string.Equals(d.Name, "foo", StringComparison.Ordinal)); await That(result).Contains(d => string.Equals(d.Name, "xyz", StringComparison.Ordinal)); await That(result).DoesNotContain(d => string.Equals(d.Name, "bar", StringComparison.Ordinal)); } #endif [Theory] [AutoData] public async Task GetFiles_WithNewline_ShouldThrowArgumentException( string path) { IDirectoryInfo baseDirectory = FileSystem.DirectoryInfo.New(path); string searchPattern = "foo\0bar"; void Act() { _ = baseDirectory.GetFiles(searchPattern).FirstOrDefault(); } await That(Act).Throws<ArgumentException>().WithHResult(-2147024809); } [Fact] public async Task GetFiles_WithoutSearchString_ShouldReturnAllDirectFiles() { IDirectoryInfo baseDirectory = FileSystem.Initialize() .WithFile("foo") .WithASubdirectory().Initialized(s => s .WithFile("xyz")) .WithFile("bar") .BaseDirectory; IFileInfo[] result = baseDirectory .GetFiles(); await That(result.Length).IsEqualTo(2); await That(result).Contains(d => string.Equals(d.Name, "foo", StringComparison.Ordinal)); await That(result) .DoesNotContain(d => string.Equals(d.Name, "xyz", StringComparison.Ordinal)); await That(result).Contains(d => string.Equals(d.Name, "bar", StringComparison.Ordinal)); } [Fact] public async Task GetFiles_WithSearchPattern_ShouldReturnMatchingFiles() { IDirectoryInfo baseDirectory = FileSystem.Initialize() .WithFile("foo") .WithFile("bar") .BaseDirectory; IEnumerable<IFileInfo> result = baseDirectory .GetFiles("foo"); await That(result).HasSingle() .Matching(d => string.Equals(d.Name, "foo", StringComparison.Ordinal)); await That(result.Count()).IsEqualTo(1); } [Fact] public async Task GetFiles_WithSearchPatternInSubdirectory_ShouldReturnMatchingFiles() { IDirectoryInfo baseDirectory = FileSystem.Initialize() .WithASubdirectory().Initialized(s => s .WithFile("xyz")) .WithASubdirectory().Initialized(s => s .WithFile("xyz")) .WithSubdirectory("xyz").Initialized(s => s .WithAFile()) .BaseDirectory; IEnumerable<IFileInfo> result = baseDirectory .GetFiles("xyz", SearchOption.AllDirectories); await That(result).HasCount(2); } }
GetFilesTests
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Common/Script/JsOperator.cs
{ "start": 6714, "end": 7020 }
public class ____ : JsBinaryOperator { public static JsMultiplication Operator = new JsMultiplication(); private JsMultiplication() { } public override string Token => "*"; public override object Evaluate(object lhs, object rhs) => DynamicNumber.Multiply(lhs, rhs); }
JsMultiplication
csharp
dotnet__maui
src/Controls/src/Core/Compatibility/Windows/FontNamedSizeService.cs
{ "start": 441, "end": 624 }
class ____ : IFontNamedSizeService { public double GetNamedSize(NamedSize size, Type targetElementType, bool useOldSizes) { return size.GetFontSize(); } } }
FontNamedSizeService
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Jira/CSharp2727Tests.cs
{ "start": 933, "end": 3988 }
public class ____ : LinqIntegrationTest<CSharp2727Tests.ClassFixture> { public CSharp2727Tests(ClassFixture fixture) : base(fixture) { } [Fact] public void Find_with_predicate_on_Body_should_work() { RequireServer.Check().Supports(Feature.AggregateToString); var collection = Fixture.Collection; var filter = new ExpressionFilterDefinition<Entity>(x => new[] { "Test1", "Test2" }.Contains((string)x.Body["name"])); var serializerRegistry = BsonSerializer.SerializerRegistry; var documentSerializer = serializerRegistry.GetSerializer<Entity>(); var renderedFilter = filter.Render(new(documentSerializer, serializerRegistry)); renderedFilter.Should().Be("{ $expr : { $in : [{ $toString : '$Body.name' }, ['Test1', 'Test2']] } }"); var cursor = collection.Find(filter); var results = cursor.ToList(); results.Select(x => x.Id).Should().Equal(1, 2); } [Fact] public void Find_with_predicate_on_Caption_should_work() { var collection = Fixture.Collection; var filter = new ExpressionFilterDefinition<Entity>(x => new[] { "Test1", "Test2" }.Contains(x.Caption)); var serializerRegistry = BsonSerializer.SerializerRegistry; var documentSerializer = serializerRegistry.GetSerializer<Entity>(); var renderedFilter = filter.Render(new(documentSerializer, serializerRegistry)); renderedFilter.Should().Be("{ Caption : { $in : ['Test1', 'Test2'] } }"); var cursor = collection.FindSync(filter); var results = cursor.ToList(); results.Select(x => x.Id).Should().Equal(1, 2); } [Fact] public void Where_with_predicate_on_Body_should_work() { RequireServer.Check().Supports(Feature.AggregateToString); var collection = Fixture.Collection; var queryable = collection .AsQueryable() .Where(x => new[] { "Test1", "Test2" }.Contains((string)x.Body["name"])); var stages = Translate(collection, queryable); AssertStages(stages, "{ $match : { $expr : { $in : [{ $toString : '$Body.name' }, ['Test1', 'Test2']] } } }"); var results = queryable.ToList(); results.Select(x => x.Id).Should().Equal(1, 2); } [Fact] public void Where_with_predicate_on_Caption_should_work() { var collection = Fixture.Collection; var queryable = collection .AsQueryable() .Where(x => new[] { "Test1", "Test2" }.Contains(x.Caption)); var stages = Translate(collection, queryable); AssertStages(stages, "{ $match : { Caption : { $in : ['Test1', 'Test2'] } } }"); var results = queryable.ToList(); results.Select(x => x.Id).Should().Equal(1, 2); }
CSharp2727Tests
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/Services/Transport/Http/Authentication/rfc_2898_password_hash_algorithm.cs
{ "start": 1714, "end": 2227 }
public class ____ { private Rfc2898PasswordHashAlgorithm _algorithm; private readonly string _password = "Pa55w0rd!"; private readonly string _hash = "HKoq6xw3Oird4KqU4RyoY9aFFRc="; private readonly string _salt = "+6eoSEkays/BOpzGMLE6Uw=="; [SetUp] public void SetUp() { _algorithm = new Rfc2898PasswordHashAlgorithm(); } [Test] public void old_hashes_should_successfully_verify() { Assert.True(_algorithm.Verify(_password, _hash, _salt)); } } } }
when_upgrading_the_hashes
csharp
smartstore__Smartstore
src/Smartstore.Web.Common/Routing/SmartUrlHelper.cs
{ "start": 761, "end": 3103 }
public class ____ : UrlHelperBase { private readonly LinkGenerator _linkGenerator; public SmartUrlHelper(ActionContext actionContext, LinkGenerator linkGenerator) : base(actionContext) { _linkGenerator = Guard.NotNull(linkGenerator, nameof(linkGenerator)); } /// <inheritdoc /> public override string Action(UrlActionContext urlActionContext) { Guard.NotNull(urlActionContext, nameof(urlActionContext)); var values = GetValuesDictionary(urlActionContext.Values); if (urlActionContext.Action == null) { if (!values.ContainsKey("action") && AmbientValues.TryGetValue("action", out var action)) { values["action"] = action; } } else { values["action"] = urlActionContext.Action; } if (urlActionContext.Controller == null) { if (!values.ContainsKey("controller") && AmbientValues.TryGetValue("controller", out var controller)) { values["controller"] = controller; } } else { values["controller"] = urlActionContext.Controller; } var path = _linkGenerator.GetPathByRouteValues( ActionContext.HttpContext, routeName: null, values, fragment: urlActionContext.Fragment == null ? FragmentString.Empty : new FragmentString("#" + urlActionContext.Fragment)); return GenerateUrl(urlActionContext.Protocol, urlActionContext.Host, path); } /// <inheritdoc /> public override string RouteUrl(UrlRouteContext routeContext) { Guard.NotNull(routeContext, nameof(routeContext)); var path = _linkGenerator.GetPathByRouteValues( ActionContext.HttpContext, routeContext.RouteName, routeContext.Values, fragment: routeContext.Fragment == null ? FragmentString.Empty : new FragmentString("#" + routeContext.Fragment)); return GenerateUrl(routeContext.Protocol, routeContext.Host, path); } } }
SmartUrlHelper
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Demo/Pages/Foo/Admin/Edit.cshtml.cs
{ "start": 363, "end": 2502 }
public class ____ : PageModel { private readonly IContentManager _contentManager; private readonly IContentItemDisplayManager _contentDisplay; private readonly IUpdateModelAccessor _updateModelAccessor; private readonly ISession _session; public EditModel( IContentManager contentManager, IContentItemDisplayManager contentDisplay, IUpdateModelAccessor updateModelAccessor, ISession session) { _contentManager = contentManager; _contentDisplay = contentDisplay; _updateModelAccessor = updateModelAccessor; _session = session; } [BindProperty(SupportsGet = true)] public string Id { get; set; } [Required] [BindProperty] public string Text { get; set; } public string Title { get; set; } public string Submit { get; set; } public async Task<ActionResult> OnGetAsync() { var contentItem = await _contentManager.GetAsync(Id); if (contentItem == null) { return NotFound(); } Title = contentItem.DisplayText ?? "Foo Title"; Text = contentItem.Content.TestContentPartA.Line; return Page(); } public async Task<IActionResult> OnPostDelete() { var contentItem = await _contentManager.GetAsync(Id); if (contentItem == null) { return NotFound(); } await _contentManager.RemoveAsync(contentItem); return RedirectToPage("/Foo/List"); } public async Task<IActionResult> OnPostUpdate() { var contentItem = await _contentManager.GetAsync(Id); if (contentItem == null) { return NotFound(); } var updater = _updateModelAccessor.ModelUpdater; _ = await _contentDisplay.UpdateEditorAsync(contentItem, updater, false); if (!ModelState.IsValid) { await _session.CancelAsync(); return Page(); } contentItem.Content.TestContentPartA.Line = Text; await _session.SaveAsync(contentItem); return RedirectToPage("/Foo/List"); } }
EditModel
csharp
dotnetcore__FreeSql
FreeSql.Tests/FreeSql.Tests.Provider.Duckdb/Duckdb/DuckdbAdo/DuckdbAdoTest.cs
{ "start": 147, "end": 2190 }
public class ____ { IFreeSql fsql => g.duckdb; [Fact] public void SlavePools() { var t2 = fsql.Ado.SlavePools.Count; } [Fact] public void ExecuteTest() { Assert.True(fsql.Ado.ExecuteConnectTest()); } [Fact] public void ExecuteDataTable() { var dataTable = fsql.Ado.ExecuteDataTable("select * from tbiou04"); using (var duck = new FreeSql.FreeSqlBuilder() .UseConnectionString(FreeSql.DataType.DuckDB, "DataSource=D:\\WeChat Files\\WeChat Files\\q2881099\\FileStorage\\File\\2025-05") .UseAutoSyncStructure(true) .UseMonitorCommand( cmd => Trace.WriteLine("\r\n线程" + Thread.CurrentThread.ManagedThreadId + ": " + cmd.CommandText) //监听SQL命令对象,在执行前 , (cmd, traceLog) => Console.WriteLine(traceLog) ) .Build()) { var dataTable2 = fsql.Ado.ExecuteDataTable("select * from db_db"); } } [Fact] public void ExecuteArray() { } [Fact] public void ExecuteNonQuery() { } [Fact] public void ExecuteScalar() { } [Fact] public void Query() { fsql.CodeFirst.SyncStructure<xxx>(); var t3 = fsql.Ado.Query<xxx>("select * from xxx"); var t4 = fsql.Ado.Query<(int, string, string)>("select * from xxx"); var t5 = fsql.Ado.Query<dynamic>("select * from xxx"); //var t6 = fsql.Ado.Query<xxx>("select * from xxx where id in $ids", new { ids = new[] { "1", "2", "3" } }); } [Fact] public void QueryMultipline() { fsql.CodeFirst.SyncStructure<xxx>(); var t3 = fsql.Ado.Query<xxx, (int, string, string), dynamic>("select * from xxx; select * from xxx; select * from xxx"); }
DuckdbAdoTest
csharp
dotnet__orleans
src/Orleans.Core/Lifecycle/IClusterClientLifecycle.cs
{ "start": 141, "end": 219 }
public interface ____ : ILifecycleObservable { } }
IClusterClientLifecycle
csharp
dotnet__aspnetcore
src/Tools/Microsoft.dotnet-openapi/src/HttpClientWrapper.cs
{ "start": 955, "end": 1763 }
public class ____ : IHttpResponseMessageWrapper { private readonly HttpResponseMessage _response; public HttpResponseMessageWrapper(HttpResponseMessage response) { _response = response; } public Task<Stream> Stream => _response.Content.ReadAsStreamAsync(); public HttpStatusCode StatusCode => _response.StatusCode; public bool IsSuccessCode() => _response.IsSuccessStatusCode; public ContentDispositionHeaderValue ContentDisposition() { if (_response.Headers.TryGetValues(BaseCommand.ContentDispositionHeaderName, out var disposition)) { return new ContentDispositionHeaderValue(disposition.First()); } return null; } public void Dispose() { _response.Dispose(); } }
HttpResponseMessageWrapper
csharp
dotnetcore__FreeSql
FreeSql/Internal/CommonProvider/UpdateProvider.cs
{ "start": 383, "end": 8587 }
partial class ____ { public IFreeSql _orm; public CommonUtils _commonUtils; public CommonExpression _commonExpression; public Dictionary<string, bool> _ignore = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase); public Dictionary<string, bool> _auditValueChangedDict = new Dictionary<string, bool>(StringComparer.CurrentCultureIgnoreCase); public TableInfo _table; public ColumnInfo[] _tempPrimarys; public ColumnInfo _versionColumn; public bool _ignoreVersion = false; public Func<string, string> _tableRule; public StringBuilder _where = new StringBuilder(); public List<GlobalFilter.Item> _whereGlobalFilter; public StringBuilder _set = new StringBuilder(); public StringBuilder _setIncr = new StringBuilder(); public List<DbParameter> _params = new List<DbParameter>(); //已经固定的 public List<DbParameter> _paramsSource = new List<DbParameter>(); //每次ToSql重新生成的 public bool _noneParameter; public int _batchRowsLimit, _batchParameterLimit; public bool _batchAutoTransaction = true; public DbTransaction _transaction; public DbConnection _connection; public int _commandTimeout = 0; public Action<StringBuilder> _interceptSql; public string _tableAlias; public object _updateVersionValue; public bool _isAutoSyncStructure; public static int ExecuteBulkUpdate<T1>(UpdateProvider<T1> update, NativeTuple<string, string, string, string, string[]> state, Action<IInsert<T1>> funcBulkCopy) where T1 : class => ExecuteBulkCommand(update._source, update._tempPrimarys, update._orm, update._connection, update._transaction, update._table, state, funcBulkCopy); public static int ExecuteBulkUpsert<T1>(InsertOrUpdateProvider<T1> upsert, NativeTuple<string, string, string, string, string[]> state, Action<IInsert<T1>> funcBulkCopy) where T1 : class => ExecuteBulkCommand(upsert._source, upsert._tempPrimarys, upsert._orm, upsert._connection, upsert._transaction, upsert._table, state, funcBulkCopy); public static int ExecuteBulkCommand<T1>(List<T1> _source, ColumnInfo[] _tempPrimarys, IFreeSql _orm, DbConnection _connection, DbTransaction _transaction, TableInfo _table, NativeTuple<string, string, string, string, string[]> state, Action<IInsert<T1>> funcBulkCopy) where T1 : class { if (_source.Any() != true || _tempPrimarys.Any() == false) return 0; var fsql = _orm; var connection = _connection; var transaction = _transaction; Object<DbConnection> poolConn = null; if (connection == null) { poolConn = fsql.Ado.MasterPool.Get(); connection = poolConn.Value; } try { var droped = false; fsql.Ado.CommandFluent(state.Item1).WithConnection(connection).WithTransaction(transaction).ExecuteNonQuery(); try { var insert = fsql.Insert<T1>(); (insert as InsertProvider<T1>)._source.AddRange(_source); //不能直接 AppendData,防止触发 Aop.AuditValue insert .AsType(_table.Type) .WithConnection(connection) .WithTransaction(transaction) .InsertIdentity() .InsertColumns(state.Item5) .AsTable(state.Item4); (insert as InsertProvider)._isAutoSyncStructure = false; funcBulkCopy(insert); switch (fsql.Ado.DataType) { case DataType.Oracle: case DataType.OdbcOracle: case DataType.CustomOracle: case DataType.Dameng: return fsql.Ado.CommandFluent(state.Item2).WithConnection(connection).WithTransaction(transaction).ExecuteNonQuery(); } var affrows = fsql.Ado.CommandFluent(state.Item2 + ";\r\n" + state.Item3).WithConnection(connection).WithTransaction(transaction).ExecuteNonQuery(); droped = true; return affrows; } finally { if (droped == false) fsql.Ado.CommandFluent(state.Item3).WithConnection(connection).WithTransaction(transaction).ExecuteNonQuery(); } } finally { poolConn?.Dispose(); } } #if net40 #else public static Task<int> ExecuteBulkUpdateAsync<T1>(UpdateProvider<T1> update, NativeTuple<string, string, string, string, string[]> state, Func<IInsert<T1>, Task> funcBulkCopy) where T1 : class => ExecuteBulkCommandAsync(update._source, update._tempPrimarys, update._orm, update._connection, update._transaction, update._table, state, funcBulkCopy); public static Task<int> ExecuteBulkUpsertAsync<T1>(InsertOrUpdateProvider<T1> upsert, NativeTuple<string, string, string, string, string[]> state, Func<IInsert<T1>, Task> funcBulkCopy) where T1 : class => ExecuteBulkCommandAsync(upsert._source, upsert._tempPrimarys, upsert._orm, upsert._connection, upsert._transaction, upsert._table, state, funcBulkCopy); async public static Task<int> ExecuteBulkCommandAsync<T1>(List<T1> _source, ColumnInfo[] _tempPrimarys, IFreeSql _orm, DbConnection _connection, DbTransaction _transaction, TableInfo _table, NativeTuple<string, string, string, string, string[]> state, Func<IInsert<T1>, Task> funcBulkCopy) where T1 : class { if (_source.Any() != true || _tempPrimarys.Any() == false) return 0; var fsql = _orm; var connection = _connection; var transaction = _transaction; Object<DbConnection> poolConn = null; if (connection == null) { poolConn = await fsql.Ado.MasterPool.GetAsync(); connection = poolConn.Value; } try { var droped = false; await fsql.Ado.CommandFluent(state.Item1).WithConnection(connection).WithTransaction(transaction).ExecuteNonQueryAsync(); try { var insert = fsql.Insert<T1>(); (insert as InsertProvider<T1>)._source.AddRange(_source); //不能直接 AppendData,防止触发 Aop.AuditValue insert .AsType(_table.Type) .WithConnection(connection) .WithTransaction(transaction) .InsertIdentity() .InsertColumns(state.Item5) .AsTable(state.Item4); (insert as InsertProvider)._isAutoSyncStructure = false; await funcBulkCopy(insert); switch (fsql.Ado.DataType) { case DataType.Oracle: case DataType.OdbcOracle: case DataType.CustomOracle: case DataType.Dameng: return await fsql.Ado.CommandFluent(state.Item2).WithConnection(connection).WithTransaction(transaction).ExecuteNonQueryAsync(); } var affrows = await fsql.Ado.CommandFluent(state.Item2 + ";\r\n" + state.Item3).WithConnection(connection).WithTransaction(transaction).ExecuteNonQueryAsync(); droped = true; return affrows; } finally { if (droped == false) await fsql.Ado.CommandFluent(state.Item3).WithConnection(connection).WithTransaction(transaction).ExecuteNonQueryAsync(); } } finally { poolConn?.Dispose(); } } #endif } public abstract
UpdateProvider
csharp
dotnet__machinelearning
src/Microsoft.ML.AutoML/API/AutoCatalog.cs
{ "start": 618, "end": 56052 }
public sealed class ____ { private readonly MLContext _context; internal AutoCatalog(MLContext context) { _context = context; } /// <summary> /// Creates a new AutoML experiment to run on a regression dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML regression experiment.</returns> /// <remarks> /// <para>See <see cref="RegressionExperiment"/> for a more detailed code example of an AutoML regression experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public RegressionExperiment CreateRegressionExperiment(uint maxExperimentTimeInSeconds) { return new RegressionExperiment(_context, new RegressionExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a regression dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML regression experiment.</returns> /// <remarks> /// See <see cref="RegressionExperiment"/> for a more detailed code example of an AutoML regression experiment. /// </remarks> public RegressionExperiment CreateRegressionExperiment(RegressionExperimentSettings experimentSettings) { return new RegressionExperiment(_context, experimentSettings); } /// <summary> /// Creates a new AutoML experiment to run on a binary classification dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML binary classification experiment.</returns> /// <remarks> /// <para>See <see cref="BinaryClassificationExperiment"/> for a more detailed code example of an AutoML binary classification experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public BinaryClassificationExperiment CreateBinaryClassificationExperiment(uint maxExperimentTimeInSeconds) { return new BinaryClassificationExperiment(_context, new BinaryExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a binary classification dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML binary classification experiment.</returns> /// <remarks> /// See <see cref="BinaryClassificationExperiment"/> for a more detailed code example of an AutoML binary classification experiment. /// </remarks> public BinaryClassificationExperiment CreateBinaryClassificationExperiment(BinaryExperimentSettings experimentSettings) { return new BinaryClassificationExperiment(_context, experimentSettings); } /// <summary> /// Creates a new AutoML experiment to run on a multiclass classification dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML multiclass classification experiment.</returns> /// <remarks> /// <para>See <see cref="MulticlassClassificationExperiment"/> for a more detailed code example of an AutoML multiclass classification experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public MulticlassClassificationExperiment CreateMulticlassClassificationExperiment(uint maxExperimentTimeInSeconds) { return new MulticlassClassificationExperiment(_context, new MulticlassExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a multiclass classification dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML multiclass classification experiment.</returns> /// <remarks> /// See <see cref="MulticlassClassificationExperiment"/> for a more detailed code example of an AutoML multiclass classification experiment. /// </remarks> public MulticlassClassificationExperiment CreateMulticlassClassificationExperiment(MulticlassExperimentSettings experimentSettings) { return new MulticlassClassificationExperiment(_context, experimentSettings); } /// <summary> /// Creates a new AutoML experiment to run on a recommendation classification dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML recommendation classification experiment.</returns> /// <remarks> /// <para>See <see cref="RecommendationExperiment"/> for a more detailed code example of an AutoML multiclass classification experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public RecommendationExperiment CreateRecommendationExperiment(uint maxExperimentTimeInSeconds) { return new RecommendationExperiment(_context, new RecommendationExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a recommendation dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML recommendation experiment.</returns> /// <remarks> /// See <see cref="RecommendationExperiment"/> for a more detailed code example of an AutoML recommendation experiment. /// </remarks> public RecommendationExperiment CreateRecommendationExperiment(RecommendationExperimentSettings experimentSettings) { return new RecommendationExperiment(_context, experimentSettings); } /// <summary> /// Creates a new AutoML experiment to run on a ranking dataset. /// </summary> /// <param name="maxExperimentTimeInSeconds">Maximum number of seconds that experiment will run.</param> /// <returns>A new AutoML ranking experiment.</returns> /// <remarks> /// <para>See <see cref="RankingExperiment"/> for a more detailed code example of an AutoML ranking experiment.</para> /// <para>An experiment may run for longer than <paramref name="maxExperimentTimeInSeconds"/>. /// This is because once AutoML starts training an ML.NET model, AutoML lets the /// model train to completion. For instance, if the first model /// AutoML trains takes 4 hours, and the second model trained takes 5 hours, /// but <paramref name="maxExperimentTimeInSeconds"/> was the number of seconds in 6 hours, /// the experiment will run for 4 + 5 = 9 hours (not 6 hours).</para> /// </remarks> public RankingExperiment CreateRankingExperiment(uint maxExperimentTimeInSeconds) { return new RankingExperiment(_context, new RankingExperimentSettings() { MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds }); } /// <summary> /// Creates a new AutoML experiment to run on a ranking dataset. /// </summary> /// <param name="experimentSettings">Settings for the AutoML experiment.</param> /// <returns>A new AutoML ranking experiment.</returns> /// <remarks> /// See <see cref="RankingExperiment"/> for a more detailed code example of an AutoML ranking experiment. /// </remarks> public RankingExperiment CreateRankingExperiment(RankingExperimentSettings experimentSettings) { return new RankingExperiment(_context, experimentSettings); } /// <summary> /// Infers information about the columns of a dataset in a file located at <paramref name="path"/>. /// </summary> /// <param name="path">Path to a dataset file.</param> /// <param name="labelColumnName">The name of the label column.</param> /// <param name="separatorChar">The character used as separator between data elements in a row. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowQuoting">Whether the file can contain columns defined by a quoted string. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowSparse">Whether the file can contain numerical vectors in sparse format. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="trimWhitespace">Whether trailing whitespace should be removed from dataset file lines.</param> /// <param name="groupColumns">Whether to group together (when possible) original columns in the dataset file into vector columns in the resulting data structures. See <see cref="TextLoader.Range"/> for more information.</param> /// <returns>Information inferred about the columns in the provided dataset.</returns> /// <remarks> /// Infers information about the name, data type, and purpose of each column. /// The returned <see cref="ColumnInferenceResults.TextLoaderOptions" /> can be used to /// instantiate a <see cref="TextLoader" />. The <see cref="TextLoader" /> can be used to /// obtain an <see cref="IDataView"/> that can be fed into an AutoML experiment, /// or used elsewhere in the ML.NET ecosystem (ie in <see cref="IEstimator{TTransformer}.Fit(IDataView)"/>. /// The <see cref="ColumnInformation"/> contains the inferred purpose of each column in the dataset. /// (For instance, is the column categorical, numeric, or text data? Should the column be ignored? Etc.) /// The <see cref="ColumnInformation"/> can be inspected and modified (or kept as is) and used by an AutoML experiment. /// </remarks> public ColumnInferenceResults InferColumns(string path, string labelColumnName = DefaultColumnNames.Label, char? separatorChar = null, bool? allowQuoting = null, bool? allowSparse = null, bool trimWhitespace = false, bool groupColumns = true) { UserInputValidationUtil.ValidateInferColumnsArgs(path, labelColumnName); return ColumnInferenceApi.InferColumns(_context, path, labelColumnName, separatorChar, allowQuoting, allowSparse, trimWhitespace, groupColumns); } /// <summary> /// Infers information about the columns of a dataset in a file located at <paramref name="path"/>. /// </summary> /// <param name="path">Path to a dataset file.</param> /// <param name="columnInformation">Column information for the dataset.</param> /// <param name="separatorChar">The character used as separator between data elements in a row. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowQuoting">Whether the file can contain columns defined by a quoted string. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowSparse">Whether the file can contain numerical vectors in sparse format. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="trimWhitespace">Whether trailing whitespace should be removed from dataset file lines.</param> /// <param name="groupColumns">Whether to group together (when possible) original columns in the dataset file into vector columns in the resulting data structures. See <see cref="TextLoader.Range"/> for more information.</param> /// <returns>Information inferred about the columns in the provided dataset.</returns> /// <remarks> /// Infers information about the name, data type, and purpose of each column. /// The returned <see cref="ColumnInferenceResults.TextLoaderOptions" /> can be used to /// instantiate a <see cref="TextLoader" />. The <see cref="TextLoader" /> can be used to /// obtain an <see cref="IDataView"/> that can be fed into an AutoML experiment, /// or used elsewhere in the ML.NET ecosystem (ie in <see cref="IEstimator{TTransformer}.Fit(IDataView)"/>. /// The <see cref="ColumnInformation"/> contains the inferred purpose of each column in the dataset. /// (For instance, is the column categorical, numeric, or text data? Should the column be ignored? Etc.) /// The <see cref="ColumnInformation"/> can be inspected and modified (or kept as is) and used by an AutoML experiment. /// </remarks> public ColumnInferenceResults InferColumns(string path, ColumnInformation columnInformation, char? separatorChar = null, bool? allowQuoting = null, bool? allowSparse = null, bool trimWhitespace = false, bool groupColumns = true) { columnInformation = columnInformation ?? new ColumnInformation(); UserInputValidationUtil.ValidateInferColumnsArgs(path, columnInformation); return ColumnInferenceApi.InferColumns(_context, path, columnInformation, separatorChar, allowQuoting, allowSparse, trimWhitespace, groupColumns); } /// <summary> /// Infers information about the columns of a dataset in a file located at <paramref name="path"/>. /// </summary> /// <param name="path">Path to a dataset file.</param> /// <param name="labelColumnIndex">Column index of the label column in the dataset.</param> /// <param name="hasHeader">Whether or not the dataset file has a header row.</param> /// <param name="separatorChar">The character used as separator between data elements in a row. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowQuoting">Whether the file can contain columns defined by a quoted string. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="allowSparse">Whether the file can contain numerical vectors in sparse format. If <see langword="null"/>, AutoML will try to infer this value.</param> /// <param name="trimWhitespace">Whether trailing whitespace should be removed from dataset file lines.</param> /// <param name="groupColumns">Whether to group together (when possible) original columns in the dataset file into vector columns in the resulting data structures. See <see cref="TextLoader.Range"/> for more information.</param> /// <returns>Information inferred about the columns in the provided dataset.</returns> /// <remarks> /// Infers information about the name, data type, and purpose of each column. /// The returned <see cref="ColumnInferenceResults.TextLoaderOptions" /> can be used to /// instantiate a <see cref="TextLoader" />. The <see cref="TextLoader" /> can be used to /// obtain an <see cref="IDataView"/> that can be fed into an AutoML experiment, /// or used elsewhere in the ML.NET ecosystem (ie in <see cref="IEstimator{TTransformer}.Fit(IDataView)"/>. /// The <see cref="ColumnInformation"/> contains the inferred purpose of each column in the dataset. /// (For instance, is the column categorical, numeric, or text data? Should the column be ignored? Etc.) /// The <see cref="ColumnInformation"/> can be inspected and modified (or kept as is) and used by an AutoML experiment. /// </remarks> public ColumnInferenceResults InferColumns(string path, uint labelColumnIndex, bool hasHeader = false, char? separatorChar = null, bool? allowQuoting = null, bool? allowSparse = null, bool trimWhitespace = false, bool groupColumns = true) { UserInputValidationUtil.ValidateInferColumnsArgs(path); return ColumnInferenceApi.InferColumns(_context, path, labelColumnIndex, hasHeader, separatorChar, allowQuoting, allowSparse, trimWhitespace, groupColumns); } /// <summary> /// Create a sweepable estimator with a custom factory and search space. /// </summary> /// <example> /// <format type="text/markdown"> /// <![CDATA[ /// [!code-csharp[AutoMLExperiment](~/../docs/samples/docs/samples/Microsoft.ML.AutoML.Samples/Sweepable/SweepableLightGBMBinaryExperiment.cs)] /// ]]> /// </format> /// </example> public SweepableEstimator CreateSweepableEstimator<T>(Func<MLContext, T, IEstimator<ITransformer>> factory, SearchSpace<T> ss = null) where T : class, new() { return new SweepableEstimator((MLContext context, Parameter param) => factory(context, param.AsType<T>()), ss); } /// <summary> /// Create an <see cref="AutoMLExperiment"/>. /// </summary> public AutoMLExperiment CreateExperiment(AutoMLExperiment.AutoMLExperimentSettings settings = null) { return new AutoMLExperiment(_context, settings ?? new AutoMLExperiment.AutoMLExperimentSettings()); } /// <summary> /// Create a list of <see cref="SweepableEstimator"/> for binary classification. /// </summary> /// <param name="labelColumnName">label column name.</param> /// <param name="featureColumnName">feature column name.</param> /// <param name="exampleWeightColumnName">example weight column name.</param> /// <param name="useFastForest">true if use fast forest as available trainer.</param> /// <param name="useLgbm">true if use lgbm as available trainer.</param> /// <param name="useFastTree">true if use fast tree as available trainer.</param> /// <param name="useLbfgsLogisticRegression">true if use <see cref="LbfgsLogisticRegressionBinaryTrainer"/> as available trainer.</param> /// <param name="useSdcaLogisticRegression">true if use <see cref="SdcaLogisticRegressionBinaryTrainer"/> as available trainer.</param> /// <param name="fastTreeOption">if provided, use it as initial option for fast tree, otherwise the default option will be used.</param> /// <param name="lgbmOption">if provided, use it as initial option for lgbm, otherwise the default option will be used.</param> /// <param name="fastForestOption">if provided, use it as initial option for fast forest, otherwise the default option will be used.</param> /// <param name="lbfgsLogisticRegressionOption">if provided, use it as initial option for <paramref name="lbfgsLogisticRegressionSearchSpace"/>, otherwise the default option will be used.</param> /// <param name="sdcaLogisticRegressionOption">if provided, use it as initial option for <paramref name="sdcaLogisticRegressionSearchSpace"/>, otherwise the default option will be used.</param> /// <param name="fastTreeSearchSpace">if provided, use it as search space for fast tree, otherwise the default search space will be used.</param> /// <param name="lgbmSearchSpace">if provided, use it as search space for lgbm, otherwise the default search space will be used.</param> /// <param name="fastForestSearchSpace">if provided, use it as search space for fast forest, otherwise the default search space will be used.</param> /// <param name="lbfgsLogisticRegressionSearchSpace">if provided, use it as search space for <see cref="LbfgsLogisticRegressionBinaryTrainer"/>, otherwise the default search space will be used.</param> /// <param name="sdcaLogisticRegressionSearchSpace">if provided, use it as search space for <see cref="SdcaLogisticRegressionBinaryTrainer"/>, otherwise the default search space will be used.</param> /// <returns></returns> public SweepablePipeline BinaryClassification(string labelColumnName = DefaultColumnNames.Label, string featureColumnName = DefaultColumnNames.Features, string exampleWeightColumnName = null, bool useFastForest = true, bool useLgbm = true, bool useFastTree = true, bool useLbfgsLogisticRegression = true, bool useSdcaLogisticRegression = true, FastTreeOption fastTreeOption = null, LgbmOption lgbmOption = null, FastForestOption fastForestOption = null, LbfgsOption lbfgsLogisticRegressionOption = null, SdcaOption sdcaLogisticRegressionOption = null, SearchSpace<FastTreeOption> fastTreeSearchSpace = null, SearchSpace<LgbmOption> lgbmSearchSpace = null, SearchSpace<FastForestOption> fastForestSearchSpace = null, SearchSpace<LbfgsOption> lbfgsLogisticRegressionSearchSpace = null, SearchSpace<SdcaOption> sdcaLogisticRegressionSearchSpace = null) { var res = new List<SweepableEstimator>(); if (useFastTree) { fastTreeOption = fastTreeOption ?? new FastTreeOption(); fastTreeOption.LabelColumnName = labelColumnName; fastTreeOption.FeatureColumnName = featureColumnName; fastTreeOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateFastTreeBinary(fastTreeOption, fastTreeSearchSpace ?? new SearchSpace<FastTreeOption>(fastTreeOption))); } if (useFastForest) { fastForestOption = fastForestOption ?? new FastForestOption(); fastForestOption.LabelColumnName = labelColumnName; fastForestOption.FeatureColumnName = featureColumnName; fastForestOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateFastForestBinary(fastForestOption, fastForestSearchSpace ?? new SearchSpace<FastForestOption>(fastForestOption))); } if (useLgbm) { lgbmOption = lgbmOption ?? new LgbmOption(); lgbmOption.LabelColumnName = labelColumnName; lgbmOption.FeatureColumnName = featureColumnName; lgbmOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateLightGbmBinary(lgbmOption, lgbmSearchSpace ?? new SearchSpace<LgbmOption>(lgbmOption))); } if (useLbfgsLogisticRegression) { lbfgsLogisticRegressionOption = lbfgsLogisticRegressionOption ?? new LbfgsOption(); lbfgsLogisticRegressionOption.LabelColumnName = labelColumnName; lbfgsLogisticRegressionOption.FeatureColumnName = featureColumnName; lbfgsLogisticRegressionOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateLbfgsLogisticRegressionBinary(lbfgsLogisticRegressionOption, lbfgsLogisticRegressionSearchSpace ?? new SearchSpace<LbfgsOption>(lbfgsLogisticRegressionOption))); } if (useSdcaLogisticRegression) { sdcaLogisticRegressionOption = sdcaLogisticRegressionOption ?? new SdcaOption(); sdcaLogisticRegressionOption.LabelColumnName = labelColumnName; sdcaLogisticRegressionOption.FeatureColumnName = featureColumnName; sdcaLogisticRegressionOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateSdcaLogisticRegressionBinary(sdcaLogisticRegressionOption, sdcaLogisticRegressionSearchSpace ?? new SearchSpace<SdcaOption>(sdcaLogisticRegressionOption))); } return new SweepablePipeline().Append(res.ToArray()); } /// <summary> /// Create a list of <see cref="SweepableEstimator"/> for multiclass classification. /// </summary> /// <param name="labelColumnName">label column name.</param> /// <param name="featureColumnName">feature column name.</param> /// <param name="exampleWeightColumnName">example weight column name.</param> /// <param name="useFastForest">true if use fast forest as available trainer.</param> /// <param name="useLgbm">true if use lgbm as available trainer.</param> /// <param name="useFastTree">true if use fast tree as available trainer.</param> /// <param name="useLbfgsMaximumEntrophy">true if use <see cref="LbfgsMaximumEntropyMulticlassTrainer"/> as available trainer.</param> /// <param name="useLbfgsLogisticRegression">true if use <see cref="LbfgsLogisticRegressionBinaryTrainer"/> as available trainer.</param> /// <param name="useSdcaMaximumEntrophy">true if use <see cref="SdcaMaximumEntropyMulticlassTrainer"/> as available trainer.</param> /// <param name="useSdcaLogisticRegression">true if use <see cref="SdcaLogisticRegressionBinaryTrainer"/> as available trainer.</param> /// <param name="fastTreeOption">if provided, use it as initial option for fast tree, otherwise the default option will be used.</param> /// <param name="lgbmOption">if provided, use it as initial option for lgbm, otherwise the default option will be used.</param> /// <param name="fastForestOption">if provided, use it as initial option for fast forest, otherwise the default option will be used.</param> /// <param name="lbfgsMaximumEntrophyOption">if provided, use it as initial option for <paramref name="lbfgsMaximumEntrophySearchSpace"/>, otherwise the default option will be used.</param> /// <param name="lbfgsLogisticRegressionOption">if provided, use it as initial option for <paramref name="lbfgsLogisticRegressionSearchSpace"/>, otherwise the default option will be used.</param> /// <param name="sdcaMaximumEntrophyOption">if provided, use it as initial option for <paramref name="sdcaMaximumEntorphySearchSpace"/>, otherwise the default option will be used.</param> /// <param name="sdcaLogisticRegressionOption">if provided, use it as initial option for <paramref name="sdcaLogisticRegressionSearchSpace"/>, otherwise the default option will be used.</param> /// <param name="fastTreeSearchSpace">if provided, use it as search space for fast tree, otherwise the default search space will be used.</param> /// <param name="lgbmSearchSpace">if provided, use it as search space for lgbm, otherwise the default search space will be used.</param> /// <param name="fastForestSearchSpace">if provided, use it as search space for fast forest, otherwise the default search space will be used.</param> /// <param name="lbfgsMaximumEntrophySearchSpace">if provided, use it as search space for <see cref="LbfgsMaximumEntropyMulticlassTrainer"/>, otherwise the default search space will be used.</param> /// <param name="lbfgsLogisticRegressionSearchSpace">if provided, use it as search space for <see cref="LbfgsMaximumEntropyMulticlassTrainer"/>, otherwise the default search space will be used.</param> /// <param name="sdcaMaximumEntorphySearchSpace">if provided, use it as search space for <see cref="SdcaMaximumEntropyMulti"/>, otherwise the default search space will be used.</param> /// <param name="sdcaLogisticRegressionSearchSpace">if provided, use it as search space for <see cref="SdcaLogisticRegressionBinaryTrainer"/>, otherwise the default search space will be used.</param> /// <returns></returns> public SweepablePipeline MultiClassification( string labelColumnName = DefaultColumnNames.Label, string featureColumnName = DefaultColumnNames.Features, string exampleWeightColumnName = null, bool useFastForest = true, bool useLgbm = true, bool useFastTree = true, bool useLbfgsMaximumEntrophy = true, bool useLbfgsLogisticRegression = true, bool useSdcaMaximumEntrophy = true, bool useSdcaLogisticRegression = true, FastTreeOption fastTreeOption = null, LgbmOption lgbmOption = null, FastForestOption fastForestOption = null, LbfgsOption lbfgsMaximumEntrophyOption = null, LbfgsOption lbfgsLogisticRegressionOption = null, SdcaOption sdcaMaximumEntrophyOption = null, SdcaOption sdcaLogisticRegressionOption = null, SearchSpace<FastTreeOption> fastTreeSearchSpace = null, SearchSpace<LgbmOption> lgbmSearchSpace = null, SearchSpace<FastForestOption> fastForestSearchSpace = null, SearchSpace<LbfgsOption> lbfgsMaximumEntrophySearchSpace = null, SearchSpace<LbfgsOption> lbfgsLogisticRegressionSearchSpace = null, SearchSpace<SdcaOption> sdcaMaximumEntorphySearchSpace = null, SearchSpace<SdcaOption> sdcaLogisticRegressionSearchSpace = null) { var res = new List<SweepableEstimator>(); if (useFastTree) { fastTreeOption = fastTreeOption ?? new FastTreeOption(); fastTreeOption.LabelColumnName = labelColumnName; fastTreeOption.FeatureColumnName = featureColumnName; fastTreeOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateFastTreeOva(fastTreeOption, fastTreeSearchSpace ?? new SearchSpace<FastTreeOption>(fastTreeOption))); } if (useFastForest) { fastForestOption = fastForestOption ?? new FastForestOption(); fastForestOption.LabelColumnName = labelColumnName; fastForestOption.FeatureColumnName = featureColumnName; fastForestOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateFastForestOva(fastForestOption, fastForestSearchSpace ?? new SearchSpace<FastForestOption>(fastForestOption))); } if (useLgbm) { lgbmOption = lgbmOption ?? new LgbmOption(); lgbmOption.LabelColumnName = labelColumnName; lgbmOption.FeatureColumnName = featureColumnName; lgbmOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateLightGbmMulti(lgbmOption, lgbmSearchSpace ?? new SearchSpace<LgbmOption>(lgbmOption))); } if (useLbfgsLogisticRegression) { lbfgsLogisticRegressionOption = lbfgsLogisticRegressionOption ?? new LbfgsOption(); lbfgsLogisticRegressionOption.LabelColumnName = labelColumnName; lbfgsLogisticRegressionOption.FeatureColumnName = featureColumnName; lbfgsLogisticRegressionOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateLbfgsLogisticRegressionOva(lbfgsLogisticRegressionOption, lbfgsLogisticRegressionSearchSpace ?? new SearchSpace<LbfgsOption>(lbfgsLogisticRegressionOption))); } if (useLbfgsMaximumEntrophy) { lbfgsMaximumEntrophyOption = lbfgsMaximumEntrophyOption ?? new LbfgsOption(); lbfgsMaximumEntrophyOption.LabelColumnName = labelColumnName; lbfgsMaximumEntrophyOption.FeatureColumnName = featureColumnName; lbfgsMaximumEntrophyOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateLbfgsMaximumEntropyMulti(lbfgsMaximumEntrophyOption, lbfgsMaximumEntrophySearchSpace ?? new SearchSpace<LbfgsOption>(lbfgsMaximumEntrophyOption))); } if (useSdcaMaximumEntrophy) { sdcaMaximumEntrophyOption = sdcaMaximumEntrophyOption ?? new SdcaOption(); sdcaMaximumEntrophyOption.LabelColumnName = labelColumnName; sdcaMaximumEntrophyOption.FeatureColumnName = featureColumnName; sdcaMaximumEntrophyOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateSdcaMaximumEntropyMulti(sdcaMaximumEntrophyOption, sdcaMaximumEntorphySearchSpace ?? new SearchSpace<SdcaOption>(sdcaMaximumEntrophyOption))); } if (useSdcaLogisticRegression) { sdcaLogisticRegressionOption = sdcaLogisticRegressionOption ?? new SdcaOption(); sdcaLogisticRegressionOption.LabelColumnName = labelColumnName; sdcaLogisticRegressionOption.FeatureColumnName = featureColumnName; sdcaLogisticRegressionOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateSdcaLogisticRegressionOva(sdcaLogisticRegressionOption, sdcaLogisticRegressionSearchSpace ?? new SearchSpace<SdcaOption>(sdcaLogisticRegressionOption))); } return new SweepablePipeline().Append(res.ToArray()); } /// <summary> /// Create a list of <see cref="SweepableEstimator"/> for regression. /// </summary> /// <param name="labelColumnName">label column name.</param> /// <param name="featureColumnName">feature column name.</param> /// <param name="exampleWeightColumnName">example weight column name.</param> /// <param name="useFastForest">true if use fast forest as available trainer.</param> /// <param name="useLgbm">true if use lgbm as available trainer.</param> /// <param name="useFastTree">true if use fast tree as available trainer.</param> /// <param name="useLbfgsPoissonRegression">true if use <see cref="LbfgsPoissonRegressionTrainer"/> as available trainer.</param> /// <param name="useSdca">true if use <see cref="SdcaRegressionTrainer"/> as available trainer.</param> /// <param name="fastTreeOption">if provided, use it as initial option for fast tree, otherwise the default option will be used.</param> /// <param name="lgbmOption">if provided, use it as initial option for lgbm, otherwise the default option will be used.</param> /// <param name="fastForestOption">if provided, use it as initial option for fast forest, otherwise the default option will be used.</param> /// <param name="lbfgsPoissonRegressionOption">if provided, use it as initial option for <paramref name="lbfgsPoissonRegressionSearchSpace"/>, otherwise the default option will be used.</param> /// <param name="sdcaOption">if provided, use it as initial option for <paramref name="sdcaSearchSpace"/>, otherwise the default option will be used.</param> /// <param name="fastTreeSearchSpace">if provided, use it as search space for fast tree, otherwise the default search space will be used.</param> /// <param name="lgbmSearchSpace">if provided, use it as search space for lgbm, otherwise the default search space will be used.</param> /// <param name="fastForestSearchSpace">if provided, use it as search space for fast forest, otherwise the default search space will be used.</param> /// <param name="lbfgsPoissonRegressionSearchSpace">if provided, use it as search space for <see cref="LbfgsPoissonRegressionTrainer"/>, otherwise the default search space will be used.</param> /// <param name="sdcaSearchSpace">if provided, use it as search space for sdca, otherwise the default search space will be used.</param> /// <returns></returns> public SweepablePipeline Regression( string labelColumnName = DefaultColumnNames.Label, string featureColumnName = DefaultColumnNames.Features, string exampleWeightColumnName = null, bool useFastForest = true, bool useLgbm = true, bool useFastTree = true, bool useLbfgsPoissonRegression = true, bool useSdca = true, FastTreeOption fastTreeOption = null, LgbmOption lgbmOption = null, FastForestOption fastForestOption = null, LbfgsOption lbfgsPoissonRegressionOption = null, SdcaOption sdcaOption = null, SearchSpace<FastTreeOption> fastTreeSearchSpace = null, SearchSpace<LgbmOption> lgbmSearchSpace = null, SearchSpace<FastForestOption> fastForestSearchSpace = null, SearchSpace<LbfgsOption> lbfgsPoissonRegressionSearchSpace = null, SearchSpace<SdcaOption> sdcaSearchSpace = null) { var res = new List<SweepableEstimator>(); if (useFastTree) { fastTreeOption = fastTreeOption ?? new FastTreeOption(); fastTreeOption.LabelColumnName = labelColumnName; fastTreeOption.FeatureColumnName = featureColumnName; fastTreeOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateFastTreeRegression(fastTreeOption, fastTreeSearchSpace ?? new SearchSpace<FastTreeOption>(fastTreeOption))); } if (useFastForest) { fastForestOption = fastForestOption ?? new FastForestOption(); fastForestOption.LabelColumnName = labelColumnName; fastForestOption.FeatureColumnName = featureColumnName; fastForestOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateFastForestRegression(fastForestOption, fastForestSearchSpace ?? new SearchSpace<FastForestOption>(fastForestOption))); } if (useLgbm) { lgbmOption = lgbmOption ?? new LgbmOption(); lgbmOption.LabelColumnName = labelColumnName; lgbmOption.FeatureColumnName = featureColumnName; lgbmOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateLightGbmRegression(lgbmOption, lgbmSearchSpace ?? new SearchSpace<LgbmOption>(lgbmOption))); } if (useLbfgsPoissonRegression) { lbfgsPoissonRegressionOption = lbfgsPoissonRegressionOption ?? new LbfgsOption(); lbfgsPoissonRegressionOption.LabelColumnName = labelColumnName; lbfgsPoissonRegressionOption.FeatureColumnName = featureColumnName; lbfgsPoissonRegressionOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateLbfgsPoissonRegressionRegression(lbfgsPoissonRegressionOption, lbfgsPoissonRegressionSearchSpace ?? new SearchSpace<LbfgsOption>(lbfgsPoissonRegressionOption))); } if (useSdca) { sdcaOption = sdcaOption ?? new SdcaOption(); sdcaOption.LabelColumnName = labelColumnName; sdcaOption.FeatureColumnName = featureColumnName; sdcaOption.ExampleWeightColumnName = exampleWeightColumnName; res.Add(SweepableEstimatorFactory.CreateSdcaRegression(sdcaOption, sdcaSearchSpace ?? new SearchSpace<SdcaOption>(sdcaOption))); } return new SweepablePipeline().Append(res.ToArray()); } /// <summary> /// Create a list of <see cref="SweepableEstimator"/> for featurizing text. /// </summary> /// <param name="outputColumnName">output column name.</param> /// <param name="inputColumnName">input column name.</param> internal SweepablePipeline TextFeaturizer(string outputColumnName, string inputColumnName) { var option = new FeaturizeTextOption { InputColumnName = inputColumnName, OutputColumnName = outputColumnName, }; return new SweepablePipeline().Append(new[] { SweepableEstimatorFactory.CreateFeaturizeText(option) }); } /// <summary> /// Create a <see cref="SweepablePipeline"/> for featurizing numeric columns. /// </summary> /// <param name="outputColumnNames">output column names.</param> /// <param name="inputColumnNames">input column names.</param> internal SweepablePipeline NumericFeaturizer(string[] outputColumnNames, string[] inputColumnNames) { Contracts.CheckValue(inputColumnNames, nameof(inputColumnNames)); Contracts.CheckValue(outputColumnNames, nameof(outputColumnNames)); Contracts.Check(outputColumnNames.Count() == inputColumnNames.Count() && outputColumnNames.Count() > 0, "outputColumnNames and inputColumnNames must have the same length and greater than 0"); var replaceMissingValueOption = new ReplaceMissingValueOption { InputColumnNames = inputColumnNames, OutputColumnNames = outputColumnNames, }; return new SweepablePipeline().Append(new[] { SweepableEstimatorFactory.CreateReplaceMissingValues(replaceMissingValueOption) }); } /// <summary> /// Create a <see cref="SweepablePipeline"/> for featurizing boolean columns. This pipeline convert all boolean column /// to numeric type. /// </summary> /// <param name="outputColumnNames">output column names.</param> /// <param name="inputColumnNames">input column names.</param> /// <returns>a list of <see cref="SweepableEstimator"/></returns> internal SweepableEstimator[] BooleanFeaturizer(string[] outputColumnNames, string[] inputColumnNames) { Contracts.CheckValue(inputColumnNames, nameof(inputColumnNames)); Contracts.CheckValue(outputColumnNames, nameof(outputColumnNames)); Contracts.Check(outputColumnNames.Count() == inputColumnNames.Count() && outputColumnNames.Count() > 0, "outputColumnNames and inputColumnNames must have the same length and greater than 0"); // by default, convertType's output kind is single var convertTypeOption = new ConvertTypeOption { InputColumnNames = inputColumnNames, OutputColumnNames = outputColumnNames, }; return new[] { SweepableEstimatorFactory.CreateConvertType(convertTypeOption) }; } /// <summary> /// Create a list of <see cref="SweepableEstimator"/> for featurizing catalog columns. /// </summary> /// <param name="outputColumnNames">output column names.</param> /// <param name="inputColumnNames">input column names.</param> internal SweepablePipeline CatalogFeaturizer(string[] outputColumnNames, string[] inputColumnNames) { Contracts.Check(outputColumnNames.Count() == inputColumnNames.Count() && outputColumnNames.Count() > 0, "outputColumnNames and inputColumnNames must have the same length and greater than 0"); var option = new OneHotOption { InputColumnNames = inputColumnNames, OutputColumnNames = outputColumnNames, }; return new SweepablePipeline().Append(new SweepableEstimator[] { SweepableEstimatorFactory.CreateOneHotEncoding(option), SweepableEstimatorFactory.CreateOneHotHashEncoding(option) }); } internal SweepablePipeline ImagePathFeaturizer(string outputColumnName, string inputColumnName) { // load image => resize image (224, 224) => extract pixels => dnn featurizer var loadImageOption = new LoadImageOption { ImageFolder = null, InputColumnName = inputColumnName, OutputColumnName = outputColumnName, }; var resizeImageOption = new ResizeImageOption { ImageHeight = 224, ImageWidth = 224, InputColumnName = inputColumnName, OutputColumnName = outputColumnName, }; var extractPixelOption = new ExtractPixelsOption { InputColumnName = inputColumnName, OutputColumnName = outputColumnName, }; var dnnFeaturizerOption = new DnnFeaturizerImageOption { InputColumnName = inputColumnName, OutputColumnName = outputColumnName, }; var pipeline = new SweepablePipeline(); return pipeline.Append(SweepableEstimatorFactory.CreateLoadImages(loadImageOption)) .Append(SweepableEstimatorFactory.CreateResizeImages(resizeImageOption)) .Append(SweepableEstimatorFactory.CreateExtractPixels(extractPixelOption)) .Append(SweepableEstimatorFactory.CreateDnnFeaturizerImage(dnnFeaturizerOption)); } /// <summary> /// Create a single featurize pipeline according to <paramref name="data"/>. This function will collect all columns in <paramref name="data"/> and not in <paramref name="excludeColumns"/>, /// featurizing them using <see cref="CatalogFeaturizer(string[], string[])"/>, <see cref="NumericFeaturizer(string[], string[])"/> or <see cref="TextFeaturizer(string, string)"/>. And combine /// them into a single feature column as output. /// </summary> /// <param name="data">input data.</param> /// <param name="catelogicalColumns">columns that should be treated as catalog. If not specified, it will automatically infer if a column is catalog or not.</param> /// <param name="numericColumns">columns that should be treated as numeric. If not specified, it will automatically infer if a column is catalog or not.</param> /// <param name="textColumns">columns that should be treated as text. If not specified, it will automatically infer if a column is catalog or not.</param> /// <param name="imagePathColumns">columns that should be treated as image path. If not specified, it will automatically infer if a column is catalog or not.</param> /// <param name="outputColumnName">output feature column.</param> /// <param name="excludeColumns">columns that won't be included when featurizing, like label</param> public SweepablePipeline Featurizer(IDataView data, string outputColumnName = "Features", string[] catelogicalColumns = null, string[] numericColumns = null, string[] textColumns = null, string[] imagePathColumns = null, string[] excludeColumns = null) { Contracts.CheckValue(data, nameof(data)); // validate if there's overlapping among catalogColumns, numericColumns, textColumns and excludeColumns var overallColumns = new string[][] { catelogicalColumns, numericColumns, textColumns, excludeColumns } .Where(c => c != null) .SelectMany(c => c); if (overallColumns != null) { Contracts.Assert(overallColumns.Count() == overallColumns.Distinct().Count(), "detect overlapping among catalogColumns, numericColumns, textColumns and excludedColumns"); } var columnInfo = new ColumnInformation(); if (excludeColumns != null) { foreach (var ignoreColumn in excludeColumns) { columnInfo.IgnoredColumnNames.Add(ignoreColumn); } } if (catelogicalColumns != null) { foreach (var catalogColumn in catelogicalColumns) { columnInfo.CategoricalColumnNames.Add(catalogColumn); } } if (numericColumns != null) { foreach (var column in numericColumns) { columnInfo.NumericColumnNames.Add(column); } } if (textColumns != null) { foreach (var column in textColumns) { columnInfo.TextColumnNames.Add(column); } } if (imagePathColumns != null) { foreach (var column in imagePathColumns) { columnInfo.ImagePathColumnNames.Add(column); } } return this.Featurizer(data, columnInfo, outputColumnName); } /// <summary> /// Create a single featurize pipeline according to <paramref name="columnInformation"/>. This function will collect all columns in <paramref name="columnInformation"/>, /// featurizing them using <see cref="CatalogFeaturizer(string[], string[])"/>, <see cref="NumericFeaturizer(string[], string[])"/> or <see cref="TextFeaturizer(string, string)"/>. And combine /// them into a single feature column as output. /// </summary> /// <param name="data">input data.</param> /// <param name="columnInformation">column information.</param> /// <param name="outputColumnName">output feature column.</param> /// <returns>A <see cref="SweepablePipeline"/> for featurization.</returns> public SweepablePipeline Featurizer(IDataView data, ColumnInformation columnInformation, string outputColumnName = "Features") { Contracts.CheckValue(data, nameof(data)); Contracts.CheckValue(columnInformation, nameof(columnInformation)); var columnPurposes = PurposeInference.InferPurposes(this._context, data, columnInformation); var textFeatures = columnPurposes.Where(c => c.Purpose == ColumnPurpose.TextFeature); var numericFeatures = columnPurposes.Where(c => c.Purpose == ColumnPurpose.NumericFeature && data.Schema[c.ColumnIndex].Type != BooleanDataViewType.Instance && !(data.Schema[c.ColumnIndex].Type is VectorDataViewType vt && vt.ItemType == BooleanDataViewType.Instance)).ToArray(); var booleanFeatures = columnPurposes.Where(c => c.Purpose == ColumnPurpose.NumericFeature && !numericFeatures.Contains(c)); var catalogFeatures = columnPurposes.Where(c => c.Purpose == ColumnPurpose.CategoricalFeature); var imagePathFeatures = columnPurposes.Where(c => c.Purpose == ColumnPurpose.ImagePath); var textFeatureColumnNames = textFeatures.Select(c => data.Schema[c.ColumnIndex].Name).ToArray(); var numericFeatureColumnNames = numericFeatures.Select(c => data.Schema[c.ColumnIndex].Name).ToArray(); var catalogFeatureColumnNames = catalogFeatures.Select(c => data.Schema[c.ColumnIndex].Name).ToArray(); var imagePathColumnNames = imagePathFeatures.Select(c => data.Schema[c.ColumnIndex].Name).ToArray(); var booleanFeatureColumnNames = booleanFeatures.Select(c => data.Schema[c.ColumnIndex].Name).ToArray(); var pipeline = new SweepablePipeline(); if (numericFeatureColumnNames.Length > 0) { pipeline = pipeline.Append(this.NumericFeaturizer(numericFeatureColumnNames, numericFeatureColumnNames)); } if (booleanFeatureColumnNames.Length > 0) { pipeline = pipeline.Append(this.BooleanFeaturizer(booleanFeatureColumnNames, booleanFeatureColumnNames)); } if (catalogFeatureColumnNames.Length > 0) { pipeline = pipeline.Append(this.CatalogFeaturizer(catalogFeatureColumnNames, catalogFeatureColumnNames)); } foreach (var imagePathColumn in imagePathColumnNames) { pipeline = pipeline.Append(this.ImagePathFeaturizer(imagePathColumn, imagePathColumn)); } foreach (var textColumn in textFeatureColumnNames) { pipeline = pipeline.Append(this.TextFeaturizer(textColumn, textColumn)); } var option = new ConcatOption { InputColumnNames = textFeatureColumnNames.Concat(numericFeatureColumnNames).Concat(catalogFeatureColumnNames).Concat(imagePathColumnNames).Concat(booleanFeatureColumnNames).ToArray(), OutputColumnName = outputColumnName, }; if (option.InputColumnNames.Length > 0) { pipeline = pipeline.Append(SweepableEstimatorFactory.CreateConcatenate(option)); } return pipeline; } } }
AutoCatalog
csharp
dotnet__aspnetcore
src/Shared/StackTrace/StackFrame/StackTraceHelper.cs
{ "start": 507, "end": 8552 }
internal sealed class ____ { [UnconditionalSuppressMessage("Trimmer", "IL2026", Justification = "MethodInfo for a stack frame might be incomplete or removed. GetFrames does the best it can to provide frame details.")] public static IList<StackFrameInfo> GetFrames(Exception exception, out AggregateException? error) { if (exception == null) { error = default; return Array.Empty<StackFrameInfo>(); } var needFileInfo = true; var stackTrace = new System.Diagnostics.StackTrace(exception, needFileInfo); var stackFrames = stackTrace.GetFrames(); if (stackFrames == null) { error = default; return Array.Empty<StackFrameInfo>(); } var frames = new List<StackFrameInfo>(stackFrames.Length); List<Exception>? exceptions = null; for (var i = 0; i < stackFrames.Length; i++) { var frame = stackFrames[i]; var method = frame.GetMethod(); // MethodInfo should always be available for methods in the stack, but double check for null here. // Apps with trimming enabled may remove some metadata. Better to be safe than sorry. if (method == null) { continue; } // Always show last stackFrame if (!ShowInStackTrace(method) && i < stackFrames.Length - 1) { continue; } var stackFrame = new StackFrameInfo(frame.GetFileLineNumber(), frame.GetFileName(), frame, GetMethodDisplayString(method)); frames.Add(stackFrame); } if (exceptions != null) { error = new AggregateException(exceptions); return frames; } error = default; return frames; } internal static MethodDisplayInfo? GetMethodDisplayString(MethodBase? method) { // Special case: no method available if (method == null) { return null; } // Type name var type = method.DeclaringType; var methodName = method.Name; string? subMethod = null; if (type != null && type.IsDefined(typeof(CompilerGeneratedAttribute)) && (typeof(IAsyncStateMachine).IsAssignableFrom(type) || typeof(IEnumerator).IsAssignableFrom(type))) { // Convert StateMachine methods to correct overload +MoveNext() if (TryResolveStateMachineMethod(ref method, out type)) { subMethod = methodName; } } string? declaringTypeName = null; // ResolveStateMachineMethod may have set declaringType to null if (type != null) { declaringTypeName = TypeNameHelper.GetTypeDisplayName(type, includeGenericParameterNames: true); } string? genericArguments = null; if (method.IsGenericMethod) { genericArguments = "<" + string.Join(", ", method.GetGenericArguments() .Select(arg => TypeNameHelper.GetTypeDisplayName(arg, fullName: false, includeGenericParameterNames: true))) + ">"; } // Method parameters var parameters = method.GetParameters().Select(parameter => { var parameterType = parameter.ParameterType; var prefix = string.Empty; if (parameter.IsOut) { prefix = "out"; } else if (parameterType != null && parameterType.IsByRef) { prefix = "ref"; } var parameterTypeString = "?"; if (parameterType != null) { if (parameterType.IsByRef) { parameterType = parameterType.GetElementType(); } parameterTypeString = TypeNameHelper.GetTypeDisplayName(parameterType!, fullName: false, includeGenericParameterNames: true); } return new ParameterDisplayInfo { Prefix = prefix, Name = parameter.Name, Type = parameterTypeString, }; }); var methodDisplayInfo = new MethodDisplayInfo(declaringTypeName, method.Name, genericArguments, subMethod, parameters); return methodDisplayInfo; } private static bool ShowInStackTrace(MethodBase method) { // Don't show any methods marked with the StackTraceHiddenAttribute // https://github.com/dotnet/coreclr/pull/14652 if (HasStackTraceHiddenAttribute(method)) { return false; } var type = method.DeclaringType; if (type == null) { return true; } if (HasStackTraceHiddenAttribute(type)) { return false; } // Fallbacks for runtime pre-StackTraceHiddenAttribute if (type == typeof(ExceptionDispatchInfo) && method.Name == "Throw") { return false; } else if (type == typeof(TaskAwaiter) || type == typeof(TaskAwaiter<>) || type == typeof(ConfiguredTaskAwaitable.ConfiguredTaskAwaiter) || type == typeof(ConfiguredTaskAwaitable<>.ConfiguredTaskAwaiter)) { switch (method.Name) { case "HandleNonSuccessAndDebuggerNotification": case "ThrowForNonSuccess": case "ValidateEnd": case "GetResult": return false; } } return true; } [UnconditionalSuppressMessage("Trimmer", "IL2075", Justification = "Unable to require a method has all information on it to resolve state machine.")] private static bool TryResolveStateMachineMethod(ref MethodBase method, out Type? declaringType) { Debug.Assert(method != null); Debug.Assert(method.DeclaringType != null); declaringType = method.DeclaringType; var parentType = declaringType.DeclaringType; if (parentType == null) { return false; } var methods = parentType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly); if (methods == null) { return false; } foreach (var candidateMethod in methods) { var attributes = candidateMethod.GetCustomAttributes<StateMachineAttribute>(); if (attributes == null) { continue; } foreach (var asma in attributes) { if (asma.StateMachineType == declaringType) { method = candidateMethod; declaringType = candidateMethod.DeclaringType; // Mark the iterator as changed; so it gets the + annotation of the original method // async statemachines resolve directly to their builder methods so aren't marked as changed return asma is IteratorStateMachineAttribute; } } } return false; } private static bool HasStackTraceHiddenAttribute(MemberInfo memberInfo) { IList<CustomAttributeData> attributes; try { // Accessing MemberInfo.GetCustomAttributesData throws for some types (such as types in dynamically generated assemblies). // We'll skip looking up StackTraceHiddenAttributes on such types. attributes = memberInfo.GetCustomAttributesData(); } catch { return false; } for (var i = 0; i < attributes.Count; i++) { if (attributes[i].AttributeType.Name == "StackTraceHiddenAttribute") { return true; } } return false; } }
StackTraceHelper
csharp
dotnet__reactive
Ix.NET/Source/System.Interactive.Async.Tests/System/Linq/Operators/Amb.cs
{ "start": 363, "end": 8929 }
public class ____ : AsyncEnumerableExTests { [Fact] public void Amb_Null() { Assert.Throws<ArgumentNullException>(() => AsyncEnumerableEx.Amb(default, Return42)); Assert.Throws<ArgumentNullException>(() => AsyncEnumerableEx.Amb(Return42, default)); } [Fact] public async Task Amb_First_Wins() { var source = AsyncEnumerable.Range(1, 5).Amb(AsyncEnumerableEx.Never<int>()); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_First_Wins_Alt() { var source = AsyncEnumerable.Range(1, 5).Amb(AsyncEnumerable.Range(1, 5).SelectAwait(async v => { await Task.Delay(500); return v; })); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Second_Wins() { var source = AsyncEnumerableEx.Never<int>().Amb(AsyncEnumerable.Range(1, 5)); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Second_Wins_Alt() { var source = AsyncEnumerable.Range(1, 5).SelectAwait(async v => { await Task.Delay(500); return v; }).Amb(AsyncEnumerable.Range(6, 5)); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i + 5, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Many_First_Wins() { var source = AsyncEnumerableEx.Amb( AsyncEnumerable.Range(1, 5), AsyncEnumerableEx.Never<int>(), AsyncEnumerableEx.Never<int>() ); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Many_Last_Wins() { var source = AsyncEnumerableEx.Amb( AsyncEnumerableEx.Never<int>(), AsyncEnumerableEx.Never<int>(), AsyncEnumerable.Range(1, 5) ); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Many_Enum_First_Wins() { var source = AsyncEnumerableEx.Amb(new[] { AsyncEnumerable.Range(1, 5), AsyncEnumerableEx.Never<int>(), AsyncEnumerableEx.Never<int>() }.AsEnumerable() ); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Many_Enum_Last_Wins() { var source = AsyncEnumerableEx.Amb(new[] { AsyncEnumerableEx.Never<int>(), AsyncEnumerableEx.Never<int>(), AsyncEnumerable.Range(1, 5) }.AsEnumerable() ); var xs = source.GetAsyncEnumerator(); try { for (var i = 1; i <= 5; i++) { Assert.True(await xs.MoveNextAsync()); Assert.Equal(i, xs.Current); } Assert.False(await xs.MoveNextAsync()); } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_First_GetAsyncEnumerator_Crashes() { var source = new FailingGetAsyncEnumerator<int>().Amb(AsyncEnumerableEx.Never<int>()); var xs = source.GetAsyncEnumerator(); try { await xs.MoveNextAsync(); Assert.Fail("Should not have gotten here"); } catch (InvalidOperationException) { // we expect this } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Second_GetAsyncEnumerator_Crashes() { var source = AsyncEnumerableEx.Never<int>().Amb(new FailingGetAsyncEnumerator<int>()); var xs = source.GetAsyncEnumerator(); try { await xs.MoveNextAsync(); Assert.Fail("Should not have gotten here"); } catch (InvalidOperationException) { // we expect this } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Many_First_GetAsyncEnumerator_Crashes() { var source = AsyncEnumerableEx.Amb( new FailingGetAsyncEnumerator<int>(), AsyncEnumerableEx.Never<int>(), AsyncEnumerableEx.Never<int>() ); var xs = source.GetAsyncEnumerator(); try { await xs.MoveNextAsync(); Assert.Fail("Should not have gotten here"); } catch (InvalidOperationException) { // we expect this } finally { await xs.DisposeAsync(); } } [Fact] public async Task Amb_Many_Last_GetAsyncEnumerator_Crashes() { var source = AsyncEnumerableEx.Amb( AsyncEnumerableEx.Never<int>(), AsyncEnumerableEx.Never<int>(), new FailingGetAsyncEnumerator<int>() ); var xs = source.GetAsyncEnumerator(); try { await xs.MoveNextAsync(); Assert.Fail("Should not have gotten here"); } catch (InvalidOperationException) { // we expect this } finally { await xs.DisposeAsync(); } }
Amb
csharp
dotnet__orleans
src/Orleans.Core/Utils/TypeConverterExtensions.cs
{ "start": 299, "end": 3939 }
internal static class ____ { private const char GenericTypeIndicator = '`'; private const char StartArgument = '['; /// <summary> /// Returns true if the provided type string is a generic type. /// </summary> public static bool IsGenericType(IdSpan type) => type.AsSpan().IndexOf((byte)GenericTypeIndicator) >= 0; /// <summary> /// Returns the generic arity of the specified grain type. /// </summary> public static int GetGenericTypeArity(IdSpan type) { var typeSpan = type.AsSpan(); var startIndex = typeSpan.IndexOf((byte)GenericTypeIndicator) + 1; if (startIndex <= 0 || startIndex >= typeSpan.Length) { return 0; } int endIndex; for (endIndex = startIndex; endIndex < typeSpan.Length; endIndex++) { var c = typeSpan[endIndex]; if (c is < ((byte)'0') or > ((byte)'9')) { break; } } if (endIndex > startIndex && Utf8Parser.TryParse(typeSpan[startIndex..endIndex], out int arity, out _)) { return arity; } throw new InvalidOperationException($"Unable to parse arity from type \"{type}\""); } /// <summary> /// Returns true if the provided type string is a constructed generic type. /// </summary> public static bool IsConstructed(IdSpan type) => type.AsSpan().IndexOf((byte)StartArgument) > 0; /// <summary> /// Returns the deconstructed form of the provided generic type. /// </summary> public static IdSpan GetDeconstructed(IdSpan type) { var span = type.AsSpan(); var index = span.IndexOf((byte)StartArgument); return index <= 0 ? type : new IdSpan(span[..index].ToArray()); } /// <summary> /// Returns the constructed form of the provided generic type. /// </summary> public static IdSpan GetConstructed(this TypeConverter formatter, IdSpan unconstructed, params Type[] typeArguments) { var typeString = unconstructed.AsSpan(); var indicatorIndex = typeString.IndexOf((byte)GenericTypeIndicator); var arityString = typeString[(indicatorIndex + 1)..]; if (indicatorIndex < 0 || arityString.IndexOf((byte)StartArgument) >= 0) { throw new InvalidOperationException("Cannot construct an already-constructed type"); } if (!Utf8Parser.TryParse(arityString, out int arity, out var len) || len < arityString.Length || typeArguments.Length != arity) { throw new InvalidOperationException($"Insufficient number of type arguments, {typeArguments.Length}, provided while constructing type \"{unconstructed}\""); } var typeSpecs = new TypeSpec[typeArguments.Length]; for (var i = 0; i < typeArguments.Length; i++) { typeSpecs[i] = RuntimeTypeNameParser.Parse(formatter.Format(typeArguments[i])); } var constructed = new ConstructedGenericTypeSpec(new NamedTypeSpec(null, unconstructed.ToString(), typeArguments.Length), typeArguments.Length, typeSpecs).Format(); return IdSpan.Create(constructed); } /// <summary> /// Returns the constructed form of the provided generic grain type using the type arguments from the provided constructed
TypeConverterExtensions
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Predicates/Expression.cs
{ "start": 233, "end": 4891 }
public class ____ { /// <summary>Constructs a new instance of <see cref="Expression"></see>.</summary> protected Expression() { } /// <summary> /// Apply an "equal" constraint to the named property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value for the property.</param> public static SimpleExpression Equal(string propertyName, object value) { return new SimpleExpression(propertyName, value, " = "); } /// <summary> /// Apply a "like" constraint to the named property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value for the property.</param> /// <param name="matchOptions">The match options for the like expression.</param> /// <returns>A <see cref="LikeExpression" />.</returns> public static IPredicate Like(string propertyName, string value, MatchOptions matchOptions) { return new LikeExpression(propertyName, value, matchOptions); } /// <summary> /// Apply a "greater than" constraint to the named property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value for the property.</param> public static SimpleExpression GreaterThan(string propertyName, object value) { return new SimpleExpression(propertyName, value, " > "); } /// <summary> /// Apply a "greater than or equal" constraint to the named property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value for the property.</param> public static SimpleExpression GreaterThanOrEqual(string propertyName, object value) { return new SimpleExpression(propertyName, value, " >= "); } /// <summary> /// Apply a "less than" constraint to the named property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value for the property.</param> public static SimpleExpression LessThan(string propertyName, object value) { return new SimpleExpression(propertyName, value, " < "); } /// <summary> /// Apply a "less than or equal" constraint to the named property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="value">The value for the property.</param> public static SimpleExpression LessThanOrEqual(string propertyName, object value) { return new SimpleExpression(propertyName, value, " <= "); } /// <summary> /// Apply an "in" constraint to the named property. /// </summary> /// <param name="propertyName">The name of the property.</param> /// <param name="values">An array of values.</param> /// <returns>An <see cref="InExpression" />.</returns> public static IPredicate In(string propertyName, object[] values) { return new InExpression(propertyName, values); } /// <summary> /// Return the conjunction of two expressions. /// </summary> /// <param name="left">The left hand side expression.</param> /// <param name="right">The right hand side expression.</param> /// <returns>An <see cref="AndExpression" />.</returns> public static IPredicate And(IPredicate left, IPredicate right) { return new AndExpression(left, right); } /// <summary> /// Return the disjunction of two expressions. /// </summary> /// <param name="left">The left hand side expression.</param> /// <param name="right">The right hand side expression.</param> /// <returns>An <see cref="OrExpression" />.</returns> public static IPredicate Or(IPredicate left, IPredicate right) { return new OrExpression(left, right); } /// <summary> /// Return the negation of an expression. /// </summary> /// <param name="expression">The expression to negate.</param> /// <returns>A <see cref="NotExpression" />.</returns> public static IPredicate Not(IPredicate expression) { return new NotExpression(expression); } /// <summary> /// Group expressions together in a single conjunction (A and B and C...) /// </summary> public static Conjunction Conjunction() { return new Conjunction(); } /// <summary> /// Group expressions together in a single disjunction (A or B or C...) /// </summary> public static Disjunction Disjunction() { return new Disjunction(); } }
Expression
csharp
microsoft__semantic-kernel
dotnet/src/InternalUtilities/src/Http/HttpClientProvider.cs
{ "start": 1871, "end": 4226 }
private sealed class ____ : DelegatingHandler { /// <summary> /// Private constructor to prevent direct instantiation of the class. /// </summary> private NonDisposableHttpClientHandler() : base(CreateHandler()) { } /// <summary> /// Gets the singleton instance of <see cref="NonDisposableHttpClientHandler"/>. /// </summary> public static NonDisposableHttpClientHandler Instance { get; } = new(); /// <summary> /// Disposes the underlying resources held by the <see cref="NonDisposableHttpClientHandler"/>. /// This implementation does nothing to prevent unintended disposal, as it may affect all references. /// </summary> /// <param name="disposing">True if called from <see cref="Dispose"/>, false if called from a finalizer.</param> protected override void Dispose(bool disposing) { // Do nothing if called explicitly from Dispose, as it may unintentionally affect all references. // The base.Dispose(disposing) is not called to avoid invoking the disposal of HttpClientHandler resources. // This implementation assumes that the HttpMessageHandler is being used as a singleton and should not be disposed directly. } #if NET private static SocketsHttpHandler CreateHandler() { return new SocketsHttpHandler() { // Limit the lifetime of connections to better respect any DNS changes PooledConnectionLifetime = TimeSpan.FromMinutes(2), // Check cert revocation SslOptions = new SslClientAuthenticationOptions() { CertificateRevocationCheckMode = X509RevocationMode.Online, }, }; } #elif NETSTANDARD2_0 private static HttpClientHandler CreateHandler() { var handler = new HttpClientHandler(); try { handler.CheckCertificateRevocationList = true; } catch (PlatformNotSupportedException) { } // not supported on older frameworks return handler; } #elif NET462 private static HttpClientHandler CreateHandler() => new(); #endif } }
NonDisposableHttpClientHandler
csharp
cake-build__cake
src/Cake.Common.Tests/Unit/Build/AzurePipelines/Data/AzurePipelinesAgentInfoTests.cs
{ "start": 4716, "end": 5564 }
public sealed class ____ { [Fact] public void Should_Return_True_On_Hosted_Agent() { // Given var info = new AzurePipelinesInfoFixture().CreateHostedAgentInfo(); // When var result = info.IsHosted; // Then Assert.True(result); } [Fact] public void Should_Return_False_On_Other_Agent() { // Given var info = new AzurePipelinesInfoFixture().CreateAgentInfo(); // When var result = info.IsHosted; // Then Assert.False(result); } } } }
TheIsHostedProperty
csharp
xunit__xunit
src/xunit.v1.tests/xunit/Sdk/Commands/TestCommands/ExceptionAndOutputCaptureCommandTests.cs
{ "start": 978, "end": 1429 }
class ____ : ITestCommand { public string DisplayName { get { return null; } } public bool ShouldCreateInstance { get { return true; } } public int Timeout { get { return 0; } } public MethodResult Execute(object testClass) { throw new TargetInvocationException(new Exception()); } public XmlNode ToStartXml() { return null; } } }
ExceptionThrowingCommand
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 350422, "end": 350903 }
public partial interface ____ { public global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateClientCommandMutation_CreateClient_Client? Client { get; } public global::System.Collections.Generic.IReadOnlyList<global::ChilliCream.Nitro.CommandLine.Cloud.Client.ICreateClientCommandMutation_CreateClient_Errors>? Errors { get; } } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
ICreateClientCommandMutation_CreateClient
csharp
dotnet__orleans
src/api/Orleans.EventSourcing/Orleans.EventSourcing.cs
{ "start": 39995, "end": 40834 }
partial class ____ : global::Orleans.Serialization.Cloning.IDeepCopier<global::Orleans.EventSourcing.Common.BatchedNotificationMessage>, global::Orleans.Serialization.Cloning.IDeepCopier { public Copier_BatchedNotificationMessage(global::Orleans.Serialization.Serializers.ICodecProvider codecProvider) { } public global::Orleans.EventSourcing.Common.BatchedNotificationMessage DeepCopy(global::Orleans.EventSourcing.Common.BatchedNotificationMessage original, global::Orleans.Serialization.Cloning.CopyContext context) { throw null; } } [System.CodeDom.Compiler.GeneratedCode("OrleansCodeGen", "9.0.0.0")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] [System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage] public sealed
Copier_BatchedNotificationMessage
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack/FluentValidation/IValidationContext.cs
{ "start": 552, "end": 1273 }
public partial interface ____ : ICommonContext { /// <summary> /// Additional data associated with the validation request. /// </summary> IDictionary<string, object> RootContextData { get; } /// <summary> /// Property chain /// </summary> PropertyChain PropertyChain { get; } /// <summary> /// Selector /// </summary> IValidatorSelector Selector { get; } /// <summary> /// Whether this is a child context /// </summary> bool IsChildContext { get; } /// <summary> /// Whether this is a child collection context. /// </summary> bool IsChildCollectionContext { get; } } /// <summary> /// Validation context /// </summary> /// <typeparam name="T"></typeparam>
IValidationContext
csharp
ServiceStack__ServiceStack
ServiceStack.Text/src/ServiceStack.Text/TypeSerializer.Generic.cs
{ "start": 413, "end": 1626 }
public class ____<T> : ITypeSerializer<T> { public bool CanCreateFromString(Type type) { return JsvReader.GetParseFn(type) != null; } /// <summary> /// Parses the specified value. /// </summary> /// <param name="value">The value.</param> /// <returns></returns> public T DeserializeFromString(string value) { if (string.IsNullOrEmpty(value)) return default(T); return (T)JsvReader<T>.Parse(value); } public T DeserializeFromReader(TextReader reader) { return DeserializeFromString(reader.ReadToEnd()); } public string SerializeToString(T value) { if (value == null) return null; if (typeof(T) == typeof(string)) return value as string; var writer = StringWriterThreadStatic.Allocate(); JsvWriter<T>.WriteObject(writer, value); return StringWriterThreadStatic.ReturnAndFree(writer); } public void SerializeToWriter(T value, TextWriter writer) { if (value == null) return; if (typeof(T) == typeof(string)) { writer.Write(value); return; } JsvWriter<T>.WriteObject(writer, value); } }
TypeSerializer
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/test/HttpStatusCodeResultTests.cs
{ "start": 470, "end": 1942 }
public class ____ { [Fact] public void HttpStatusCodeResult_ExecuteResultSetsResponseStatusCode() { // Arrange var result = new StatusCodeResult(StatusCodes.Status404NotFound); var httpContext = GetHttpContext(); var routeData = new RouteData(); var actionDescriptor = new ActionDescriptor(); var context = new ActionContext(httpContext, routeData, actionDescriptor); // Act result.ExecuteResult(context); // Assert Assert.Equal(StatusCodes.Status404NotFound, httpContext.Response.StatusCode); } [Fact] public void HttpStatusCodeResult_ReturnsCorrectStatusCodeAsIStatusCodeActionResult() { // Arrange var result = new StatusCodeResult(StatusCodes.Status404NotFound); // Act var statusResult = result as IStatusCodeActionResult; // Assert Assert.Equal(StatusCodes.Status404NotFound, statusResult?.StatusCode); } private static IServiceCollection CreateServices() { var services = new ServiceCollection(); services.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance); return services; } private static HttpContext GetHttpContext() { var services = CreateServices(); var httpContext = new DefaultHttpContext(); httpContext.RequestServices = services.BuildServiceProvider(); return httpContext; } }
HttpStatusCodeResultTests
csharp
unoplatform__uno
src/Uno.UI.Tests/Windows_UI_Xaml/Controls/SomeNotImplType.cs
{ "start": 191, "end": 451 }
public class ____ { public static int CreationAttempts { get; private set; } [Uno.NotImplemented] public SomeNotImplType() { CreationAttempts++; throw new NotImplementedException(); } public double SomeProperty { get; set; } } }
SomeNotImplType
csharp
dotnetcore__Util
src/Util.Data.Sql/Builders/Clauses/IGroupByClause.cs
{ "start": 89, "end": 1216 }
public interface ____ : ISqlClause { /// <summary> /// 添加分组列 /// </summary> /// <param name="columns">分组字段</param> void GroupBy( string columns ); /// <summary> /// 添加分组条件 /// </summary> /// <param name="expression">聚合表达式</param> /// <param name="value">值</param> /// <param name="operator">运算符</param> /// <param name="isParameterization">是否参数化</param> void Having( string expression, object value, Operator @operator = Operator.Equal,bool isParameterization = true ); /// <summary> /// 添加到Group By子句 /// </summary> /// <param name="sql">Sql语句</param> /// <param name="raw">是否原样添加</param> void AppendGroupBy( string sql, bool raw ); /// <summary> /// 添加到Having子句 /// </summary> /// <param name="sql">Sql语句</param> /// <param name="raw">是否原样添加</param> void AppendHaving( string sql, bool raw ); /// <summary> /// 清理 /// </summary> void Clear(); /// <summary> /// 复制Group By子句 /// </summary> /// <param name="builder">Sql生成器</param> IGroupByClause Clone( SqlBuilderBase builder ); }
IGroupByClause
csharp
FastEndpoints__FastEndpoints
Web/[Features]/TestCases/Binding/FormBindingComplexDtos/Endpoint.cs
{ "start": 46, "end": 122 }
sealed class ____ { [FromForm] public Book Book { get; set; } }
Request
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Controls.UnitTests/Mixins/SelectableMixinTests.cs
{ "start": 1336, "end": 1893 }
private class ____ : Control, ISelectable { public static readonly StyledProperty<bool> IsSelectedProperty = AvaloniaProperty.Register<TestControl, bool>(nameof(IsSelected)); static TestControl() { SelectableMixin.Attach<TestControl>(IsSelectedProperty); } public bool IsSelected { get { return GetValue(IsSelectedProperty); } set { SetValue(IsSelectedProperty, value); } } } } }
TestControl
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Domain/Entities/Auditing/IHasDeletionTime.cs
{ "start": 297, "end": 490 }
public interface ____ : ISoftDelete { /// <summary> /// Deletion time of this entity. /// </summary> DateTime? DeletionTime { get; set; } } }
IHasDeletionTime
csharp
abpframework__abp
framework/test/Volo.Abp.BlobStoring.Bunny.Tests/Volo/Abp/BlobStoring/Bunny/AbpBlobStoringBunnyTestBase.cs
{ "start": 316, "end": 554 }
public class ____ : AbpIntegratedTest<AbpBlobStoringBunnyTestModule> { protected override void SetAbpApplicationCreationOptions(AbpApplicationCreationOptions options) { options.UseAutofac(); } }
AbpBlobStoringBunnyTestBase
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Bugzilla/Bugzilla41153.cs
{ "start": 584, "end": 2215 }
class ____ : INotifyPropertyChanged { string _toolBarItemText; public string ToolbarItemText { get { return _toolBarItemText; } set { _toolBarItemText = value; OnPropertyChanged(); } } ICommand _toolBarItemCommand; public ICommand ToolbarItemCommand { get { if (_toolBarItemCommand == null) { _toolBarItemCommand = new Command(() => { ToolbarItemText = Success; }); } return _toolBarItemCommand; } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } protected override void Init() { var page1 = new ContentPage { Content = new Label { Text = Tab1Content, AutomationId = Tab1Content }, BindingContext = _Vm }; var toolBarItem = new ToolbarItem() { AutomationId = ToolbarItemText }; toolBarItem.SetBinding(ToolbarItem.CommandProperty, nameof(MyViewModel.ToolbarItemCommand)); toolBarItem.SetBinding(ToolbarItem.TextProperty, nameof(MyViewModel.ToolbarItemText)); page1.ToolbarItems.Add(toolBarItem); var page2 = new ContentPage(); var page3 = new ContentPage { Content = new Label { Text = Tab3Content, AutomationId = Tab3Content } }; Children.Add(new NavigationPage(page1) { Title = Tab1, AutomationId = Tab1 }); Children.Add(new NavigationPage(page2) { Title = Tab2, AutomationId = Tab2 }); Children.Add(new NavigationPage(page3) { Title = Tab3, AutomationId = Tab3 }); _Vm.ToolbarItemText = ToolbarItemText; } }
MyViewModel
csharp
neuecc__MessagePack-CSharp
tests/MessagePack.SourceGenerator.ExecutionTests/HasRequiredMembers.cs
{ "start": 187, "end": 410 }
public record ____ { [Key(0)] public int A { get; set; } [Key(1)] public required int? B { get; set; } [Key(2)] public required int? C; [Key(3)] public int D { get; set; } }
HasRequiredMembers
csharp
louthy__language-ext
LanguageExt.Core/Prelude/Hash code functions/Prelude.Hash.cs
{ "start": 948, "end": 4159 }
class ____ for a map // /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<A>(Arr<A> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<K, V>(HashMap<K, V> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<EqK, K, V>(HashMap<EqK, K, V> xs) where EqK : Eq<K> => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<A>(HashSet<A> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<EqA, A>(HashSet<EqA, A> xs) where EqA : Eq<A> => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<A>(Lst<A> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<K, V>(Map<K, V> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<OrdK, K, V>(Map<OrdK, K, V> xs) where OrdK : Ord<K> => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<A>(Que<A> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<A>(Seq<A> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<A>(Set<A> xs) => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<OrdA, A>(Set<OrdA, A> xs) where OrdA : Ord<A> => xs.GetHashCode(); /// <summary> /// Calculate a hash-code for the collection provided /// </summary> [Pure] [MethodImpl(MethodImplOptions.AggressiveInlining)] public static int hash<A>(Stck<A> xs) => xs.GetHashCode(); }
function
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/MessageData/DataBus_Specs.cs
{ "start": 4369, "end": 7771 }
public class ____ : InMemoryTestFixture { [Test] public async Task Should_be_able_to_write_bytes_too() { var data = new byte[10000]; var message = new MessageWithByteArrayImpl { Bytes = await _repository.PutBytes(data) }; await InputQueueSendEndpoint.Send(message); await _receivedBytes; Assert.That(_receivedBytesArray, Is.EqualTo(data)); } [Test] public async Task Should_be_able_to_write_stream_too() { var data = new byte[10000]; using MemoryStream ms = new MemoryStream(data); var message = new MessageWithStreamImpl { Stream = await _repository.PutStream(ms) }; await InputQueueSendEndpoint.Send(message); await _receivedStream; using MemoryStream receivedMemoryStream = new MemoryStream(); await _receivedStreamData.CopyToAsync(receivedMemoryStream); Assert.That(receivedMemoryStream.ToArray(), Is.EqualTo(data)); } [Test] public async Task Should_load_the_data_from_the_repository() { var data = new string('*', 10000); var message = new SendMessageWithBigData { Body = await _repository.PutString(data) }; await InputQueueSendEndpoint.Send(message); await _received; Assert.That(_receivedBody, Is.EqualTo(data)); } IMessageDataRepository _repository; #pragma warning disable NUnit1032 Task<ConsumeContext<MessageWithBigData>> _received; Task<ConsumeContext<MessageWithByteArray>> _receivedBytes; Task<ConsumeContext<MessageWithStream>> _receivedStream; #pragma warning restore NUnit1032 string _receivedBody; byte[] _receivedBytesArray; Stream _receivedStreamData; protected override void ConfigureInMemoryBus(IInMemoryBusFactoryConfigurator configurator) { var baseDirectory = AppDomain.CurrentDomain.BaseDirectory; var messageDataPath = Path.Combine(baseDirectory, "MessageData"); var dataDirectory = new DirectoryInfo(messageDataPath); _repository = new FileSystemMessageDataRepository(dataDirectory); configurator.UseMessageData(_repository); } protected override void ConfigureInMemoryReceiveEndpoint(IInMemoryReceiveEndpointConfigurator configurator) { _received = Handler<MessageWithBigData>(configurator, async context => { _receivedBody = await context.Message.Body.Value; }); _receivedBytes = Handler<MessageWithByteArray>(configurator, async context => { _receivedBytesArray = await context.Message.Bytes.Value; }); _receivedStream = Handler<MessageWithStream>(configurator, async context => { _receivedStreamData = await context.Message.Stream.Value; }); } } [TestFixture]
Sending_a_large_message_through_the_file_system
csharp
microsoft__PowerToys
src/modules/MouseWithoutBorders/App/Class/Common.ShutdownWithPowerToys.cs
{ "start": 377, "end": 872 }
internal class ____ { public static void WaitForPowerToysRunner(ETWTrace etwTrace) { try { RunnerHelper.WaitForPowerToysRunnerExitFallback(() => { etwTrace?.Dispose(); Common.MainForm.Quit(true, false); }); } catch (Exception e) { Logger.Log(e); } } } }
ShutdownWithPowerToys
csharp
open-telemetry__opentelemetry-dotnet
src/OpenTelemetry/ReadOnlyTagCollection.cs
{ "start": 379, "end": 1335 }
struct ____ #pragma warning restore CA1711 // Identifiers should not have incorrect suffix { internal readonly KeyValuePair<string, object?>[] KeyAndValues; internal ReadOnlyTagCollection(KeyValuePair<string, object?>[]? keyAndValues) { this.KeyAndValues = keyAndValues ?? []; } /// <summary> /// Gets the number of tags in the collection. /// </summary> public int Count => this.KeyAndValues.Length; /// <summary> /// Returns an enumerator that iterates through the tags. /// </summary> /// <returns><see cref="Enumerator"/>.</returns> public Enumerator GetEnumerator() => new(this); /// <summary> /// Enumerates the elements of a <see cref="ReadOnlyTagCollection"/>. /// </summary> // Note: Does not implement IEnumerator<> to prevent accidental boxing. #pragma warning disable CA1034 // Nested types should not be visible - already part of public API
ReadOnlyTagCollection
csharp
dotnet__efcore
test/EFCore.Tests/Extensions/TypeExtensionsTest.cs
{ "start": 28779, "end": 28831 }
private static class ____<T1> {
OuterGeneric
csharp
dotnetcore__Util
test/Util.Localization.Tests/Samples/TestType.cs
{ "start": 84, "end": 175 }
public class ____ { } /// <summary> /// 测试类型2 /// </summary> [LocalizedType("test2")]
TestType
csharp
aspnetboilerplate__aspnetboilerplate
test/aspnet-core-demo/AbpAspNetCoreDemo/Controllers/DateTimeFormatController.cs
{ "start": 364, "end": 462 }
public class ____ : EntityDto { public DateTime TestDate { get; set; } } }
TestInputDto
csharp
bitwarden__server
src/Core/Settings/GlobalSettings.cs
{ "start": 25773, "end": 26195 }
public class ____ { /// <summary> /// List of Notification Hub settings to use for sending push notifications. /// /// Note that hubs on the same namespace share active device limits, so multiple namespaces should be used to increase capacity. /// </summary> public List<NotificationHubSettings> NotificationHubs { get; set; } = new(); }
NotificationHubPoolSettings
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/test/ApplicationModels/ControllerActionDescriptorProviderTests.cs
{ "start": 63893, "end": 64341 }
public class ____ { [HttpGet("list")] public void ControllerAndAction() { } [HttpGet("/PRODUCTS/LIST")] public void OverrideOnAction() { } [HttpGet("list")] [HttpPost("list")] [HttpPut("list")] [HttpPatch("list")] [HttpDelete("list")] public void DifferentHttpMethods() { } } [MyRouteValue] [MySecondRouteValue]
NonDuplicatedAttributeRouteController
csharp
dotnet__maui
src/Core/tests/DeviceTests/Handlers/Editor/EditorHandlerTests.cs
{ "start": 16131, "end": 16261 }
public class ____ : TextStyleHandlerTests<EditorHandler, EditorStub> { } [Category(TestCategory.Editor)]
EditorTextStyleTests
csharp
smartstore__Smartstore
src/Smartstore/Pdf/WkHtml/WkHtmlToPdfException.cs
{ "start": 39, "end": 307 }
public sealed class ____ : Exception { public WkHtmlToPdfException(int errCode, string message) : base($"{message} (exit code: {errCode})") { ErrorCode = errCode; } public int ErrorCode { get; } } }
WkHtmlToPdfException
csharp
MassTransit__MassTransit
src/MassTransit/JsonMessageBody.cs
{ "start": 207, "end": 308 }
public interface ____ { JsonElement? GetJsonElement(JsonSerializerOptions options); }
JsonMessageBody
csharp
dotnet__orleans
src/api/AWS/Orleans.Reminders.DynamoDB/Orleans.Reminders.DynamoDB.cs
{ "start": 1712, "end": 1999 }
partial class ____ { public static ISiloBuilder UseDynamoDBReminderService(this ISiloBuilder builder, System.Action<Configuration.DynamoDBReminderStorageOptions> configure) { throw null; } } } namespace Orleans.Reminders.DynamoDB {
DynamoDBSiloBuilderReminderExtensions
csharp
Cysharp__ZLogger
tests/ZLogger.Generator.Tests/GenerateTest.cs
{ "start": 6000, "end": 6167 }
public struct ____ { public int X { get; set; } public int Y { get; set; } public int Z { get; set; } } // not supported. //
MyVec3
csharp
unoplatform__uno
src/Uno.UI.Composition/Generated/3.0.0.0/Microsoft.UI.Composition/Vector3KeyFrameAnimation.cs
{ "start": 259, "end": 688 }
public partial class ____ : global::Microsoft.UI.Composition.KeyFrameAnimation { // Skipping already declared method Microsoft.UI.Composition.Vector3KeyFrameAnimation.InsertKeyFrame(float, System.Numerics.Vector3, Microsoft.UI.Composition.CompositionEasingFunction) // Skipping already declared method Microsoft.UI.Composition.Vector3KeyFrameAnimation.InsertKeyFrame(float, System.Numerics.Vector3) } }
Vector3KeyFrameAnimation
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/ContentControl/ContentControl.reference.cs
{ "start": 168, "end": 452 }
public partial class ____ { internal void SetUpdateControlTemplate() { } private bool HasParent() => true; partial void RegisterContentTemplateRoot() { } protected override Size MeasureOverride(Size availableSize) => base.MeasureOverride(availableSize); } }
ContentControl
csharp
dotnet__maui
src/Controls/tests/TestCases.Shared.Tests/Tests/Issues/Bugzilla/Bugzilla31330.cs
{ "start": 336, "end": 943 }
public class ____ : _IssuesUITest { public Bugzilla31330(TestDevice testDevice) : base(testDevice) { } public override string Issue => "Disabled context actions appear enabled"; [Test] [Category(UITestCategories.ListView)] public void Bugzilla31330Test() { App.WaitForElement("Something 2"); App.ActivateContextMenu("Something 1"); App.WaitForElement("Delete"); App.Tap("Delete"); App.DismissContextMenu(); App.Tap("Something 2"); App.ActivateContextMenu("Something 2"); App.WaitForElement("Delete"); App.Tap("Delete"); App.WaitForNoElement("Something 2"); } } #endif
Bugzilla31330
csharp
microsoft__FASTER
cs/playground/CacheStoreConcurrent/Types.cs
{ "start": 1100, "end": 1440 }
public class ____ : BinaryObjectSerializer<CacheValue> { public override void Deserialize(out CacheValue obj) { obj = new CacheValue(reader.ReadInt64()); } public override void Serialize(ref CacheValue obj) { writer.Write(obj.value); } }
CacheValueSerializer
csharp
dotnet__orleans
src/Orleans.Transactions/OrleansTransactionException.cs
{ "start": 5819, "end": 7547 }
public sealed class ____ : OrleansTransactionTransientFailureException { [Id(0)] public string DependentTransactionId { get; private set; } public OrleansCascadingAbortException(string transactionId, string dependentId) : base(transactionId, string.Format("Transaction {0} aborted because its dependent transaction {1} aborted", transactionId, dependentId)) { this.DependentTransactionId = dependentId; } public OrleansCascadingAbortException(string transactionId) : base(transactionId, string.Format("Transaction {0} aborted because a dependent transaction aborted", transactionId)) { } public OrleansCascadingAbortException(string transactionId, Exception innerException) : base(transactionId, string.Format("Transaction {0} aborted because a dependent transaction aborted", transactionId), innerException) { } [Obsolete] private OrleansCascadingAbortException(SerializationInfo info, StreamingContext context) : base(info, context) { this.DependentTransactionId = info.GetString(nameof(this.DependentTransactionId)); } [Obsolete] public override void GetObjectData(SerializationInfo info, StreamingContext context) { base.GetObjectData(info, context); info.AddValue(nameof(this.DependentTransactionId), this.DependentTransactionId); } } /// <summary> /// Signifies that the executing transaction has aborted because a method did not await all its pending calls. /// </summary> [Serializable] [GenerateSerializer]
OrleansCascadingAbortException
csharp
cake-build__cake
src/Cake.Common.Tests/Unit/Build/WoodpeckerCI/Data/WoodpeckerCIPipelineInfoTests.cs
{ "start": 3294, "end": 4279 }
public sealed class ____ { [Fact] public void Should_Return_Correct_Uri_For_Valid_Url() { // Given var info = new WoodpeckerCIInfoFixture().CreatePipelineInfo(); // When var result = info.Url; // Then Assert.NotNull(result); Assert.Equal("https://ci.example.com/repos/john-doe/my-repo/pipeline/123", result.ToString()); } [Fact] public void Should_Return_Null_For_Invalid_Url() { // Given var fixture = new WoodpeckerCIInfoFixture(); fixture.SetEnvironmentVariable("CI_PIPELINE_URL", "not-a-valid-url"); var info = fixture.CreatePipelineInfo(); // When var result = info.Url; // Then Assert.Null(result); } }
TheUrlProperty
csharp
dotnet__machinelearning
test/Microsoft.ML.Tests/PermutationFeatureImportanceTests.cs
{ "start": 604, "end": 51320 }
public class ____ : BaseTestPredictors { public PermutationFeatureImportanceTests(ITestOutputHelper output) : base(output) { } #region Regression Tests /// <summary> /// Test PFI Regression for Dense Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiRegressionOnDenseFeatures(bool saveModel) { var data = GetDenseDataset(); var model = ML.Regression.Trainers.OnlineGradientDescent().Fit(data); ImmutableArray<RegressionMetricsStatistics> pfi; ImmutableDictionary<string, RegressionMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiRegressionOnDenseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as RegressionPredictionTransformer<LinearRegressionModelParameters>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Regression.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.Regression.PermutationFeatureImportance(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Regression.PermutationFeatureImportance(model, data); pfiDict = ml2.Regression.PermutationFeatureImportance((ITransformer)model, data); } // Pfi Indices: // X1: 0 // X2Important: 1 // X3: 2 // X4Rand: 3 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["X2Important"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["X3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["X4Rand"])); // For the following metrics lower is better, so maximum delta means more important feature, and vice versa Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanAbsoluteError.Mean)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanAbsoluteError.Mean)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanSquaredError.Mean)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanSquaredError.Mean)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.RootMeanSquaredError.Mean)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RootMeanSquaredError.Mean)); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(1, MinDeltaIndex(pfi, m => m.RSquared.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.RSquared.Mean)); Done(); } /// <summary> /// Test PFI Regression for Dense Features in a transformer chain /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiRegressionOnDenseFeaturesInTransformerChain(bool saveModel) { var data = GetDenseDataset(); var model = ML.Transforms.CopyColumns("Label", "Label").Append(ML.Regression.Trainers.OnlineGradientDescent()).Fit(data); ImmutableArray<RegressionMetricsStatistics> pfi; ImmutableDictionary<string, RegressionMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiRegressionOnDenseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); ITransformer lastTransformer = null; if (loadedModel is ITransformerChainAccessor chain) { lastTransformer = chain.Transformers.Last(); } var castedModel = lastTransformer as RegressionPredictionTransformer<LinearRegressionModelParameters>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Regression.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.Regression.PermutationFeatureImportance(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Regression.PermutationFeatureImportance(model.LastTransformer, data); pfiDict = ml2.Regression.PermutationFeatureImportance(model, data); } // Pfi Indices: // X1: 0 // X2Important: 1 // X3: 2 // X4Rand: 3 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["X2Important"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["X3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["X4Rand"])); // For the following metrics lower is better, so maximum delta means more important feature, and vice versa Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanAbsoluteError.Mean)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanAbsoluteError.Mean)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanSquaredError.Mean)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanSquaredError.Mean)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.RootMeanSquaredError.Mean)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RootMeanSquaredError.Mean)); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(1, MinDeltaIndex(pfi, m => m.RSquared.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.RSquared.Mean)); Done(); } /// <summary> /// Test PFI Regression Standard Deviation and Standard Error for Dense Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiRegressionStandardDeviationAndErrorOnDenseFeatures(bool saveModel) { var data = GetDenseDataset(); var model = ML.Regression.Trainers.OnlineGradientDescent().Fit(data); ImmutableArray<RegressionMetricsStatistics> pfi; ImmutableDictionary<string, RegressionMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiRegressionStandardDeviationAndErrorOnDenseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as RegressionPredictionTransformer<LinearRegressionModelParameters>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Regression.PermutationFeatureImportance(castedModel, data, permutationCount: 20); pfiDict = ml2.Regression.PermutationFeatureImportance(loadedModel, data, permutationCount: 20); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Regression.PermutationFeatureImportance(model, data, permutationCount: 20); pfiDict = ml2.Regression.PermutationFeatureImportance((ITransformer)model, data, permutationCount: 20); } // Keep the permutation count high so fluctuations are kept to a minimum // but not high enough to slow down the tests // (fluctuations lead to random test failures) // Pfi Indices: // X1: 0 // X2Important: 1 // X3: 2 // X4Rand: 3 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["X2Important"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["X3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["X4Rand"])); // For these metrics, the magnitude of the difference will be greatest for 1, least for 3 // Stardard Deviation will scale with the magnitude of the measure Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardDeviation)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardDeviation)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanSquaredError.StandardDeviation)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanSquaredError.StandardDeviation)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardDeviation)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardDeviation)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.RSquared.StandardDeviation)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RSquared.StandardDeviation)); // Stardard Error will scale with the magnitude of the measure (as it's SD/sqrt(N)) Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardError)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanAbsoluteError.StandardError)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.MeanSquaredError.StandardError)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.MeanSquaredError.StandardError)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardError)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RootMeanSquaredError.StandardError)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.RSquared.StandardError)); Assert.Equal(1, MaxDeltaIndex(pfi, m => m.RSquared.StandardError)); // And test that the Standard Deviation and Standard Error are related as we expect Assert.Equal(pfi[0].RootMeanSquaredError.StandardError, pfi[0].RootMeanSquaredError.StandardDeviation / Math.Sqrt(pfi[0].RootMeanSquaredError.Count)); Done(); } /// <summary> /// Test PFI Regression for Sparse Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiRegressionOnSparseFeatures(bool saveModel) { var data = GetSparseDataset(); var model = ML.Regression.Trainers.OnlineGradientDescent().Fit(data); ImmutableArray<RegressionMetricsStatistics> results; ImmutableDictionary<string, RegressionMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiRegressionOnSparseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as RegressionPredictionTransformer<LinearRegressionModelParameters>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); results = ML.Regression.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.Regression.PermutationFeatureImportance(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); results = ML.Regression.PermutationFeatureImportance(model, data); pfiDict = ml2.Regression.PermutationFeatureImportance((ITransformer)model, data); } // Pfi Indices: // X1: 0 // X2VBuffer-Slot-0: 1 // X2VBuffer-Slot-1: 2 // X2VBuffer-Slot-2: 3 // X2VBuffer-Slot-3: 4 // X3Important: 5 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(results[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(results[1]), JsonConvert.SerializeObject(pfiDict["Slot 1"])); Assert.Equal(JsonConvert.SerializeObject(results[2]), JsonConvert.SerializeObject(pfiDict["Slot 2"])); Assert.Equal(JsonConvert.SerializeObject(results[3]), JsonConvert.SerializeObject(pfiDict["Slot 3"])); Assert.Equal(JsonConvert.SerializeObject(results[4]), JsonConvert.SerializeObject(pfiDict["Slot 4"])); Assert.Equal(JsonConvert.SerializeObject(results[5]), JsonConvert.SerializeObject(pfiDict["X3Important"])); // Permuted X2VBuffer-Slot-1 lot (f2) should have min impact on SGD metrics, X3Important -- max impact. // For the following metrics lower is better, so maximum delta means more important feature, and vice versa Assert.Equal(2, MinDeltaIndex(results, m => m.MeanAbsoluteError.Mean)); Assert.Equal(5, MaxDeltaIndex(results, m => m.MeanAbsoluteError.Mean)); Assert.Equal(2, MinDeltaIndex(results, m => m.MeanSquaredError.Mean)); Assert.Equal(5, MaxDeltaIndex(results, m => m.MeanSquaredError.Mean)); Assert.Equal(2, MinDeltaIndex(results, m => m.RootMeanSquaredError.Mean)); Assert.Equal(5, MaxDeltaIndex(results, m => m.RootMeanSquaredError.Mean)); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(2, MaxDeltaIndex(results, m => m.RSquared.Mean)); Assert.Equal(5, MinDeltaIndex(results, m => m.RSquared.Mean)); } #endregion #region Binary Classification Tests /// <summary> /// Test PFI Binary Classification for Dense Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiBinaryClassificationOnDenseFeatures(bool saveModel) { var data = GetDenseDataset(TaskType.BinaryClassification); var model = ML.BinaryClassification.Trainers.LbfgsLogisticRegression( new LbfgsLogisticRegressionBinaryTrainer.Options { NumberOfThreads = 1 }).Fit(data); ImmutableArray<BinaryClassificationMetricsStatistics> pfi; ImmutableDictionary<string, BinaryClassificationMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiBinaryClassificationOnDenseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as BinaryPredictionTransformer<CalibratedModelParametersBase<LinearBinaryModelParameters, PlattCalibrator>>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.BinaryClassification.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.BinaryClassification.PermutationFeatureImportanceNonCalibrated(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.BinaryClassification.PermutationFeatureImportance(model, data); pfiDict = ml2.BinaryClassification.PermutationFeatureImportanceNonCalibrated((ITransformer)model, data); } // Pfi Indices: // X1: 0 // X2Important: 1 // X3: 2 // X4Rand: 3 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["X2Important"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["X3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["X4Rand"])); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(3, MaxDeltaIndex(pfi, m => m.AreaUnderRocCurve.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.AreaUnderRocCurve.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.Accuracy.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.Accuracy.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.PositivePrecision.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.PositivePrecision.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.PositiveRecall.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.PositiveRecall.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.NegativePrecision.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.NegativePrecision.Mean)); Assert.Equal(0, MaxDeltaIndex(pfi, m => m.NegativeRecall.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.NegativeRecall.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.F1Score.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.F1Score.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.AreaUnderPrecisionRecallCurve.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.AreaUnderPrecisionRecallCurve.Mean)); Done(); } /// <summary> /// Test PFI Binary Classification for Sparse Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiBinaryClassificationOnSparseFeatures(bool saveModel) { var data = GetSparseDataset(TaskType.BinaryClassification); var model = ML.BinaryClassification.Trainers.LbfgsLogisticRegression( new LbfgsLogisticRegressionBinaryTrainer.Options { NumberOfThreads = 1 }).Fit(data); ImmutableArray<BinaryClassificationMetricsStatistics> pfi; ImmutableDictionary<string, BinaryClassificationMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiBinaryClassificationOnSparseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as BinaryPredictionTransformer<CalibratedModelParametersBase<LinearBinaryModelParameters, PlattCalibrator>>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.BinaryClassification.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.BinaryClassification.PermutationFeatureImportanceNonCalibrated(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.BinaryClassification.PermutationFeatureImportance(model, data); pfiDict = ml2.BinaryClassification.PermutationFeatureImportanceNonCalibrated((ITransformer)model, data); } // Pfi Indices: // X1: 0 // X2VBuffer-Slot-0: 1 // X2VBuffer-Slot-1: 2 // X2VBuffer-Slot-2: 3 // X2VBuffer-Slot-3: 4 // X3Important: 5 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["Slot 1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["Slot 2"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["Slot 3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[4]), JsonConvert.SerializeObject(pfiDict["Slot 4"])); Assert.Equal(JsonConvert.SerializeObject(pfi[5]), JsonConvert.SerializeObject(pfiDict["X3Important"])); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(2, MaxDeltaIndex(pfi, m => m.AreaUnderRocCurve.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.AreaUnderRocCurve.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.Accuracy.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.Accuracy.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.PositivePrecision.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.PositivePrecision.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.PositiveRecall.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.PositiveRecall.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.NegativePrecision.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.NegativePrecision.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.NegativeRecall.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.NegativeRecall.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.F1Score.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.F1Score.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.AreaUnderPrecisionRecallCurve.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.AreaUnderPrecisionRecallCurve.Mean)); Done(); } [Fact] public void TestBinaryClassificationWithoutCalibrator() { var dataPath = GetDataPath(TestDatasets.breastCancer.trainFilename); var ff = ML.BinaryClassification.Trainers.FastForest(); var data = ML.Data.LoadFromTextFile(dataPath, new[] { new TextLoader.Column("Label", DataKind.Boolean, 0), new TextLoader.Column("Features", DataKind.Single, 1, 9) }); var model = ff.Fit(data); var pfi = ML.BinaryClassification.PermutationFeatureImportance(model, data); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(7, MaxDeltaIndex(pfi, m => m.AreaUnderRocCurve.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.AreaUnderRocCurve.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.Accuracy.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.Accuracy.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.PositivePrecision.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.PositivePrecision.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.PositiveRecall.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.PositiveRecall.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.NegativePrecision.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.NegativePrecision.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.NegativeRecall.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.NegativeRecall.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.F1Score.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.F1Score.Mean)); Assert.Equal(7, MaxDeltaIndex(pfi, m => m.AreaUnderPrecisionRecallCurve.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.AreaUnderPrecisionRecallCurve.Mean)); } #endregion #region Multiclass Classification Tests /// <summary> /// Test PFI Multiclass Classification for Dense Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiMulticlassClassificationOnDenseFeatures(bool saveModel) { var data = GetDenseDataset(TaskType.MulticlassClassification); var model = ML.MulticlassClassification.Trainers.LbfgsMaximumEntropy().Fit(data); ImmutableArray<MulticlassClassificationMetricsStatistics> pfi; ImmutableDictionary<string, MulticlassClassificationMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiMulticlassClassificationOnDenseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as MulticlassPredictionTransformer<MaximumEntropyModelParameters>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.MulticlassClassification.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.MulticlassClassification.PermutationFeatureImportance(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.MulticlassClassification.PermutationFeatureImportance(model, data); pfiDict = ml2.MulticlassClassification.PermutationFeatureImportance((ITransformer)model, data); } // Pfi Indices: // X1: 0 // X2Important: 1 // X3: 2 // X4Rand: 3 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["X2Important"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["X3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["X4Rand"])); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(3, MaxDeltaIndex(pfi, m => m.MicroAccuracy.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.MicroAccuracy.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.MacroAccuracy.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.MacroAccuracy.Mean)); Assert.Equal(3, MaxDeltaIndex(pfi, m => m.LogLossReduction.Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.LogLossReduction.Mean)); // For the following metrics-delta lower is better, so maximum delta means more important feature, and vice versa // Because they are _negative_, the difference will be positive for worse classifiers. Assert.Equal(1, MaxDeltaIndex(pfi, m => m.LogLoss.Mean)); Assert.Equal(3, MinDeltaIndex(pfi, m => m.LogLoss.Mean)); for (int i = 0; i < pfi[0].PerClassLogLoss.Count; i++) { Assert.True(MaxDeltaIndex(pfi, m => m.PerClassLogLoss[i].Mean) == 1); Assert.True(MinDeltaIndex(pfi, m => m.PerClassLogLoss[i].Mean) == 3); } Done(); } /// <summary> /// Test PFI Multiclass Classification for Sparse Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiMulticlassClassificationOnSparseFeatures(bool saveModel) { var data = GetSparseDataset(TaskType.MulticlassClassification); var model = ML.MulticlassClassification.Trainers.LbfgsMaximumEntropy( new LbfgsMaximumEntropyMulticlassTrainer.Options { MaximumNumberOfIterations = 1000 }).Fit(data); ImmutableArray<MulticlassClassificationMetricsStatistics> pfi; ImmutableDictionary<string, MulticlassClassificationMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiMulticlassClassificationOnSparseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as MulticlassPredictionTransformer<MaximumEntropyModelParameters>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.MulticlassClassification.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.MulticlassClassification.PermutationFeatureImportance(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.MulticlassClassification.PermutationFeatureImportance(model, data); pfiDict = ml2.MulticlassClassification.PermutationFeatureImportance((ITransformer)model, data); } // Pfi Indices: // X1: 0 // X2VBuffer-Slot-0: 1 // X2VBuffer-Slot-1: 2 // Least important // X2VBuffer-Slot-2: 3 // X2VBuffer-Slot-3: 4 // X3Important: 5 // Most important // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["Slot 1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["Slot 2"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["Slot 3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[4]), JsonConvert.SerializeObject(pfiDict["Slot 4"])); Assert.Equal(JsonConvert.SerializeObject(pfi[5]), JsonConvert.SerializeObject(pfiDict["X3Important"])); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa Assert.Equal(2, MaxDeltaIndex(pfi, m => m.MicroAccuracy.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.MicroAccuracy.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.MacroAccuracy.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.MacroAccuracy.Mean)); Assert.Equal(2, MaxDeltaIndex(pfi, m => m.LogLossReduction.Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.LogLossReduction.Mean)); // For the following metrics-delta lower is better, so maximum delta means more important feature, and vice versa // Because they are negative metrics, the _difference_ will be positive for worse classifiers. Assert.Equal(5, MaxDeltaIndex(pfi, m => m.LogLoss.Mean)); Assert.Equal(2, MinDeltaIndex(pfi, m => m.LogLoss.Mean)); for (int i = 0; i < pfi[0].PerClassLogLoss.Count; i++) { Assert.Equal(5, MaxDeltaIndex(pfi, m => m.PerClassLogLoss[i].Mean)); Assert.Equal(2, MinDeltaIndex(pfi, m => m.PerClassLogLoss[i].Mean)); } Done(); } #endregion #region Ranking Tests /// <summary> /// Test PFI Ranking Classification for Dense Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiRankingOnDenseFeatures(bool saveModel) { var data = GetDenseDataset(TaskType.Ranking); var model = ML.Ranking.Trainers.FastTree().Fit(data); ImmutableArray<RankingMetricsStatistics> pfi; ImmutableDictionary<string, RankingMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiRankingOnDenseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as RankingPredictionTransformer<FastTreeRankingModelParameters>; // Saving and Loading the model cause the internal random state to change, so we reset the seed // here and create another seed for both PFI to match to help the tests pass. ML = new MLContext(0); var ml2 = new MLContext(0); pfi = ML.Ranking.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.Ranking.PermutationFeatureImportance(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(0); var ml2 = new MLContext(0); pfi = ML.Ranking.PermutationFeatureImportance(model, data); pfiDict = ml2.Ranking.PermutationFeatureImportance((ITransformer)model, data); } // Pfi Indices: // X1: 0 // For Ranking, this column won't result in misorderings // X2Important: 1 // X3: 2 // X4Rand: 3 // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["X2Important"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["X3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["X4Rand"])); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa for (int i = 0; i < pfi[0].DiscountedCumulativeGains.Count; i++) { Assert.Equal(0, MaxDeltaIndex(pfi, m => m.DiscountedCumulativeGains[i].Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.DiscountedCumulativeGains[i].Mean)); } for (int i = 0; i < pfi[0].NormalizedDiscountedCumulativeGains.Count; i++) { Assert.Equal(0, MaxDeltaIndex(pfi, m => m.NormalizedDiscountedCumulativeGains[i].Mean)); Assert.Equal(1, MinDeltaIndex(pfi, m => m.NormalizedDiscountedCumulativeGains[i].Mean)); } Done(); } /// <summary> /// Test PFI Ranking Classification for Sparse Features /// </summary> [Theory] [InlineData(true)] [InlineData(false)] public void TestPfiRankingOnSparseFeatures(bool saveModel) { var data = GetSparseDataset(TaskType.Ranking); var model = ML.Ranking.Trainers.FastTree().Fit(data); ImmutableArray<RankingMetricsStatistics> pfi; ImmutableDictionary<string, RankingMetricsStatistics> pfiDict; if (saveModel) { var modelAndSchemaPath = GetOutputPath("TestPfiRankingOnSparseFeatures.zip"); ML.Model.Save(model, data.Schema, modelAndSchemaPath); var loadedModel = ML.Model.Load(modelAndSchemaPath, out var schema); var castedModel = loadedModel as RankingPredictionTransformer<FastTreeRankingModelParameters>; // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Ranking.PermutationFeatureImportance(castedModel, data); pfiDict = ml2.Ranking.PermutationFeatureImportance(loadedModel, data); } else { // PFI changes the random state, so we need to reset it and create another seed for both PFI to match ML = new MLContext(42); var ml2 = new MLContext(42); pfi = ML.Ranking.PermutationFeatureImportance(model, data); pfiDict = ml2.Ranking.PermutationFeatureImportance((ITransformer)model, data); } // Pfi Indices: // X1: 0 // X2VBuffer-Slot-0: 1 // X2VBuffer-Slot-1: 2 // Least important // X2VBuffer-Slot-2: 3 // X2VBuffer-Slot-3: 4 // X3Important: 5 // Most important // Make sure that PFI from the array and the dictionary both have the same value for each feature. Assert.Equal(JsonConvert.SerializeObject(pfi[0]), JsonConvert.SerializeObject(pfiDict["X1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[1]), JsonConvert.SerializeObject(pfiDict["Slot 1"])); Assert.Equal(JsonConvert.SerializeObject(pfi[2]), JsonConvert.SerializeObject(pfiDict["Slot 2"])); Assert.Equal(JsonConvert.SerializeObject(pfi[3]), JsonConvert.SerializeObject(pfiDict["Slot 3"])); Assert.Equal(JsonConvert.SerializeObject(pfi[4]), JsonConvert.SerializeObject(pfiDict["Slot 4"])); Assert.Equal(JsonConvert.SerializeObject(pfi[5]), JsonConvert.SerializeObject(pfiDict["X3Important"])); // For the following metrics higher is better, so minimum delta means more important feature, and vice versa for (int i = 0; i < pfi[0].DiscountedCumulativeGains.Count; i++) { Assert.Equal(2, MaxDeltaIndex(pfi, m => m.DiscountedCumulativeGains[i].Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.DiscountedCumulativeGains[i].Mean)); } for (int i = 0; i < pfi[0].NormalizedDiscountedCumulativeGains.Count; i++) { Assert.Equal(2, MaxDeltaIndex(pfi, m => m.NormalizedDiscountedCumulativeGains[i].Mean)); Assert.Equal(5, MinDeltaIndex(pfi, m => m.NormalizedDiscountedCumulativeGains[i].Mean)); } Done(); } #endregion #region Helpers /// <summary> /// Features: x1, x2, x3, xRand; y = 10*x1 + 20x2 + 5.5x3 + e, xRand- random and Label y is to dependant on xRand. /// xRand has the least importance: Evaluation metrics do not change a lot when xRand is permuted. /// x2 has the biggest importance. /// </summary> private IDataView GetDenseDataset(TaskType task = TaskType.Regression) { // Setup synthetic dataset. const int numberOfInstances = 1000; var rand = new Random(10); float[] yArray = new float[numberOfInstances]; float[] x1Array = new float[numberOfInstances]; float[] x2Array = new float[numberOfInstances]; float[] x3Array = new float[numberOfInstances]; float[] x4RandArray = new float[numberOfInstances]; for (var i = 0; i < numberOfInstances; i++) { var x1 = rand.Next(1000); x1Array[i] = x1; var x2Important = rand.Next(10000); x2Array[i] = x2Important; var x3 = rand.Next(5000); x3Array[i] = x3; var x4Rand = rand.Next(1000); x4RandArray[i] = x4Rand; var noise = rand.Next(50); yArray[i] = (float)(10 * x1 + 20 * x2Important + 5.5 * x3 + noise); } // If binary classification, modify the labels if (task == TaskType.BinaryClassification || task == TaskType.MulticlassClassification) GetBinaryClassificationLabels(yArray); else if (task == TaskType.Ranking) GetRankingLabels(yArray); // Create data view. var bldr = new ArrayDataViewBuilder(Env); bldr.AddColumn("X1", NumberDataViewType.Single, x1Array); bldr.AddColumn("X2Important", NumberDataViewType.Single, x2Array); bldr.AddColumn("X3", NumberDataViewType.Single, x3Array); bldr.AddColumn("X4Rand", NumberDataViewType.Single, x4RandArray); bldr.AddColumn("Label", NumberDataViewType.Single, yArray); if (task == TaskType.Ranking) bldr.AddColumn("GroupId", NumberDataViewType.UInt32, CreateGroupIds(yArray.Length)); var srcDV = bldr.GetDataView(); var pipeline = ML.Transforms.Concatenate("Features", "X1", "X2Important", "X3", "X4Rand") .Append(ML.Transforms.NormalizeMinMax("Features")); if (task == TaskType.BinaryClassification) return pipeline.Append(ML.Transforms.Conversion.ConvertType("Label", outputKind: DataKind.Boolean)) .Fit(srcDV).Transform(srcDV); else if (task == TaskType.MulticlassClassification) return pipeline.Append(ML.Transforms.Conversion.MapValueToKey("Label")) .Fit(srcDV).Transform(srcDV); else if (task == TaskType.Ranking) return pipeline.Append(ML.Transforms.Conversion.MapValueToKey("GroupId")) .Fit(srcDV).Transform(srcDV); return pipeline.Fit(srcDV).Transform(srcDV); } /// <summary> /// Features: x1, x2vBuff(sparce vector), x3. /// y = 10x1 + 10x2vBuff + 30x3 + e. /// Within xBuff feature 2nd slot will be sparse most of the time. /// 2nd slot of xBuff has the least importance: Evaluation metrics do not change a lot when this slot is permuted. /// x2 has the biggest importance. /// </summary> private IDataView GetSparseDataset(TaskType task = TaskType.Regression) { // Setup synthetic dataset. const int numberOfInstances = 10000; var rand = new Random(10); float[] yArray = new float[numberOfInstances]; float[] x1Array = new float[numberOfInstances]; float[] x3Array = new float[numberOfInstances]; VBuffer<float>[] vbArray = new VBuffer<float>[numberOfInstances]; for (var i = 0; i < numberOfInstances; i++) { var x1 = rand.Next(1000); x1Array[i] = x1; var x3Important = rand.Next(10000); x3Array[i] = x3Important; VBuffer<float> vb; if (i % 10 != 0) { vb = new VBuffer<float>(4, 3, new float[] { rand.Next(1000), rand.Next(1000), rand.Next(1000) }, new int[] { 0, 2, 3 }); } else { vb = new VBuffer<float>(4, 4, new float[] { rand.Next(1000), rand.Next(1000), rand.Next(1000), rand.Next(1000) }, new int[] { 0, 1, 2, 3 }); } vbArray[i] = vb; float vbSum = 0; foreach (var vbValue in vb.DenseValues()) { vbSum += vbValue * 10; } var noise = rand.Next(50); yArray[i] = 10 * x1 + vbSum + 20 * x3Important + noise; } // If binary classification, modify the labels if (task == TaskType.BinaryClassification || task == TaskType.MulticlassClassification) GetBinaryClassificationLabels(yArray); else if (task == TaskType.Ranking) GetRankingLabels(yArray); // Create data view. var bldr = new ArrayDataViewBuilder(Env); bldr.AddColumn("X1", NumberDataViewType.Single, x1Array); bldr.AddColumn("X2VBuffer", NumberDataViewType.Single, vbArray); bldr.AddColumn("X3Important", NumberDataViewType.Single, x3Array); bldr.AddColumn("Label", NumberDataViewType.Single, yArray); if (task == TaskType.Ranking) bldr.AddColumn("GroupId", NumberDataViewType.UInt32, CreateGroupIds(yArray.Length)); var srcDV = bldr.GetDataView(); var pipeline = ML.Transforms.Concatenate("Features", "X1", "X2VBuffer", "X3Important") .Append(ML.Transforms.NormalizeMinMax("Features")); if (task == TaskType.BinaryClassification) { return pipeline.Append(ML.Transforms.Conversion.ConvertType("Label", outputKind: DataKind.Boolean)) .Fit(srcDV).Transform(srcDV); } else if (task == TaskType.MulticlassClassification) { return pipeline.Append(ML.Transforms.Conversion.MapValueToKey("Label")) .Fit(srcDV).Transform(srcDV); } else if (task == TaskType.Ranking) return pipeline.Append(ML.Transforms.Conversion.MapValueToKey("GroupId")) .Fit(srcDV).Transform(srcDV); return pipeline.Fit(srcDV).Transform(srcDV); } private int MinDeltaIndex<T>( ImmutableArray<T> metricsDelta, Func<T, double> metricSelector) { var min = metricsDelta.OrderBy(m => metricSelector(m)).First(); return metricsDelta.IndexOf(min); } private int MaxDeltaIndex<T>( ImmutableArray<T> metricsDelta, Func<T, double> metricSelector) { var max = metricsDelta.OrderByDescending(m => metricSelector(m)).First(); return metricsDelta.IndexOf(max); } private void GetBinaryClassificationLabels(float[] rawScores) { float averageScore = GetArrayAverage(rawScores); // Center the response and then take the sigmoid to generate the classes for (int i = 0; i < rawScores.Length; i++) rawScores[i] = MathUtils.Sigmoid(rawScores[i] - averageScore) > 0.5 ? 1 : 0; } private void GetRankingLabels(float[] rawScores) { var min = MathUtils.Min(rawScores); var max = MathUtils.Max(rawScores); for (int i = 0; i < rawScores.Length; i++) { // Bin from [zero,one), then expand out to [0,5) and truncate rawScores[i] = (int)(5 * (rawScores[i] - min) / (max - min)); if (rawScores[i] == 5) rawScores[i] = 4; } } private float GetArrayAverage(float[] scores) { // Compute the average so we can center the response float averageScore = 0.0f; for (int i = 0; i < scores.Length; i++) averageScore += scores[i]; averageScore /= scores.Length; return averageScore; } private uint[] CreateGroupIds(int numRows, int rowsPerGroup = 5) { var groupIds = new uint[numRows]; // Construct groups of rowsPerGroup using a modulo counter uint group = 0; for (int i = 0; i < groupIds.Length; i++) { if (i % rowsPerGroup == 0) group++; groupIds[i] = group; } return groupIds; }
PermutationFeatureImportanceTests
csharp
dotnet__orleans
src/Orleans.Serialization.Abstractions/Annotations.cs
{ "start": 22334, "end": 22959 }
public sealed class ____ : ActivatorUtilitiesConstructorAttribute { /// <summary> /// Initializes a new instance of the <see cref="GeneratedActivatorConstructorAttribute"/> class. /// </summary> public GeneratedActivatorConstructorAttribute() { } } /// <summary> /// Indicates that the source generator should also inspect and generate code for the assembly containing the specified type. /// </summary> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
GeneratedActivatorConstructorAttribute
csharp
unoplatform__uno
src/Uno.UI.Composition/Composition/ExpressionAnimationParser/ExpressionAnimationTokenKind.cs
{ "start": 37, "end": 355 }
internal enum ____ { DotToken, CommaToken, PlusToken, MinusToken, MultiplyToken, DivisionToken, OpenParenToken, CloseParenToken, QuestionMarkToken, ColonToken, GreaterThanEqualsToken, GreaterThanToken, LessThanEqualsToken, LessThanToken, IdentifierToken, NumericLiteralToken, }
ExpressionAnimationTokenKind
csharp
dotnet__orleans
src/api/Redis/Orleans.GrainDirectory.Redis/Orleans.GrainDirectory.Redis.cs
{ "start": 1293, "end": 2541 }
public partial class ____ : IGrainDirectory, ILifecycleParticipant<Runtime.ISiloLifecycle> { public RedisGrainDirectory(Configuration.RedisGrainDirectoryOptions directoryOptions, Microsoft.Extensions.Options.IOptions<Configuration.ClusterOptions> clusterOptions, Microsoft.Extensions.Logging.ILogger<RedisGrainDirectory> logger) { } public System.Threading.Tasks.Task Initialize(System.Threading.CancellationToken ct = default) { throw null; } public System.Threading.Tasks.Task<Runtime.GrainAddress?> Lookup(Runtime.GrainId grainId) { throw null; } public void Participate(Runtime.ISiloLifecycle lifecycle) { } public System.Threading.Tasks.Task<Runtime.GrainAddress?> Register(Runtime.GrainAddress address, Runtime.GrainAddress? previousAddress) { throw null; } public System.Threading.Tasks.Task<Runtime.GrainAddress?> Register(Runtime.GrainAddress address) { throw null; } public System.Threading.Tasks.Task Unregister(Runtime.GrainAddress address) { throw null; } public System.Threading.Tasks.Task UnregisterSilos(System.Collections.Generic.List<Runtime.SiloAddress> siloAddresses) { throw null; } } } namespace Orleans.Hosting { public static
RedisGrainDirectory
csharp
Cysharp__ZLogger
tests/ZLogger.Generator.Tests/GenerateTest.cs
{ "start": 4515, "end": 5935 }
partial class ____ { // check for static [ZLoggerMessage(Information, "Hello {name}")] public static partial void Hello(ILogger logger, string name); // check for extension method [ZLoggerMessage(Information, "Hello {name}")] public static partial void Hello2(this ILogger logger, string name); // check for typed logger [ZLoggerMessage(Information, "Hello {x} {y}")] public static partial void Hello3(this ILogger<GenerateTest> logger, int x, int y); [ZLoggerMessage(Information, "Hello{x,-10}Bar{dt,15:yyyy-MM-dd}desu")] public static partial void AlignmentAndFormatCheck(this ILogger<GenerateTest> logger, int x, DateTime dt); [ZLoggerMessage(Information, "Hello {vec3:json} and {array}")] public static partial void JsonAndEnumerable(this ILogger<GenerateTest> logger, MyVec3 vec3, int[] array); [ZLoggerMessage(Information, "{e} {ne} {dt:yyyy-MM-dd} {dto:yyyy-MM-ddzzz} {dtn:yyyy-MM-dd} {gd} {gdd} {inn}")] public static partial void ManyTypes(this ILogger<GenerateTest> logger, MyEnum e, MyEnum? ne, DateTime dt, DateTimeOffset dto, DateTime? dtn, Guid gd, Guid? gdd, int? inn); [ZLoggerMessage(Information, "Hello {name:@no-name} {age:@a ge pa n da:00000000}")] public static partial void CustomFormat(this ILogger logger, string name, int age); }
StaticHolder
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.ContentFields/Indexing/UserPickerFieldIndexHandler.cs
{ "start": 153, "end": 1243 }
public class ____ : ContentFieldIndexHandler<UserPickerField> { public override Task BuildIndexAsync(UserPickerField field, BuildFieldIndexContext context) { var options = DocumentIndexOptions.Keyword | DocumentIndexOptions.Store; if (field.UserIds.Length > 0) { foreach (var userId in field.UserIds) { foreach (var key in context.Keys) { context.DocumentIndex.Set(key, userId, options); } } var userNames = field.GetUserNames(); foreach (var userName in userNames) { foreach (var key in context.Keys) { context.DocumentIndex.Set(key, userName, options); } } } else { foreach (var key in context.Keys) { context.DocumentIndex.Set(key, ContentIndexingConstants.NullValue, options); } } return Task.CompletedTask; } }
UserPickerFieldIndexHandler
csharp
dotnet__machinelearning
src/Microsoft.ML.CodeGenerator/CodeGenerator/CSharp/Interface/ICSharpProject.cs
{ "start": 330, "end": 457 }
internal interface ____ : IWritable, IEnumerable<ICSharpFile> { public string Name { get; set; } } }
ICSharpProject
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Core/test/ModelBinding/Metadata/DefaultValidationMetadataProviderTest.cs
{ "start": 6756, "end": 6879 }
private class ____ : ValidateNeverClass { public string SubclassName { get; set; } }
ValidateNeverSubclass
csharp
dotnet__orleans
test/TestInfrastructure/TestExtensions/MockStorageProvider.cs
{ "start": 1869, "end": 4234 }
public class ____ { [Id(0)] public int InitCount { get; set; } [Id(1)] public int CloseCount { get; set; } [Id(2)] public int ReadCount { get; set; } [Id(3)] public int WriteCount { get; set; } [Id(4)] public int DeleteCount { get; set; } } private static int _instanceNum; private readonly int _id; private readonly int initCount; private int closeCount; private int readCount; private int writeCount; private int deleteCount; private readonly int numKeys; private readonly DeepCopier copier; private readonly ILocalDataStore StateStore; private const string stateStoreKey = "State"; private readonly ILogger logger; public string LastId { get; private set; } public object LastState { get; private set; } public string Name { get; private set; } public MockStorageProvider(ILoggerFactory loggerFactory, DeepCopier copier) : this(Guid.NewGuid().ToString(), 2, loggerFactory, copier) { } public MockStorageProvider(string name, ILoggerFactory loggerFactory, DeepCopier copier) : this(name, 2, loggerFactory, copier) { } public MockStorageProvider(string name, int numKeys, ILoggerFactory loggerFactory, DeepCopier copier) { _id = ++_instanceNum; this.numKeys = numKeys; this.copier = copier; this.Name = name; this.logger = loggerFactory.CreateLogger($"Storage.{this.GetType().Name}-{this._id}"); logger.LogInformation("Init Name={Name}", name); Interlocked.Increment(ref initCount); StateStore = new HierarchicalKeyStore(numKeys); logger.LogInformation("Finished Init Name={Name}", name); } public StateForTest GetProviderState() { var state = new StateForTest(); state.InitCount = initCount; state.CloseCount = closeCount; state.DeleteCount = deleteCount; state.ReadCount = readCount; state.WriteCount = writeCount; return state; } [Serializable] [GenerateSerializer]
StateForTest
csharp
NLog__NLog
src/NLog/Conditions/ConditionMethodExpression.cs
{ "start": 8201, "end": 9602 }
private sealed class ____ : IEvaluateMethod { private readonly Func<LogEventInfo, object?, object?, object?, object?> _method; private readonly Func<LogEventInfo, object?> _methodParameterArg1; private readonly Func<LogEventInfo, object?> _methodParameterArg2; private readonly Func<LogEventInfo, object?> _methodParameterArg3; public EvaluateMethodThreeParameters(Func<LogEventInfo, object?, object?, object?, object?> method, Func<LogEventInfo, object?> methodParameterArg1, Func<LogEventInfo, object?> methodParameterArg2, Func<LogEventInfo, object?> methodParameterArg3) { _method = Guard.ThrowIfNull(method); _methodParameterArg1 = Guard.ThrowIfNull(methodParameterArg1); _methodParameterArg2 = Guard.ThrowIfNull(methodParameterArg2); _methodParameterArg3 = Guard.ThrowIfNull(methodParameterArg3); } public object? EvaluateNode(LogEventInfo logEvent) { var inputParameter1 = _methodParameterArg1(logEvent); var inputParameter2 = _methodParameterArg2(logEvent); var inputParameter3 = _methodParameterArg3(logEvent); return _method(logEvent, inputParameter1, inputParameter2, inputParameter3); } }
EvaluateMethodThreeParameters
csharp
microsoft__garnet
libs/storage/Tsavorite/cs/src/core/Index/Checkpointing/StateMachineBase.cs
{ "start": 143, "end": 264 }
class ____ IStateMachine that implements that state machine logic /// with IStateMachineTasks /// </summary>
for
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.ContentManagement.GraphQL/Queries/Types/ContentItemWhereInput.cs
{ "start": 385, "end": 2582 }
public sealed class ____ : WhereInputObjectGraphType { private readonly IOptions<GraphQLContentOptions> _optionsAccessor; public ContentItemWhereInput(string contentItemName, IOptions<GraphQLContentOptions> optionsAccessor, IStringLocalizer<ContentItemWhereInput> stringLocalizer) : base(stringLocalizer) { _optionsAccessor = optionsAccessor; Name = $"{contentItemName}WhereInput"; Description = S["the {0} content item filters", contentItemName]; AddScalarFilterFields<IdGraphType>("contentItemId", S["content item id"]); AddScalarFilterFields<IdGraphType>("contentItemVersionId", S["the content item version id"]); AddScalarFilterFields<StringGraphType>("displayText", S["the display text of the content item"]); AddScalarFilterFields<DateTimeGraphType>("createdUtc", S["the date and time of creation"]); AddScalarFilterFields<DateTimeGraphType>("modifiedUtc", S["the date and time of modification"]); AddScalarFilterFields<DateTimeGraphType>("publishedUtc", S["the date and time of publication"]); AddScalarFilterFields<StringGraphType>("owner", S["the owner of the content item"]); AddScalarFilterFields<StringGraphType>("author", S["the author of the content item"]); var whereInputType = new ListGraphType(this); Field<ListGraphType<ContentItemWhereInput>>("Or") .Description(S["OR logical operation"]) .Type(whereInputType); Field<ListGraphType<ContentItemWhereInput>>("And") .Description(S["AND logical operation"]) .Type(whereInputType); Field<ListGraphType<ContentItemWhereInput>>("Not") .Description(S["NOT logical operation"]) .Type(whereInputType); } public override void AddScalarFilterFields(Type graphType, string fieldName, string description, string aliasName, string contentPart, string contentField) { if (!_optionsAccessor.Value.ShouldSkip(typeof(ContentItemType), fieldName)) { base.AddScalarFilterFields(graphType, fieldName, description, aliasName, contentPart, contentField); } } }
ContentItemWhereInput
csharp
unoplatform__uno
src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Media.Imaging/SvgImageSourceFailedEventArgs.cs
{ "start": 266, "end": 476 }
public partial class ____ { // Skipping already declared property Status // Forced skipping of method Microsoft.UI.Xaml.Media.Imaging.SvgImageSourceFailedEventArgs.Status.get } }
SvgImageSourceFailedEventArgs
csharp
smartstore__Smartstore
src/Smartstore.Web.Common/Rendering/Extensions/HtmlHelperRenderingExtensions.cs
{ "start": 3713, "end": 4226 }
enum ____. /// </summary> /// <typeparam name="TEnum">The type of enumeration.</typeparam> public static IHtmlContent DropDownListForEnum<TModel, TEnum>( this IHtmlHelper<TModel> helper, Expression<Func<TModel, TEnum>> expression) where TEnum : struct { return DropDownListForEnum(helper, expression, optionLabel: null, htmlAttributes: null); } /// <summary> /// Returns a single-selection HTML select element for the
values
csharp
dotnet__efcore
src/EFCore/ChangeTracking/Internal/IInternalEntry.cs
{ "start": 709, "end": 28938 }
public interface ____ { /// <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> object? this[IPropertyBase propertyBase] { get; set; } /// <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> EntityState EntityState { get; } /// <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> DbContext Context { get; } /// <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> IRuntimeTypeBase StructuralType { get; } /// <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> InternalEntityEntry EntityEntry { get; } /// <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> IInternalEntry ContainingEntry { get; } /// <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 object Entity => EntityEntry.Entity; /// <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> IReadOnlyList<int> GetOrdinals(); /// <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> bool HasConceptualNull { get; } /// <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> IStateManager StateManager { get; } /// <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> void AcceptChanges(); /// <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> void DiscardStoreGeneratedValues(); /// <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 void EnsureOriginalValues(); /// <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 void EnsureTemporaryValues(); /// <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 void EnsureStoreGeneratedValues(); /// <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> object? GetCurrentValue(IPropertyBase propertyBase); /// <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> TProperty GetCurrentValue<TProperty>(IPropertyBase propertyBase); /// <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> object? GetOriginalValue(IPropertyBase propertyBase); /// <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> TProperty GetOriginalValue<TProperty>(IProperty property); /// <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> object? GetPreStoreGeneratedCurrentValue(IPropertyBase propertyBase); /// <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> bool HasExplicitValue(IProperty property); /// <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> bool HasTemporaryValue(IProperty property); /// <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> bool IsConceptualNull(IProperty property); /// <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> bool IsModified(IProperty property); /// <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> bool IsModified(IComplexProperty property); /// <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> bool FlaggedAsStoreGenerated(int propertyIndex); /// <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> bool FlaggedAsTemporary(int propertyIndex); /// <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> bool IsStoreGenerated(IProperty property); /// <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> bool IsUnknown(IProperty property); /// <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> void MarkAsTemporary(IProperty property, bool temporary); /// <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> void MarkUnknown(IProperty property); /// <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> IInternalEntry PrepareToSave(); /// <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 void HandleConceptualNulls(bool sensitiveLoggingEnabled, bool force, bool isCascadeDelete); /// <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> T ReadOriginalValue<T>(IProperty property, int originalValueIndex); /// <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> object? ReadPropertyValue(IPropertyBase propertyBase); /// <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> T ReadStoreGeneratedValue<T>(int storeGeneratedIndex); /// <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> T ReadTemporaryValue<T>(int storeGeneratedIndex); /// <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> T ReadShadowValue<T>(int shadowIndex); /// <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> void SetOriginalValue(IPropertyBase propertyBase, object? value, int index = -1); /// <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> void SetProperty( IPropertyBase propertyBase, object? value, bool isMaterialization, bool setModified = true, bool isCascadeDelete = false); /// <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> void SetPropertyModified( IProperty property, bool changeState = true, bool isModified = true, bool isConceptualNull = false, bool acceptChanges = false); /// <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> void SetPropertyModified(IComplexProperty property, bool isModified = true, bool recurse = false); /// <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> void SetEntityState( EntityState entityState, bool acceptChanges = false, bool modifyProperties = true, EntityState? forceStateWhenUnknownKey = null, EntityState? fallbackState = null); /// <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> void OnComplexPropertyModified(IComplexProperty property, bool isModified = true); /// <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> void SetStoreGeneratedValue(IProperty property, object? value, bool setModified = true); /// <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> void SetTemporaryValue(IProperty property, object? value, bool setModified = true); /// <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> InternalComplexEntry GetComplexCollectionEntry(IComplexProperty property, int ordinal); /// <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> InternalComplexEntry GetComplexCollectionOriginalEntry(IComplexProperty property, int originalOrdinal); /// <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> IReadOnlyList<InternalComplexEntry?> GetComplexCollectionEntries(IComplexProperty property); /// <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> IReadOnlyList<InternalComplexEntry?> GetComplexCollectionOriginalEntries(IComplexProperty property); /// <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> IEnumerable<InternalComplexEntry> GetFlattenedComplexEntries(); /// <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> void OnComplexElementStateChange(InternalComplexEntry entry, EntityState oldState, EntityState newState); }
IInternalEntry
csharp
EventStore__EventStore
src/KurrentDB.Core/Services/Transport/Enumerators/ReadResponseException.cs
{ "start": 1015, "end": 1142 }
public class ____(string streamName) : ReadResponseException { public readonly string StreamName = streamName; }
StreamDeleted
csharp
SixLabors__ImageSharp
tests/ImageSharp.Tests/TestUtilities/Attributes/GroupOutputAttribute.cs
{ "start": 252, "end": 438 }
public class ____ : Attribute { public GroupOutputAttribute(string subfolder) { this.Subfolder = subfolder; } public string Subfolder { get; } }
GroupOutputAttribute
csharp
NSubstitute__NSubstitute
tests/NSubstitute.Acceptance.Specs/NullReferenceCheckingForSubstituteExtensions.cs
{ "start": 130, "end": 1612 }
public class ____ { IEngine _engine; [SetUp] public void SetUp() { _engine = null; } [Test] public void Call_to_received() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.Received().Rev()); } [Test] public void Call_to_did_not_receive() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.DidNotReceive().Rev()); } [Test] public void Call_to_received_with_any_args() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.ReceivedWithAnyArgs().Rev()); } [Test] public void Call_to_did_not_receive_with_any_args() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.DidNotReceiveWithAnyArgs().Rev()); } [Test] public void Call_to_when() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.When(x => x.Rev()).Do(x => { })); } [Test] public void Call_to_clear_received_calls() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.ClearReceivedCalls()); } [Test] public void Call_to_clear_substitute() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.ClearSubstitute(ClearOptions.CallActions)); } [Test] public void Call_to_received_calls() { Assert.Throws<NullSubstituteReferenceException>(() => _engine.ReceivedCalls()); }
NullReferenceCheckingForSubstituteExtensions
csharp
dotnet__orleans
src/Orleans.DurableJobs/LocalDurableJobManager.Log.cs
{ "start": 106, "end": 4891 }
internal partial class ____ { [LoggerMessage( Level = LogLevel.Debug, Message = "Scheduling job '{JobName}' for grain {TargetGrain} at {DueTime}" )] private static partial void LogSchedulingJob(ILogger logger, string jobName, GrainId targetGrain, DateTimeOffset dueTime); [LoggerMessage( Level = LogLevel.Debug, Message = "Job '{JobName}' (ID: {JobId}) scheduled to shard {ShardId} for grain {TargetGrain}" )] private static partial void LogJobScheduled(ILogger logger, string jobName, string jobId, string shardId, GrainId targetGrain); [LoggerMessage( Level = LogLevel.Information, Message = "LocalDurableJobManager starting" )] private static partial void LogStarting(ILogger logger); [LoggerMessage( Level = LogLevel.Information, Message = "LocalDurableJobManager started" )] private static partial void LogStarted(ILogger logger); [LoggerMessage( Level = LogLevel.Information, Message = "LocalDurableJobManager stopping. Running shards: {RunningShardCount}" )] private static partial void LogStopping(ILogger logger, int runningShardCount); [LoggerMessage( Level = LogLevel.Information, Message = "LocalDurableJobManager stopped" )] private static partial void LogStopped(ILogger logger); [LoggerMessage( Level = LogLevel.Debug, Message = "Attempting to cancel job {JobId} (Name: '{JobName}') in shard {ShardId}" )] private static partial void LogCancellingJob(ILogger logger, string jobId, string jobName, string shardId); [LoggerMessage( Level = LogLevel.Warning, Message = "Failed to cancel job {JobId} (Name: '{JobName}') - shard {ShardId} not found in cache" )] private static partial void LogJobCancellationFailed(ILogger logger, string jobId, string jobName, string shardId); [LoggerMessage( Level = LogLevel.Information, Message = "Job {JobId} (Name: '{JobName}') cancelled from shard {ShardId}" )] private static partial void LogJobCancelled(ILogger logger, string jobId, string jobName, string shardId); [LoggerMessage( Level = LogLevel.Error, Message = "Error processing cluster membership update" )] private static partial void LogErrorProcessingClusterMembership(ILogger logger, Exception exception); [LoggerMessage( Level = LogLevel.Debug, Message = "Checking for unassigned shards" )] private static partial void LogCheckingForUnassignedShards(ILogger logger); [LoggerMessage( Level = LogLevel.Information, Message = "Assigned {ShardCount} shard(s)" )] private static partial void LogAssignedShards(ILogger logger, int shardCount); [LoggerMessage( Level = LogLevel.Trace, Message = "No unassigned shards found" )] private static partial void LogNoShardsToAssign(ILogger logger); [LoggerMessage( Level = LogLevel.Information, Message = "Starting shard {ShardId} (Start: {StartTime}, End: {EndTime})" )] private static partial void LogStartingShard(ILogger logger, string shardId, DateTimeOffset startTime, DateTimeOffset endTime); [LoggerMessage( Level = LogLevel.Debug, Message = "Shard {ShardId} not ready yet. Start time: {StartTime}" )] private static partial void LogShardNotReadyYet(ILogger logger, string shardId, DateTimeOffset startTime); [LoggerMessage( Level = LogLevel.Trace, Message = "Checking for pending shards to start" )] private static partial void LogCheckingPendingShards(ILogger logger); [LoggerMessage( Level = LogLevel.Error, Message = "Error in periodic shard check" )] private static partial void LogErrorInPeriodicCheck(ILogger logger, Exception exception); [LoggerMessage( Level = LogLevel.Information, Message = "Unregistered shard {ShardId}" )] private static partial void LogUnregisteredShard(ILogger logger, string shardId); [LoggerMessage( Level = LogLevel.Error, Message = "Error unregistering shard {ShardId}" )] private static partial void LogErrorUnregisteringShard(ILogger logger, Exception exception, string shardId); [LoggerMessage( Level = LogLevel.Error, Message = "Error disposing shard {ShardId}" )] private static partial void LogErrorDisposingShard(ILogger logger, Exception exception, string shardId); [LoggerMessage( Level = LogLevel.Information, Message = "Creating new shard for key {ShardKey}" )] private static partial void LogCreatingNewShard(ILogger logger, DateTimeOffset shardKey); }
LocalDurableJobManager
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/Testing/StateMachineSagaTest_Specs.cs
{ "start": 5120, "end": 5309 }
public class ____ : CorrelatedBy<Guid> { public string TestKey { get; set; } public Guid CorrelationId { get; set; } }
StartMessage
csharp
dotnet__aspire
src/Aspire.Cli/Projects/ProjectLocator.cs
{ "start": 26273, "end": 26360 }
internal enum ____ { Prompt, Throw, None }
MultipleAppHostProjectsFoundBehavior
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/RawRequestTests.cs
{ "start": 313, "end": 443 }
public class ____ : IRequiresRequestStream { public Stream RequestStream { get; set; } } [Route("/rawrequest/{Path}")]
RawRequest
csharp
ChilliCream__graphql-platform
src/Nitro/CommandLine/src/CommandLine.Cloud/Generated/ApiClient.Client.cs
{ "start": 3132226, "end": 3132611 }
public partial interface ____ : IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_Changes_3, IArgumentChanged { } [global::System.CodeDom.Compiler.GeneratedCode("StrawberryShake", "15.1.8.0")]
IOnFusionConfigurationPublishingTaskChanged_OnFusionConfigurationPublishingTaskChanged_Changes_Changes_Changes_ArgumentChanged
csharp
RicoSuter__NJsonSchema
src/NJsonSchema.CodeGeneration.CSharp/Models/ClassTemplateModel.cs
{ "start": 6493, "end": 7024 }
class ____.</summary> public string ClassType => _settings.GenerateNativeRecords ? "record" : "class"; /// <summary>Gets a value indicating whether to generate records as C# 9.0 records.</summary> public bool GenerateNativeRecords => _settings.GenerateNativeRecords; /// <summary>Gets a value indicating whether to render ToJson() and FromJson() methods.</summary> public bool GenerateJsonMethods => _settings.GenerateJsonMethods; /// <summary>Gets a value indicating whether the
type
csharp
xunit__xunit
src/xunit.v2.tests/Sdk/Frameworks/Runners/XunitTestAssemblyRunnerTests.cs
{ "start": 10846, "end": 13313 }
class ____ : ITestCollectionOrderer { public IEnumerable<ITestCollection> OrderTestCollections(IEnumerable<ITestCollection> TestCollections) { return TestCollections.OrderByDescending(c => c.DisplayName); } } [Fact] public static void UnknownType_HaltsProcessing() { var ordererAttribute = Mocks.TestCollectionOrdererAttribute("UnknownType", "UnknownAssembly"); var assembly = Mocks.TestAssembly(new[] { ordererAttribute }); var executionMessages = new List<IMessageSinkMessage>(); var executionSink = SpyMessageSink.Create(messages: executionMessages); var runner = TestableXunitTestAssemblyRunner.Create(assembly: assembly, executionMessageSink: executionSink); runner.Initialize(); var errorMessage = Assert.Single(executionMessages.OfType<IErrorMessage>()); var type = Assert.Single(errorMessage.ExceptionTypes); Assert.Equal(typeof(XunitException).FullName, type); var index = Assert.Single(errorMessage.ExceptionParentIndices); Assert.Equal(-1, index); var msg = Assert.Single(errorMessage.Messages); Assert.Equal("Could not find type 'UnknownType' in 'UnknownAssembly' for assembly-level test collection orderer", msg); Assert.Empty(runner.TestCases); } [Fact] public static void ThrowsDuringConstruction_HaltsProcessing() { Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; var ordererAttribute = Mocks.TestCollectionOrdererAttribute<MyCtorThrowingTestCollectionOrderer>(); var assembly = Mocks.TestAssembly(new[] { ordererAttribute }); var executionMessages = new List<IMessageSinkMessage>(); var executionSink = SpyMessageSink.Create(messages: executionMessages); var runner = TestableXunitTestAssemblyRunner.Create(assembly: assembly, executionMessageSink: executionSink); runner.Initialize(); var errorMessage = Assert.Single(executionMessages.OfType<IErrorMessage>()); var type = Assert.Single(errorMessage.ExceptionTypes); Assert.Equal(typeof(XunitException).FullName, type); var index = Assert.Single(errorMessage.ExceptionParentIndices); Assert.Equal(-1, index); var msg = Assert.Single(errorMessage.Messages); Assert.Equal("Assembly-level test collection orderer 'XunitTestAssemblyRunnerTests+TestCollectionOrderer+MyCtorThrowingTestCollectionOrderer' threw 'System.DivideByZeroException' during construction: Attempted to divide by zero.", msg); Assert.Empty(runner.TestCases); }
MyTestCollectionOrderer
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Data/Migrations/UpgradeTo460/StoreMigration.cs
{ "start": 178, "end": 2570 }
public class ____ : ForwardOnlyMigration { public override void Up() { if (!Schema.Table(nameof(Store)).Column(nameof(Store.Deleted)).Exists()) { //add new column Alter.Table(nameof(Store)) .AddColumn(nameof(Store.Deleted)).AsBoolean().WithDefaultValue(false); Alter.Table(nameof(Store)) .AlterColumn(nameof(Store.Deleted)).AsBoolean(); } if (!Schema.Table(nameof(Store)).Column(nameof(Store.DefaultTitle)).Exists()) //add new column Alter.Table(nameof(Store)) .AddColumn(nameof(Store.DefaultTitle)).AsString(int.MaxValue).Nullable(); else Alter.Table(nameof(Store)).AlterColumn(nameof(Store.DefaultTitle)).AsString(int.MaxValue).Nullable(); if (!Schema.Table(nameof(Store)).Column(nameof(Store.DefaultMetaDescription)).Exists()) //add new column Alter.Table(nameof(Store)) .AddColumn(nameof(Store.DefaultMetaDescription)).AsString(int.MaxValue).Nullable(); else Alter.Table(nameof(Store)).AlterColumn(nameof(Store.DefaultMetaDescription)).AsString(int.MaxValue).Nullable(); if (!Schema.Table(nameof(Store)).Column(nameof(Store.DefaultMetaKeywords)).Exists()) //add new column Alter.Table(nameof(Store)) .AddColumn(nameof(Store.DefaultMetaKeywords)).AsString(int.MaxValue).Nullable(); else Alter.Table(nameof(Store)).AlterColumn(nameof(Store.DefaultMetaKeywords)).AsString(int.MaxValue).Nullable(); if (!Schema.Table(nameof(Store)).Column(nameof(Store.HomepageDescription)).Exists()) //add new column Alter.Table(nameof(Store)) .AddColumn(nameof(Store.HomepageDescription)).AsString(int.MaxValue).Nullable(); else Alter.Table(nameof(Store)).AlterColumn(nameof(Store.HomepageDescription)).AsString(int.MaxValue).Nullable(); if (!Schema.Table(nameof(Store)).Column(nameof(Store.HomepageTitle)).Exists()) //add new column Alter.Table(nameof(Store)) .AddColumn(nameof(Store.HomepageTitle)).AsString(int.MaxValue).Nullable(); else Alter.Table(nameof(Store)).AlterColumn(nameof(Store.HomepageTitle)).AsString(int.MaxValue).Nullable(); } }
StoreMigration
csharp
npgsql__efcore.pg
test/EFCore.PG.FunctionalTests/MusicStoreNpgsqlTest.cs
{ "start": 276, "end": 867 }
public class ____ : MusicStoreFixtureBase { protected override ITestStoreFactory TestStoreFactory => NpgsqlTestStoreFactory.Instance; protected override void OnModelCreating(ModelBuilder modelBuilder, DbContext context) { base.OnModelCreating(modelBuilder, context); modelBuilder.Entity<CartItem>().Property(s => s.DateCreated).HasColumnType("timestamp without time zone"); modelBuilder.Entity<Order>().Property(s => s.OrderDate).HasColumnType("timestamp without time zone"); } } }
MusicStoreNpgsqlFixture
csharp
ServiceStack__ServiceStack.OrmLite
tests/ServiceStack.OrmLite.Tests/CustomSqlExpressionTests.cs
{ "start": 312, "end": 26476 }
public class ____ : OrmLiteProvidersTestBase { public CustomSqlExpressionTests(DialectContext context) : base(context) { // override the default sqlite provider and dbfactory with the custom one var customSqlServerDialectProvider = new CustomSqlServerDialectProvider(); DialectProvider = customSqlServerDialectProvider; DbFactory = new OrmLiteConnectionFactory(SqliteDb.MemoryConnection, customSqlServerDialectProvider, false); } [SetUp] public void Setup() { using var db = OpenDbConnection(); db.DropTable<WaybillBase>(); db.CreateTable<WaybillBase>(); db.Insert(new WaybillBase { Id = 1, Number = 100, Name = "first", Id1 = Guid.Parse("11111111-1111-1111-1111-111111111111"), Id2 = Guid.Parse("51111111-1111-1111-1111-111111111111"), Date = DateTime.Parse("2001-01-01"), Amount = 20M }); db.Insert(new WaybillBase { Id = 2, Number = 200, Name = "second", Id1 = Guid.Parse("22222222-2222-2222-2222-222222222222"), Id2 = Guid.Parse("52222222-2222-2222-2222-222222222222"), Date = DateTime.Parse("2002-01-01"), Amount = 30M }); db.Insert(new WaybillBase { Id = 3, Number = 300, Name = "third", Id1 = Guid.Parse("33333333-3333-3333-3333-333333333333"), Id2 = Guid.Parse("53333333-3333-3333-3333-333333333333"), Date = DateTime.Parse("2003-01-01"), Amount = 40M }); db.DropTable<SeparateWaybillIn>(); db.CreateTable<SeparateWaybillIn>(); db.Insert(new SeparateWaybillIn { Id = 1, DateBegin = DateTime.Parse("2014-01-01"), DateEnd = DateTime.Parse("2014-01-03"), Note = "firstNote"}); db.Insert(new SeparateWaybillIn { Id = 2, DateBegin = DateTime.Parse("2015-01-01"), DateEnd = DateTime.Parse("2015-01-03"), Note = "secondNote" }); db.Insert(new SeparateWaybillIn { Id = 3, DateBegin = DateTime.Parse("2016-01-01"), DateEnd = DateTime.Parse("2016-01-03"), Note = "thirdNote" }); } [Test] public void Can_Where_using_constant_filter1() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == "WaybillVirtPropertyValue"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_filter2() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == "Any"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_constant_filter3() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty != "WaybillVirtPropertyValue"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_constant_filter4() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty != "Any"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_filter5() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == "WaybillVirtPropertyValue" || x.VirtProperty2 == "WaybillVirtPropertyValue2"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_filter6() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == "WaybillVirtPropertyValue" && x.VirtProperty2 == "WaybillVirtPropertyValue2"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_filter7() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == "WaybillVirtPropertyValue" || x.VirtProperty2 == "Any"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_filter8() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == "WaybillVirtPropertyValue" && x.VirtProperty2 == "Any"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_constant_filter9() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.BoolVirtProperty; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_constant_filter10() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => !x.BoolVirtProperty; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_filter11() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.BoolVirtProperty && x.VirtProperty == "WaybillVirtPropertyValue"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_constant_filter12() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => !x.BoolVirtProperty || x.VirtProperty == "WaybillVirtPropertyValue"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_filter13() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => !x.BoolVirtProperty && x.VirtProperty == "WaybillVirtPropertyValue" && x.Number == 100; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(1, target.Count); } [Test] public void Can_Where_using_constant_filter14() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.Number == 100 && (x.BoolVirtProperty || x.VirtProperty == "WaybillVirtPropertyValue"); var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(1, target.Count); } [Test] public void Can_Select_hierarchy_classes1() { using var db = OpenDbConnection(); var q1 = db.From<WaybillIn>(); q1.PrefixFieldWithTableName = true; q1.Select(x => new {x.Name, x.Number}); q1.SelectInto<WaybillIn>(QueryType.Select); var sql1 = q1.SelectExpression; var q2 = db.From<WaybillBase>(); q2.PrefixFieldWithTableName = true; q2.Select(x => new {x.Name, x.Number}); q2.SelectInto<WaybillIn>(QueryType.Select); var sql2 = q2.SelectExpression; Assert.AreEqual(sql1, sql2); } [Test] public void Can_Select_hierarchy_classes2() { using var db = OpenDbConnection(); var q = db.From<WaybillIn>(); q.PrefixFieldWithTableName = true; q.Join<WaybillBase>((x, y) => x.Id == y.Id); q.Where(x => x.Name == "first" && x.Note == "firstNote"); var target = db.Select(q); Assert.AreEqual(1, target.Count); var obj = target[0]; Assert.AreEqual(DateTime.Parse("2014-01-01"), obj.DateBegin); } [Test] public void Can_Select_hierarchy_classes3() { using var db = OpenDbConnection(); var q = db.From<WaybillIn>(); q.PrefixFieldWithTableName = true; q.Join<WaybillBase>((x, y) => x.Id == y.Id); q.Where(x => x.Name == "first" && x.Note == "firstNote"); q.Select(new[] {nameof(WaybillBase.Number)}); var target = db.Column<int>(q); Assert.AreEqual(1, target.Count); var obj = target[0]; Assert.AreEqual(100, obj); } [Test] public void Can_Select_hierarchy_classes4() { using var db = OpenDbConnection(); var q = db.From<WaybillIn>(); q.PrefixFieldWithTableName = true; q.Join<WaybillBase>((x, y) => x.Id == y.Id); q.Where(x => x.Name == "first" && x.Note == "firstNote"); q.OrderByFields(nameof(WaybillBase.Number)); var target = db.Select(q); Assert.AreEqual(1, target.Count); var obj = target[0]; Assert.AreEqual(DateTime.Parse("2014-01-01"), obj.DateBegin); } [Test] public void Can_Where_using_constant_orderBy1() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => !x.BoolVirtProperty; Expression<Func<WaybillBase, object>> orderBy = x => x.BoolVirtProperty; var q = db.From<WaybillBase>().Where(filter).OrderBy(orderBy); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_constant_orderBy2() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => !x.BoolVirtProperty && x.VirtPropertyEmpty != "WaybillVirtPropertyValue" && x.Number == 100; Expression<Func<WaybillBase, object>> orderBy = x => x.VirtPropertyEmpty; var q = db.From<WaybillBase>().Where(filter).OrderBy(orderBy); var target = db.Select(q); Assert.AreEqual(1, target.Count); } [Test] public void Can_Where_using_constant_conditionalOrderBy() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => !x.BoolVirtProperty && x.VirtPropertyEmpty != "WaybillVirtPropertyValue" && x.Number == 100; Expression<Func<WaybillBase, object>> orderBy = x => x.Number > 0 ? x.VirtPropertyEmpty : x.Name; var q = db.From<WaybillBase>().Where(filter).OrderBy(orderBy); var target = db.Select(q); Assert.AreEqual(1, target.Count); } [Test] public void Can_Where_using_constant_func_where() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty.StartsWith("Way"); Expression<Func<WaybillBase, object>> orderBy = x => x.Name; var q = db.From<WaybillBase>().Where(filter).OrderByDescending(orderBy); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Select_using_constant() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => !x.BoolVirtProperty && x.VirtPropertyEmpty != "WaybillVirtPropertyValue" && x.Number == 100; Expression<Func<WaybillBase, object>> select = x => x.VirtProperty; var q = db.From<WaybillBase>().Where(filter).Select(@select); var target = db.Column<string>(q); Assert.AreEqual(1, target.Count); Assert.AreEqual("WaybillVirtPropertyValue", target[0]); } [Test] public void Can_Where_using_guid_constant_conditional() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => (x.Number > 0 ? x.GuidVirtProperty : x.Id1) == Guid.Parse("00000000-0000-0000-0000-000000000000"); var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_null_constant_conditional() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => (x.Number == 0 ? x.VirtPropertyNull : x.Name) == "first"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(1, target.Count); } [Test] public void Can_Where_using_datetime_constant_conditional() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => (x.Number > 0 ? x.DateVirtProperty : x.Date) == DateTime.Parse("2000-01-01"); var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_int_constant_conditional() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => (x.Number > 0 ? x.IntVirtProperty : x.Number) == 5; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_decimal_constant_conditional() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => (x.Number > 0 ? x.DecimalVirtProperty : x.Amount) == 10M; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_GroupBy_using_constant() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => (x.Number > 0 ? x.DecimalVirtProperty : x.Amount) == 10M; var q = db.From<WaybillBase>() .Where(filter) .GroupBy(x => x.VirtPropertyEmpty); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Having_using_constant() { using var db = OpenDbConnection(); OrmLiteUtils.PrintSql(); Expression<Func<WaybillBase, bool>> filter = x => (x.Number > 0 ? x.DecimalVirtProperty : x.Amount) == 10M; var q = db.From<WaybillBase>().Where(filter).Select(x => x.Name) .GroupBy(x => x.Name) .Having(x => x.VirtProperty == "WaybillVirtPropertyValue"); var target = db.Column<string>(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty1() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty.Length == 0; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty2() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty.Length == 24; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty3() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty.Length == 0 && x.Id > 0; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty4() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtPropertyNull.Length == 0; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty5() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtPropertyNull.Length == 0 && x.Id > 0; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty6() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.BoolVirtProperty != null; //should be always true var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where null")); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty7() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => null != x.BoolVirtProperty; //should be always true var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where null")); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty8() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => null != x.BoolVirtProperty && x.Id > 0; var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where null")); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty9() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.BoolVirtProperty == null; //should be always false var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where not (null)")); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty10() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => null == x.BoolVirtProperty; //should be always false var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where not (null)")); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty11() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.NullableTrueBoolVirtProperty == null; var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where null")); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty12() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.NullableTrueBoolVirtProperty != null; var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where not (null)")); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty13() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.NullableNullBoolVirtProperty == null; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty14() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.NullableNullBoolVirtProperty != null; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty15() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.NullableNullBoolVirtProperty == true; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty16() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.BoolVirtProperty != false; var q = db.From<WaybillBase>().Where(filter); Assert.That(q.ToSelectStatement().ToLower(), Does.Not.Contain("where null")); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty17() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtPropertyNull == null; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty18() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtPropertyNull != null; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty19() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtPropertyNull == "null"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty20() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == null; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(0, target.Count); } [Test] public void Can_Where_using_StringLengthVirtualProperty21() { using var db = OpenDbConnection(); Expression<Func<WaybillBase, bool>> filter = x => x.VirtProperty == "WaybillVirtPropertyValue"; var q = db.From<WaybillBase>().Where(filter); var target = db.Select(q); Assert.AreEqual(3, target.Count); } }
CustomSqlExpressionTests
csharp
dotnet__aspnetcore
src/Http/Http.Abstractions/src/CookieBuilder.cs
{ "start": 298, "end": 4750 }
public class ____ { private string? _name; private List<string>? _extensions; /// <summary> /// The name of the cookie. /// </summary> public virtual string? Name { get => _name; set => _name = !string.IsNullOrEmpty(value) ? value : throw new ArgumentException(Resources.ArgumentCannotBeNullOrEmpty, nameof(value)); } /// <summary> /// The cookie path. /// </summary> /// <remarks> /// Determines the value that will be set for <see cref="CookieOptions.Path"/>. /// </remarks> public virtual string? Path { get; set; } /// <summary> /// The domain to associate the cookie with. /// </summary> /// <remarks> /// Determines the value that will be set for <see cref="CookieOptions.Domain"/>. /// </remarks> public virtual string? Domain { get; set; } /// <summary> /// Indicates whether a cookie is inaccessible by client-side script. The default value is <c>false</c> /// but specific components may use a different value. /// </summary> /// <remarks> /// Determines the value that will be set on <see cref="CookieOptions.HttpOnly"/>. /// </remarks> public virtual bool HttpOnly { get; set; } /// <summary> /// The SameSite attribute of the cookie. The default value is <see cref="SameSiteMode.Unspecified"/> /// but specific components may use a different value. /// </summary> /// <remarks> /// Determines the value that will be set for <see cref="CookieOptions.SameSite"/>. /// </remarks> public virtual SameSiteMode SameSite { get; set; } = SameSiteMode.Unspecified; /// <summary> /// The policy that will be used to determine <see cref="CookieOptions.Secure"/>. /// This is determined from the <see cref="HttpContext"/> passed to <see cref="Build(HttpContext, DateTimeOffset)"/>. /// </summary> public virtual CookieSecurePolicy SecurePolicy { get; set; } /// <summary> /// Gets or sets the lifespan of a cookie. /// </summary> public virtual TimeSpan? Expiration { get; set; } /// <summary> /// Gets or sets the max-age for the cookie. /// </summary> public virtual TimeSpan? MaxAge { get; set; } /// <summary> /// Indicates if this cookie is essential for the application to function correctly. If true then /// consent policy checks may be bypassed. The default value is <c>false</c> /// but specific components may use a different value. /// </summary> public virtual bool IsEssential { get; set; } /// <summary> /// Gets a collection of additional values to append to the cookie. /// </summary> public IList<string> Extensions { get => _extensions ??= new List<string>(); } /// <summary> /// Creates the cookie options from the given <paramref name="context"/>. /// </summary> /// <param name="context">The <see cref="HttpContext"/>.</param> /// <returns>The cookie options.</returns> public CookieOptions Build(HttpContext context) => Build(context, DateTimeOffset.Now); /// <summary> /// Creates the cookie options from the given <paramref name="context"/> with an expiration based on <paramref name="expiresFrom"/> and <see cref="Expiration"/>. /// </summary> /// <param name="context">The <see cref="HttpContext"/>.</param> /// <param name="expiresFrom">The time to use as the base for computing <see cref="CookieOptions.Expires" />.</param> /// <returns>The cookie options.</returns> public virtual CookieOptions Build(HttpContext context, DateTimeOffset expiresFrom) { ArgumentNullException.ThrowIfNull(context); var options = new CookieOptions { Path = Path ?? "/", SameSite = SameSite, HttpOnly = HttpOnly, MaxAge = MaxAge, Domain = Domain, IsEssential = IsEssential, Secure = SecurePolicy == CookieSecurePolicy.Always || (SecurePolicy == CookieSecurePolicy.SameAsRequest && context.Request.IsHttps), Expires = Expiration.HasValue ? expiresFrom.Add(Expiration.GetValueOrDefault()) : default(DateTimeOffset?) }; if (_extensions?.Count > 0) { foreach (var extension in _extensions) { options.Extensions.Add(extension); } } return options; } }
CookieBuilder
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Payments/Infrastructure/AggregateStore/SqlOutboxAccessor.cs
{ "start": 228, "end": 1522 }
public class ____ : IOutbox { private readonly ISqlConnectionFactory _sqlConnectionFactory; private readonly List<OutboxMessage> _messages; public SqlOutboxAccessor(ISqlConnectionFactory sqlConnectionFactory) { _sqlConnectionFactory = sqlConnectionFactory; _messages = []; } public void Add(OutboxMessage message) { _messages.Add(message); } public async Task Save() { if (_messages.Any()) { using var connection = _sqlConnectionFactory.CreateNewConnection(); const string sql = "INSERT INTO [payments].[OutboxMessages] " + "([Id], [OccurredOn], [Type], [Data]) VALUES " + "(@Id, @OccurredOn, @Type, @Data)"; foreach (var message in _messages) { await connection.ExecuteScalarAsync(sql, new { message.Id, message.OccurredOn, message.Type, message.Data }); } _messages.Clear(); } } } }
SqlOutboxAccessor
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Abstractions/Modules/Extensions/InvokeExtensions.cs
{ "start": 69, "end": 9312 }
public static class ____ { /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static void Invoke<TEvents>(this IEnumerable<TEvents> events, Action<TEvents> dispatch, ILogger logger) { foreach (var sink in events) { try { dispatch(sink); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static void Invoke<TEvents, T1>(this IEnumerable<TEvents> events, Action<TEvents, T1> dispatch, T1 arg1, ILogger logger) { foreach (var sink in events) { try { dispatch(sink, arg1); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } public static IEnumerable<TResult> Invoke<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, TResult> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = dispatch(sink); results.Add(result); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } return results; } public static IEnumerable<TResult> Invoke<TEvents, T1, TResult>(this IEnumerable<TEvents> events, Func<TEvents, T1, TResult> dispatch, T1 arg1, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = dispatch(sink, arg1); results.Add(result); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } return results; } public static IEnumerable<TResult> Invoke<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, IEnumerable<TResult>> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = dispatch(sink); results.AddRange(result); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } return results; } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static async Task InvokeAsync<TEvents>(this IEnumerable<TEvents> events, Func<TEvents, Task> dispatch, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static async Task InvokeAsync<TEvents, T1>(this IEnumerable<TEvents> events, Func<TEvents, T1, Task> dispatch, T1 arg1, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static async Task InvokeAsync<TEvents, T1, T2>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, Task> dispatch, T1 arg1, T2 arg2, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static async Task InvokeAsync<TEvents, T1, T2, T3>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, T3, Task> dispatch, T1 arg1, T2 arg2, T3 arg3, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2, arg3); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static async Task InvokeAsync<TEvents, T1, T2, T3, T4>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, T3, T4, Task> dispatch, T1 arg1, T2 arg2, T3 arg3, T4 arg4, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2, arg3, arg4); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them. /// </summary> public static async Task InvokeAsync<TEvents, T1, T2, T3, T4, T5>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, T3, T4, T5, Task> dispatch, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2, arg3, arg4, arg5); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } } public static async Task<IEnumerable<TResult>> InvokeAsync<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, Task<TResult>> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = await dispatch(sink); results.Add(result); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } return results; } public static async Task<IEnumerable<TResult>> InvokeAsync<TEvents, T1, TResult>(this IEnumerable<TEvents> events, Func<TEvents, T1, Task<TResult>> dispatch, T1 arg1, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = await dispatch(sink, arg1); results.Add(result); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } return results; } public static async Task<IEnumerable<TResult>> InvokeAsync<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, Task<IEnumerable<TResult>>> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = await dispatch(sink); results.AddRange(result); } catch (Exception ex) when (!ex.IsFatal()) { ex.LogException(logger, typeof(TEvents), sink.GetType().FullName); } } return results; } [Obsolete("This method rethrows the given exception, which loses the original call stack. It is not recommended for new code. " + "Use ExceptionExtensions.LogException instead, which only logs exceptions without rethrowing.")] public static void HandleException(Exception ex, ILogger logger, string sourceType, string method) { if (IsLogged(ex)) { logger.LogError(ex, "{Type} thrown from {Method} by {Exception}", sourceType, method, ex.GetType().Name); } if (ex.IsFatal()) { throw ex; } } private static bool IsLogged(Exception ex) { return !ex.IsFatal(); } }
InvokeExtensions
csharp
abpframework__abp
framework/src/Volo.Abp.Core/Volo/Abp/ExceptionHandling/ExceptionNotificationContext.cs
{ "start": 120, "end": 734 }
public class ____ { /// <summary> /// The exception object. /// </summary> [NotNull] public Exception Exception { get; } public LogLevel LogLevel { get; } /// <summary> /// True, if it is handled. /// </summary> public bool Handled { get; } public ExceptionNotificationContext( [NotNull] Exception exception, LogLevel? logLevel = null, bool handled = true) { Exception = Check.NotNull(exception, nameof(exception)); LogLevel = logLevel ?? exception.GetLogLevel(); Handled = handled; } }
ExceptionNotificationContext
csharp
aspnetboilerplate__aspnetboilerplate
src/Abp/Runtime/Caching/IAbpCache.cs
{ "start": 8715, "end": 9097 }
public interface ____ { /// <summary> /// Unique name of the cache. /// </summary> string Name { get; } /// <summary> /// Clears all items in this cache. /// </summary> void Clear(); /// <summary> /// Clears all items in this cache. /// </summary> Task ClearAsync(); } }
IAbpCache
csharp
FastEndpoints__FastEndpoints
Web/[Features]/Customers/List/Recent/Endpoint.cs
{ "start": 992, "end": 1186 }
public class ____ : Endpoint { public override void Configure() { base.Configure(); Version(1, deprecateAt: 2); AuthSchemes("ApiKey", "Cookies"); } }
Endpoint_V1
csharp
RicoSuter__NSwag
src/NSwag.Commands/Commands/CodeGeneration/OpenApiToTypeScriptClientCommand.cs
{ "start": 10152, "end": 12984 }
class ____ extension class (default: false).")] public bool UseTransformResultMethod { get => Settings.UseTransformResultMethod; set => Settings.UseTransformResultMethod = value; } [Argument(Name = "GenerateDtoTypes", IsRequired = false, Description = "Specifies whether to generate DTO classes.")] public bool GenerateDtoTypes { get => Settings.GenerateDtoTypes; set => Settings.GenerateDtoTypes = value; } [Argument(Name = "OperationGenerationMode", IsRequired = false, Description = "The operation generation mode ('SingleClientFromOperationId' or 'MultipleClientsFromPathSegments').")] public OperationGenerationMode OperationGenerationMode { get => OperationGenerationModeConverter.GetOperationGenerationMode(Settings.OperationNameGenerator); set => Settings.OperationNameGenerator = OperationGenerationModeConverter.GetOperationNameGenerator(value); } [Argument(Name = "IncludedOperationIds", IsRequired = false, Description = "The operations that should be included or excluded.")] public string[] IncludedOperationIds { get => Settings.IncludedOperationIds; set => Settings.IncludedOperationIds = value; } [Argument(Name = "ExcludedOperationIds", IsRequired = false, Description = "The operations that should be included or excluded.")] public string[] ExcludedOperationIds { get => Settings.ExcludedOperationIds; set => Settings.ExcludedOperationIds = value; } [Argument(Name = "MarkOptionalProperties", IsRequired = false, Description = "Specifies whether to mark optional properties with ? (default: false).")] public bool MarkOptionalProperties { get => Settings.TypeScriptGeneratorSettings.MarkOptionalProperties; set => Settings.TypeScriptGeneratorSettings.MarkOptionalProperties = value; } [Argument(Name = "GenerateCloneMethod", IsRequired = false, Description = "Specifies whether a clone() method should be generated in the DTO classes (default: false).")] public bool GenerateCloneMethod { get => Settings.TypeScriptGeneratorSettings.GenerateCloneMethod; set => Settings.TypeScriptGeneratorSettings.GenerateCloneMethod = value; } [Argument(Name = "TypeStyle", IsRequired = false, Description = "The type style (default: Class).")] public TypeScriptTypeStyle TypeStyle { get => Settings.TypeScriptGeneratorSettings.TypeStyle; set => Settings.TypeScriptGeneratorSettings.TypeStyle = value; } [Argument(Name = "EnumStyle", IsRequired = false, Description = "The
or
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Core/Events/ConnectionPoolOpeningEvent.cs
{ "start": 834, "end": 2398 }
public struct ____ : IEvent { private readonly ConnectionPoolSettings _connectionPoolSettings; private readonly ServerId _serverId; private readonly DateTime _timestamp; /// <summary> /// Initializes a new instance of the <see cref="ConnectionPoolOpeningEvent"/> struct. /// </summary> /// <param name="serverId">The server identifier.</param> /// <param name="connectionPoolSettings">The connection pool settings.</param> public ConnectionPoolOpeningEvent(ServerId serverId, ConnectionPoolSettings connectionPoolSettings) { _serverId = serverId; _connectionPoolSettings = connectionPoolSettings; _timestamp = DateTime.UtcNow; } /// <summary> /// Gets the cluster identifier. /// </summary> public ClusterId ClusterId { get { return _serverId.ClusterId; } } /// <summary> /// Gets the connection pool settings. /// </summary> public ConnectionPoolSettings ConnectionPoolSettings { get { return _connectionPoolSettings; } } /// <summary> /// Gets the server identifier. /// </summary> public ServerId ServerId { get { return _serverId; } } /// <summary> /// Gets the timestamp. /// </summary> public DateTime Timestamp { get { return _timestamp; } } // explicit
ConnectionPoolOpeningEvent
csharp
AutoFixture__AutoFixture
Src/AutoFixtureUnitTest/Kernel/ListFavoringConstructorQueryTest.cs
{ "start": 240, "end": 4596 }
public class ____ { [Fact] public void SutIsMethodQuery() { // Arrange // Act var sut = new ListFavoringConstructorQuery(); // Assert Assert.IsAssignableFrom<IMethodQuery>(sut); } [Fact] public void SelectMethodsFromNullTypeThrows() { // Arrange var sut = new ListFavoringConstructorQuery(); // Act & assert Assert.Throws<ArgumentNullException>(() => sut.SelectMethods(null)); } [Fact] public void SelectMethodsFromTypeWithNoPublicConstructorReturnsCorrectResult() { // Arrange var sut = new ListFavoringConstructorQuery(); var typeWithNoPublicConstructors = typeof(AbstractType); // Act var result = sut.SelectMethods(typeWithNoPublicConstructors); // Assert Assert.False(result.Any()); } [Theory] [InlineData(typeof(SingleParameterType<object>))] [InlineData(typeof(ConcreteType))] [InlineData(typeof(MultiUnorderedConstructorType))] public void SelectMethodsFromTypeReturnsAllAppropriateResults(Type type) { // Arrange var expectedConstructors = from ci in type.GetConstructors() let parameters = ci.GetParameters() select new ConstructorMethod(ci) as IMethod; var sut = new ListFavoringConstructorQuery(); // Act var result = sut.SelectMethods(type); // Assert Assert.True(expectedConstructors.All(m => result.Any(m.Equals))); } [Theory] [InlineData(typeof(Collection<object>))] [InlineData(typeof(Collection<string>))] [InlineData(typeof(Collection<int>))] [InlineData(typeof(Collection<Version>))] public void SelectMethodsFromTypeReturnsFirstMethodThatTakesListAsArgument(Type type) { // Arrange var sut = new ListFavoringConstructorQuery(); // Act var result = sut.SelectMethods(type); // Assert var genericParameterType = type.GetGenericArguments().Single(); Assert.Contains(result.First().Parameters, p => typeof(IList<>).MakeGenericType(genericParameterType).IsAssignableFrom(p.ParameterType)); } [Theory] [InlineData(typeof(SingleParameterType<object>))] [InlineData(typeof(ConcreteType))] [InlineData(typeof(MultiUnorderedConstructorType))] [InlineData(typeof(ItemHolder<object>))] public void SelectMethodsFromTypeReturnsCorrectlyOrderedResultWhenNoConstructorContainsEnumerableArguments(Type type) { // Arrange var expectedConstructors = from ci in type.GetConstructors() let parameters = ci.GetParameters() orderby parameters.Length ascending select new ConstructorMethod(ci) as IMethod; var sut = new ListFavoringConstructorQuery(); // Act var result = sut.SelectMethods(type); // Assert Assert.True(expectedConstructors.SequenceEqual(result)); } [Theory] [InlineData(typeof(ItemHolder<IList<object>, Collection<object>>))] [InlineData(typeof(ItemHolder<Collection<object>, IList<object>>))] public void SelectMethodsPrefersSpecificListParameterOverDerivedParameter(Type type) { // Arrange var sut = new ListFavoringConstructorQuery(); // Act var result = sut.SelectMethods(type); // Assert Assert.Contains(result.First().Parameters, p => typeof(IList<object>) == p.ParameterType); } [Fact] public void DoesNotReturnConstructorsWithParametersOfEnclosingType() { // Arrange var sut = new ListFavoringConstructorQuery(); // Act var result = sut.SelectMethods(typeof(TypeWithCopyConstructorsOnly)); // Assert Assert.Empty(result); }
ListFavoringConstructorQueryTest
csharp
dotnet__maui
src/BlazorWebView/src/Maui/Android/WebKitWebViewClient.cs
{ "start": 7657, "end": 8044 }
private class ____ : Java.Lang.Object, IValueCallback { private readonly Action<Java.Lang.Object?> _callback; public JavaScriptValueCallback(Action<Java.Lang.Object?> callback) { ArgumentNullException.ThrowIfNull(callback); _callback = callback; } public void OnReceiveValue(Java.Lang.Object? value) { _callback(value); } } } }
JavaScriptValueCallback
csharp
AutoMapper__AutoMapper
src/IntegrationTests/ExplicitExpansion/ProjectionWithExplicitExpansion.cs
{ "start": 8743, "end": 8909 }
public class ____(DatabaseFixture databaseFixture) : IntegrationTest<ConstructorExplicitExpansion.DatabaseInitializer>(databaseFixture) {
ConstructorExplicitExpansion
csharp
jellyfin__jellyfin
src/Jellyfin.Database/Jellyfin.Database.Implementations/Entities/Libraries/MovieMetadata.cs
{ "start": 290, "end": 2084 }
public class ____ : ItemMetadata, IHasCompanies { /// <summary> /// Initializes a new instance of the <see cref="MovieMetadata"/> class. /// </summary> /// <param name="title">The title or name of the movie.</param> /// <param name="language">ISO-639-3 3-character language codes.</param> public MovieMetadata(string title, string language) : base(title, language) { Studios = new HashSet<Company>(); } /// <summary> /// Gets or sets the outline. /// </summary> /// <remarks> /// Max length = 1024. /// </remarks> [MaxLength(1024)] [StringLength(1024)] public string? Outline { get; set; } /// <summary> /// Gets or sets the tagline. /// </summary> /// <remarks> /// Max length = 1024. /// </remarks> [MaxLength(1024)] [StringLength(1024)] public string? Tagline { get; set; } /// <summary> /// Gets or sets the plot. /// </summary> /// <remarks> /// Max length = 65535. /// </remarks> [MaxLength(65535)] [StringLength(65535)] public string? Plot { get; set; } /// <summary> /// Gets or sets the country code. /// </summary> /// <remarks> /// Max length = 2. /// </remarks> [MaxLength(2)] [StringLength(2)] public string? Country { get; set; } /// <summary> /// Gets the studios that produced this movie. /// </summary> public virtual ICollection<Company> Studios { get; private set; } /// <inheritdoc /> public ICollection<Company> Companies => Studios; } }
MovieMetadata
csharp
MaterialDesignInXAML__MaterialDesignInXamlToolkit
src/MaterialDesignThemes.Wpf/CustomPopupPlacementCallbackHelper.cs
{ "start": 38, "end": 383 }
public static class ____ { public static readonly CustomPopupPlacementCallback LargePopupCallback; static CustomPopupPlacementCallbackHelper() { LargePopupCallback = (size, targetSize, offset) => new[] { new CustomPopupPlacement(new Point(), PopupPrimaryAxis.Horizontal) }; } }
CustomPopupPlacementCallbackHelper
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.Inventory/Areas/Inventory/Controllers/StockApiController.cs
{ "start": 655, "end": 6154 }
public class ____ : Controller { private readonly IRepository<Stock> _stockRepository; private readonly IStockService _stockService; private readonly IStockSubscriptionService _stockSubscriptionService; private readonly IWorkContext _workContext; private readonly IRepository<Warehouse> _warehouseRepository; private readonly IRepository<StockHistory> _stockHistoryRepository; private readonly IRepository<ProductBackInStockSubscription> _backInStockSubscriptionRepository; public StockApiController(IRepository<Stock> stockRepository, IStockService stockService, IWorkContext workContext, IRepository<Warehouse> warehouseRepository, IRepository<StockHistory> stockHistoryRepository, IRepository<ProductBackInStockSubscription> backInStockSubscriptionRepository, IStockSubscriptionService stockSubscriptionService) { _stockRepository = stockRepository; _stockService = stockService; _workContext = workContext; _warehouseRepository = warehouseRepository; _stockHistoryRepository = stockHistoryRepository; _backInStockSubscriptionRepository = backInStockSubscriptionRepository; _stockSubscriptionService = stockSubscriptionService; } [HttpPost("grid")] public async Task<IActionResult> List(long warehouseId, [FromBody] SmartTableParam param) { var currentUser = await _workContext.GetCurrentUser(); var warehouse = _warehouseRepository.Query().FirstOrDefault(x => x.Id == warehouseId); if(warehouse == null) { return NotFound(); } if (!User.IsInRole("admin") && warehouse.VendorId != currentUser.VendorId) { return BadRequest(new { error = "You don't have permission to manage this warehouse" }); } var query = _stockRepository.Query().Where(x => x.WarehouseId == warehouseId && !x.Product.HasOptions && !x.Product.IsDeleted); if (param.Search.PredicateObject != null) { dynamic search = param.Search.PredicateObject; if (search.ProductName != null) { string productName = search.ProductName; query = query.Where(x => x.Product.Name.Contains(productName)); } if (search.ProductSku != null) { string productSku = search.productSku; query = query.Where(x => x.Product.Sku.Contains(productSku)); } } var products = query.ToSmartTableResult( param, x => new { x.Id, x.ProductId, ProductName = x.Product.Name, ProductSku = x.Product.Sku, x.Quantity, AdjustedQuantity = 0 }); return Ok(products); } [HttpPut] public async Task<IActionResult> Put(long warehouseId, [FromBody] IList<StockVm> stockVms) { var currentUser = await _workContext.GetCurrentUser(); var warehouse = _warehouseRepository.Query().FirstOrDefault(x => x.Id == warehouseId); if (warehouse == null) { return NotFound(); } if (!User.IsInRole("admin") && warehouse.VendorId != currentUser.VendorId) { return BadRequest(new { error = "You don't have permission to manage this warehouse" }); } foreach(var item in stockVms) { if(item.AdjustedQuantity == 0) { continue; } var stockUpdateRequest = new StockUpdateRequest { WarehouseId = warehouseId, ProductId = item.ProductId, AdjustedQuantity = item.AdjustedQuantity, Note = item.Note, UserId = currentUser.Id }; await _stockService.UpdateStock(stockUpdateRequest); } return Accepted(); } [HttpGet("history")] public async Task<IActionResult> GetStockHistory(int warehouseId, int productId) { var query = _stockHistoryRepository.Query(); query = query.Where(x => x.WarehouseId == warehouseId && x.ProductId == productId); var stockHistory = await query.Select(x => new { x.Id, x.Product.Name, x.CreatedOn, x.CreatedBy.FullName, x.AdjustedQuantity, x.Note }).ToListAsync(); return Ok(stockHistory); } [AllowAnonymous] [HttpPost("back-in-stock")] public async Task<IActionResult> BackInStockSubscribe(long productId, string customerEmail) { if (await _backInStockSubscriptionRepository.Query() .AnyAsync(o => o.ProductId == productId && o.CustomerEmail == customerEmail)) { return Conflict(); } await _stockSubscriptionService.ProductBackInStockSubscribeAsync(productId, customerEmail); return Ok(); } } }
StockApiController
csharp
Testably__Testably.Abstractions
Tests/Helpers/Testably.Abstractions.Tests.SourceGenerator/SourceGenerationHelper.TimeSystem.cs
{ "start": 154, "end": 2213 }
partial class ____ { public static string GenerateTimeSystemTestClasses(ClassModel model) { StringBuilder? sb = GetSourceBuilder(); sb.AppendLine($$""" using Testably.Abstractions.TestHelpers; using Testably.Abstractions.TestHelpers.Settings; namespace {{model.Namespace}} { public abstract partial class {{model.Name}} { /// <summary> /// The delay in milliseconds when wanting to ensure a timeout in the test. /// </summary> public const int EnsureTimeout = 500; /// <summary> /// The delay in milliseconds when expecting a success in the test. /// </summary> public const int ExpectSuccess = 30000; /// <summary> /// The delay in milliseconds when expecting a timeout in the test. /// </summary> public const int ExpectTimeout = 30; public ITimeSystem TimeSystem { get; } protected {{model.Name}}(ITimeSystem timeSystem) { TimeSystem = timeSystem; } /// <summary> /// Specifies, if brittle tests should be skipped on the real time system. /// </summary> /// <param name="condition"> /// (optional) A condition that must be <see langword="true" /> for the test to be skipped on the /// real time system. /// </param> public abstract void SkipIfBrittleTestsShouldBeSkipped(bool condition = true); // ReSharper disable once UnusedMember.Global
SourceGenerationHelper
csharp
microsoft__FASTER
cs/benchmark/Functions.cs
{ "start": 216, "end": 4552 }
public struct ____ : IFunctions<Key, Value, Input, Output, Empty> { public void RMWCompletionCallback(ref Key key, ref Input input, ref Output output, Empty ctx, Status status, RecordMetadata recordMetadata) { } public void ReadCompletionCallback(ref Key key, ref Input input, ref Output output, Empty ctx, Status status, RecordMetadata recordMetadata) { } public void CheckpointCompletionCallback(int sessionID, string sessionName, CommitPoint commitPoint) { Debug.WriteLine($"Session {sessionID} ({(sessionName ?? "null")}) reports persistence until {commitPoint.UntilSerialNo}"); } // Read functions [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool SingleReader(ref Key key, ref Input input, ref Value value, ref Output dst, ref ReadInfo readInfo) { dst.value = value; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ConcurrentReader(ref Key key, ref Input input, ref Value value, ref Output dst, ref ReadInfo readInfo) { dst.value = value; return true; } public bool SingleDeleter(ref Key key, ref Value value, ref DeleteInfo deleteInfo) { value = default; return true; } public bool ConcurrentDeleter(ref Key key, ref Value value, ref DeleteInfo deleteInfo) => true; // Upsert functions [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool SingleWriter(ref Key key, ref Input input, ref Value src, ref Value dst, ref Output output, ref UpsertInfo upsertInfo, WriteReason reason) { dst = src; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool ConcurrentWriter(ref Key key, ref Input input, ref Value src, ref Value dst, ref Output output, ref UpsertInfo upsertInfo) { dst = src; return true; } // RMW functions [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool InitialUpdater(ref Key key, ref Input input, ref Value value, ref Output output, ref RMWInfo rmwInfo) { value.value = input.value; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool InPlaceUpdater(ref Key key, ref Input input, ref Value value, ref Output output, ref RMWInfo rmwInfo) { value.value += input.value; return true; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CopyUpdater(ref Key key, ref Input input, ref Value oldValue, ref Value newValue, ref Output output, ref RMWInfo rmwInfo) { newValue.value = input.value + oldValue.value; return true; } public void PostCopyUpdater(ref Key key, ref Input input, ref Value oldValue, ref Value newValue, ref Output output, ref RMWInfo rmwInfo) { } public bool NeedInitialUpdate(ref Key key, ref Input input, ref Output output, ref RMWInfo rmwInfo) => true; public void PostInitialUpdater(ref Key key, ref Input input, ref Value value, ref Output output, ref RMWInfo rmwInfo) { } public bool NeedCopyUpdate(ref Key key, ref Input input, ref Value oldValue, ref Output output, ref RMWInfo rmwInfo) => true; public void PostSingleDeleter(ref Key key, ref DeleteInfo deleteInfo) { } public void PostSingleWriter(ref Key key, ref Input input, ref Value src, ref Value dst, ref Output output, ref UpsertInfo upsertInfo, WriteReason reason) { } public void DisposeSingleWriter(ref Key key, ref Input input, ref Value src, ref Value dst, ref Output output, ref UpsertInfo upsertInfo, WriteReason reason) { } public void DisposeCopyUpdater(ref Key key, ref Input input, ref Value oldValue, ref Value newValue, ref Output output, ref RMWInfo rmwInfo) { } public void DisposeInitialUpdater(ref Key key, ref Input input, ref Value value, ref Output output, ref RMWInfo rmwInfo) { } public void DisposeSingleDeleter(ref Key key, ref Value value, ref DeleteInfo deleteInfo) { } public void DisposeDeserializedFromDisk(ref Key key, ref Value value) { } } }
Functions