language stringclasses 1 value | repo stringclasses 133 values | path stringlengths 13 229 | class_span dict | source stringlengths 14 2.92M | target stringlengths 1 153 |
|---|---|---|---|---|---|
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.Driver.Tests/AggregateFluentFacetTests.cs | {
"start": 26720,
"end": 27179
} | private class ____
{
[BsonElement("categorizedByTags")]
public CategorizedByTag[] CategorizedByTags { get; set; }
[BsonElement("categorizedByYears")]
public CategorizedByYear[] CategorizedByYears { get; set; }
[BsonElement("categorizedByYears(Auto)")]
public CategorizedByYearAuto[] CategorizedByYearsAuto { get; set; }
}
| CategorizedByTagsAndYearsAndYearsAutoResults |
csharp | MassTransit__MassTransit | src/Transports/MassTransit.EventHubIntegration/EventHubIntegration/IConnectionContextSupervisor.cs | {
"start": 72,
"end": 182
} | public interface ____ :
ITransportSupervisor<ConnectionContext>
{
}
}
| IConnectionContextSupervisor |
csharp | dotnet__aspnetcore | src/Components/test/testassets/BasicTestApp/FormsTest/CustomFieldCssClassProvider.cs | {
"start": 342,
"end": 478
} | class ____. It isn't very efficient (it does reflection
// and allocates on every invocation) but is sufficient for testing purposes.
| names |
csharp | dotnet__extensions | test/Libraries/Microsoft.Extensions.DataIngestion.Tests/Chunkers/SemanticSimilarityChunkerTests.cs | {
"start": 378,
"end": 12431
} | public class ____ : DocumentChunkerTests
{
protected override IngestionChunker<string> CreateDocumentChunker(int maxTokensPerChunk = 2_000, int overlapTokens = 500)
{
#pragma warning disable CA2000 // Dispose objects before losing scope
TestEmbeddingGenerator embeddingClient = new();
#pragma warning restore CA2000 // Dispose objects before losing scope
return CreateSemanticSimilarityChunker(embeddingClient, maxTokensPerChunk, overlapTokens);
}
private static IngestionChunker<string> CreateSemanticSimilarityChunker(TestEmbeddingGenerator embeddingClient, int maxTokensPerChunk = 2_000, int overlapTokens = 500)
{
Tokenizer tokenizer = TiktokenTokenizer.CreateForModel("gpt-4o");
return new SemanticSimilarityChunker(embeddingClient,
new(tokenizer) { MaxTokensPerChunk = maxTokensPerChunk, OverlapTokens = overlapTokens });
}
[Fact]
public async Task SingleParagraph()
{
string text = ".NET is a free, cross-platform, open-source developer platform for building many " +
"kinds of applications. It can run programs written in multiple languages, with C# being the most popular. " +
"It relies on a high-performance runtime that is used in production by many high-scale apps.";
IngestionDocument doc = new IngestionDocument("doc");
doc.Sections.Add(new IngestionDocumentSection
{
Elements =
{
new IngestionDocumentParagraph(text)
}
});
using TestEmbeddingGenerator customGenerator = new()
{
GenerateAsyncCallback = static async (values, options, ct) =>
{
var embeddings = values.Select(v =>
new Embedding<float>(new float[] { 1.0f, 2.0f, 3.0f, 4.0f }))
.ToArray();
return [.. embeddings];
}
};
IngestionChunker<string> chunker = CreateSemanticSimilarityChunker(customGenerator);
IReadOnlyList<IngestionChunk<string>> chunks = await chunker.ProcessAsync(doc).ToListAsync();
Assert.Single(chunks);
Assert.Equal(text, chunks[0].Content);
}
[Fact]
public async Task TwoTopicsParagraphs()
{
IngestionDocument doc = new IngestionDocument("doc");
string text1 = ".NET is a free, cross-platform, open-source developer platform for building many" +
"kinds of applications. It can run programs written in multiple languages, with C# being the most popular.";
string text2 = "It relies on a high-performance runtime that is used in production by many high-scale apps.";
string text3 = "Zeus is the chief deity of the Greek pantheon. He is a sky and thunder god in ancient Greek religion and mythology.";
doc.Sections.Add(new IngestionDocumentSection
{
Elements =
{
new IngestionDocumentParagraph(text1),
new IngestionDocumentParagraph(text2),
new IngestionDocumentParagraph(text3)
}
});
using var customGenerator = new TestEmbeddingGenerator
{
GenerateAsyncCallback = async (values, options, ct) =>
{
var embeddings = values.Select((_, index) =>
{
return index switch
{
0 => new Embedding<float>(new float[] { 1.0f, 1.0f, 1.0f, 1.0f }),
1 => new Embedding<float>(new float[] { 1.0f, 1.0f, 1.0f, 1.0f }),
2 => new Embedding<float>(new float[] { -1.0f, -1.0f, -1.0f, -1.0f }),
_ => throw new InvalidOperationException("Unexpected call count")
};
}).ToArray();
return [.. embeddings];
}
};
IngestionChunker<string> chunker = CreateSemanticSimilarityChunker(customGenerator);
IReadOnlyList<IngestionChunk<string>> chunks = await chunker.ProcessAsync(doc).ToListAsync();
Assert.Equal(2, chunks.Count);
Assert.Equal(text1 + Environment.NewLine + text2, chunks[0].Content);
Assert.Equal(text3, chunks[1].Content);
}
[Fact]
public async Task TwoSeparateTopicsWithAllKindsOfElements()
{
string dotNetTableMarkdown = """
| Language | Type | Status |
| --- | --- | --- |
| C# | Object-oriented | Primary |
| F# | Functional | Official |
| Visual Basic | Object-oriented | Official |
| PowerShell | Scripting | Supported |
| IronPython | Dynamic | Community |
| IronRuby | Dynamic | Community |
| Boo | Object-oriented | Community |
| Nemerle | Functional/OOP | Community |
""";
string godsTableMarkdown = """
| God | Domain | Symbol | Roman Name |
| --- | --- | --- | --- |
| Zeus | Sky & Thunder | Lightning Bolt | Jupiter |
| Hera | Marriage & Family | Peacock | Juno |
| Poseidon | Sea & Earthquakes | Trident | Neptune |
| Athena | Wisdom & War | Owl | Minerva |
| Apollo | Sun & Music | Lyre | Apollo |
| Artemis | Hunt & Moon | Silver Bow | Diana |
| Aphrodite | Love & Beauty | Dove | Venus |
| Ares | War & Courage | Spear | Mars |
| Hephaestus | Fire & Forge | Hammer | Vulcan |
| Demeter | Harvest & Nature | Wheat | Ceres |
| Dionysus | Wine & Festivity | Grapes | Bacchus |
| Hermes | Messages & Trade | Caduceus | Mercury |
""";
IngestionDocument doc = new("dotnet-languages");
doc.Sections.Add(new IngestionDocumentSection
{
Elements =
{
new IngestionDocumentHeader("# .NET Supported Languages") { Level = 1 },
new IngestionDocumentParagraph("The .NET platform supports multiple programming languages:"),
new IngestionDocumentTable(dotNetTableMarkdown,
ToParagraphCells(CreateLanguageTableCells())),
new IngestionDocumentParagraph("C# remains the most popular language for .NET development."),
new IngestionDocumentHeader("# Ancient Greek Olympian Gods") { Level = 1 },
new IngestionDocumentParagraph("The twelve Olympian gods were the principal deities of the Greek pantheon:"),
new IngestionDocumentTable(godsTableMarkdown,
ToParagraphCells(CreateGreekGodsTableCells())),
new IngestionDocumentParagraph("These gods resided on Mount Olympus and ruled over different aspects of mortal and divine life.")
}
});
using var customGenerator = new TestEmbeddingGenerator
{
GenerateAsyncCallback = async (values, options, ct) =>
{
var embeddings = values.Select((_, index) =>
{
return index switch
{
<= 3 => new Embedding<float>(new float[] { 1.0f, 1.0f, 1.0f, 1.0f }),
>= 4 and <= 7 => new Embedding<float>(new float[] { -1.0f, -1.0f, -1.0f, -1.0f }),
_ => throw new InvalidOperationException($"Unexpected index: {index}")
};
}).ToArray();
return [.. embeddings];
}
};
IngestionChunker<string> chunker = CreateSemanticSimilarityChunker(customGenerator, 200, 0);
IReadOnlyList<IngestionChunk<string>> chunks = await chunker.ProcessAsync(doc).ToListAsync();
Assert.Equal(3, chunks.Count);
Assert.All(chunks, chunk => Assert.Same(doc, chunk.Document));
Assert.Equal($@"# .NET Supported Languages
The .NET platform supports multiple programming languages:
{dotNetTableMarkdown}
C# remains the most popular language for .NET development.",
chunks[0].Content, ignoreLineEndingDifferences: true);
Assert.Equal($@"# Ancient Greek Olympian Gods
The twelve Olympian gods were the principal deities of the Greek pantheon:
| God | Domain | Symbol | Roman Name |
| --- | --- | --- | --- |
| Zeus | Sky & Thunder | Lightning Bolt | Jupiter |
| Hera | Marriage & Family | Peacock | Juno |
| Poseidon | Sea & Earthquakes | Trident | Neptune |
| Athena | Wisdom & War | Owl | Minerva |
| Apollo | Sun & Music | Lyre | Apollo |
| Artemis | Hunt & Moon | Silver Bow | Diana |
| Aphrodite | Love & Beauty | Dove | Venus |
| Ares | War & Courage | Spear | Mars |
| Hephaestus | Fire & Forge | Hammer | Vulcan |
| Demeter | Harvest & Nature | Wheat | Ceres |
| Dionysus | Wine & Festivity | Grapes | Bacchus |",
chunks[1].Content, ignoreLineEndingDifferences: true);
Assert.Equal("""
| God | Domain | Symbol | Roman Name |
| --- | --- | --- | --- |
| Hermes | Messages & Trade | Caduceus | Mercury |
These gods resided on Mount Olympus and ruled over different aspects of mortal and divine life.
""", chunks[2].Content, ignoreLineEndingDifferences: true);
static string[,] CreateGreekGodsTableCells() => new string[,]
{
{ "God", "Domain", "Symbol", "Roman Name" },
{ "Zeus", "Sky & Thunder", "Lightning Bolt", "Jupiter" },
{ "Hera", "Marriage & Family", "Peacock", "Juno" },
{ "Poseidon", "Sea & Earthquakes", "Trident", "Neptune" },
{ "Athena", "Wisdom & War", "Owl", "Minerva" },
{ "Apollo", "Sun & Music", "Lyre", "Apollo" },
{ "Artemis", "Hunt & Moon", "Silver Bow", "Diana" },
{ "Aphrodite", "Love & Beauty", "Dove", "Venus" },
{ "Ares", "War & Courage", "Spear", "Mars" },
{ "Hephaestus", "Fire & Forge", "Hammer", "Vulcan" },
{ "Demeter", "Harvest & Nature", "Wheat", "Ceres" },
{ "Dionysus", "Wine & Festivity", "Grapes", "Bacchus" },
{ "Hermes", "Messages & Trade", "Caduceus", "Mercury" }
};
static string[,] CreateLanguageTableCells() => new string[,]
{
{ "Language", "Type", "Status" },
{ "C#", "Object-oriented", "Primary" },
{ "F#", "Functional", "Official" },
{ "Visual Basic", "Object-oriented", "Official" },
{ "PowerShell", "Scripting", "Supported" },
{ "IronPython", "Dynamic", "Community" },
{ "IronRuby", "Dynamic", "Community" },
{ "Boo", "Object-oriented", "Community" },
{ "Nemerle", "Functional/OOP", "Community" }
};
}
private static IngestionDocumentParagraph?[,] ToParagraphCells(string[,] cells)
{
int rows = cells.GetLength(0);
int cols = cells.GetLength(1);
var result = new IngestionDocumentParagraph?[rows, cols];
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
result[i, j] = new IngestionDocumentParagraph(cells[i, j]);
}
}
return result;
}
}
}
| SemanticSimilarityChunkerTests |
csharp | nuke-build__nuke | source/Nuke.Components/IHazGitVersion.cs | {
"start": 295,
"end": 474
} | public interface ____ : INukeBuild
{
[GitVersion(NoFetch = true, Framework = "net8.0")]
[Required]
GitVersion Versioning => TryGetValue(() => Versioning);
}
| IHazGitVersion |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Automation.Peers/SelectorAutomationPeer.cs | {
"start": 269,
"end": 2848
} | public partial class ____ : global::Microsoft.UI.Xaml.Automation.Peers.ItemsControlAutomationPeer, global::Microsoft.UI.Xaml.Automation.Provider.ISelectionProvider
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public bool CanSelectMultiple
{
get
{
throw new global::System.NotImplementedException("The member bool SelectorAutomationPeer.CanSelectMultiple is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20SelectorAutomationPeer.CanSelectMultiple");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public bool IsSelectionRequired
{
get
{
throw new global::System.NotImplementedException("The member bool SelectorAutomationPeer.IsSelectionRequired is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20SelectorAutomationPeer.IsSelectionRequired");
}
}
#endif
// Skipping already declared method Microsoft.UI.Xaml.Automation.Peers.SelectorAutomationPeer.SelectorAutomationPeer(Microsoft.UI.Xaml.Controls.Primitives.Selector)
// Forced skipping of method Microsoft.UI.Xaml.Automation.Peers.SelectorAutomationPeer.SelectorAutomationPeer(Microsoft.UI.Xaml.Controls.Primitives.Selector)
// Forced skipping of method Microsoft.UI.Xaml.Automation.Peers.SelectorAutomationPeer.CanSelectMultiple.get
// Forced skipping of method Microsoft.UI.Xaml.Automation.Peers.SelectorAutomationPeer.IsSelectionRequired.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Microsoft.UI.Xaml.Automation.Provider.IRawElementProviderSimple[] GetSelection()
{
throw new global::System.NotImplementedException("The member IRawElementProviderSimple[] SelectorAutomationPeer.GetSelection() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IRawElementProviderSimple%5B%5D%20SelectorAutomationPeer.GetSelection%28%29");
}
#endif
// Processing: Microsoft.UI.Xaml.Automation.Provider.ISelectionProvider
}
}
| SelectorAutomationPeer |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/IL/Instructions.cs | {
"start": 66290,
"end": 67088
} | partial class ____ : BinaryInstruction
{
public override void AcceptVisitor(ILVisitor visitor)
{
visitor.VisitComp(this);
}
public override T AcceptVisitor<T>(ILVisitor<T> visitor)
{
return visitor.VisitComp(this);
}
public override T AcceptVisitor<C, T>(ILVisitor<C, T> visitor, C context)
{
return visitor.VisitComp(this, context);
}
protected internal override bool PerformMatch(ILInstruction? other, ref Patterns.Match match)
{
var o = other as Comp;
return o != null && this.Left.PerformMatch(o.Left, ref match) && this.Right.PerformMatch(o.Right, ref match) && this.Kind == o.Kind && this.Sign == o.Sign && this.LiftingKind == o.LiftingKind;
}
}
}
namespace ICSharpCode.Decompiler.IL
{
/// <summary>Non-virtual method call.</summary>
public sealed | Comp |
csharp | unoplatform__uno | src/Uno.UI/Generated/3.0.0.0/Microsoft.UI.Xaml.Controls/Expander.cs | {
"start": 261,
"end": 3060
} | public partial class ____ : global::Microsoft.UI.Xaml.Controls.ContentControl
{
// Skipping already declared property IsExpanded
// Skipping already declared property HeaderTemplateSelector
// Skipping already declared property HeaderTemplate
// Skipping already declared property Header
// Skipping already declared property ExpandDirection
// Skipping already declared property TemplateSettings
// Skipping already declared property ExpandDirectionProperty
// Skipping already declared property HeaderProperty
// Skipping already declared property HeaderTemplateProperty
// Skipping already declared property HeaderTemplateSelectorProperty
// Skipping already declared property IsExpandedProperty
// Skipping already declared method Microsoft.UI.Xaml.Controls.Expander.Expander()
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.Expander()
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.Header.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.Header.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.HeaderTemplate.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.HeaderTemplate.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.HeaderTemplateSelector.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.HeaderTemplateSelector.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.IsExpanded.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.IsExpanded.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.ExpandDirection.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.ExpandDirection.set
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.Expanding.add
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.Expanding.remove
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.Collapsed.add
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.Collapsed.remove
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.TemplateSettings.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.HeaderProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.HeaderTemplateProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.HeaderTemplateSelectorProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.IsExpandedProperty.get
// Forced skipping of method Microsoft.UI.Xaml.Controls.Expander.ExpandDirectionProperty.get
// Skipping already declared event Microsoft.UI.Xaml.Controls.Expander.Collapsed
// Skipping already declared event Microsoft.UI.Xaml.Controls.Expander.Expanding
}
}
| Expander |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Web.Http/HttpVersion.cs | {
"start": 254,
"end": 791
} | public enum ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
None = 0,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Http10 = 1,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Http11 = 2,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
Http20 = 3,
#endif
}
#endif
}
| HttpVersion |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/src/Fusion.Execution.Types/Completion/AggregateCompositeTypeInterceptor.cs | {
"start": 134,
"end": 1486
} | internal sealed class ____ : CompositeTypeInterceptor
{
private readonly CompositeTypeInterceptor[] _interceptors;
public AggregateCompositeTypeInterceptor(CompositeTypeInterceptor[] interceptors)
{
ArgumentNullException.ThrowIfNull(interceptors);
_interceptors = interceptors;
}
public override void OnBeforeCompleteSchema(
ICompositeSchemaBuilderContext context,
ref IFeatureCollection features)
{
foreach (var interceptor in _interceptors)
{
interceptor.OnBeforeCompleteSchema(context, ref features);
}
}
public override void OnCompleteOutputField(
ICompositeSchemaBuilderContext context,
IComplexTypeDefinition type,
IOutputFieldDefinition field,
OperationType? operationType,
ref IFeatureCollection features)
{
foreach (var interceptor in _interceptors)
{
interceptor.OnCompleteOutputField(context, type, field, operationType, ref features);
}
}
public override void OnAfterCompleteSchema(
ICompositeSchemaBuilderContext context,
FusionSchemaDefinition schema)
{
foreach (var interceptor in _interceptors)
{
interceptor.OnAfterCompleteSchema(context, schema);
}
}
}
| AggregateCompositeTypeInterceptor |
csharp | aspnetboilerplate__aspnetboilerplate | test/Abp.Tests/Json/SystemTextJson/AbpSystemTextJsonExtensions_Tests.cs | {
"start": 6197,
"end": 6526
} | public class ____ : AbpSystemTextJsonExtensions_Datetime_Kind_Tests
{
public AbpSystemTextJsonExtensionsDatetimeKindUnspecifiedTests()
{
Kind = DateTimeKind.Unspecified;
Clock.Provider = ClockProviders.Unspecified;;
}
}
}
| AbpSystemTextJsonExtensionsDatetimeKindUnspecifiedTests |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/XmlnsCollision.rt.xaml.cs | {
"start": 1179,
"end": 2647
} | class ____
{
[SetUp] public void Setup() => AppInfo.SetCurrent(new MockAppInfo());
[TearDown] public void TearDown() => AppInfo.SetCurrent(null);
[Test]
public void ConflictInXmlns([Values] XamlInflator inflator)
{
switch (inflator)
{
case XamlInflator.XamlC:
Assert.Throws<BuildException>(() =>
{
MockCompiler.Compile(typeof(XmlnsCollision), out var hasLoggedErrors);
Assert.IsTrue(hasLoggedErrors);
});
break;
case XamlInflator.SourceGen:
var result = CreateMauiCompilation()
.WithAdditionalSource(
"""
using System.Linq;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.Controls;
using Microsoft.Maui.Controls.Build.Tasks;
using Microsoft.Maui.Controls.Core.UnitTests;
using NUnit.Framework;
using static Microsoft.Maui.Controls.Xaml.UnitTests.MockSourceGenerator;
[assembly: XmlnsDefinition("http://companyone.com/schemas/toolkit", "CompanyOne.Controls")]
[assembly: XmlnsPrefix("http://companyone.com/schemas/toolkit", "c1")]
[assembly: XmlnsDefinition("http://companytwo.com/schemas/toolkit", "CompanyTwo.Controls")]
[assembly: XmlnsPrefix("http://companytwo.com/schemas/toolkit", "c2")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/dotnet/maui/global", "http://companyone.com/schemas/toolkit")]
[assembly: XmlnsDefinition("http://schemas.microsoft.com/dotnet/maui/global", "http://companytwo.com/schemas/toolkit")]
namespace CompanyOne.Controls
{
| Test |
csharp | dotnet__machinelearning | src/Microsoft.Data.Analysis/PrimitiveDataFrameColumn.BinaryOperators.cs | {
"start": 218736,
"end": 222274
} | public partial class ____
{
public static UInt32DataFrameColumn operator /(UInt32DataFrameColumn left, byte right)
{
return left.Divide(right);
}
public static UInt32DataFrameColumn operator /(byte left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static DecimalDataFrameColumn operator /(UInt32DataFrameColumn left, decimal right)
{
return left.Divide(right);
}
public static DecimalDataFrameColumn operator /(decimal left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static DoubleDataFrameColumn operator /(UInt32DataFrameColumn left, double right)
{
return left.Divide(right);
}
public static DoubleDataFrameColumn operator /(double left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static SingleDataFrameColumn operator /(UInt32DataFrameColumn left, float right)
{
return left.Divide(right);
}
public static SingleDataFrameColumn operator /(float left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static Int64DataFrameColumn operator /(UInt32DataFrameColumn left, int right)
{
return left.Divide(right);
}
public static Int64DataFrameColumn operator /(int left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static Int64DataFrameColumn operator /(UInt32DataFrameColumn left, long right)
{
return left.Divide(right);
}
public static Int64DataFrameColumn operator /(long left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static Int64DataFrameColumn operator /(UInt32DataFrameColumn left, sbyte right)
{
return left.Divide(right);
}
public static Int64DataFrameColumn operator /(sbyte left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static Int64DataFrameColumn operator /(UInt32DataFrameColumn left, short right)
{
return left.Divide(right);
}
public static Int64DataFrameColumn operator /(short left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static UInt32DataFrameColumn operator /(UInt32DataFrameColumn left, uint right)
{
return left.Divide(right);
}
public static UInt32DataFrameColumn operator /(uint left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static UInt64DataFrameColumn operator /(UInt32DataFrameColumn left, ulong right)
{
return left.Divide(right);
}
public static UInt64DataFrameColumn operator /(ulong left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
public static UInt32DataFrameColumn operator /(UInt32DataFrameColumn left, ushort right)
{
return left.Divide(right);
}
public static UInt32DataFrameColumn operator /(ushort left, UInt32DataFrameColumn right)
{
return right.ReverseDivide(left);
}
}
| UInt32DataFrameColumn |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.OpenApi.Tests/Services/CodeGenTestTypes.cs | {
"start": 3304,
"end": 3447
} | public class ____
{
[DataMember]
public string Result { get; set; }
}
[Route("/all-types")]
| HelloAnnotatedResponse |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/Zip.NAry.cs | {
"start": 73929,
"end": 80324
} | internal sealed class ____ : ZipSink<TResult>
{
private readonly Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> _resultSelector;
private readonly ZipObserver<T1> _observer1;
private readonly ZipObserver<T2> _observer2;
private readonly ZipObserver<T3> _observer3;
private readonly ZipObserver<T4> _observer4;
private readonly ZipObserver<T5> _observer5;
private readonly ZipObserver<T6> _observer6;
private readonly ZipObserver<T7> _observer7;
private readonly ZipObserver<T8> _observer8;
private readonly ZipObserver<T9> _observer9;
private readonly ZipObserver<T10> _observer10;
private readonly ZipObserver<T11> _observer11;
private readonly ZipObserver<T12> _observer12;
private readonly ZipObserver<T13> _observer13;
private readonly ZipObserver<T14> _observer14;
private readonly ZipObserver<T15> _observer15;
private readonly ZipObserver<T16> _observer16;
public _(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, TResult> resultSelector, IObserver<TResult> observer)
: base(16, observer)
{
_resultSelector = resultSelector;
_observer1 = new ZipObserver<T1>(_gate, this, 0);
_observer2 = new ZipObserver<T2>(_gate, this, 1);
_observer3 = new ZipObserver<T3>(_gate, this, 2);
_observer4 = new ZipObserver<T4>(_gate, this, 3);
_observer5 = new ZipObserver<T5>(_gate, this, 4);
_observer6 = new ZipObserver<T6>(_gate, this, 5);
_observer7 = new ZipObserver<T7>(_gate, this, 6);
_observer8 = new ZipObserver<T8>(_gate, this, 7);
_observer9 = new ZipObserver<T9>(_gate, this, 8);
_observer10 = new ZipObserver<T10>(_gate, this, 9);
_observer11 = new ZipObserver<T11>(_gate, this, 10);
_observer12 = new ZipObserver<T12>(_gate, this, 11);
_observer13 = new ZipObserver<T13>(_gate, this, 12);
_observer14 = new ZipObserver<T14>(_gate, this, 13);
_observer15 = new ZipObserver<T15>(_gate, this, 14);
_observer16 = new ZipObserver<T16>(_gate, this, 15);
}
public void Run(IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, IObservable<T7> source7, IObservable<T8> source8, IObservable<T9> source9, IObservable<T10> source10, IObservable<T11> source11, IObservable<T12> source12, IObservable<T13> source13, IObservable<T14> source14, IObservable<T15> source15, IObservable<T16> source16)
{
var disposables = new IDisposable[16];
disposables[0] = _observer1;
Queues[0] = _observer1.Values;
disposables[1] = _observer2;
Queues[1] = _observer2.Values;
disposables[2] = _observer3;
Queues[2] = _observer3.Values;
disposables[3] = _observer4;
Queues[3] = _observer4.Values;
disposables[4] = _observer5;
Queues[4] = _observer5.Values;
disposables[5] = _observer6;
Queues[5] = _observer6.Values;
disposables[6] = _observer7;
Queues[6] = _observer7.Values;
disposables[7] = _observer8;
Queues[7] = _observer8.Values;
disposables[8] = _observer9;
Queues[8] = _observer9.Values;
disposables[9] = _observer10;
Queues[9] = _observer10.Values;
disposables[10] = _observer11;
Queues[10] = _observer11.Values;
disposables[11] = _observer12;
Queues[11] = _observer12.Values;
disposables[12] = _observer13;
Queues[12] = _observer13.Values;
disposables[13] = _observer14;
Queues[13] = _observer14.Values;
disposables[14] = _observer15;
Queues[14] = _observer15.Values;
disposables[15] = _observer16;
Queues[15] = _observer16.Values;
_observer1.SetResource(source1.SubscribeSafe(_observer1));
_observer2.SetResource(source2.SubscribeSafe(_observer2));
_observer3.SetResource(source3.SubscribeSafe(_observer3));
_observer4.SetResource(source4.SubscribeSafe(_observer4));
_observer5.SetResource(source5.SubscribeSafe(_observer5));
_observer6.SetResource(source6.SubscribeSafe(_observer6));
_observer7.SetResource(source7.SubscribeSafe(_observer7));
_observer8.SetResource(source8.SubscribeSafe(_observer8));
_observer9.SetResource(source9.SubscribeSafe(_observer9));
_observer10.SetResource(source10.SubscribeSafe(_observer10));
_observer11.SetResource(source11.SubscribeSafe(_observer11));
_observer12.SetResource(source12.SubscribeSafe(_observer12));
_observer13.SetResource(source13.SubscribeSafe(_observer13));
_observer14.SetResource(source14.SubscribeSafe(_observer14));
_observer15.SetResource(source15.SubscribeSafe(_observer15));
_observer16.SetResource(source16.SubscribeSafe(_observer16));
SetUpstream(StableCompositeDisposable.CreateTrusted(disposables));
}
protected override TResult GetResult() => _resultSelector(_observer1.Values.Dequeue(), _observer2.Values.Dequeue(), _observer3.Values.Dequeue(), _observer4.Values.Dequeue(), _observer5.Values.Dequeue(), _observer6.Values.Dequeue(), _observer7.Values.Dequeue(), _observer8.Values.Dequeue(), _observer9.Values.Dequeue(), _observer10.Values.Dequeue(), _observer11.Values.Dequeue(), _observer12.Values.Dequeue(), _observer13.Values.Dequeue(), _observer14.Values.Dequeue(), _observer15.Values.Dequeue(), _observer16.Values.Dequeue());
}
}
#endregion
#endregion
}
| _ |
csharp | cake-build__cake | src/Cake.Testing/Fixtures/ToolFixture`2.cs | {
"start": 580,
"end": 4705
} | public abstract class ____<TToolSettings, TFixtureResult>
where TToolSettings : ToolSettings, new()
where TFixtureResult : ToolFixtureResult
{
/// <summary>
/// Gets or sets the file system.
/// </summary>
/// <value>The file system.</value>
public FakeFileSystem FileSystem { get; set; }
/// <summary>
/// Gets or sets the process runner.
/// </summary>
/// <value>The process runner.</value>
public ToolFixtureProcessRunner<TFixtureResult> ProcessRunner { get; set; }
/// <summary>
/// Gets or sets the environment.
/// </summary>
/// <value>The environment.</value>
public FakeEnvironment Environment { get; set; }
/// <summary>
/// Gets or sets the globber.
/// </summary>
/// <value>The globber.</value>
public IGlobber Globber { get; set; }
/// <summary>
/// Gets or sets the configuration.
/// </summary>
/// <value>The configuration.</value>
public FakeConfiguration Configuration { get; set; }
/// <summary>
/// Gets or sets the tool locator.
/// </summary>
/// <value>The tool locator.</value>
public IToolLocator Tools { get; set; }
/// <summary>
/// Gets or sets the tool settings.
/// </summary>
/// <value>The tool settings.</value>
public TToolSettings Settings { get; set; }
/// <summary>
/// Gets the default tool path.
/// </summary>
/// <value>The default tool path.</value>
public FilePath DefaultToolPath { get; }
/// <summary>
/// Initializes a new instance of the <see cref="ToolFixture{TToolSettings, TFixtureResult}"/> class.
/// </summary>
/// <param name="toolFilename">The tool filename.</param>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
protected ToolFixture(string toolFilename)
{
Settings = new TToolSettings();
ProcessRunner = new ToolFixtureProcessRunner<TFixtureResult>(CreateResult);
Environment = FakeEnvironment.CreateUnixEnvironment();
FileSystem = new FakeFileSystem(Environment);
Globber = new Globber(FileSystem, Environment);
Configuration = new FakeConfiguration();
Tools = new ToolLocator(Environment, new ToolRepository(Environment), new ToolResolutionStrategy(FileSystem, Environment, Globber, Configuration, new NullLog()));
// ReSharper disable once VirtualMemberCallInConstructor
DefaultToolPath = GetDefaultToolPath(toolFilename);
FileSystem.CreateFile(DefaultToolPath);
}
/// <summary>
/// Gets the default tool path.
/// </summary>
/// <param name="toolFilename">The tool filename.</param>
/// <returns>The default tool path.</returns>
protected virtual FilePath GetDefaultToolPath(string toolFilename)
{
return new FilePath("./tools/" + toolFilename).MakeAbsolute(Environment);
}
/// <summary>
/// Runs the tool.
/// </summary>
/// <returns>The result from running the tool.</returns>
public TFixtureResult Run()
{
// Run the tool.
RunTool();
// Returned the intercepted result.
return ProcessRunner.Results.LastOrDefault();
}
/// <summary>
/// Creates the tool fixture result from the provided
/// tool path and process settings.
/// </summary>
/// <param name="path">The tool path.</param>
/// <param name="process">The process settings.</param>
/// <returns>A tool fixture result.</returns>
protected abstract TFixtureResult CreateResult(FilePath path, ProcessSettings process);
/// <summary>
/// Runs the tool.
/// </summary>
protected abstract void RunTool();
}
} | ToolFixture |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack/FluentValidation/DefaultValidatorExtensions_Validate.cs | {
"start": 953,
"end": 11122
} | partial class ____ {
/// <summary>
/// Validates the specified instance using a combination of extra options
/// </summary>
/// <param name="validator">The validator</param>
/// <param name="instance">The instance to validate</param>
/// <param name="options">Callback to configure additional options</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, Action<ValidationStrategy<T>> options) {
return validator.Validate(ValidationContext<T>.CreateWithOptions(instance, options));
}
/// <summary>
/// Validates the specified instance using a combination of extra options
/// </summary>
/// <param name="validator">The validator</param>
/// <param name="instance">The instance to validate</param>
/// <param name="cancellation">Cancellation token</param>
/// <param name="options">Callback to configure additional options</param>
/// <typeparam name="T"></typeparam>
/// <returns></returns>
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, Action<ValidationStrategy<T>> options, CancellationToken cancellation = default) {
return validator.ValidateAsync(ValidationContext<T>.CreateWithOptions(instance, options), cancellation);
}
/// <summary>
/// Performs validation and then throws an exception if validation fails.
/// This method is a shortcut for: Validate(instance, options => options.ThrowOnFailures());
/// </summary>
/// <param name="validator">The validator this method is extending.</param>
/// <param name="instance">The instance of the type we are validating.</param>
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance) {
validator.Validate(instance, options => {
options.ThrowOnFailures();
});
}
/// <summary>
/// Performs validation asynchronously and then throws an exception if validation fails.
/// This method is a shortcut for: ValidateAsync(instance, options => options.ThrowOnFailures());
/// </summary>
/// <param name="validator">The validator this method is extending.</param>
/// <param name="instance">The instance of the type we are validating.</param>
/// <param name="cancellationToken"></param>
public static async Task ValidateAndThrowAsync<T>(this IValidator<T> validator, T instance, CancellationToken cancellationToken = default) {
await validator.ValidateAsync(instance, options => {
options.ThrowOnFailures();
}, cancellationToken);
}
/// <summary>
/// Validates certain properties of the specified instance.
/// </summary>
/// <param name="validator">The current validator</param>
/// <param name="instance">The object to validate</param>
/// <param name="propertyExpressions">Expressions to specify the properties to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
[Obsolete("This method will be removed in FluentValidation 10. Instead use Validate(instance, options => options.IncludeProperties(expressions))")]
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, params Expression<Func<T, object>>[] propertyExpressions) {
return validator.Validate(instance, options => {
options.IncludeProperties(propertyExpressions);
});
}
/// <summary>
/// Validates certain properties of the specified instance.
/// </summary>
/// <param name="validator"></param>
/// <param name="instance">The object to validate</param>
/// <param name="properties">The names of the properties to validate.</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
[Obsolete("This method will be removed in FluentValidation 10. Instead use Validate(instance, options => options.IncludeProperties(properties))")]
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, params string[] properties) {
return validator.Validate(instance, options => {
options.IncludeProperties(properties);
});
}
/// <summary>
/// Validates an object using either a custom validator selector or a ruleset.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="validator"></param>
/// <param name="instance"></param>
/// <param name="selector"></param>
/// <param name="ruleSet"></param>
/// <returns></returns>
[Obsolete("This method will be removed in FluentValidation 10. Instead call Validate(instance, options => options.IncludeRuleSets(\"someRuleSet\",\"anotherRuleSet\")). Be sure to pass in separate strings rather than a comma-separated string.")]
public static ValidationResult Validate<T>(this IValidator<T> validator, T instance, IValidatorSelector selector = null, string ruleSet = null) {
return validator.Validate(instance, options => {
if (selector != null) {
options.UseCustomSelector(selector);
}
if (ruleSet != null) {
options.IncludeRuleSets(RulesetValidatorSelector.LegacyRulesetSplit(ruleSet));
}
});
}
/// <summary>
/// Validates certain properties of the specified instance asynchronously.
/// </summary>
/// <param name="validator">The current validator</param>
/// <param name="instance">The object to validate</param>
/// <param name="cancellationToken"></param>
/// <param name="propertyExpressions">Expressions to specify the properties to validate</param>
/// <returns>A ValidationResult object containing any validation failures</returns>
[Obsolete("This method will be removed in FluentValidation 10. Instead use ValidateAsync(instance, options => options.IncludeProperties(expressions), cancellationToken)")]
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, CancellationToken cancellationToken = default, params Expression<Func<T, object>>[] propertyExpressions) {
return validator.ValidateAsync(instance, options => options.IncludeProperties(propertyExpressions), cancellationToken);
}
/// <summary>
/// Validates certain properties of the specified instance asynchronously.
/// </summary>
/// <param name="validator"></param>
/// <param name="instance">The object to validate</param>
/// <param name="cancellationToken"></param>
/// <param name="properties">The names of the properties to validate.</param>
/// <returns>A ValidationResult object containing any validation failures.</returns>
[Obsolete("This method will be removed in FluentValidation 10. Instead use ValidateAsync(instance, options => options.IncludeProperties(properties), cancellationToken)")]
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, CancellationToken cancellationToken = default, params string[] properties) {
return validator.ValidateAsync(instance, options => options.IncludeProperties(properties), cancellationToken);
}
/// <summary>
/// Validates an object asynchronously using a custom validator selector or a ruleset
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="validator"></param>
/// <param name="instance"></param>
/// <param name="cancellationToken"></param>
/// <param name="selector"></param>
/// <param name="ruleSet"></param>
/// <returns></returns>
[Obsolete("This method will be removed in FluentValidation 10. Instead call ValidateAsync(instance, options => options.IncludeRuleSets(\"someRuleSet\",\"anotherRuleSet\"), cancellationToken). Be sure to pass in separate strings rather than a comma-separated string.")]
public static Task<ValidationResult> ValidateAsync<T>(this IValidator<T> validator, T instance, CancellationToken cancellationToken = default, IValidatorSelector selector = null, string ruleSet = null) {
return validator.ValidateAsync(instance, options => {
if (selector != null) {
options.UseCustomSelector(selector);
}
if (ruleSet != null) {
options.IncludeRuleSets(RulesetValidatorSelector.LegacyRulesetSplit(ruleSet));
}
}, cancellationToken);
}
/// <summary>
/// Performs validation and then throws an exception if validation fails.
/// </summary>
/// <param name="validator">The validator this method is extending.</param>
/// <param name="instance">The instance of the type we are validating.</param>
/// <param name="ruleSet">Optional: a ruleset when need to validate against.</param>
[Obsolete("This method will be removed in FluentValidation 10. Instead call Validate(instance, options => options.IncludeRuleSets(\"someRuleSet\",\"anotherRuleSet\").ThrowOnFailures()). Be sure to pass in separate strings rather than a comma-separated string for rulesets.")]
public static void ValidateAndThrow<T>(this IValidator<T> validator, T instance, string ruleSet) {
validator.Validate(instance, options => {
if (ruleSet != null) {
options.IncludeRuleSets(RulesetValidatorSelector.LegacyRulesetSplit(ruleSet));
}
options.ThrowOnFailures();
});
}
/// <summary>
/// Performs validation asynchronously and then throws an exception if validation fails.
/// </summary>
/// <param name="validator">The validator this method is extending.</param>
/// <param name="instance">The instance of the type we are validating.</param>
/// <param name="cancellationToken"></param>
/// <param name="ruleSet">Optional: a ruleset when need to validate against.</param>
[Obsolete("This method will be removed in FluentValidation 10. Instead call ValidateAsync(instance, options => options.IncludeRuleSets(\"someRuleSet\",\"anotherRuleSet\").ThrowOnFailures(), cancellationToken). Be sure to pass in separate strings rather than a comma-separated string for rulesets.")]
public static async Task ValidateAndThrowAsync<T>(this IValidator<T> validator, T instance, string ruleSet, CancellationToken cancellationToken = default) {
await validator.ValidateAsync(instance, options => {
if (ruleSet != null) {
options.IncludeRuleSets(RulesetValidatorSelector.LegacyRulesetSplit(ruleSet));
}
options.ThrowOnFailures();
}, cancellationToken);
}
}
}
| DefaultValidatorExtensions |
csharp | louthy__language-ext | LanguageExt.Core/Monads/Alternative Monads/Try/Try.Module.cs | {
"start": 66,
"end": 2541
} | public partial class ____
{
/// <summary>
/// Lifts a pure success value into a `Try` monad
/// </summary>
/// <param name="value">Value to lift</param>
/// <returns>`Try`</returns>
public static Try<A> Succ<A>(A value) =>
new (() => value);
/// <summary>
/// Lifts a failure value into a `Try` monad
/// </summary>
/// <param name="value">Failure value to lift</param>
/// <returns>`Try`</returns>
public static Try<A> Fail<A>(Error value) =>
new (() => value);
/// <summary>
/// Lifts a given function into a `Try` monad
/// </summary>
/// <param name="f">Function to lift</param>
/// <returns>`Try`</returns>
public static Try<A> lift<A>(Func<Fin<A>> f) =>
new(() =>
{
try
{
return f();
}
catch (Exception e)
{
return Fin.Fail<A>(e);
}
});
/// <summary>
/// Lifts a given value into a `Try` monad
/// </summary>
/// <param name="ma">Value to lift</param>
/// <returns>`Try`</returns>
public static Try<A> lift<A>(Fin<A> ma) =>
new (() => ma);
/// <summary>
/// Lifts a given value into a `Try` monad
/// </summary>
/// <param name="ma">Value to lift</param>
/// <returns>`Try`</returns>
public static Try<A> lift<A>(Pure<A> ma) =>
new (() => ma.Value);
/// <summary>
/// Lifts a given value into a `Try` monad
/// </summary>
/// <param name="ma">Value to lift</param>
/// <returns>`Try`</returns>
public static Try<A> lift<A>(Fail<Error> ma) =>
new (() => ma.Value);
/// <summary>
/// Lifts a given function into a `Try` monad
/// </summary>
/// <param name="f">Function to lift</param>
/// <returns>`Try`</returns>
public static Try<A> lift<A>(Func<A> f) =>
new(() =>
{
try
{
return f();
}
catch (Exception e)
{
return Fin.Fail<A>(e);
}
});
/// <summary>
/// Lifts a given function into a `Try` monad
/// </summary>
/// <param name="f">Function to lift</param>
/// <returns>`Try`</returns>
public static Try<Unit> lift(Action f) =>
lift<Unit>(() => { f(); return default; });
}
| Try |
csharp | dotnet__aspnetcore | src/OpenApi/gen/Helpers/AddOpenApiInvocation.cs | {
"start": 599,
"end": 774
} | internal sealed record ____(
AddOpenApiOverloadVariant Variant,
InvocationExpressionSyntax InvocationExpression,
InterceptableLocation? Location);
| AddOpenApiInvocation |
csharp | dotnet__machinelearning | src/Microsoft.ML.LightGbm/WrappedLightGbmInterface.cs | {
"start": 708,
"end": 860
} | public enum ____ : int
{
Float32 = 0,
Float64 = 1,
Int32 = 2,
Int64 = 3
}
| CApiDType |
csharp | moq__moq4 | src/Moq.Tests/ProtectedAsMockFixture.cs | {
"start": 16475,
"end": 16600
} | public interface ____
{
void HandleImpl<TMessage>(TMessage message);
}
| MessageHandlerBaseish |
csharp | aspnetboilerplate__aspnetboilerplate | src/Abp.EntityFrameworkCore/EntityFrameworkCore/DatabaseFacadeExtensions.cs | {
"start": 182,
"end": 397
} | public static class ____
{
public static bool IsRelational(this DatabaseFacade database)
{
return database.GetInfrastructure().GetService<IRelationalConnection>() != null;
}
} | DatabaseFacadeExtensions |
csharp | dotnet__aspnetcore | src/Components/Endpoints/test/EndpointHtmlRendererTest.cs | {
"start": 79436,
"end": 80243
} | private class ____ : ComponentBase
{
private bool hasRendered;
protected override void BuildRenderTree(RenderTreeBuilder builder)
{
builder.OpenElement(0, "form");
if (!hasRendered)
{
builder.AddAttribute(1, "onsubmit", () => { });
builder.AddNamedEvent("onsubmit", "default");
}
else
{
builder.AddAttribute(1, "onsubmit", () => { GC.KeepAlive(new object()); });
builder.AddNamedEvent("onsubmit", "default");
}
builder.CloseElement();
if (!hasRendered)
{
hasRendered = true;
StateHasChanged();
}
}
}
| MultiRenderNamedEventHandlerComponent |
csharp | abpframework__abp | framework/src/Volo.Abp.Security/Volo/Abp/Security/Claims/CurrentPrincipalAccessorBase.cs | {
"start": 107,
"end": 972
} | public abstract class ____ : ICurrentPrincipalAccessor
{
public ClaimsPrincipal Principal => _currentPrincipal.Value ?? GetClaimsPrincipal();
private readonly AsyncLocal<ClaimsPrincipal> _currentPrincipal = new AsyncLocal<ClaimsPrincipal>();
protected abstract ClaimsPrincipal GetClaimsPrincipal();
public virtual IDisposable Change(ClaimsPrincipal principal)
{
return SetCurrent(principal);
}
private IDisposable SetCurrent(ClaimsPrincipal principal)
{
var parent = Principal;
_currentPrincipal.Value = principal;
return new DisposeAction<ValueTuple<AsyncLocal<ClaimsPrincipal>, ClaimsPrincipal>>(static (state) =>
{
var (currentPrincipal, parent) = state;
currentPrincipal.Value = parent;
}, (_currentPrincipal, parent));
}
}
| CurrentPrincipalAccessorBase |
csharp | MassTransit__MassTransit | tests/MassTransit.EventHubIntegration.Tests/MultiBus_Specs.cs | {
"start": 429,
"end": 3737
} | public class ____ :
InMemoryTestFixture
{
const string EventHubNameOne = "multibus-eh1";
const string EventHubNameTwo = "multibus-eh2";
public MultiBus_Specs()
{
TestTimeout = TimeSpan.FromMinutes(1);
}
[Test]
public async Task Should_receive_in_both_buses()
{
await using var provider = new ServiceCollection()
.AddSingleton<ILoggerFactory>(LoggerFactory)
.AddSingleton(typeof(ILogger<>), typeof(Logger<>))
.AddSingleton(GetTask<ConsumeContext<FirstBusMessage>>())
.AddSingleton(GetTask<ConsumeContext<SecondBusMessage>>())
.AddMassTransit<IFirstBus>(x =>
{
x.AddRider(r =>
{
r.AddConsumer<FirstBusMessageConsumer>();
r.UsingEventHub((context, k) =>
{
k.Host(Configuration.EventHubNamespace);
k.Storage(Configuration.StorageAccount);
k.ReceiveEndpoint(EventHubNameOne, Configuration.ConsumerGroup, c =>
{
c.ConfigureConsumer<FirstBusMessageConsumer>(context);
});
});
});
x.UsingInMemory();
})
.AddMassTransit<ISecondBus>(x =>
{
x.AddRider(r =>
{
r.AddConsumer<SecondBusMessageConsumer>();
r.UsingEventHub((context, k) =>
{
k.Host(Configuration.EventHubNamespace);
k.Storage(Configuration.StorageAccount);
k.ReceiveEndpoint(EventHubNameTwo, Configuration.ConsumerGroup, c =>
{
c.ConfigureConsumer<SecondBusMessageConsumer>(context);
});
});
});
x.UsingInMemory();
})
.BuildServiceProvider(true);
IEnumerable<IHostedService> hostedServices = provider.GetServices<IHostedService>().ToArray();
await Task.WhenAll(hostedServices.Select(x => x.StartAsync(TestCancellationToken)));
var serviceScope = provider.CreateAsyncScope();
var producerProvider = serviceScope.ServiceProvider.GetRequiredService<Bind<IFirstBus, IEventHubProducerProvider>>().Value;
var producer = await producerProvider.GetProducer(EventHubNameOne);
await producer.Produce(new FirstBusMessage(), TestCancellationToken);
await provider.GetRequiredService<TaskCompletionSource<ConsumeContext<FirstBusMessage>>>().Task.OrCanceled(TestCancellationToken);
await provider.GetRequiredService<TaskCompletionSource<ConsumeContext<SecondBusMessage>>>().Task.OrCanceled(TestCancellationToken);
await serviceScope.DisposeAsync();
await Task.WhenAll(hostedServices.Select(x => x.StopAsync(TestCancellationToken)));
}
| MultiBus_Specs |
csharp | scriban__scriban | src/Scriban/ScribanVisitors.generated.cs | {
"start": 736,
"end": 1161
} |
partial class ____
{
public override int ChildrenCount => 1;
protected override ScriptNode GetChildrenImpl(int index) => Function;
public override void Accept(ScriptVisitor visitor) => visitor.Visit(this);
public override TResult Accept<TResult>(ScriptVisitor<TResult> visitor) => visitor.Visit(this);
}
#if SCRIBAN_PUBLIC
public
#else
internal
#endif | ScriptAnonymousFunction |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 122105,
"end": 122322
} | public class ____
{
public int Id { get; set; }
public RelatedEntity563 ParentEntity { get; set; }
public IEnumerable<RelatedEntity565> ChildEntities { get; set; }
}
| RelatedEntity564 |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Interfaces/Web/IHasResponseFilter.cs | {
"start": 520,
"end": 667
} | interface ____ be implemented by an attribute
/// which adds an response filter for the specific response DTO the attribute marked.
/// </summary>
| can |
csharp | dotnet__aspnetcore | src/Shared/ServerInfrastructure/BufferExtensions.cs | {
"start": 333,
"end": 8333
} | internal static class ____
{
private const int _maxULongByteLength = 20;
[ThreadStatic]
private static byte[]? _numericBytesScratch;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ReadOnlySpan<byte> ToSpan(in this ReadOnlySequence<byte> buffer)
{
if (buffer.IsSingleSegment)
{
return buffer.FirstSpan;
}
return buffer.ToArray();
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static void CopyTo(in this ReadOnlySequence<byte> buffer, PipeWriter pipeWriter)
{
if (buffer.IsSingleSegment)
{
pipeWriter.Write(buffer.FirstSpan);
}
else
{
CopyToMultiSegment(buffer, pipeWriter);
}
}
private static void CopyToMultiSegment(in ReadOnlySequence<byte> buffer, PipeWriter pipeWriter)
{
foreach (var item in buffer)
{
pipeWriter.Write(item.Span);
}
}
public static ArraySegment<byte> GetArray(this Memory<byte> buffer)
{
return ((ReadOnlyMemory<byte>)buffer).GetArray();
}
public static ArraySegment<byte> GetArray(this ReadOnlyMemory<byte> memory)
{
if (!MemoryMarshal.TryGetArray(memory, out var result))
{
throw new InvalidOperationException("Buffer backed by array was expected");
}
return result;
}
/// <summary>
/// Returns position of first occurrence of item in the <see cref="ReadOnlySequence{T}"/>
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static SequencePosition? PositionOfAny<T>(in this ReadOnlySequence<T> source, T value0, T value1) where T : IEquatable<T>
{
if (source.IsSingleSegment)
{
int index = source.First.Span.IndexOfAny(value0, value1);
if (index != -1)
{
return source.GetPosition(index);
}
return null;
}
else
{
return PositionOfAnyMultiSegment(source, value0, value1);
}
}
private static SequencePosition? PositionOfAnyMultiSegment<T>(in ReadOnlySequence<T> source, T value0, T value1) where T : IEquatable<T>
{
SequencePosition position = source.Start;
SequencePosition result = position;
while (source.TryGet(ref position, out ReadOnlyMemory<T> memory))
{
int index = memory.Span.IndexOfAny(value0, value1);
if (index != -1)
{
return source.GetPosition(index, result);
}
else if (position.GetObject() == null)
{
break;
}
result = position;
}
return null;
}
internal static void WriteAscii(ref this BufferWriter<PipeWriter> buffer, string data)
{
if (string.IsNullOrEmpty(data))
{
return;
}
var dest = buffer.Span;
var sourceLength = data.Length;
// Fast path, try encoding to the available memory directly
if (sourceLength <= dest.Length)
{
Encoding.ASCII.GetBytes(data, dest);
buffer.Advance(sourceLength);
}
else
{
WriteEncodedMultiWrite(ref buffer, data, sourceLength, Encoding.ASCII);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
internal static void WriteNumeric(ref this BufferWriter<PipeWriter> bufferWriter, ulong number)
{
const byte AsciiDigitStart = (byte)'0';
var buffer = bufferWriter.Span;
// Fast path, try copying to the available memory directly
if (number < 10 && buffer.Length >= 1)
{
buffer[0] = (byte)(((uint)number) + AsciiDigitStart);
bufferWriter.Advance(1);
}
else if (number < 100 && buffer.Length >= 2)
{
var val = (uint)number;
var tens = (uint)(byte)((val * 205u) >> 11); // div10, valid to 1028
buffer[0] = (byte)(tens + AsciiDigitStart);
buffer[1] = (byte)(val - (tens * 10) + AsciiDigitStart);
bufferWriter.Advance(2);
}
else if (number < 1000 && buffer.Length >= 3)
{
var val = (uint)number;
var digit0 = (uint)(byte)((val * 41u) >> 12); // div100, valid to 1098
var digits01 = (uint)(byte)((val * 205u) >> 11); // div10, valid to 1028
buffer[0] = (byte)(digit0 + AsciiDigitStart);
buffer[1] = (byte)(digits01 - (digit0 * 10) + AsciiDigitStart);
buffer[2] = (byte)(val - (digits01 * 10) + AsciiDigitStart);
bufferWriter.Advance(3);
}
else
{
WriteNumericMultiWrite(ref bufferWriter, number);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void WriteNumericMultiWrite(ref this BufferWriter<PipeWriter> buffer, ulong number)
{
const byte AsciiDigitStart = (byte)'0';
var value = number;
var position = _maxULongByteLength;
var byteBuffer = NumericBytesScratch;
do
{
// Consider using Math.DivRem() if available
var quotient = value / 10;
byteBuffer[--position] = (byte)(AsciiDigitStart + (value - quotient * 10)); // 0x30 = '0'
value = quotient;
}
while (value != 0);
var length = _maxULongByteLength - position;
buffer.Write(new ReadOnlySpan<byte>(byteBuffer, position, length));
}
internal static void WriteEncoded(ref this BufferWriter<PipeWriter> buffer, string data, Encoding encoding)
{
if (string.IsNullOrEmpty(data))
{
return;
}
var dest = buffer.Span;
var sourceLength = encoding.GetByteCount(data);
// Fast path, try encoding to the available memory directly
if (sourceLength <= dest.Length)
{
encoding.GetBytes(data, dest);
buffer.Advance(sourceLength);
}
else
{
WriteEncodedMultiWrite(ref buffer, data, sourceLength, encoding);
}
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static void WriteEncodedMultiWrite(ref this BufferWriter<PipeWriter> buffer, string data, int encodedLength, Encoding encoding)
{
var source = data.AsSpan();
var totalBytesUsed = 0;
var encoder = encoding.GetEncoder();
var minBufferSize = encoding.GetMaxByteCount(1);
buffer.Ensure(minBufferSize);
var bytes = buffer.Span;
var completed = false;
// This may be a bug, but encoder.Convert returns completed = true for UTF7 too early.
// Therefore, we check encodedLength - totalBytesUsed too.
while (!completed || encodedLength - totalBytesUsed != 0)
{
// Zero length spans are possible, though unlikely.
// encoding.Convert and .Advance will both handle them so we won't special case for them.
encoder.Convert(source, bytes, flush: true, out var charsUsed, out var bytesUsed, out completed);
buffer.Advance(bytesUsed);
totalBytesUsed += bytesUsed;
if (totalBytesUsed >= encodedLength)
{
Debug.Assert(totalBytesUsed == encodedLength);
// Encoded everything
break;
}
source = source.Slice(charsUsed);
// Get new span, more to encode.
buffer.Ensure(minBufferSize);
bytes = buffer.Span;
}
}
private static byte[] NumericBytesScratch => _numericBytesScratch ?? CreateNumericBytesScratch();
[MethodImpl(MethodImplOptions.NoInlining)]
private static byte[] CreateNumericBytesScratch()
{
var bytes = new byte[_maxULongByteLength];
_numericBytesScratch = bytes;
return bytes;
}
}
| BufferExtensions |
csharp | mongodb__mongo-csharp-driver | tests/MongoDB.TestHelpers/XunitExtensions/TimeoutEnforcing/TimeoutEnforcingXunitTestFramework.cs | {
"start": 776,
"end": 1214
} | public sealed class ____ : XunitTestFramework
{
public TimeoutEnforcingXunitTestFramework(IMessageSink messageSink)
: base(messageSink)
{
}
protected override ITestFrameworkExecutor CreateExecutor(AssemblyName assemblyName) =>
new TimeoutEnforcingXunitTestFrameworkExecutor(assemblyName, SourceInformationProvider, DiagnosticMessageSink);
}
}
| TimeoutEnforcingXunitTestFramework |
csharp | mongodb__mongo-csharp-driver | src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToFilterTranslators/ExpressionTranslators/ParameterExpressionToFilterTranslator.cs | {
"start": 849,
"end": 1585
} | internal static class ____
{
public static AstFilter Translate(TranslationContext context, ParameterExpression expression)
{
if (expression.Type == typeof(bool))
{
if (context.SymbolTable.TryGetSymbol(expression, out var symbol))
{
var serializer = symbol.Serializer;
var field = AstFilter.Field(symbol.Name);
var serializedTrue = SerializationHelper.SerializeValue(serializer, true);
return AstFilter.Eq(field, serializedTrue);
}
}
throw new ExpressionNotSupportedException(expression);
}
}
}
| ParameterExpressionToFilterTranslator |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Server/PostgresUtils.cs | {
"start": 233,
"end": 6018
} | public static class ____
{
public static void CreatePartitionTableIfNotExists<T>(IDbConnection db, Expression<Func<T, DateTime>> dateField)
{
var dialect = db.GetDialectProvider();
var modelDef = ModelDefinition<T>.Definition;
var member = dateField.Body as MemberExpression;
var unary = dateField.Body as UnaryExpression;
var dateFieldExpr = member ?? unary?.Operand as MemberExpression;
var dateFieldName = dateFieldExpr?.Member.Name
?? throw new NotSupportedException("Expected Property Expression");
var fieldDef = modelDef.GetFieldDefinition(dateFieldName);
var sql = CreatePartitionTableSql(dialect, typeof(T), fieldDef);
db.ExecuteSql(sql);
}
public static string CreatePartitionTableSql(IOrmLiteDialectProvider dialect, Type modelType, string dateField)
{
var modelDef = modelType.GetModelMetadata();
var createdFieldDef = modelDef.GetFieldDefinition(dateField)
?? throw new Exception($"Field {dateField} not found on {modelType.Name}");
return CreatePartitionTableSql(dialect, modelType, createdFieldDef);
}
public static string CreatePartitionTableSql(IOrmLiteDialectProvider dialect, Type modelType, FieldDefinition dateField)
{
var modelDef = modelType.GetModelMetadata();
var createTableSql = dialect.ToCreateTableStatement(modelType);
var rawSql = createTableSql
.Replace("CREATE TABLE ", "CREATE TABLE IF NOT EXISTS ")
.Replace(" PRIMARY KEY", "").LastLeftPart(')').Trim();
var idField = dialect.GetQuotedColumnName(modelDef.PrimaryKey);
var createdField = dialect.GetQuotedColumnName(dateField);
var newSql = rawSql +
$"""
,
PRIMARY KEY ({idField},{createdField})
) PARTITION BY RANGE ({createdField});
""";
return newSql;
}
public static string CreatePartitionSql(IOrmLiteDialectProvider dialect, Type modelType, DateTime createdDate)
{
// Normalize to first day of month to avoid overlapping partitions
var monthStart = new DateTime(createdDate.Year, createdDate.Month, 1);
var partitionName = GetMonthTableName(dialect, modelType, createdDate);
var quotedPartitionName = dialect.QuoteTable(partitionName);
var quotedTableName = dialect.GetQuotedTableName(modelType);
var sql = $"""
CREATE TABLE IF NOT EXISTS {quotedPartitionName}
PARTITION OF {quotedTableName}
FOR VALUES FROM ('{monthStart:yyyy-MM-dd} 00:00:00') TO ('{monthStart.AddMonths(1):yyyy-MM-dd} 00:00:00');
""";
return sql;
}
public static Func<IOrmLiteDialectProvider, Type, DateTime, string> GetMonthTableName { get; set; } = DefaultGetMonthTableName;
public static string DefaultGetMonthTableName(IOrmLiteDialectProvider dialect, Type modelType, DateTime createdDate)
{
var suffix = createdDate.ToString("_yyyy_MM");
var tableName = dialect.GetTableName(modelType);
return tableName.EndsWith(suffix)
? tableName
: tableName + suffix;
}
public static List<DateTime> GetTableMonths(IOrmLiteDialectProvider dialect, IDbConnection db, Type modelType)
{
var quotedTable = dialect.GetQuotedTableName(modelType);
var partitionNames = db.SqlColumn<string>(
$"SELECT relid::text\nFROM pg_partition_tree('{quotedTable}'::regclass)\nWHERE parentrelid IS NOT NULL");
//["RequestLog_2025_10"]
var monthDbs = partitionNames
.Where(x => x.Contains('_'))
.Select(x =>
DateTime.TryParse(x.StripDbQuotes().RightPart('_').Replace('_', '-') + "-01", out var date) ? date : (DateTime?)null)
.Where(x => x != null)
.Select(x => x!.Value)
.OrderByDescending(x => x)
.ToList();
return monthDbs;
}
// strftime('%Y-%m-%d %H:%M:%S', 'now')
public static Dictionary<string, string> DateFormatMap = new() {
{"%Y", "YYYY"},
{"%m", "MM"},
{"%d", "DD"},
{"%H", "HH24"},
{"%M", "MI"},
{"%S", "SS"},
};
public static string SqlDateFormat(string quotedColumn, string format)
{
var fmt = format.Contains('\'')
? format.Replace("'", "")
: format;
foreach (var entry in DateFormatMap)
{
fmt = fmt.Replace(entry.Key, entry.Value);
}
return $"TO_CHAR({quotedColumn}, '{fmt}')";
}
public static void DropAllPartitions(IOrmLiteDialectProvider dialect, IDbConnection db, Type modelType)
{
var quotedTable = dialect.GetQuotedTableName(modelType);
var partitionNames = db.SqlColumn<string>(
$"SELECT relid::regclass::text FROM pg_partition_tree('{quotedTable}'::regclass) WHERE parentrelid IS NOT NULL");
foreach (var partitionName in partitionNames)
{
db.ExecuteSql($"DROP TABLE IF EXISTS {partitionName} CASCADE;");
}
}
static ConcurrentDictionary<string, bool> monthDbs = new();
public static IDbConnection OpenMonthDb<T>(IDbConnection db, DateTime createdDate, Action<IDbConnection>? configure=null)
{
var dialect = db.GetDialectProvider();
var partTableName = GetMonthTableName(dialect, typeof(T), createdDate);
configure?.Invoke(db);
if (monthDbs.TryAdd(partTableName, true))
{
db.ExecuteSql(CreatePartitionSql(dialect, typeof(T), createdDate));
}
return db;
}
} | PostgresUtils |
csharp | unoplatform__uno | src/Uno.UI/UI/Xaml/Input/FocusManagerGotFocusEventArgs.cs | {
"start": 145,
"end": 1133
} | public partial class ____
{
internal FocusManagerGotFocusEventArgs(DependencyObject? newFocusedElement, Guid correlationId)
{
NewFocusedElement = newFocusedElement;
CorrelationId = correlationId;
}
/// <summary>
/// Gets the most recent focused element.
/// </summary>
public DependencyObject? NewFocusedElement { get; internal set; }
/// <summary>
/// Gets the unique ID generated when a focus movement event is initiated.
/// </summary>
/// <remarks>
/// Each time a focus event is initiated, a unique CorrelationId is generated
/// to help you track a focus event throughout these focus actions.
/// A new CorrelationId is generated when:
/// - The user moves focus.
/// - The app moves focus using methods such as Control.Focus or FocusManager.TryFocusAsync.
/// - The app gets/loses focus due to window activation(see CoreWindow.Activated ).
/// </remarks>
public Guid CorrelationId { get; internal set; }
}
}
| FocusManagerGotFocusEventArgs |
csharp | HangfireIO__Hangfire | src/Hangfire.Core/GlobalJobFilters.cs | {
"start": 852,
"end": 1685
} | public static class ____
{
static GlobalJobFilters()
{
// ReSharper disable once UseObjectOrCollectionInitializer
Filters = new JobFilterCollection();
// Filters should be added with the `Add` method call: some
// of them indirectly use `GlobalJobFilters.Filters` property,
// and it is null, when we are using collection initializer.
Filters.Add(new CaptureCultureAttribute());
Filters.Add(new AutomaticRetryAttribute());
Filters.Add(new StatisticsHistoryAttribute());
Filters.Add(new ContinuationsSupportAttribute());
}
/// <summary>
/// Gets the global filter collection.
/// </summary>
public static JobFilterCollection Filters { get; }
}
}
| GlobalJobFilters |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler.Tests/TestCases/Pretty/TypeMemberTests.cs | {
"start": 6730,
"end": 6840
} | public class ____
{
public virtual int P {
get {
return 0;
}
set {
}
}
}
| T22_A_HideProperty |
csharp | dotnet__reactive | Rx.NET/Source/src/System.Reactive/Linq/Observable/Zip.NAry.cs | {
"start": 35884,
"end": 40399
} | internal sealed class ____ : ZipSink<TResult>
{
private readonly Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> _resultSelector;
private readonly ZipObserver<T1> _observer1;
private readonly ZipObserver<T2> _observer2;
private readonly ZipObserver<T3> _observer3;
private readonly ZipObserver<T4> _observer4;
private readonly ZipObserver<T5> _observer5;
private readonly ZipObserver<T6> _observer6;
private readonly ZipObserver<T7> _observer7;
private readonly ZipObserver<T8> _observer8;
private readonly ZipObserver<T9> _observer9;
private readonly ZipObserver<T10> _observer10;
private readonly ZipObserver<T11> _observer11;
public _(Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, TResult> resultSelector, IObserver<TResult> observer)
: base(11, observer)
{
_resultSelector = resultSelector;
_observer1 = new ZipObserver<T1>(_gate, this, 0);
_observer2 = new ZipObserver<T2>(_gate, this, 1);
_observer3 = new ZipObserver<T3>(_gate, this, 2);
_observer4 = new ZipObserver<T4>(_gate, this, 3);
_observer5 = new ZipObserver<T5>(_gate, this, 4);
_observer6 = new ZipObserver<T6>(_gate, this, 5);
_observer7 = new ZipObserver<T7>(_gate, this, 6);
_observer8 = new ZipObserver<T8>(_gate, this, 7);
_observer9 = new ZipObserver<T9>(_gate, this, 8);
_observer10 = new ZipObserver<T10>(_gate, this, 9);
_observer11 = new ZipObserver<T11>(_gate, this, 10);
}
public void Run(IObservable<T1> source1, IObservable<T2> source2, IObservable<T3> source3, IObservable<T4> source4, IObservable<T5> source5, IObservable<T6> source6, IObservable<T7> source7, IObservable<T8> source8, IObservable<T9> source9, IObservable<T10> source10, IObservable<T11> source11)
{
var disposables = new IDisposable[11];
disposables[0] = _observer1;
Queues[0] = _observer1.Values;
disposables[1] = _observer2;
Queues[1] = _observer2.Values;
disposables[2] = _observer3;
Queues[2] = _observer3.Values;
disposables[3] = _observer4;
Queues[3] = _observer4.Values;
disposables[4] = _observer5;
Queues[4] = _observer5.Values;
disposables[5] = _observer6;
Queues[5] = _observer6.Values;
disposables[6] = _observer7;
Queues[6] = _observer7.Values;
disposables[7] = _observer8;
Queues[7] = _observer8.Values;
disposables[8] = _observer9;
Queues[8] = _observer9.Values;
disposables[9] = _observer10;
Queues[9] = _observer10.Values;
disposables[10] = _observer11;
Queues[10] = _observer11.Values;
_observer1.SetResource(source1.SubscribeSafe(_observer1));
_observer2.SetResource(source2.SubscribeSafe(_observer2));
_observer3.SetResource(source3.SubscribeSafe(_observer3));
_observer4.SetResource(source4.SubscribeSafe(_observer4));
_observer5.SetResource(source5.SubscribeSafe(_observer5));
_observer6.SetResource(source6.SubscribeSafe(_observer6));
_observer7.SetResource(source7.SubscribeSafe(_observer7));
_observer8.SetResource(source8.SubscribeSafe(_observer8));
_observer9.SetResource(source9.SubscribeSafe(_observer9));
_observer10.SetResource(source10.SubscribeSafe(_observer10));
_observer11.SetResource(source11.SubscribeSafe(_observer11));
SetUpstream(StableCompositeDisposable.CreateTrusted(disposables));
}
protected override TResult GetResult() => _resultSelector(_observer1.Values.Dequeue(), _observer2.Values.Dequeue(), _observer3.Values.Dequeue(), _observer4.Values.Dequeue(), _observer5.Values.Dequeue(), _observer6.Values.Dequeue(), _observer7.Values.Dequeue(), _observer8.Values.Dequeue(), _observer9.Values.Dequeue(), _observer10.Values.Dequeue(), _observer11.Values.Dequeue());
}
}
| _ |
csharp | EventStore__EventStore | src/KurrentDB.Projections.Core.Tests/Services/projections_manager/when_a_disabled_projection_has_been_loaded.cs | {
"start": 671,
"end": 3785
} | public class ____<TLogFormat, TStreamId> : TestFixtureWithProjectionCoreAndManagementServices<TLogFormat, TStreamId> {
protected override void Given() {
base.Given();
NoStream("$projections-test-projection-result");
NoStream("$projections-test-projection-order");
AllWritesToSucceed("$projections-test-projection-order");
NoStream("$projections-test-projection-checkpoint");
ExistingEvent(ProjectionNamesBuilder.ProjectionsRegistrationStream, ProjectionEventTypes.ProjectionCreated,
null, "test-projection");
ExistingEvent(
"$projections-test-projection", ProjectionEventTypes.ProjectionUpdated, null,
@"{
""Query"":""fromAll(); on_any(function(){});log('hello-from-projection-definition');"",
""Mode"":""3"",
""Enabled"":false,
""HandlerType"":""JS"",
""SourceDefinition"":{
""AllEvents"":true,
""AllStreams"":true,
}
}");
AllWritesSucceed();
}
private string _projectionName;
protected override IEnumerable<WhenStep> When() {
_projectionName = "test-projection";
yield return new ProjectionSubsystemMessage.StartComponents(Guid.NewGuid());
}
[Test]
public void the_projection_source_can_be_retrieved() {
_manager.Handle(
new ProjectionManagementMessage.Command.GetQuery(
_bus, _projectionName, ProjectionManagementMessage.RunAs.Anonymous));
Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.ProjectionQuery>().Count());
var projectionQuery =
_consumer.HandledMessages.OfType<ProjectionManagementMessage.ProjectionQuery>().Single();
Assert.AreEqual(_projectionName, projectionQuery.Name);
}
[Test]
public void the_projection_status_is_stopped() {
_manager.Handle(
new ProjectionManagementMessage.Command.GetStatistics(_bus, null, _projectionName));
Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Count());
Assert.AreEqual(
1,
_consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Single().Projections.Length);
Assert.AreEqual(
_projectionName,
_consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Single().Projections.Single()
.Name);
Assert.AreEqual(
ManagedProjectionState.Stopped,
_consumer.HandledMessages.OfType<ProjectionManagementMessage.Statistics>().Single().Projections.Single()
.LeaderStatus);
}
[Test]
public void the_projection_state_can_be_retrieved() {
_manager.Handle(
new ProjectionManagementMessage.Command.GetState(_bus, _projectionName, ""));
_queue.Process();
Assert.AreEqual(1, _consumer.HandledMessages.OfType<ProjectionManagementMessage.ProjectionState>().Count());
Assert.AreEqual(
_projectionName,
_consumer.HandledMessages.OfType<ProjectionManagementMessage.ProjectionState>().Single().Name);
Assert.AreEqual(
"", _consumer.HandledMessages.OfType<ProjectionManagementMessage.ProjectionState>().Single().State);
}
}
| when_a_disabled_projection_has_been_loaded |
csharp | EventStore__EventStore | src/KurrentDB.Core/Metrics/MaxTracker.cs | {
"start": 327,
"end": 500
} | public interface ____<T> {
void Record(T value);
}
// Similar to DurationMaxTracker (see notes there)
// One thread can Record while another Observes concurrently.
| IMaxTracker |
csharp | dotnet__aspnetcore | src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/CompletenessTests.cs | {
"start": 17304,
"end": 17845
} | class ____ an example of sharing comments across methods.", inheritAllButRemarks.Description);
path = document.Paths["/generic-class"].Operations[HttpMethod.Post];
var genericClass = path.RequestBody.Content["application/json"].Schema;
Assert.Equal("This is a generic class.", genericClass.Description);
path = document.Paths["/generic-parent"].Operations[HttpMethod.Post];
var genericParent = path.RequestBody.Content["application/json"].Schema;
Assert.Equal("This | shows |
csharp | kgrzybek__modular-monolith-with-ddd | src/BuildingBlocks/Tests/IntegrationTests/Probing/IProbe.cs | {
"start": 80,
"end": 215
} | public interface ____
{
bool IsSatisfied();
Task SampleAsync();
string DescribeFailureTo();
}
| IProbe |
csharp | grandnode__grandnode2 | src/Plugins/Payments.BrainTree/EndpointProvider.cs | {
"start": 143,
"end": 541
} | public class ____ : IEndpointProvider
{
public void RegisterEndpoint(IEndpointRouteBuilder endpointRouteBuilder)
{
endpointRouteBuilder.MapControllerRoute("Plugin.PaymentBrainTree",
"Plugins/PaymentBrainTree/PaymentInfo",
new { controller = "PaymentBrainTree", action = "PaymentInfo", area = "" }
);
}
public int Priority => 0;
} | EndpointProvider |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 90857,
"end": 91074
} | public class ____
{
public int Id { get; set; }
public RelatedEntity419 ParentEntity { get; set; }
public IEnumerable<RelatedEntity421> ChildEntities { get; set; }
}
| RelatedEntity420 |
csharp | graphql-dotnet__graphql-dotnet | samples/GraphQL.Federation.Tests/Schema/TestSchema.cs | {
"start": 91,
"end": 317
} | public class ____ : GraphQL.Types.Schema
{
public TestSchema(IServiceProvider provider, TestQuery query)
: base(provider)
{
Query = query;
this.RegisterType<FederatedTestType>();
}
}
| TestSchema |
csharp | ServiceStack__ServiceStack | ServiceStack/src/ServiceStack.Razor/Html/IViewPage.cs | {
"start": 41,
"end": 139
} | public interface ____
{
bool IsCompiled { get; }
void Compile(bool force=false);
}
}
| IViewPage |
csharp | getsentry__sentry-dotnet | src/Sentry/ISpanData.cs | {
"start": 1215,
"end": 2790
} | public static class ____
{
/// <summary>
/// Sets a measurement on the transaction.
/// </summary>
/// <param name="spanData">The transaction.</param>
/// <param name="name">The name of the measurement.</param>
/// <param name="value">The value of the measurement.</param>
/// <param name="unit">The optional unit of the measurement.</param>
public static void SetMeasurement(this ISpanData spanData, string name, int value,
MeasurementUnit unit = default) =>
spanData.SetMeasurement(name, new Measurement(value, unit));
/// <inheritdoc cref="SetMeasurement(Sentry.ISpanData,string,int,Sentry.MeasurementUnit)" />
public static void SetMeasurement(this ISpanData spanData, string name, long value,
MeasurementUnit unit = default) =>
spanData.SetMeasurement(name, new Measurement(value, unit));
/// <inheritdoc cref="SetMeasurement(Sentry.ISpanData,string,int,Sentry.MeasurementUnit)" />
#if !__MOBILE__
// ulong parameter is not CLS compliant
[CLSCompliant(false)]
#endif
public static void SetMeasurement(this ISpanData spanData, string name, ulong value,
MeasurementUnit unit = default) =>
spanData.SetMeasurement(name, new Measurement(value, unit));
/// <inheritdoc cref="SetMeasurement(Sentry.ISpanData,string,int,Sentry.MeasurementUnit)" />
public static void SetMeasurement(this ISpanData spanData, string name, double value,
MeasurementUnit unit = default) =>
spanData.SetMeasurement(name, new Measurement(value, unit));
}
| SpanDataExtensions |
csharp | nopSolutions__nopCommerce | src/Libraries/Nop.Core/Domain/Catalog/ProductManufacturer.cs | {
"start": 112,
"end": 697
} | public partial class ____ : BaseEntity
{
/// <summary>
/// Gets or sets the product identifier
/// </summary>
public int ProductId { get; set; }
/// <summary>
/// Gets or sets the manufacturer identifier
/// </summary>
public int ManufacturerId { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the product is featured
/// </summary>
public bool IsFeaturedProduct { get; set; }
/// <summary>
/// Gets or sets the display order
/// </summary>
public int DisplayOrder { get; set; }
} | ProductManufacturer |
csharp | icsharpcode__ILSpy | ICSharpCode.Decompiler/Solution/SolutionCreator.cs | {
"start": 1413,
"end": 9054
} | public static class ____
{
static readonly XNamespace NonSDKProjectFileNamespace = XNamespace.Get("http://schemas.microsoft.com/developer/msbuild/2003");
/// <summary>
/// Writes a solution file to the specified <paramref name="targetFile"/>.
/// Also fixes intra-solution project references in the project files.
/// </summary>
/// <param name="targetFile">The full path of the file to write.</param>
/// <param name="projects">The projects contained in this solution.</param>
///
/// <exception cref="ArgumentException">Thrown when <paramref name="targetFile"/> is null or empty.</exception>
/// <exception cref="ArgumentNullException">Thrown when <paramref name="projects"/> is null.</exception>
/// <exception cref="InvalidOperationException">Thrown when <paramref name="projects"/> contains no items.</exception>
public static void WriteSolutionFile(string targetFile, List<ProjectItem> projects)
{
if (string.IsNullOrWhiteSpace(targetFile))
{
throw new ArgumentException("The target file cannot be null or empty.", nameof(targetFile));
}
if (projects == null)
{
throw new ArgumentNullException(nameof(projects));
}
if (!projects.Any())
{
throw new InvalidOperationException("At least one project is expected.");
}
using (var writer = new StreamWriter(targetFile))
{
WriteSolutionFile(writer, projects, targetFile);
}
FixAllProjectReferences(projects);
}
static void WriteSolutionFile(TextWriter writer, List<ProjectItem> projects, string solutionFilePath)
{
WriteHeader(writer);
WriteProjects(writer, projects, solutionFilePath);
writer.WriteLine("Global");
var platforms = WriteSolutionConfigurations(writer, projects);
WriteProjectConfigurations(writer, projects, platforms);
writer.WriteLine("\tGlobalSection(SolutionProperties) = preSolution");
writer.WriteLine("\t\tHideSolutionNode = FALSE");
writer.WriteLine("\tEndGlobalSection");
writer.WriteLine("EndGlobal");
}
private static void WriteHeader(TextWriter writer)
{
writer.WriteLine("Microsoft Visual Studio Solution File, Format Version 12.00");
writer.WriteLine("# Visual Studio 14");
writer.WriteLine("VisualStudioVersion = 14.0.24720.0");
writer.WriteLine("MinimumVisualStudioVersion = 10.0.40219.1");
}
static void WriteProjects(TextWriter writer, List<ProjectItem> projects, string solutionFilePath)
{
foreach (var project in projects)
{
var projectRelativePath = GetRelativePath(solutionFilePath, project.FilePath);
var typeGuid = project.TypeGuid.ToString("B").ToUpperInvariant();
var projectGuid = project.Guid.ToString("B").ToUpperInvariant();
writer.WriteLine($"Project(\"{typeGuid}\") = \"{project.ProjectName}\", \"{projectRelativePath}\", \"{projectGuid}\"");
writer.WriteLine("EndProject");
}
}
static List<string> WriteSolutionConfigurations(TextWriter writer, List<ProjectItem> projects)
{
var platforms = projects.GroupBy(p => p.PlatformName).Select(g => g.Key).ToList();
platforms.Sort();
writer.WriteLine("\tGlobalSection(SolutionConfigurationPlatforms) = preSolution");
foreach (var platform in platforms)
{
writer.WriteLine($"\t\tDebug|{platform} = Debug|{platform}");
}
foreach (var platform in platforms)
{
writer.WriteLine($"\t\tRelease|{platform} = Release|{platform}");
}
writer.WriteLine("\tEndGlobalSection");
return platforms;
}
static void WriteProjectConfigurations(
TextWriter writer,
List<ProjectItem> projects,
List<string> solutionPlatforms)
{
writer.WriteLine("\tGlobalSection(ProjectConfigurationPlatforms) = postSolution");
foreach (var project in projects)
{
var projectGuid = project.Guid.ToString("B").ToUpperInvariant();
foreach (var platform in solutionPlatforms)
{
writer.WriteLine($"\t\t{projectGuid}.Debug|{platform}.ActiveCfg = Debug|{project.PlatformName}");
writer.WriteLine($"\t\t{projectGuid}.Debug|{platform}.Build.0 = Debug|{project.PlatformName}");
}
foreach (var platform in solutionPlatforms)
{
writer.WriteLine($"\t\t{projectGuid}.Release|{platform}.ActiveCfg = Release|{project.PlatformName}");
writer.WriteLine($"\t\t{projectGuid}.Release|{platform}.Build.0 = Release|{project.PlatformName}");
}
}
writer.WriteLine("\tEndGlobalSection");
}
static void FixAllProjectReferences(List<ProjectItem> projects)
{
var projectsMap = projects.ToDictionary(
p => p.ProjectName,
p => p);
foreach (var project in projects)
{
XDocument projectDoc = XDocument.Load(project.FilePath);
if (projectDoc.Root?.Name.LocalName != "Project")
{
throw new InvalidOperationException(
$"The file {project.FilePath} is not a valid project file, " +
$"no <Project> at the root; could not fix project references.");
}
// sdk style projects don't use a namespace for the elements,
// but we still need to use the namespace for non-sdk style projects.
var sdkStyle = projectDoc.Root.Attribute("Sdk") != null;
var itemGroupTagName = sdkStyle ? "ItemGroup" : NonSDKProjectFileNamespace + "ItemGroup";
var referenceTagName = sdkStyle ? "Reference" : NonSDKProjectFileNamespace + "Reference";
var referencesItemGroups = projectDoc.Root
.Elements(itemGroupTagName)
.Where(e => e.Elements(referenceTagName).Any())
.ToList();
foreach (var itemGroup in referencesItemGroups)
{
FixProjectReferences(project.FilePath, itemGroup, projectsMap, sdkStyle);
}
projectDoc.Save(project.FilePath);
}
}
static void FixProjectReferences(string projectFilePath, XElement itemGroup,
Dictionary<string, ProjectItem> projects, bool sdkStyle)
{
XName GetElementName(string name) => sdkStyle ? name : NonSDKProjectFileNamespace + name;
var referenceTagName = GetElementName("Reference");
var projectReferenceTagName = GetElementName("ProjectReference");
foreach (var item in itemGroup.Elements(referenceTagName).ToList())
{
var assemblyName = item.Attribute("Include")?.Value;
if (assemblyName != null && projects.TryGetValue(assemblyName, out var referencedProject))
{
item.Remove();
var projectReference = new XElement(
projectReferenceTagName,
new XAttribute("Include", GetRelativePath(projectFilePath, referencedProject.FilePath)));
// SDK-style projects do not use the <Project> and <Name> elements for project references.
// (Instead, those get read from the .csproj file in "Include".)
if (!sdkStyle)
{
projectReference.Add(
// no ToUpper() for uuids, most Microsoft tools seem to emit them in lowercase
// (no .ToLower() as .ToString("B") already outputs lowercase)
new XElement(NonSDKProjectFileNamespace + "Project", referencedProject.Guid.ToString("B")),
new XElement(NonSDKProjectFileNamespace + "Name", referencedProject.ProjectName));
}
itemGroup.Add(projectReference);
}
}
}
static string GetRelativePath(string fromFilePath, string toFilePath)
{
Uri fromUri = new Uri(fromFilePath);
Uri toUri = new Uri(toFilePath);
if (fromUri.Scheme != toUri.Scheme)
{
return toFilePath;
}
Uri relativeUri = fromUri.MakeRelativeUri(toUri);
string relativePath = Uri.UnescapeDataString(relativeUri.ToString());
if (string.Equals(toUri.Scheme, Uri.UriSchemeFile, StringComparison.OrdinalIgnoreCase))
{
relativePath = relativePath.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
}
return relativePath;
}
}
}
| SolutionCreator |
csharp | cake-build__cake | src/Cake.Core.Tests/Unit/CakeTaskBuilderExtensionsTests.cs | {
"start": 26868,
"end": 28427
} | public sealed class ____
{
private static readonly Func<ICakeContext, IEnumerable<int>> FuncDeferredItemsWithContext = ctx => new[] { 1, 2, 3 };
private static readonly Action<int> DefaultFunc = (item) => { };
private static readonly Action<int> NullFunc = null;
private static readonly Action<int> ExceptionFunc = (item) => throw new NotImplementedException();
private static readonly Action<int, ICakeContext> DefaultFuncWithContext = (item, ctx) => { };
private static readonly Action<int, ICakeContext> NullFuncWithContext = null;
private static readonly Action<int, ICakeContext> ExceptionFuncWithContext = (item, ctx) => throw new NotImplementedException();
private static readonly Action<string, int> DefaultFuncWithData = (data, item) => { };
private static readonly Action<string, int> NullFuncWithData = null;
private static readonly Action<string, int> ExceptionFuncWithData = (data, item) => throw new NotImplementedException();
private static readonly Action<string, int, ICakeContext> DefaultFuncWithDataAndContext = (data, item, ctx) => { };
private static readonly Action<string, int, ICakeContext> NullFuncWithDataAndContext = null;
private static readonly Action<string, int, ICakeContext> ExceptionFuncWithDataAndContext = (data, item, ctx) => throw new NotImplementedException();
| ForDeferredItemsWithContext |
csharp | protobuf-net__protobuf-net | src/protobuf-net.Core/IProtoOutputT.cs | {
"start": 231,
"end": 695
} | public interface ____<[DynamicallyAccessedMembers(DynamicAccess.ContractType)] TOutput>
{
/// <summary>
/// Serialize the provided value
/// </summary>
void Serialize<T>(TOutput destination, T value, object userState = null);
}
/// <summary>
/// Represents the ability to serialize values to an output of type <typeparamref name="TOutput"/>
/// with pre-computation of the length
/// </summary>
| IProtoOutput |
csharp | dotnet__orleans | src/api/Orleans.Serialization/Orleans.Serialization.cs | {
"start": 184062,
"end": 184426
} | partial class ____
{
public SerializerSessionPool(TypeSystem.TypeCodec typeCodec, WellKnownTypeCollection wellKnownTypes, Serializers.CodecProvider codecProvider) { }
public Serializers.CodecProvider CodecProvider { get { throw null; } }
public SerializerSession GetSession() { throw null; }
}
public sealed | SerializerSessionPool |
csharp | ChilliCream__graphql-platform | src/HotChocolate/MongoDb/test/Data.MongoDb.Filters.Tests/MongoDbFilterVisitorStringTests.cs | {
"start": 21129,
"end": 21347
} | public class ____
{
[BsonId]
[BsonGuidRepresentation(GuidRepresentation.Standard)]
public Guid Id { get; set; } = Guid.NewGuid();
public string Bar { get; set; } = null!;
}
| Foo |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Federation/Attributes/RequiresAttribute.cs | {
"start": 1499,
"end": 2065
} | class ____ multiple strings representing the required fields.
/// </summary>
/// <param name="fields">An array of field names that are required by this field.</param>
public RequiresAttribute(params string[] fields)
: this(string.Join(" ", fields))
{ }
/// <inheritdoc/>
public override void Modify(FieldType fieldType, bool isInputType)
{
if (isInputType)
throw new ArgumentOutOfRangeException(nameof(isInputType), isInputType, "Input types are not supported.");
fieldType.Requires(_fields);
}
}
| with |
csharp | DuendeSoftware__IdentityServer | identity-server/test/IdentityServer.IntegrationTests/Endpoints/Authorize/ConsentTests.cs | {
"start": 594,
"end": 14250
} | public class ____
{
private const string Category = "Authorize and consent tests";
private IdentityServerPipeline _mockPipeline = new IdentityServerPipeline();
public ConsentTests()
{
_mockPipeline.Clients.AddRange(new Client[] {
new Client
{
ClientId = "client1",
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = false,
AllowedScopes = new List<string> { "openid", "profile" },
RedirectUris = new List<string> { "https://client1/callback" },
AllowAccessTokensViaBrowser = true
},
new Client
{
ClientId = "client2",
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = true,
AllowedScopes = new List<string> { "openid", "profile", "api1", "api2" },
RedirectUris = new List<string> { "https://client2/callback" },
AllowAccessTokensViaBrowser = true
},
new Client
{
ClientId = "client3",
AllowedGrantTypes = GrantTypes.Implicit,
RequireConsent = false,
AllowedScopes = new List<string> { "openid", "profile", "api1", "api2" },
RedirectUris = new List<string> { "https://client3/callback" },
AllowAccessTokensViaBrowser = true,
IdentityProviderRestrictions = new List<string> { "google" }
}
});
_mockPipeline.Users.Add(new TestUser
{
SubjectId = "bob",
Username = "bob",
Claims = new Claim[]
{
new Claim("name", "Bob Loblaw"),
new Claim("email", "bob@loblaw.com"),
new Claim("role", "Attorney")
}
});
_mockPipeline.IdentityScopes.AddRange(new IdentityResource[] {
new IdentityResources.OpenId(),
new IdentityResources.Profile(),
new IdentityResources.Email()
});
_mockPipeline.ApiResources.AddRange(new ApiResource[] {
new ApiResource
{
Name = "api",
Scopes = { "api1", "api2" }
}
});
_mockPipeline.ApiScopes.AddRange(new ApiScope[]
{
new ApiScope
{
Name = "api1"
},
new ApiScope
{
Name = "api2"
}
});
_mockPipeline.Initialize();
}
[Fact]
[Trait("Category", Category)]
public async Task client_requires_consent_should_show_consent_page()
{
await _mockPipeline.LoginAsync("bob");
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token",
scope: "openid",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce"
);
var response = await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ConsentWasCalled.ShouldBeTrue();
}
[Theory]
[InlineData((Type)null)]
[InlineData(typeof(QueryStringAuthorizationParametersMessageStore))]
[InlineData(typeof(DistributedCacheAuthorizationParametersMessageStore))]
[Trait("Category", Category)]
public async Task consent_page_should_have_authorization_params(Type storeType)
{
if (storeType != null)
{
_mockPipeline.OnPostConfigureServices += services =>
{
services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType);
};
_mockPipeline.Initialize();
}
var user = new IdentityServerUser("bob") { Tenant = "tenant_value" };
await _mockPipeline.LoginAsync(user.CreatePrincipal());
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token token",
scope: "openid api1 api2",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce",
acrValues: "acr_1 acr_2 tenant:tenant_value",
extra: new
{
display = "popup", // must use a valid value form the spec for display
ui_locales = "ui_locale_value",
custom_foo = "foo_value"
}
);
var response = await _mockPipeline.BrowserClient.GetAsync(url);
_mockPipeline.ConsentRequest.ShouldNotBeNull();
_mockPipeline.ConsentRequest.Client.ClientId.ShouldBe("client2");
_mockPipeline.ConsentRequest.DisplayMode.ShouldBe("popup");
_mockPipeline.ConsentRequest.UiLocales.ShouldBe("ui_locale_value");
_mockPipeline.ConsentRequest.Tenant.ShouldBe("tenant_value");
_mockPipeline.ConsentRequest.AcrValues.ShouldBe(["acr_1", "acr_2"]);
_mockPipeline.ConsentRequest.Parameters.AllKeys.ShouldContain("custom_foo");
_mockPipeline.ConsentRequest.Parameters["custom_foo"].ShouldBe("foo_value");
_mockPipeline.ConsentRequest.ValidatedResources.RawScopeValues.ShouldBe(["openid", "api1", "api2"], true);
}
[Theory]
[InlineData((Type)null)]
[InlineData(typeof(QueryStringAuthorizationParametersMessageStore))]
[InlineData(typeof(DistributedCacheAuthorizationParametersMessageStore))]
[Trait("Category", Category)]
public async Task consent_response_should_allow_successful_authorization_response(Type storeType)
{
if (storeType != null)
{
_mockPipeline.OnPostConfigureServices += services =>
{
services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType);
};
_mockPipeline.Initialize();
}
await _mockPipeline.LoginAsync("bob");
_mockPipeline.ConsentResponse = new ConsentResponse()
{
ScopesValuesConsented = new string[] { "openid", "api2" }
};
_mockPipeline.BrowserClient.StopRedirectingAfter = 2;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token token",
scope: "openid profile api1 api2",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
response.Headers.Location.ToString().ShouldStartWith("https://client2/callback");
var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
authorization.IsError.ShouldBeFalse();
authorization.IdentityToken.ShouldNotBeNull();
authorization.State.ShouldBe("123_state");
var scopes = authorization.Scope.Split(' ');
scopes.ShouldBe(["api2", "openid"], true);
}
[Fact]
[Trait("Category", Category)]
public async Task consent_response_should_reject_modified_request_params()
{
await _mockPipeline.LoginAsync("bob");
_mockPipeline.ConsentResponse = new ConsentResponse()
{
ScopesValuesConsented = new string[] { "openid", "api2" }
};
_mockPipeline.BrowserClient.AllowAutoRedirect = false;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token token",
scope: "openid profile api2",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
response.Headers.Location.ToString().ShouldStartWith("https://server/consent");
response = await _mockPipeline.BrowserClient.GetAsync(response.Headers.Location.ToString());
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
response.Headers.Location.ToString().ShouldStartWith("/connect/authorize/callback");
var modifiedAuthorizeCallback = "https://server" + response.Headers.Location;
modifiedAuthorizeCallback = modifiedAuthorizeCallback.Replace("api2", "api1%20api2");
response = await _mockPipeline.BrowserClient.GetAsync(modifiedAuthorizeCallback);
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
response.Headers.Location.ToString().ShouldStartWith("https://server/consent");
}
[Fact()]
[Trait("Category", Category)]
public async Task consent_response_missing_required_scopes_should_error()
{
await _mockPipeline.LoginAsync("bob");
_mockPipeline.ConsentResponse = new ConsentResponse()
{
ScopesValuesConsented = new string[] { "api2" }
};
_mockPipeline.BrowserClient.StopRedirectingAfter = 2;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token token",
scope: "openid profile api1 api2",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
response.Headers.Location.ToString().ShouldStartWith("https://client2/callback");
var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
authorization.IsError.ShouldBeTrue();
authorization.Error.ShouldBe("access_denied");
authorization.State.ShouldBe("123_state");
}
[Theory]
[InlineData((Type)null)]
[InlineData(typeof(QueryStringAuthorizationParametersMessageStore))]
[InlineData(typeof(DistributedCacheAuthorizationParametersMessageStore))]
[Trait("Category", Category)]
public async Task consent_response_of_temporarily_unavailable_should_return_error_to_client(Type storeType)
{
if (storeType != null)
{
_mockPipeline.OnPostConfigureServices += services =>
{
services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType);
};
_mockPipeline.Initialize();
}
await _mockPipeline.LoginAsync("bob");
_mockPipeline.ConsentResponse = new ConsentResponse()
{
Error = AuthorizationError.TemporarilyUnavailable,
ErrorDescription = "some description"
};
_mockPipeline.BrowserClient.StopRedirectingAfter = 2;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token token",
scope: "openid profile api1 api2",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
response.Headers.Location.ToString().ShouldStartWith("https://client2/callback");
var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
authorization.IsError.ShouldBeTrue();
authorization.Error.ShouldBe("temporarily_unavailable");
authorization.ErrorDescription.ShouldBe("some description");
}
[Theory]
[InlineData((Type)null)]
[InlineData(typeof(QueryStringAuthorizationParametersMessageStore))]
[InlineData(typeof(DistributedCacheAuthorizationParametersMessageStore))]
[Trait("Category", Category)]
public async Task consent_response_of_unmet_authentication_requirements_should_return_error_to_client(Type storeType)
{
if (storeType != null)
{
_mockPipeline.OnPostConfigureServices += services =>
{
services.AddTransient(typeof(IAuthorizationParametersMessageStore), storeType);
};
_mockPipeline.Initialize();
}
await _mockPipeline.LoginAsync("bob");
_mockPipeline.ConsentResponse = new ConsentResponse()
{
Error = AuthorizationError.UnmetAuthenticationRequirements,
ErrorDescription = "some description"
};
_mockPipeline.BrowserClient.StopRedirectingAfter = 2;
var url = _mockPipeline.CreateAuthorizeUrl(
clientId: "client2",
responseType: "id_token token",
scope: "openid profile api1 api2",
redirectUri: "https://client2/callback",
state: "123_state",
nonce: "123_nonce");
var response = await _mockPipeline.BrowserClient.GetAsync(url);
response.StatusCode.ShouldBe(HttpStatusCode.Redirect);
response.Headers.Location.ToString().ShouldStartWith("https://client2/callback");
var authorization = new Duende.IdentityModel.Client.AuthorizeResponse(response.Headers.Location.ToString());
authorization.IsError.ShouldBeTrue();
authorization.Error.ShouldBe("unmet_authentication_requirements");
authorization.ErrorDescription.ShouldBe("some description");
}
[Fact]
[Trait("Category", Category)]
public async Task legacy_consents_should_apply_and_be_migrated_to_hex_encoding()
{
var clientId = "client2";
var subjectId = "bob";
// Create and serialize a consent | ConsentTests |
csharp | dotnet__maui | src/Controls/tests/DeviceTests/Elements/Border/BorderTests.cs | {
"start": 401,
"end": 9986
} | public partial class ____ : ControlsHandlerTestBase
{
void SetupBuilder()
{
EnsureHandlerCreated(builder =>
{
builder.ConfigureMauiHandlers(handlers =>
{
handlers.AddHandler<Border, BorderHandler>();
handlers.AddHandler<Grid, LayoutHandler>();
handlers.AddHandler<Label, LabelHandler>();
});
});
}
#if ANDROID
[Fact("Checks that the default background is transparent", Skip = "Android Helix is failing this test")]
public async Task DefaultBackgroundIsTransparent ()
{
// We use a Grid container to set a background color and then make sure that the Border background
// is transparent by making sure that the parent Grid's Blue background shows through.
var grid = new Grid
{
ColumnDefinitions = new ColumnDefinitionCollection()
{
new ColumnDefinition(GridLength.Star)
},
RowDefinitions = new RowDefinitionCollection()
{
new RowDefinition(GridLength.Star)
},
BackgroundColor = Colors.Blue,
WidthRequest = 200,
HeightRequest = 200
};
var border = new Border {
WidthRequest = 200,
HeightRequest = 200,
Stroke = Colors.Red,
StrokeThickness = 10
};
grid.Add(border, 0, 0);
await CreateHandlerAsync<BorderHandler>(border);
await CreateHandlerAsync<LayoutHandler>(grid);
var bitmap = await GetRawBitmap(grid, typeof(LayoutHandler));
Assert.Equal(200, bitmap.Width, 2d);
Assert.Equal(200, bitmap.Height, 2d);
// Analyze red border - we expect it to fill a 200x200 area
var redBlob = ConnectedComponentAnalysis.FindConnectedPixels(bitmap, (c) => c.Red > .5).Single();
Assert.Equal(200, redBlob.Width, 2d);
Assert.Equal(200, redBlob.Height, 2d);
// Analyze the blue blob - it should fill the inside of the border (minus the stroke thickness)
var blueBlobs = ConnectedComponentAnalysis.FindConnectedPixels(bitmap, (c) => c.Blue > .5);
// Note: There is a 1px blue border around the red border, so we need to find the one
// that represents the inner bounds of the border.
var innerBlob = blueBlobs[0];
for (int i = 1; i < blueBlobs.Count; i++)
{
if (blueBlobs[i].MinColumn > innerBlob.MinColumn && blueBlobs[i].MaxColumn < innerBlob.MaxColumn)
innerBlob = blueBlobs[i];
}
Assert.Equal(180, innerBlob.Width, 2d);
Assert.Equal(180, innerBlob.Height, 2d);
}
#endif
[Fact(DisplayName = "Rounded Rectangle Border occupies correct space")]
public async Task RoundedRectangleBorderLayoutIsCorrect()
{
Color stroke = Colors.Black;
const int strokeThickness = 4;
const int radius = 20;
var grid = new Grid()
{
ColumnDefinitions = new ColumnDefinitionCollection()
{
new ColumnDefinition(GridLength.Star),
new ColumnDefinition(GridLength.Star)
},
RowDefinitions = new RowDefinitionCollection()
{
new RowDefinition(GridLength.Star),
new RowDefinition(GridLength.Star)
},
BackgroundColor = Colors.White
};
var shape = new RoundRectangle()
{
CornerRadius = new CornerRadius(radius),
};
var border = new Border()
{
StrokeShape = shape,
Stroke = stroke,
StrokeThickness = strokeThickness,
BackgroundColor = Colors.Red,
};
grid.Add(border, 0, 0);
grid.WidthRequest = 200;
grid.HeightRequest = 200;
await CreateHandlerAsync<BorderHandler>(border);
await CreateHandlerAsync<LayoutHandler>(grid);
Point[] corners = new Point[4]
{
new Point(0, 0), // upper-left corner
new Point(100, 0), // upper-right corner
new Point(0, 100), // lower-left corner
new Point(100, 100) // lower-right corner
};
var points = new Point[16];
var colors = new Color[16];
int index = 0;
// To calculate the x and y offsets (from the center) for a 45-45-90 triangle, we can use the radius as the hypotenuse
// which means that the x and y offsets would be radius / sqrt(2).
var xy = radius - (radius / Math.Sqrt(2));
for (int i = 0; i < corners.Length; i++)
{
int xdir = i == 0 || i == 2 ? 1 : -1;
int ydir = i == 0 || i == 1 ? 1 : -1;
// This marks the outside edge of the rounded corner.
var outerX = corners[i].X + (xdir * xy);
var outerY = corners[i].Y + (ydir * xy);
// Add stroke thickness to find the inner edge of the rounded corner.
var innerX = outerX + (xdir * strokeThickness);
var innerY = outerY + (ydir * strokeThickness);
// Verify that the color outside of the rounded corner is the parent's color (White)
points[index] = new Point(outerX - (xdir * 0.25), outerY - (ydir * 0.25));
colors[index] = Colors.White;
index++;
// Verify that the rounded corner stroke is where we expect it to be
points[index] = new Point(outerX + (xdir * 1.25), outerY + (ydir * 1.25));
colors[index] = stroke;
index++;
points[index] = new Point(innerX - (xdir * 1.25), innerY - (ydir * 1.25));
colors[index] = stroke;
index++;
// Verify that the background color starts where we'd expect it to start
points[index] = new Point(innerX + (xdir * 0.25), innerY + (ydir * 0.25));
colors[index] = border.BackgroundColor;
index++;
}
await AssertColorsAtPoints(grid, typeof(LayoutHandler), colors, points);
}
[Fact(DisplayName = "StrokeThickness does not inset stroke path")]
public async Task BorderStrokeThicknessDoesNotInsetStrokePath()
{
var grid = new Grid()
{
ColumnDefinitions = new ColumnDefinitionCollection()
{
new ColumnDefinition(GridLength.Star),
new ColumnDefinition(GridLength.Star)
},
RowDefinitions = new RowDefinitionCollection()
{
new RowDefinition(GridLength.Star),
new RowDefinition(GridLength.Star)
},
BackgroundColor = Colors.White
};
var border = new Border()
{
Stroke = Colors.Black,
StrokeThickness = 10,
BackgroundColor = Colors.Red
};
grid.Add(border, 0, 0);
grid.WidthRequest = 200;
grid.HeightRequest = 200;
await CreateHandlerAsync<BorderHandler>(border);
await CreateHandlerAsync<LayoutHandler>(grid);
var points = new Point[2];
var colors = new Color[2];
#if IOS
// FIXME: iOS seems to have a white boarder around the Border stroke
int offset = 1;
#else
int offset = 0;
#endif
// Verify that the stroke is where we expect
points[0] = new Point(offset + 1, offset + 1);
colors[0] = Colors.Black;
// Verify that the stroke is only as thick as we expect
points[1] = new Point(offset + border.StrokeThickness + 1, offset + border.StrokeThickness + 1);
colors[1] = Colors.Red;
await AssertColorsAtPoints(grid, typeof(LayoutHandler), colors, points);
}
// NOTE: this test is slightly different than MemoryTests.HandlerDoesNotLeak
// It adds a child to the Border, which is a worthwhile test case.
[Fact("Border Does Not Leak")]
public async Task DoesNotLeak()
{
SetupBuilder();
WeakReference platformViewReference = null;
WeakReference handlerReference = null;
await InvokeOnMainThreadAsync(() =>
{
var layout = new Grid();
var border = new Border();
var label = new Label();
border.Content = label;
layout.Add(border);
var handler = CreateHandler<LayoutHandler>(layout);
handlerReference = new WeakReference(label.Handler);
platformViewReference = new WeakReference(label.Handler.PlatformView);
});
await AssertionExtensions.WaitForGC(handlerReference, platformViewReference);
}
[Fact(DisplayName = "Border With Stroke Shape And Name Does Not Leak")]
public async Task DoesNotLeakWithStrokeShape()
{
SetupBuilder();
WeakReference platformViewReference = null;
WeakReference handlerReference = null;
await InvokeOnMainThreadAsync(() =>
{
var layout = new Grid();
var border = new Border();
var rect = new RoundRectangle();
border.StrokeShape = rect;
layout.Add(border);
var nameScope = new NameScope();
((INameScope)nameScope).RegisterName("Border", border);
layout.transientNamescope = nameScope;
border.transientNamescope = nameScope;
rect.transientNamescope = nameScope;
var handler = CreateHandler<LayoutHandler>(layout);
handlerReference = new WeakReference(border.Handler);
platformViewReference = new WeakReference(border.Handler.PlatformView);
});
await AssertionExtensions.WaitForGC(handlerReference, platformViewReference);
}
[Fact("Ensures the border renders the expected size - Issue 15339")]
public async Task BorderAndStrokeIsCorrectSize()
{
double borderThickness = 10;
Border border = new Border() { WidthRequest = 200, HeightRequest = 100 };
border.BackgroundColor = Colors.Red;
border.Stroke = Colors.Blue;
border.StrokeThickness = borderThickness;
// This is randomly failing on iOS, so let's add a timeout to avoid device tests running for hours
var bitmap = await GetRawBitmap(border, typeof(BorderHandler)).WaitAsync(TimeSpan.FromSeconds(5));
Assert.Equal(200, bitmap.Width, 2d);
Assert.Equal(100, bitmap.Height, 2d);
// Analyze blue border - we expect it to fill the 200x100 area
var blueBlob = ConnectedComponentAnalysis.FindConnectedPixels(bitmap, (c) => c.Blue > .5).Single();
Assert.Equal(200, blueBlob.Width, 2d);
Assert.Equal(100, blueBlob.Height, 2d);
// Analyze red inside- we expect it to fill the area minus the stroke thickness
var redBlob = ConnectedComponentAnalysis.FindConnectedPixels(bitmap, (c) => c.Red > .5).Single();
Assert.Equal(180, redBlob.Width, 2d);
Assert.Equal(80, redBlob.Height, 2d);
}
}
}
| BorderTests |
csharp | bchavez__Bogus | Source/Builder/Utils.cs | {
"start": 3951,
"end": 4603
} | public static class ____
{
public static string All(AbsolutePath historyFile)
{
return System.IO.File.ReadAllText(historyFile);
}
public static string NugetText(AbsolutePath historyFile, string githubUrl)
{
var allText = All(historyFile);
var q = allText.Split("##")
.Where(s => s.IsNotNullOrEmpty())
.Take(5);
var text = q.StringJoin("##");
var historyUrl = $"{githubUrl}/blob/master/HISTORY.md";
var sb = new StringBuilder();
sb.AppendLine($"##{text}");
sb.Append($"Full History Here: {historyUrl}");
var result = sb.ToString();
return result;
}
}
| History |
csharp | dotnet__machinelearning | src/Microsoft.ML.Transforms/Text/NgramTransform.cs | {
"start": 48471,
"end": 55304
} | internal sealed class ____
{
/// <summary>Name of the column resulting from the transformation of <see cref="InputColumnName"/>.</summary>
public readonly string Name;
/// <summary>Name of column to transform.</summary>
public readonly string InputColumnName;
/// <summary>Maximum n-gram length.</summary>
public readonly int NgramLength;
/// <summary>Maximum number of tokens to skip when constructing an n-gram.</summary>
public readonly int SkipLength;
/// <summary>Whether to store all n-gram lengths up to ngramLength, or only ngramLength.</summary>
public readonly bool UseAllLengths;
/// <summary>The weighting criteria.</summary>
public readonly WeightingCriteria Weighting;
/// <summary>
/// Underlying state of <see cref="MaximumNgramsCounts"/>.
/// </summary>
private readonly ImmutableArray<int> _maximumNgramsCounts;
/// <summary>
/// Contains the maximum number of terms (that is, n-grams) to store in the dictionary, for each level of n-grams,
/// from n=1 (in position 0) up to n=<see cref="NgramLength"/> (in position <see cref="NgramLength"/>-1)
/// </summary>
public IReadOnlyList<int> MaximumNgramsCounts => _maximumNgramsCounts;
/// <summary>
/// Describes how the transformer handles one Gcn column pair.
/// </summary>
/// <param name="name">Name of the column resulting from the transformation of <paramref name="inputColumnName"/>.</param>
/// <param name="inputColumnName">Name of column to transform. If set to <see langword="null"/>, the value of the <paramref name="name"/> will be used as source.</param>
/// <param name="ngramLength">Maximum n-gram length.</param>
/// <param name="skipLength">Maximum number of tokens to skip when constructing an n-gram.</param>
/// <param name="useAllLengths">Whether to store all n-gram lengths up to ngramLength, or only ngramLength.</param>
/// <param name="weighting">The weighting criteria.</param>
/// <param name="maximumNgramsCount">Maximum number of n-grams to store in the dictionary.</param>
public ColumnOptions(string name, string inputColumnName = null,
int ngramLength = Defaults.NgramLength,
int skipLength = Defaults.SkipLength,
bool useAllLengths = Defaults.UseAllLengths,
WeightingCriteria weighting = Defaults.Weighting,
int maximumNgramsCount = Defaults.MaximumNgramsCount)
: this(name, ngramLength, skipLength, useAllLengths, weighting, new int[] { maximumNgramsCount }, inputColumnName ?? name)
{
}
internal ColumnOptions(string name,
int ngramLength,
int skipLength,
bool useAllLengths,
WeightingCriteria weighting,
int[] maximumNgramsCounts,
string inputColumnName = null)
{
if (ngramLength == 1 && skipLength != 0)
throw Contracts.ExceptUserArg(nameof(skipLength), string.Format(
"{0} (actual value: {1}) can only be zero when {2} set to one.", nameof(skipLength), skipLength, nameof(ngramLength)));
if (ngramLength + skipLength > NgramBufferBuilder.MaxSkipNgramLength)
throw Contracts.ExceptUserArg(nameof(skipLength),
$"The sum of skipLength and ngramLength must be less than or equal to {NgramBufferBuilder.MaxSkipNgramLength}");
Contracts.CheckUserArg(0 < ngramLength && ngramLength <= NgramBufferBuilder.MaxSkipNgramLength, nameof(ngramLength));
var limits = new int[ngramLength];
if (!useAllLengths)
{
Contracts.CheckUserArg(Utils.Size(maximumNgramsCounts) == 0 ||
Utils.Size(maximumNgramsCounts) == 1 && maximumNgramsCounts[0] > 0, nameof(maximumNgramsCounts));
limits[ngramLength - 1] = Utils.Size(maximumNgramsCounts) == 0 ? Defaults.MaximumNgramsCount : maximumNgramsCounts[0];
}
else
{
Contracts.CheckUserArg(Utils.Size(maximumNgramsCounts) <= ngramLength, nameof(maximumNgramsCounts));
Contracts.CheckUserArg(Utils.Size(maximumNgramsCounts) == 0 || maximumNgramsCounts.All(i => i >= 0) && maximumNgramsCounts[maximumNgramsCounts.Length - 1] > 0, nameof(maximumNgramsCounts));
var extend = Utils.Size(maximumNgramsCounts) == 0 ? Defaults.MaximumNgramsCount : maximumNgramsCounts[maximumNgramsCounts.Length - 1];
limits = Utils.BuildArray(ngramLength, i => i < Utils.Size(maximumNgramsCounts) ? maximumNgramsCounts[i] : extend);
}
_maximumNgramsCounts = ImmutableArray.Create(limits);
Name = name;
InputColumnName = inputColumnName ?? name;
NgramLength = ngramLength;
SkipLength = skipLength;
UseAllLengths = useAllLengths;
Weighting = weighting;
}
}
/// <summary>
/// Returns the <see cref="SchemaShape"/> of the schema which will be produced by the transformer.
/// Used for schema propagation and verification in a pipeline.
/// </summary>
public SchemaShape GetOutputSchema(SchemaShape inputSchema)
{
_host.CheckValue(inputSchema, nameof(inputSchema));
var result = inputSchema.ToDictionary(x => x.Name);
foreach (var colInfo in _columns)
{
if (!inputSchema.TryFindColumn(colInfo.InputColumnName, out var col))
throw _host.ExceptSchemaMismatch(nameof(inputSchema), "input", colInfo.InputColumnName);
if (!IsSchemaColumnValid(col))
throw _host.ExceptSchemaMismatch(nameof(inputSchema), "input", colInfo.InputColumnName, ExpectedColumnType, col.GetTypeString());
var metadata = new List<SchemaShape.Column>();
if (col.NeedsSlotNames())
metadata.Add(new SchemaShape.Column(AnnotationUtils.Kinds.SlotNames, SchemaShape.Column.VectorKind.Vector, TextDataViewType.Instance, false));
result[colInfo.Name] = new SchemaShape.Column(colInfo.Name, SchemaShape.Column.VectorKind.Vector, NumberDataViewType.Single, false, new SchemaShape(metadata));
}
return new SchemaShape(result.Values);
}
}
}
| ColumnOptions |
csharp | dotnet__aspnetcore | src/OpenApi/test/Microsoft.AspNetCore.OpenApi.SourceGenerators.Tests/CompletenessTests.cs | {
"start": 13731,
"end": 13807
} | class ____ different XML comment scenarios for properties.
/// </summary>
| tests |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL/Types/TypeCollectionContext.cs | {
"start": 270,
"end": 2571
} | internal sealed class ____
{
/// <summary>
/// Initializes a new instance with the specified parameters.
/// </summary>
/// <param name="resolver">A delegate which returns an instance of a graph type from its .NET type.</param>
/// <param name="addType">A delegate which adds a graph type instance to the list of named graph types for the schema.</param>
/// <param name="typeMappings">CLR-GraphType type mappings.</param>
/// <param name="schema">The schema.</param>
internal TypeCollectionContext(Func<Type, IGraphType> resolver, Action<string, IGraphType, TypeCollectionContext> addType, IEnumerable<IGraphTypeMappingProvider>? typeMappings, ISchema schema)
{
ResolveType = resolver;
AddType = addType;
ClrToGraphTypeMappings = typeMappings;
Schema = schema;
if (GlobalSwitches.TrackGraphTypeInitialization)
InitializationTrace = [];
}
/// <summary>
/// Returns a delegate which returns an instance of a graph type from its .NET type.
/// </summary>
internal Func<Type, IGraphType> ResolveType { get; }
/// <summary>
/// Returns a delegate which adds a graph type instance to the list of named graph types for the schema.
/// </summary>
internal Action<string, IGraphType, TypeCollectionContext> AddType { get; }
internal IEnumerable<IGraphTypeMappingProvider>? ClrToGraphTypeMappings { get; }
internal Stack<Type> InFlightRegisteredTypes { get; } = new();
internal ISchema Schema { get; }
internal List<string>? InitializationTrace { get; set; }
internal TypeCollectionContextInitializationTrace Trace(string traceElement) =>
InitializationTrace == null
? default
: new(this, traceElement);
internal TypeCollectionContextInitializationTrace Trace(string traceElement, object? arg1)
{
return InitializationTrace == null
? default
: new(this, string.Format(traceElement, arg1));
}
internal TypeCollectionContextInitializationTrace Trace(string traceElement, object? arg1, object? arg2)
{
return InitializationTrace == null
? default
: new(this, string.Format(traceElement, arg1, arg2));
}
}
internal readonly | TypeCollectionContext |
csharp | dotnet__machinelearning | src/Microsoft.ML.OnnxConverter/OnnxContextImpl.cs | {
"start": 457,
"end": 19176
} | internal sealed class ____ : OnnxContext
{
private const int CurrentOpSetVersion = 12;
private const int MinimumOpSetVersion = 9;
private readonly List<OnnxCSharpToProtoWrapper.NodeProto> _nodes;
private readonly List<OnnxUtils.ModelArgs> _inputs;
// The map from IDataView column names to variable names.
private readonly List<OnnxCSharpToProtoWrapper.TensorProto> _initializers;
private readonly List<OnnxUtils.ModelArgs> _intermediateValues;
private readonly List<OnnxUtils.ModelArgs> _outputs;
private readonly Dictionary<string, string> _columnNameMap;
// All existing variable names. New variables must not exist in this set.
private readonly HashSet<string> _variableNames;
// All existing node names. New node names must not alrady exist in this set.
private readonly HashSet<string> _nodeNames;
private readonly string _name;
private readonly string _producerName;
private readonly IHost _host;
private readonly string _domain;
private readonly string _producerVersion;
private readonly long _modelVersion;
private readonly OnnxVersion _onnxVersion;
private readonly int _opSetVersion;
public OnnxContextImpl(IHostEnvironment env, string name, string producerName,
string producerVersion, long modelVersion, string domain, OnnxVersion onnxVersion, int opSetVersion = CurrentOpSetVersion)
{
Contracts.CheckValue(env, nameof(env));
_host = env.Register(nameof(OnnxContext));
_host.CheckValue(name, nameof(name));
_host.CheckValue(name, nameof(domain));
_nodes = new List<OnnxCSharpToProtoWrapper.NodeProto>();
_intermediateValues = new List<OnnxUtils.ModelArgs>();
_inputs = new List<OnnxUtils.ModelArgs>();
_initializers = new List<OnnxCSharpToProtoWrapper.TensorProto>();
_outputs = new List<OnnxUtils.ModelArgs>();
_columnNameMap = new Dictionary<string, string>();
_variableNames = new HashSet<string>();
_nodeNames = new HashSet<string>();
_name = name;
_producerName = producerName;
_producerVersion = producerVersion;
_modelVersion = modelVersion;
_domain = domain;
_onnxVersion = onnxVersion;
_opSetVersion = opSetVersion <= CurrentOpSetVersion ?
opSetVersion >= MinimumOpSetVersion ? opSetVersion : throw _host.ExceptParam(nameof(opSetVersion), $"Requested OpSet version {opSetVersion} is lower than the minimum required OpSet version {MinimumOpSetVersion}") :
throw _host.ExceptParam(nameof(opSetVersion), $"Requested OpSet version {opSetVersion} is higher than the current most updated OpSet version {CurrentOpSetVersion}");
}
public override bool ContainsColumn(string colName) => _columnNameMap.ContainsKey(colName);
public override bool IsVariableDefined(string variableName) => _variableNames.Contains(variableName);
/// <summary>
/// Stops tracking a column. If removeVariable is true then it also removes the
/// variable associated with it, this is useful in the event where an output variable is
/// created before realizing the transform cannot actually save as ONNX.
/// </summary>
/// <param name="colName">IDataView column name to stop tracking</param>
/// <param name="removeVariable">Remove associated ONNX variable at the time.</param>
public override void RemoveColumn(string colName, bool removeVariable)
{
_host.CheckNonEmpty(colName, nameof(colName));
if (removeVariable)
{
foreach (var val in _intermediateValues)
{
if (val.Name == _columnNameMap[colName])
{
_intermediateValues.Remove(val);
break;
}
}
}
_columnNameMap.Remove(colName);
}
/// <summary>
/// Removes an ONNX variable. If removeColumn is true then it also removes the
/// IDataView column associated with it.
/// </summary>
/// <param name="variableName">ONNX variable to remove.</param>
/// <param name="removeColumn">IDataView column to stop tracking</param>
public override void RemoveVariable(string variableName, bool removeColumn)
{
_host.CheckNonEmpty(variableName, nameof(variableName));
if (!_columnNameMap.ContainsValue(variableName))
throw _host.ExceptParam(nameof(variableName), $"Could not find '{variableName}' declared in ONNX graph");
if (removeColumn)
{
foreach (var val in _intermediateValues)
{
if (val.Name == variableName)
{
_intermediateValues.Remove(val);
break;
}
}
}
string columnName = _columnNameMap.Single(kvp => kvp.Value == variableName).Key;
Contracts.Assert(_variableNames.Contains(columnName));
_columnNameMap.Remove(columnName);
_variableNames.Remove(columnName);
}
/// <summary>
/// Generates a unique name for the node based on a prefix.
/// </summary>
public override string GetNodeName(string prefix)
{
_host.CheckNonEmpty(prefix, nameof(prefix));
return GetUniqueName(prefix, _nodeNames.Contains);
}
public override void CheckOpSetVersion(int thisTransformerMinumumOpSetVersion, string registerTransformerName)
{
if (_opSetVersion < thisTransformerMinumumOpSetVersion)
throw _host.ExceptParam(nameof(thisTransformerMinumumOpSetVersion), $"Requested OpSet version {_opSetVersion} is lower than {registerTransformerName}'s minimum OpSet version requirement: {thisTransformerMinumumOpSetVersion}");
}
/// <summary>
/// Adds a node to the node list of the graph.
/// </summary>
/// <param name="node"></param>
private void AddNode(OnnxCSharpToProtoWrapper.NodeProto node)
{
_host.CheckValue(node, nameof(node));
_host.Assert(!_nodeNames.Contains(node.Name));
_nodeNames.Add(node.Name);
_nodes.Add(node);
}
public override OnnxNode CreateNode(string opType, IEnumerable<string> inputs,
IEnumerable<string> outputs, string name, string domain = null)
{
_host.CheckNonEmpty(opType, nameof(opType));
_host.CheckValue(inputs, nameof(inputs));
_host.CheckValue(outputs, nameof(outputs));
_host.CheckNonEmpty(name, nameof(name));
var innerNode = OnnxUtils.MakeNode(opType, inputs, outputs, name, domain);
AddNode(innerNode);
return new OnnxNodeImpl(innerNode);
}
/// <summary>
/// Generates a unique name based on a prefix.
/// </summary>
private string GetUniqueName(string prefix, Func<string, bool> pred)
{
_host.CheckNonEmpty(prefix, nameof(prefix));
_host.CheckValue(pred, nameof(pred));
if (!pred(prefix))
return prefix;
int count = 0;
while (pred(prefix + count++)) ;
return prefix + --count;
}
/// <summary>
/// Retrieves the variable name that maps to the IDataView column name at a
/// given point in the pipeline execution.
/// </summary>
/// <returns>Column Name mapping.</returns>
public override string GetVariableName(string colName)
{
_host.CheckNonEmpty(colName, nameof(colName));
_host.Assert(_columnNameMap.ContainsKey(colName));
return _columnNameMap[colName];
}
/// <summary>
/// Retrieves the variable name that maps to the IDataView column name at a
/// given point in the pipeline execution.
/// </summary>
/// <returns>Column Name mapping.</returns>
public string TryGetVariableName(string colName)
{
_host.CheckNonEmpty(colName, nameof(colName));
if (_columnNameMap.ContainsKey(colName))
return GetVariableName(colName);
return null;
}
/// <summary>
/// Generates a unique column name based on the IDataView column name if
/// there is a collision between names in the pipeline at any point.
/// </summary>
/// <param name="colName">IDataView column name.</param>
/// <param name="makeUniqueName">Whether a unique name should be chosen for this variable.</param>
/// <returns>Unique variable name.</returns>
public string AddVariable(string colName, bool makeUniqueName = true)
{
_host.CheckNonEmpty(colName, nameof(colName));
_columnNameMap[colName] = makeUniqueName ? GetUniqueName(colName, _variableNames.Contains) : colName;
_variableNames.Add(_columnNameMap[colName]);
return _columnNameMap[colName];
}
/// <summary>
/// Adds an intermediate column to the list.
/// </summary>
public override string AddIntermediateVariable(DataViewType type, string colName, bool skip = false)
{
colName = AddVariable(colName);
// Let the runtime figure the shape.
if (!skip)
{
_host.CheckValue(type, nameof(type));
_intermediateValues.Add(OnnxUtils.GetModelArgs(type, colName));
}
return colName;
}
/// <summary>
/// Adds an output variable to the list.
/// </summary>
public void AddOutputVariable(DataViewType type, string variableName, List<long> dim = null)
{
_host.CheckValue(type, nameof(type));
_host.CheckParam(IsVariableDefined(variableName), nameof(variableName));
_outputs.Add(OnnxUtils.GetModelArgs(type, variableName, dim));
}
/// <summary>
/// Adds an input variable to the list.
/// </summary>
public void AddInputVariable(DataViewType type, string colName)
{
_host.CheckValue(type, nameof(type));
_host.CheckValue(colName, nameof(colName));
colName = AddVariable(colName);
_inputs.Add(OnnxUtils.GetModelArgs(type, colName));
}
public override void RemoveInputVariable(string colName)
{
var variableName = TryGetVariableName(colName);
_host.CheckValue(variableName, nameof(variableName));
RemoveVariable(variableName, true);
_inputs.Remove(_inputs.Single(modelArg => modelArg.Name == variableName));
}
/// <summary>
/// Retrieve the shape of an ONNX variable. Returns null if no shape for the specified variable can be found.
/// </summary>
/// <param name="variableName">The ONNX name of the returned shape</param>
/// <returns>The shape of the retrieved variable</returns>
public override List<long> RetrieveShapeOrNull(string variableName)
{
foreach (var arg in _inputs)
if (arg.Name == variableName)
return arg.Dims;
foreach (var arg in _intermediateValues)
if (arg.Name == variableName)
return arg.Dims;
foreach (var arg in _outputs)
if (arg.Name == variableName)
return arg.Dims;
return null;
}
/// Adds constant tensor into the graph.
public override string AddInitializer(bool value, string name = null, bool makeUniqueName = true)
{
name = AddVariable(name ?? "bool", makeUniqueName);
_initializers.Add(OnnxUtils.MakeInt32(name, typeof(bool), value ? 1 : 0));
return name;
}
public override string AddInitializer(float value, string name = null, bool makeUniqueName = true)
{
name = AddVariable(name ?? "float", makeUniqueName);
_initializers.Add(OnnxUtils.MakeFloat(name, value));
return name;
}
public override string AddInitializer(int value, Type type, string name = null, bool makeUniqueName = true)
{
name = AddVariable(name ?? "int32", makeUniqueName);
_initializers.Add(OnnxUtils.MakeInt32(name, type, value));
return name;
}
public override string AddInitializer(string value, string name = null, bool makeUniqueName = true)
{
name = AddVariable(name ?? "string", makeUniqueName);
_initializers.Add(OnnxUtils.MakeString(name, value));
return name;
}
public override string AddInitializer(long value, string name = null, bool makeUniqueName = true)
{
name = AddVariable(name ?? "int64", makeUniqueName);
_initializers.Add(OnnxUtils.MakeInt64(name, value));
return name;
}
public override string AddInitializer(double value, string name = null, bool makeUniqueName = true)
{
name = AddVariable(name ?? "double", makeUniqueName);
_initializers.Add(OnnxUtils.MakeDouble(name, value));
return name;
}
public override string AddInitializer(ulong value, bool isUint64, string name = null, bool makeUniqueName = true)
{
name = AddVariable(name ?? "uint64", makeUniqueName);
_initializers.Add(OnnxUtils.MakeUInt(name, isUint64, value));
return name;
}
public override string AddInitializer(IEnumerable<bool> values, IEnumerable<long> dims, string name = null, bool makeUniqueName = true)
{
_host.CheckValue(values, nameof(values));
if (dims != null)
_host.Check(dims.Aggregate((x, y) => x * y) == values.Count(), "Number of elements doesn't match tensor size");
name = AddVariable(name ?? "bools", makeUniqueName);
_initializers.Add(OnnxUtils.MakeInt32s(name, typeof(bool), values.Select(v => Convert.ToInt32(v)), dims));
return name;
}
public override string AddInitializer(IEnumerable<float> values, IEnumerable<long> dims, string name = null, bool makeUniqueName = true)
{
_host.CheckValue(values, nameof(values));
if (dims != null)
_host.Check(dims.Aggregate((x, y) => x * y) == values.Count(), "Number of elements doesn't match tensor size");
name = AddVariable(name ?? "floats", makeUniqueName);
_initializers.Add(OnnxUtils.MakeFloats(name, values, dims));
return name;
}
public override string AddInitializer(IEnumerable<int> values, Type type, IEnumerable<long> dims, string name = null, bool makeUniqueName = true)
{
_host.CheckValue(values, nameof(values));
if (dims != null)
_host.Check(dims.Aggregate((x, y) => x * y) == values.Count(), "Number of elements doesn't match tensor size");
name = AddVariable(name ?? "int32s", makeUniqueName);
_initializers.Add(OnnxUtils.MakeInt32s(name, type, values, dims));
return name;
}
public override string AddInitializer(IEnumerable<string> values, IEnumerable<long> dims, string name = null, bool makeUniqueName = true)
{
_host.CheckValue(values, nameof(values));
if (dims != null)
_host.Check(dims.Aggregate((x, y) => x * y) == values.Count(), "Number of elements doesn't match tensor size");
name = AddVariable(name ?? "strings", makeUniqueName);
_initializers.Add(OnnxUtils.MakeStrings(name, values, dims));
return name;
}
public override string AddInitializer(IEnumerable<long> values, IEnumerable<long> dims, string name = null, bool makeUniqueName = true)
{
_host.CheckValue(values, nameof(values));
if (dims != null)
_host.Check(dims.Aggregate((x, y) => x * y) == values.Count(), "Number of elements doesn't match tensor size");
name = AddVariable(name ?? "int64s", makeUniqueName);
_initializers.Add(OnnxUtils.MakeInt64s(name, values, dims));
return name;
}
public override string AddInitializer(IEnumerable<double> values, IEnumerable<long> dims, string name = null, bool makeUniqueName = true)
{
_host.CheckValue(values, nameof(values));
if (dims != null)
_host.Check(dims.Aggregate((x, y) => x * y) == values.Count(), "Number of elements doesn't match tensor size");
name = AddVariable(name ?? "doubles", makeUniqueName);
_initializers.Add(OnnxUtils.MakeDoubles(name, values, dims));
return name;
}
public override string AddInitializer(IEnumerable<ulong> values, bool isUint64, IEnumerable<long> dims, string name = null, bool makeUniqueName = true)
{
_host.CheckValue(values, nameof(values));
if (dims != null)
_host.Check(dims.Aggregate((x, y) => x * y) == values.Count(), "Number of elements doesn't match tensor size");
name = AddVariable(name ?? "uints", makeUniqueName);
_initializers.Add(OnnxUtils.MakeUInts(name, isUint64, values, dims));
return name;
}
/// <summary>
/// Makes the ONNX model based on the context.
/// </summary>
public OnnxCSharpToProtoWrapper.ModelProto MakeModel()
=> OnnxUtils.MakeModel(_nodes, _producerName, _name, _domain, _producerVersion, _modelVersion, _opSetVersion, _inputs, _outputs, _intermediateValues, _initializers);
/// <summary>
/// Return either "Experimental" or "Stable". The string "Experimental" indicates that some experimental features which are
/// not officially supported in the official ONNX standard. Otherwise, only official ONNX features should be used.
/// </summary>
public override OnnxVersion GetOnnxVersion() => _onnxVersion;
}
}
| OnnxContextImpl |
csharp | cake-build__cake | src/Cake.Common.Tests/Unit/ProcessAliasesTests.cs | {
"start": 3086,
"end": 8345
} | public sealed class ____
{
[Fact]
public void Should_Throw_If_Context_Is_Null()
{
// Given
const string fileName = "git";
var settings = new ProcessSettings();
// When
var result = Record.Exception(() =>
ProcessAliases.StartProcess(null, fileName, settings));
// Then
AssertEx.IsArgumentNullException(result, "context");
}
[Fact]
public void Should_Throw_If_Filename_Is_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
var settings = new ProcessSettings();
// When
var result = Record.Exception(() =>
context.StartProcess(null, settings));
// Then
AssertEx.IsArgumentNullException(result, "fileName");
}
[Fact]
public void Should_Throw_If_Settings_Are_Null()
{
// Given
var context = Substitute.For<ICakeContext>();
const string fileName = "git";
// When
var result = Record.Exception(() =>
context.StartProcess(fileName, (ProcessSettings)null));
// Then
AssertEx.IsArgumentNullException(result, "settings");
}
[Fact]
public void Should_Use_Environments_Working_Directory_If_Not_Working_Directory_Is_Set()
{
// Given
var fixture = new ProcessFixture();
const string fileName = "hello.exe";
var settings = new ProcessSettings();
// When
fixture.Start(fileName, settings);
// Then
fixture.ProcessRunner.Received(1).Start(
Arg.Any<FilePath>(),
Arg.Is<ProcessSettings>(info =>
info.WorkingDirectory.FullPath == "/Working"));
}
[Fact]
public void Should_Use_Provided_Working_Directory_If_Set()
{
// Given
var fixture = new ProcessFixture();
const string fileName = "hello.exe";
var settings = new ProcessSettings();
settings.WorkingDirectory = "/OtherWorking";
// When
fixture.Start(fileName, settings);
// Then
fixture.ProcessRunner.Received(1).Start(
Arg.Any<FilePath>(),
Arg.Is<ProcessSettings>(info =>
info.WorkingDirectory.FullPath == "/OtherWorking"));
}
[Fact]
public void Should_Make_Working_Directory_Absolute_If_Set()
{
// Given
var fixture = new ProcessFixture();
const string fileName = "hello.exe";
var settings = new ProcessSettings();
settings.WorkingDirectory = "OtherWorking";
// When
fixture.Start(fileName, settings);
// Then
fixture.ProcessRunner.Received(1).Start(
Arg.Any<FilePath>(),
Arg.Is<ProcessSettings>(info =>
info.WorkingDirectory.FullPath == "/Working/OtherWorking"));
}
[Fact]
public void Should_Throw_If_No_Process_Was_Returned_From_Process_Runner()
{
// Given
var fixture = new ProcessFixture();
const string fileName = "hello.exe";
var settings = new ProcessSettings();
fixture.ProcessRunner.Start(
Arg.Any<FilePath>(),
Arg.Any<ProcessSettings>()).Returns((IProcess)null);
// When
var result = Record.Exception(() => fixture.Start(fileName, settings));
// Then
Assert.IsType<CakeException>(result);
Assert.Equal("Could not start process.", result?.Message);
}
[Fact]
public void Should_Return_Exit_Code()
{
// Given
var fixture = new ProcessFixture();
const string fileName = "hello.exe";
var settings = new ProcessSettings();
fixture.Process.GetExitCode().Returns(12);
// When
var result = fixture.Start(fileName, settings);
// Then
Assert.Equal(12, result);
}
}
| WithSettings |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Common/Helpers/AdminStoreService.cs | {
"start": 252,
"end": 1063
} | public class ____ : IAdminStoreService
{
private readonly IStoreService _storeService;
private readonly IContextAccessor _contextAccessor;
public AdminStoreService(IStoreService storeService, IContextAccessor contextAccessor)
{
_storeService = storeService;
_contextAccessor = contextAccessor;
}
public async Task<string> GetActiveStore()
{
var stores = await _storeService.GetAllStores();
if (stores.Count < 2)
return stores.FirstOrDefault()!.Id;
var storeId = _contextAccessor.WorkContext.CurrentCustomer.GetUserFieldFromEntity<string>(SystemCustomerFieldNames.AdminAreaStoreScopeConfiguration);
var store = await _storeService.GetStoreById(storeId);
return store != null ? store.Id : "";
}
} | AdminStoreService |
csharp | dotnet__maui | src/Compatibility/Core/src/iOS/CollectionView/GroupableItemsViewDelegator.cs | {
"start": 150,
"end": 1417
} | public class ____<TItemsView, TViewController> : SelectableItemsViewDelegator<TItemsView, TViewController>
where TItemsView : GroupableItemsView
where TViewController : GroupableItemsViewController<TItemsView>
{
public GroupableItemsViewDelegator(ItemsViewLayout itemsViewLayout, TViewController itemsViewController)
: base(itemsViewLayout, itemsViewController)
{
}
public override CGSize GetReferenceSizeForHeader(UICollectionView collectionView, UICollectionViewLayout layout, nint section)
{
return ViewController.GetReferenceSizeForHeader(collectionView, layout, section);
}
public override CGSize GetReferenceSizeForFooter(UICollectionView collectionView, UICollectionViewLayout layout, nint section)
{
return ViewController.GetReferenceSizeForFooter(collectionView, layout, section);
}
public override void ScrollAnimationEnded(UIScrollView scrollView)
{
ViewController?.HandleScrollAnimationEnded();
}
public override UIEdgeInsets GetInsetForSection(UICollectionView collectionView, UICollectionViewLayout layout, nint section)
{
if (ItemsViewLayout == null)
{
return default;
}
return ViewController.GetInsetForSection(ItemsViewLayout, collectionView, section);
}
}
} | GroupableItemsViewDelegator |
csharp | unoplatform__uno | src/Uno.Foundation/Generated/2.0.0.0/Windows.Foundation.Collections/IIterator.cs | {
"start": 265,
"end": 775
} | public partial interface ____<T>
{
// Skipping already declared property Current
// Skipping already declared property HasCurrent
// Forced skipping of method Windows.Foundation.Collections.IIterator<T>.Current.get
// Forced skipping of method Windows.Foundation.Collections.IIterator<T>.HasCurrent.get
// Skipping already declared method Windows.Foundation.Collections.IIterator<T>.MoveNext()
// Skipping already declared method Windows.Foundation.Collections.IIterator<T>.GetMany(T[])
}
}
| IIterator |
csharp | AutoMapper__AutoMapper | src/UnitTests/OpenGenerics.cs | {
"start": 161,
"end": 218
} | class ____
{
public int Id;
}
| InnerSource |
csharp | graphql-dotnet__graphql-dotnet | src/GraphQL.Tests/Execution/VariablesTests.cs | {
"start": 4400,
"end": 5825
} | public class ____ : QueryTestBase<VariablesSchema>
{
[Fact]
public void executes_with_complex_input()
{
const string query = """
{
fieldWithObjectInput(input: {a: "foo", b: ["bar"], c: "baz"})
}
""";
const string expected = """{ "fieldWithObjectInput": "{\"a\":\"foo\",\"b\":[\"bar\"],\"c\":\"baz\"}" }""";
AssertQuerySuccess(query, expected);
}
[Fact]
public void properly_parses_single_value_to_list()
{
const string query = """
{
fieldWithObjectInput(input: {a: "foo", b: "bar", c: "baz"})
}
""";
const string expected = """{ "fieldWithObjectInput": "{\"a\":\"foo\",\"b\":[\"bar\"],\"c\":\"baz\"}" }""";
AssertQuerySuccess(query, expected);
}
[Fact]
public void fail_on_incorrect_value()
{
const string query = """
{
fieldWithObjectInput(input: ["foo", "bar", "baz"])
}
""";
var result = AssertQueryWithErrors(query, null, rules: Enumerable.Empty<IValidationRule>(), expectedErrorCount: 1, executed: false);
result.Errors![0].Message.ShouldBe("""Invalid literal for argument 'input' of field 'fieldWithObjectInput'. Expected object value for 'TestInputObject', found not an object '["foo", "bar", "baz"]'.""");
}
}
| Variables_With_Inline_Structs_Tests |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml/Clipping/ClippingRoundedCorners.xaml.cs | {
"start": 167,
"end": 293
} | partial class ____ : Page
{
public ClippingRoundedCorners()
{
this.InitializeComponent();
}
}
}
| ClippingRoundedCorners |
csharp | dotnet__efcore | test/EFCore.OData.FunctionalTests/Query/ODataQueryTestBase.cs | {
"start": 187,
"end": 405
} | public abstract class ____(IODataQueryTestFixture fixture)
{
public string BaseAddress { get; } = fixture.BaseAddress;
public HttpClient Client { get; } = fixture.ClientFactory.CreateClient();
}
| ODataQueryTestBase |
csharp | dotnet__maui | src/Controls/tests/Xaml.UnitTests/BindablePropertiesAccessModifiers.xaml.cs | {
"start": 121,
"end": 736
} | public class ____ : View
{
public static BindableProperty PublicFooProperty = BindableProperty.Create(nameof(PublicFoo),
typeof(string),
typeof(AccessModifiersControl),
"");
public string PublicFoo
{
get => (string)GetValue(PublicFooProperty);
set => SetValue(PublicFooProperty, value);
}
internal static BindableProperty InternalBarProperty = BindableProperty.Create(nameof(InternalBar),
typeof(string),
typeof(AccessModifiersControl),
"");
public string InternalBar
{
get => (string)GetValue(InternalBarProperty);
set => SetValue(InternalBarProperty, value);
}
}
| AccessModifiersControl |
csharp | nunit__nunit | src/NUnitFramework/tests/Assertions/AssertThatTests.cs | {
"start": 45788,
"end": 46083
} | private sealed class ____
{
public ParentClass(ChildClass one, ChildClass two)
{
One = one;
Two = two;
}
public ChildClass One { get; }
public ChildClass Two { get; }
}
| ParentClass |
csharp | FluentValidation__FluentValidation | src/FluentValidation/Resources/Languages/BulgarianLanguage.cs | {
"start": 810,
"end": 3935
} | internal class ____ {
public const string Culture = "bg";
public static string GetTranslation(string key) => key switch {
"EmailValidator" => "'{PropertyName}' не е валиден е-мейл адрес.",
"GreaterThanOrEqualValidator" => "'{PropertyName}' трябва да бъде по-голямо или равно на '{ComparisonValue}'.",
"GreaterThanValidator" => "'{PropertyName}' трябва да бъде по-голямо от '{ComparisonValue}'.",
"LengthValidator" => "'{PropertyName}' символите трябва да бъдат между {MinLength} и {MaxLength}. Въведохте {TotalLength} знака.",
"MinimumLengthValidator" => "Дължината на '{PropertyName}' трябва да бъде най-малко {MinLength} брой символи. Въведохте {TotalLength} знака.",
"MaximumLengthValidator" => "Дължината на '{PropertyName}' трябва да бъде {MaxLength} брой символи. Въведохте {TotalLength} знака.",
"LessThanOrEqualValidator" => "'{PropertyName}' трябва да бъде по-малко или равно на '{ComparisonValue}'.",
"LessThanValidator" => "'{PropertyName}' трябва да бъде по-малко от '{ComparisonValue}'.",
"NotEmptyValidator" => "'{PropertyName}' не трябва да бъде празно.",
"NotEqualValidator" => "'{PropertyName}' не трябва да бъде равно на '{ComparisonValue}'.",
"NotNullValidator" => "'{PropertyName}' не трябва да бъде празно.",
"PredicateValidator" => "Специалните изисквания за '{PropertyName}' не са спазени.",
"AsyncPredicateValidator" => "Специалните изисквания за '{PropertyName}' не са спазени.",
"RegularExpressionValidator" => "'{PropertyName}' не е в правилния формат.",
"EqualValidator" => "'{PropertyName}' трябва да бъде равно на '{ComparisonValue}'.",
"ExactLengthValidator" => "'{PropertyName}' трябва да бъде {MaxLength} брой на символите. Въведохте {TotalLength} знака.",
"InclusiveBetweenValidator" => "'{PropertyName}' трябва да бъде между {From} и {To}. Вие въведохте {PropertyValue}.",
"ExclusiveBetweenValidator" => "'{PropertyName}' трябва да бъде между {From} и {To} (изключително). Вие въведохте {PropertyValue}.",
"CreditCardValidator" => "'{PropertyName}' не е валиден номер на кредитна карта.",
"ScalePrecisionValidator" => "'{PropertyName}' не трябва да е повече от {ExpectedPrecision} цифри и трябва да бъде до {ExpectedScale} знака след запетаята. В момента има {Digits} цифри и {ActualScale} знака след запетаята.",
"EmptyValidator" => "'{PropertyName}' трябва да бъде празно.",
"NullValidator" => "'{PropertyName}' трябва да бъде празно.",
"EnumValidator" => "'{PropertyName}' има диапазон, които не обхващат '{PropertyValue}'.",
// Additional fallback messages used by clientside validation integration.
"Length_Simple" => "'{PropertyName}' трябва да бъде межди {MinLength} и {MaxLength} брой символи.",
"MinimumLength_Simple" => "Дължината на '{PropertyName}' трябва да бъде поне {MinLength} символи.",
"MaximumLength_Simple" => "Дължината на '{PropertyName}' трябва да бъде {MaxLength} или по-малко брой символи.",
"ExactLength_Simple" => "'{PropertyName}' трябва да бъде {MaxLength} дължина на символите.",
"InclusiveBetween_Simple" => "'{PropertyName}' трябва да бъде между {From} и {To}.",
_ => null,
};
}
| BulgarianLanguage |
csharp | dotnet__machinelearning | test/Microsoft.ML.AutoML.Tests/SuggestedPipelineBuilderTests.cs | {
"start": 355,
"end": 3161
} | public class ____ : BaseTestClass
{
private static MLContext _context = new MLContext(1);
public SuggestedPipelineBuilderTests(ITestOutputHelper output) : base(output)
{
}
[Fact]
public void TrainerWantsCaching()
{
TestPipelineBuilderCaching(BuildAveragedPerceptronTrainer(),
new CacheBeforeTrainer[] { CacheBeforeTrainer.On, CacheBeforeTrainer.Off, CacheBeforeTrainer.Auto },
new[] { true, false, true });
}
[Fact]
public void TrainerDoesntWantCaching()
{
TestPipelineBuilderCaching(BuildLightGbmTrainer(),
new CacheBeforeTrainer[] { CacheBeforeTrainer.On, CacheBeforeTrainer.Off, CacheBeforeTrainer.Auto },
new[] { true, false, false });
}
[Fact]
public void TrainerNeedsNormalization()
{
var pipeline = BuildSuggestedPipeline(BuildAveragedPerceptronTrainer());
Assert.Equal(EstimatorName.Normalizing.ToString(),
pipeline.Transforms[0].PipelineNode.Name);
}
[Fact]
public void TrainerNotNeedNormalization()
{
var pipeline = BuildSuggestedPipeline(BuildLightGbmTrainer());
Assert.Empty(pipeline.Transforms);
}
private static void TestPipelineBuilderCaching(
SuggestedTrainer trainer,
CacheBeforeTrainer[] cacheBeforeTrainerSettings,
bool[] resultShouldHaveCaching)
{
for (var i = 0; i < cacheBeforeTrainerSettings.Length; i++)
{
var suggestedPipeline = BuildSuggestedPipeline(trainer,
cacheBeforeTrainerSettings[i]);
Assert.Equal(resultShouldHaveCaching[i],
suggestedPipeline.ToPipeline().CacheBeforeTrainer);
}
}
private static SuggestedTrainer BuildAveragedPerceptronTrainer()
{
return new SuggestedTrainer(_context,
new AveragedPerceptronBinaryExtension(),
new ColumnInformation());
}
private static SuggestedTrainer BuildLightGbmTrainer()
{
return new SuggestedTrainer(_context,
new LightGbmBinaryExtension(),
new ColumnInformation());
}
private static SuggestedPipeline BuildSuggestedPipeline(SuggestedTrainer trainer,
CacheBeforeTrainer cacheBeforeTrainer = CacheBeforeTrainer.Auto)
{
return SuggestedPipelineBuilder.Build(_context,
new List<SuggestedTransform>(),
new List<SuggestedTransform>(),
trainer, cacheBeforeTrainer);
}
}
}
| SuggestedPipelineBuilderTests |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.Devices.Printers/IppAttributeError.cs | {
"start": 299,
"end": 2537
} | public partial class ____
{
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
internal IppAttributeError()
{
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Exception ExtendedError
{
get
{
throw new global::System.NotImplementedException("The member Exception IppAttributeError.ExtendedError is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=Exception%20IppAttributeError.ExtendedError");
}
}
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::Windows.Devices.Printers.IppAttributeErrorReason Reason
{
get
{
throw new global::System.NotImplementedException("The member IppAttributeErrorReason IppAttributeError.Reason is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IppAttributeErrorReason%20IppAttributeError.Reason");
}
}
#endif
// Forced skipping of method Windows.Devices.Printers.IppAttributeError.Reason.get
// Forced skipping of method Windows.Devices.Printers.IppAttributeError.ExtendedError.get
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
[global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")]
public global::System.Collections.Generic.IReadOnlyList<global::Windows.Devices.Printers.IppAttributeValue> GetUnsupportedValues()
{
throw new global::System.NotImplementedException("The member IReadOnlyList<IppAttributeValue> IppAttributeError.GetUnsupportedValues() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IReadOnlyList%3CIppAttributeValue%3E%20IppAttributeError.GetUnsupportedValues%28%29");
}
#endif
}
}
| IppAttributeError |
csharp | OrchardCMS__OrchardCore | src/OrchardCore/OrchardCore.Mvc.Core/RazorPages/ModularPageApplicationModelProvider.cs | {
"start": 239,
"end": 1765
} | public class ____ : IPageApplicationModelProvider
{
private readonly ILookup<string, string> _featureIdsByArea;
public ModularPageApplicationModelProvider(
IExtensionManager extensionManager,
ShellDescriptor shellDescriptor)
{
// Available features by area in the current shell.
_featureIdsByArea = extensionManager.GetFeatures()
.Where(f => shellDescriptor.Features.Any(sf => sf.Id == f.Id))
.ToLookup(f => f.Extension.Id, f => f.Id);
}
public int Order => -1000 + 10;
public void OnProvidersExecuting(PageApplicationModelProviderContext context)
{
}
// Called the 1st time a page is requested or if any page has been updated.
public void OnProvidersExecuted(PageApplicationModelProviderContext context)
{
// Check if the page belongs to an enabled feature.
var found = false;
var area = context.PageApplicationModel.AreaName;
if (_featureIdsByArea.Contains(area))
{
found = true;
var pageModelType = context.PageApplicationModel.ModelType.AsType();
var attribute = pageModelType.GetCustomAttributes<FeatureAttribute>(false).FirstOrDefault();
if (attribute != null)
{
found = _featureIdsByArea[area].Contains(attribute.FeatureName);
}
}
context.PageApplicationModel.Filters.Add(new ModularPageViewEnginePathFilter(found));
}
}
| ModularPageApplicationModelProvider |
csharp | getsentry__sentry-dotnet | test/Sentry.Tests/Internals/ApplicationVersionLocatorTests.cs | {
"start": 75,
"end": 1924
} | public class ____
{
[Theory]
[InlineData("5fd7a6cda8444965bade9ccfd3df9882")]
[InlineData("1.0")]
[InlineData("1.0 - 5fd7a6c")]
[InlineData("1.0-beta")]
[InlineData("2.1.0.0")]
[InlineData("2.1.0.0-preview1")]
public void GetCurrent_ValidVersion_ReturnsVersion(string expectedVersion)
{
var name = "dynamic-assembly";
var asm = AssemblyCreationHelper.CreateWithInformationalVersion(expectedVersion, new AssemblyName(name));
var actual = ApplicationVersionLocator.GetCurrent(asm);
Assert.Equal($"{name}@{expectedVersion}", actual);
}
[Fact]
public void GetCurrent_VersionWithPrefix_ReturnsVersionAsIs()
{
// Arrange
var asm = AssemblyCreationHelper.CreateWithInformationalVersion(
"app@1.0.0",
new AssemblyName("dynamic-assembly"));
// Act
var version = ApplicationVersionLocator.GetCurrent(asm);
// Assert
version.Should().Be("app@1.0.0");
}
[Theory]
[InlineData("")]
public void GetCurrent_InvalidCases_DoesNotReturnNull(string version)
{
var asm = AssemblyCreationHelper.CreateWithInformationalVersion(version);
var actual = ApplicationVersionLocator.GetCurrent(asm);
Assert.NotNull(actual);
}
[Fact]
public void GetCurrent_NoAsmInformationalVersion_ReturnsAsmVersion()
{
const string expectedName = "foo";
const string expectedVersion = "2.1.0.0";
var asmName = new AssemblyName(expectedName)
{
Version = Version.Parse(expectedVersion)
};
var asm = AssemblyCreationHelper.CreateAssembly(asmName);
var actual = ApplicationVersionLocator.GetCurrent(asm);
Assert.Equal(expectedName + '@' + expectedVersion, actual);
}
}
| ApplicationVersionLocatorTests |
csharp | dotnet__maui | src/Compatibility/Core/src/GTK/Extensions/ButtonContentLayoutExtensions.cs | {
"start": 160,
"end": 749
} | public static class ____
{
public static PositionType AsPositionType(this ButtonContentLayout.ImagePosition position)
{
switch (position)
{
case ButtonContentLayout.ImagePosition.Bottom:
return PositionType.Bottom;
case ButtonContentLayout.ImagePosition.Left:
return PositionType.Left;
case ButtonContentLayout.ImagePosition.Right:
return PositionType.Right;
case ButtonContentLayout.ImagePosition.Top:
return PositionType.Top;
default:
throw new ArgumentOutOfRangeException(nameof(position));
}
}
}
}
| ButtonContentLayoutExtensions |
csharp | ServiceStack__ServiceStack.OrmLite | tests/ServiceStack.OrmLite.Tests/Issues/NullReferenceIssues.cs | {
"start": 253,
"end": 1452
} | public class ____
{
public int Id { get; set; }
public string Name { get; set; }
public string Key { get; set; }
public int Int { get; set; }
}
[Test]
[IgnoreDialect(Dialect.Sqlite, "Not supported")]
public void Can_AlterColumn()
{
using (var db = OpenDbConnection())
{
db.DropAndCreateTable<Foo>();
db.AlterColumn(typeof(Foo), new FieldDefinition
{
Name = nameof(Foo.Name),
FieldType = typeof(string),
IsNullable = true,
DefaultValue = null
});
db.AlterColumn(typeof(Foo), new FieldDefinition
{
Name = nameof(Foo.Int),
FieldType = typeof(int),
IsNullable = true,
DefaultValue = null
});
db.AddColumn(typeof(Foo), new FieldDefinition
{
Name = "Bool",
FieldType = typeof(bool),
});
}
}
}
} | Foo |
csharp | bitwarden__server | test/Infrastructure.EFIntegration.Test/Vault/AutoFixture/FolderFixtures.cs | {
"start": 1033,
"end": 1557
} | internal class ____ : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customizations.Add(new IgnoreVirtualMembersCustomization());
fixture.Customizations.Add(new GlobalSettingsBuilder());
fixture.Customizations.Add(new FolderBuilder());
fixture.Customizations.Add(new UserBuilder());
fixture.Customizations.Add(new EfRepositoryListBuilder<FolderRepository>());
fixture.Customizations.Add(new EfRepositoryListBuilder<UserRepository>());
}
}
| EfFolder |
csharp | dotnet__reactive | AsyncRx.NET/System.Reactive.Async/Joins/AsyncPlan.Generated.cs | {
"start": 46018,
"end": 51275
} | internal abstract class ____<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10, TResult> : AsyncPlan<TResult>
{
private readonly AsyncPattern<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10> _expression;
internal AsyncPlanBase(AsyncPattern<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10> expression)
{
_expression = expression;
}
protected abstract ValueTask<TResult> EvalAsync(TSource1 arg1, TSource2 arg2, TSource3 arg3, TSource4 arg4, TSource5 arg5, TSource6 arg6, TSource7 arg7, TSource8 arg8, TSource9 arg9, TSource10 arg10);
internal override ActiveAsyncPlan Activate(Dictionary<object, IAsyncJoinObserver> externalSubscriptions, IAsyncObserver<TResult> observer, Func<ActiveAsyncPlan, ValueTask> deactivate)
{
var onError = new Func<Exception, ValueTask>(observer.OnErrorAsync);
var joinObserver1 = AsyncPlan<TResult>.CreateObserver<TSource1>(externalSubscriptions, _expression.Source1, onError);
var joinObserver2 = AsyncPlan<TResult>.CreateObserver<TSource2>(externalSubscriptions, _expression.Source2, onError);
var joinObserver3 = AsyncPlan<TResult>.CreateObserver<TSource3>(externalSubscriptions, _expression.Source3, onError);
var joinObserver4 = AsyncPlan<TResult>.CreateObserver<TSource4>(externalSubscriptions, _expression.Source4, onError);
var joinObserver5 = AsyncPlan<TResult>.CreateObserver<TSource5>(externalSubscriptions, _expression.Source5, onError);
var joinObserver6 = AsyncPlan<TResult>.CreateObserver<TSource6>(externalSubscriptions, _expression.Source6, onError);
var joinObserver7 = AsyncPlan<TResult>.CreateObserver<TSource7>(externalSubscriptions, _expression.Source7, onError);
var joinObserver8 = AsyncPlan<TResult>.CreateObserver<TSource8>(externalSubscriptions, _expression.Source8, onError);
var joinObserver9 = AsyncPlan<TResult>.CreateObserver<TSource9>(externalSubscriptions, _expression.Source9, onError);
var joinObserver10 = AsyncPlan<TResult>.CreateObserver<TSource10>(externalSubscriptions, _expression.Source10, onError);
var activePlan = default(ActiveAsyncPlan<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10>);
activePlan = new ActiveAsyncPlan<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10>(
joinObserver1,
joinObserver2,
joinObserver3,
joinObserver4,
joinObserver5,
joinObserver6,
joinObserver7,
joinObserver8,
joinObserver9,
joinObserver10,
async (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10) =>
{
var res = default(TResult);
try
{
res = await EvalAsync(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10).ConfigureAwait(false);
}
catch (Exception ex)
{
await observer.OnErrorAsync(ex).ConfigureAwait(false);
return;
}
await observer.OnNextAsync(res).ConfigureAwait(false);
},
async () =>
{
await joinObserver1.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver2.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver3.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver4.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver5.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver6.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver7.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver8.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver9.RemoveActivePlan(activePlan).ConfigureAwait(false);
await joinObserver10.RemoveActivePlan(activePlan).ConfigureAwait(false);
await deactivate(activePlan).ConfigureAwait(false);
}
);
joinObserver1.AddActivePlan(activePlan);
joinObserver2.AddActivePlan(activePlan);
joinObserver3.AddActivePlan(activePlan);
joinObserver4.AddActivePlan(activePlan);
joinObserver5.AddActivePlan(activePlan);
joinObserver6.AddActivePlan(activePlan);
joinObserver7.AddActivePlan(activePlan);
joinObserver8.AddActivePlan(activePlan);
joinObserver9.AddActivePlan(activePlan);
joinObserver10.AddActivePlan(activePlan);
return activePlan;
}
}
| AsyncPlanBase |
csharp | unoplatform__uno | src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/Repeater/ItemsRepeater_Nested.xaml.cs | {
"start": 561,
"end": 900
} | partial class ____ : Page
{
public ItemsRepeater_Nested()
{
this.InitializeComponent();
}
private void SetSource(object sender, RoutedEventArgs e)
{
((FrameworkElement)sender).Visibility = Visibility.Collapsed;
SUT.ItemsSource = Enumerable.Range(0, 5000).GroupBy(i => Math.Floor(i / 500.0));
}
}
}
| ItemsRepeater_Nested |
csharp | unoplatform__uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Activation/ActivationKind.cs | {
"start": 233,
"end": 5000
} | public enum ____
{
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.Launch
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.Search
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.ShareTarget
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.File
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.Protocol
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.FileOpenPicker
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.FileSavePicker
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.CachedFileUpdater
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.ContactPicker
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.Device
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.PrintTaskSettings
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.CameraSettings
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.RestrictedLaunch
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.AppointmentsProvider
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.Contact
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.LockScreenCall
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.VoiceCommand
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.LockScreen
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.PickerReturned
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.WalletAction
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.PickFileContinuation
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.PickSaveFileContinuation
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.PickFolderContinuation
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.WebAuthenticationBrokerContinuation
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.WebAccountProvider
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.ComponentUI
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.ProtocolForResults
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.ToastNotification
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.Print3DWorkflow
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.DialReceiver
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.DevicePairing
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.UserDataAccountsProvider
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.FilePickerExperience
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.LockScreenComponent
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.ContactPanel
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.PrintWorkflowForegroundTask
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.GameUIProvider
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.StartupTask
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.CommandLineLaunch
// Skipping already declared field Windows.ApplicationModel.Activation.ActivationKind.BarcodeScannerProvider
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
PrintSupportJobUI = 1023,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
PrintSupportSettingsUI = 1024,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
PhoneCallActivation = 1025,
#endif
#if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__
VpnForeground = 1026,
#endif
}
#endif
}
| ActivationKind |
csharp | dotnet__aspire | playground/AspireEventHub/EventHubsConsumer/Processor.cs | {
"start": 1463,
"end": 2474
} | internal sealed class ____(EventProcessorClient client, ILogger<Processor> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
logger.LogInformation("Starting processor...");
client.ProcessEventAsync += async arg =>
{
logger.LogInformation(arg.Data.EventBody.ToString());
// save our current position in the configured storage account
await arg.UpdateCheckpointAsync(stoppingToken);
};
client.ProcessErrorAsync += args =>
{
logger.LogError(args.Exception, "Error processing message: {Error}", args.Exception.Message);
return Task.CompletedTask;
};
await client.StartProcessingAsync(stoppingToken);
}
public override async Task StopAsync(CancellationToken cancellationToken)
{
logger.LogInformation("Stopping processor...");
await client.StopProcessingAsync(cancellationToken);
}
}
| Processor |
csharp | duplicati__duplicati | Duplicati/Library/RestAPI/NotificationUpdateService.cs | {
"start": 1216,
"end": 1641
} | public interface ____
{
/// <summary>
/// An event ID that increases whenever the database is updated
/// </summary>
long LastDataUpdateId { get; }
/// <summary>
/// An event ID that increases whenever a notification is updated
/// </summary>
long LastNotificationUpdateId { get; }
void IncrementLastDataUpdateId();
void IncrementLastNotificationUpdateId();
}
| INotificationUpdateService |
csharp | MassTransit__MassTransit | src/Transports/MassTransit.RabbitMqTransport/RabbitMqTransport/Configuration/IRabbitMqEndpointConfiguration.cs | {
"start": 99,
"end": 255
} | public interface ____ :
IEndpointConfiguration
{
new IRabbitMqTopologyConfiguration Topology { get; }
}
}
| IRabbitMqEndpointConfiguration |
csharp | EventStore__EventStore | src/KurrentDB.Surge.Tests/Components/Processors/SystemProcessorTests.cs | {
"start": 706,
"end": 2176
} | public class ____(ITestOutputHelper output, SystemComponentsAssemblyFixture fixture) : SystemComponentsIntegrationTests(output, fixture) {
[Theory]
[InlineData(1)]
[InlineData(10)]
public Task processes_records_from_earliest(int numberOfMessages) => Fixture.TestWithTimeout(
TimeSpan.FromSeconds(30),
async cancellator => {
// Arrange
var streamId = Fixture.NewStreamId();
var requests = await Fixture.ProduceTestEvents(streamId, 1, numberOfMessages);
var messages = requests.SelectMany(r => r.Messages).ToList();
var processedRecords = new List<SurgeRecord>();
var processor = Fixture.NewProcessor()
.ProcessorId($"{streamId}-prx")
.Stream(streamId)
.InitialPosition(SubscriptionInitialPosition.Earliest)
.DisableAutoCommit()
.Process<TestEvent>(
async (_, ctx) => {
processedRecords.Add(ctx.Record);
if (processedRecords.Count == messages.Count)
await cancellator.CancelAsync();
}
)
.Create();
// Act
await processor.RunUntilDeactivated(cancellator.Token);
// Assert
processedRecords.Should()
.HaveCount(numberOfMessages, "because there should be one | SystemProcessorTests |
csharp | dotnet__aspnetcore | src/Identity/Extensions.Stores/src/RoleStoreBase.cs | {
"start": 568,
"end": 734
} | class ____ a role.</typeparam>
/// <typeparam name="TKey">The type of the primary key for a role.</typeparam>
/// <typeparam name="TUserRole">The type of the | representing |
csharp | NSubstitute__NSubstitute | tests/NSubstitute.Specs/CallSpecificationSpecs.cs | {
"start": 5947,
"end": 7101
} | public class ____ : Concern
{
private IMethodInfoFormatter _callFormatter;
private string _specAsString;
private const string FormattedCallSpec = "CallSpec(first, second)";
public override void Context()
{
base.Context();
_callFormatter = mock<IMethodInfoFormatter>();
_callFormatter
.stub(x => x.Format(_methodInfoSpecified, new[] { _firstArgSpec.ToString(), _secondArgSpec.ToString() }))
.Return(FormattedCallSpec);
}
public override void AfterContextEstablished()
{
base.AfterContextEstablished();
sut.CallFormatter = _callFormatter;
}
public override void Because()
{
_specAsString = sut.ToString();
}
[Test]
public void Should_return_formatted_method_and_argument_specifications()
{
Assert.That(_specAsString, Is.EqualTo(FormattedCallSpec));
}
}
}
}
| When_converting_call_spec_to_string |
csharp | CommunityToolkit__WindowsCommunityToolkit | Microsoft.Toolkit.Uwp.UI/Extensions/TextBox/TextBoxExtensions.Regex.Internals.cs | {
"start": 425,
"end": 4249
} | partial class ____
{
private static void TextBoxRegexPropertyOnChange(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
var textBox = sender as TextBox;
if (textBox == null)
{
return;
}
ValidateTextBox(textBox, false);
textBox.Loaded -= TextBox_Loaded;
textBox.LostFocus -= TextBox_LostFocus;
textBox.TextChanged -= TextBox_TextChanged;
textBox.Loaded += TextBox_Loaded;
textBox.LostFocus += TextBox_LostFocus;
textBox.TextChanged += TextBox_TextChanged;
}
private static void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
var textBox = (TextBox)sender;
var validationMode = (ValidationMode)textBox.GetValue(ValidationModeProperty);
ValidateTextBox(textBox, validationMode == ValidationMode.Dynamic);
}
private static void TextBox_Loaded(object sender, RoutedEventArgs e)
{
var textBox = (TextBox)sender;
ValidateTextBox(textBox);
}
private static void TextBox_LostFocus(object sender, RoutedEventArgs e)
{
var textBox = (TextBox)sender;
ValidateTextBox(textBox);
}
private static void ValidateTextBox(TextBox textBox, bool force = true)
{
var validationType = (ValidationType)textBox.GetValue(ValidationTypeProperty);
string regex;
bool regexMatch;
switch (validationType)
{
default:
regex = textBox.GetValue(RegexProperty) as string;
if (string.IsNullOrWhiteSpace(regex))
{
Debug.WriteLine("Regex property can't be null or empty when custom mode is selected");
return;
}
regexMatch = Regex.IsMatch(textBox.Text, regex);
break;
case ValidationType.Decimal:
regexMatch = textBox.Text.IsDecimal();
break;
case ValidationType.Email:
regexMatch = textBox.Text.IsEmail();
break;
case ValidationType.Number:
regexMatch = textBox.Text.IsNumeric();
break;
case ValidationType.PhoneNumber:
regexMatch = textBox.Text.IsPhoneNumber();
break;
case ValidationType.Characters:
regexMatch = textBox.Text.IsCharacterString();
break;
}
if (!regexMatch && force)
{
if (!string.IsNullOrEmpty(textBox.Text))
{
var validationModel = (ValidationMode)textBox.GetValue(ValidationModeProperty);
if (validationModel == ValidationMode.Forced)
{
textBox.Text = string.Empty;
}
else if (validationType != ValidationType.Email && validationType != ValidationType.PhoneNumber)
{
if (validationModel == ValidationMode.Dynamic)
{
int selectionStart = textBox.SelectionStart == 0 ? textBox.SelectionStart : textBox.SelectionStart - 1;
textBox.Text = textBox.Text.Remove(selectionStart, 1);
textBox.SelectionStart = selectionStart;
}
}
}
}
textBox.SetValue(IsValidProperty, regexMatch);
}
}
} | TextBoxExtensions |
csharp | dotnet__reactive | Rx.NET/Source/tests/Tests.System.Reactive/Tests/Linq/Observable/AggregateTest.cs | {
"start": 435,
"end": 14498
} | public class ____ : ReactiveTest
{
[TestMethod]
public void Aggregate_ArgumentChecking()
{
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Aggregate<int, int>(default, 1, (x, y) => x + y));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Aggregate(DummyObservable<int>.Instance, 1, default));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Aggregate<int>(default, (x, y) => x + y));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Aggregate(DummyObservable<int>.Instance, default));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Aggregate<int, int, int>(default, 1, (x, y) => x + y, x => x));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Aggregate(DummyObservable<int>.Instance, 1, default, x => x));
ReactiveAssert.Throws<ArgumentNullException>(() => Observable.Aggregate<int, int, int>(DummyObservable<int>.Instance, 1, (x, y) => x + y, default));
}
[TestMethod]
public void AggregateWithSeed_Empty()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnCompleted<int>(250)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnNext(250, 42),
OnCompleted<int>(250)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 250)
);
}
[TestMethod]
public void AggregateWithSeed_Return()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 24),
OnCompleted<int>(250)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnNext(250, 42 + 24),
OnCompleted<int>(250)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 250)
);
}
[TestMethod]
public void AggregateWithSeed_Throw()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnError<int>(210, ex)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnError<int>(210, ex)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 210)
);
}
[TestMethod]
public void AggregateWithSeed_Never()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x)
);
res.Messages.AssertEqual(
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 1000)
);
}
[TestMethod]
public void AggregateWithSeed_Range()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 0),
OnNext(220, 1),
OnNext(230, 2),
OnNext(240, 3),
OnNext(250, 4),
OnCompleted<int>(260)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnNext(260, 42 + Enumerable.Range(0, 5).Sum()),
OnCompleted<int>(260)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 260)
);
}
[TestMethod]
public void AggregateWithSeed_AccumulatorThrows()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 0),
OnNext(220, 1),
OnNext(230, 2),
OnNext(240, 3),
OnNext(250, 4),
OnCompleted<int>(260)
);
var res = scheduler.Start(() =>
xs.Aggregate(0, (acc, x) => { if (x < 3) { return acc + x; } throw ex; })
);
res.Messages.AssertEqual(
OnError<int>(240, ex)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 240)
);
}
[TestMethod]
public void AggregateWithSeedAndResult_Empty()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnCompleted<int>(250)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x, x => x * 5)
);
res.Messages.AssertEqual(
OnNext(250, 42 * 5),
OnCompleted<int>(250)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 250)
);
}
[TestMethod]
public void AggregateWithSeedAndResult_Return()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 24),
OnCompleted<int>(250)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x, x => x * 5)
);
res.Messages.AssertEqual(
OnNext(250, (42 + 24) * 5),
OnCompleted<int>(250)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 250)
);
}
[TestMethod]
public void AggregateWithSeedAndResult_Throw()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnError<int>(210, ex)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x, x => x * 5)
);
res.Messages.AssertEqual(
OnError<int>(210, ex)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 210)
);
}
[TestMethod]
public void AggregateWithSeedAndResult_Never()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x, x => x * 5)
);
res.Messages.AssertEqual(
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 1000)
);
}
[TestMethod]
public void AggregateWithSeedAndResult_Range()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 0),
OnNext(220, 1),
OnNext(230, 2),
OnNext(240, 3),
OnNext(250, 4),
OnCompleted<int>(260)
);
var res = scheduler.Start(() =>
xs.Aggregate(42, (acc, x) => acc + x, x => x * 5)
);
res.Messages.AssertEqual(
OnNext(260, (42 + Enumerable.Range(0, 5).Sum()) * 5),
OnCompleted<int>(260)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 260)
);
}
[TestMethod]
public void AggregateWithSeedAndResult_AccumulatorThrows()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 0),
OnNext(220, 1),
OnNext(230, 2),
OnNext(240, 3),
OnNext(250, 4),
OnCompleted<int>(260)
);
var res = scheduler.Start(() =>
xs.Aggregate(0, (acc, x) => { if (x < 3) { return acc + x; } throw ex; }, x => x * 5)
);
res.Messages.AssertEqual(
OnError<int>(240, ex)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 240)
);
}
[TestMethod]
public void AggregateWithSeedAndResult_ResultSelectorThrows()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 0),
OnNext(220, 1),
OnNext(230, 2),
OnNext(240, 3),
OnNext(250, 4),
OnCompleted<int>(260)
);
var res = scheduler.Start(() =>
xs.Aggregate<int, int, int>(0, (acc, x) => acc + x, x => { throw ex; })
);
res.Messages.AssertEqual(
OnError<int>(260, ex)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 260)
);
}
[TestMethod]
public void AggregateWithoutSeed_Empty()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnCompleted<int>(250)
);
var res = scheduler.Start(() =>
xs.Aggregate((acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnError<int>(250, e => e is InvalidOperationException)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 250)
);
}
[TestMethod]
public void AggregateWithoutSeed_Return()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 24),
OnCompleted<int>(250)
);
var res = scheduler.Start(() =>
xs.Aggregate((acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnNext(250, 24),
OnCompleted<int>(250)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 250)
);
}
[TestMethod]
public void AggregateWithoutSeed_Throw()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnError<int>(210, ex)
);
var res = scheduler.Start(() =>
xs.Aggregate((acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnError<int>(210, ex)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 210)
);
}
[TestMethod]
public void AggregateWithoutSeed_Never()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1)
);
var res = scheduler.Start(() =>
xs.Aggregate((acc, x) => acc + x)
);
res.Messages.AssertEqual(
);
}
[TestMethod]
public void AggregateWithoutSeed_Range()
{
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 0),
OnNext(220, 1),
OnNext(230, 2),
OnNext(240, 3),
OnNext(250, 4),
OnCompleted<int>(260)
);
var res = scheduler.Start(() =>
xs.Aggregate((acc, x) => acc + x)
);
res.Messages.AssertEqual(
OnNext(260, Enumerable.Range(0, 5).Sum()),
OnCompleted<int>(260)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 260)
);
}
[TestMethod]
public void AggregateWithoutSeed_AccumulatorThrows()
{
var ex = new Exception();
var scheduler = new TestScheduler();
var xs = scheduler.CreateHotObservable(
OnNext(150, 1),
OnNext(210, 0),
OnNext(220, 1),
OnNext(230, 2),
OnNext(240, 3),
OnNext(250, 4),
OnCompleted<int>(260)
);
var res = scheduler.Start(() =>
xs.Aggregate((acc, x) => { if (x < 3) { return acc + x; } throw ex; })
);
res.Messages.AssertEqual(
OnError<int>(240, ex)
);
xs.Subscriptions.AssertEqual(
Subscribe(200, 240)
);
}
}
}
| AggregateTest |
csharp | dotnet__aspnetcore | src/Http/Authentication.Abstractions/src/IAuthenticationHandlerProvider.cs | {
"start": 352,
"end": 820
} | public interface ____
{
/// <summary>
/// Returns the handler instance that will be used.
/// </summary>
/// <param name="context">The <see cref="HttpContext"/>.</param>
/// <param name="authenticationScheme">The name of the authentication scheme being handled.</param>
/// <returns>The handler instance.</returns>
Task<IAuthenticationHandler?> GetHandlerAsync(HttpContext context, string authenticationScheme);
}
| IAuthenticationHandlerProvider |
csharp | xunit__xunit | src/xunit.v3.runner.utility/SimpleRunner/ReportType.cs | {
"start": 1354,
"end": 1839
} | static class ____
{
public static string ToKey(this ReportType reportType) =>
reportType switch
{
ReportType.CTRF => "ctrf",
ReportType.HTML => "html",
ReportType.JUnit => "junit",
ReportType.NUnit_2_5 => "nunit",
ReportType.TRX => "trx",
ReportType.XMLv1 => "xmlv1",
ReportType.XMLv2 => "xml",
_ => throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid report type '{0}'", reportType), nameof(reportType)),
};
}
| ReportTypeExtensions |
csharp | dotnet__aspnetcore | src/Middleware/StaticFiles/src/IContentTypeProvider.cs | {
"start": 301,
"end": 703
} | public interface ____
{
/// <summary>
/// Given a file path, determine the MIME type
/// </summary>
/// <param name="subpath">A file path</param>
/// <param name="contentType">The resulting MIME type</param>
/// <returns>True if MIME type could be determined</returns>
bool TryGetContentType(string subpath, [MaybeNullWhen(false)] out string contentType);
}
| IContentTypeProvider |
csharp | dotnet__extensions | src/Shared/EmptyCollections/Empty.cs | {
"start": 466,
"end": 1985
} | internal static class ____
{
/// <summary>
/// Returns an optimized empty collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <returns>Returns an efficient static instance of an empty collection.</returns>
public static IReadOnlyCollection<T> ReadOnlyCollection<T>() => EmptyReadOnlyList<T>.Instance;
/// <summary>
/// Returns an optimized empty collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <returns>Returns an efficient static instance of an empty collection.</returns>
public static IEnumerable<T> Enumerable<T>() => EmptyReadOnlyList<T>.Instance;
/// <summary>
/// Returns an optimized empty collection.
/// </summary>
/// <typeparam name="T">The type of the collection.</typeparam>
/// <returns>Returns an efficient static instance of an empty list.</returns>
public static IReadOnlyList<T> ReadOnlyList<T>() => EmptyReadOnlyList<T>.Instance;
/// <summary>
/// Returns an optimized empty dictionary.
/// </summary>
/// <typeparam name="TKey">The key type of the dictionary.</typeparam>
/// <typeparam name="TValue">The value type of the dictionary.</typeparam>
/// <returns>Returns an efficient static instance of an empty dictionary.</returns>
public static IReadOnlyDictionary<TKey, TValue> ReadOnlyDictionary<TKey, TValue>()
where TKey : notnull
=> EmptyReadOnlyDictionary<TKey, TValue>.Instance;
}
| Empty |
csharp | fluentassertions__fluentassertions | Tests/FluentAssertions.Specs/Common/TypeExtensionsSpecs.cs | {
"start": 9371,
"end": 10102
} | private struct ____ : IEquatable<MyStructWithOverriddenEquality>
{
[UsedImplicitly]
public int Value { get; set; }
public bool Equals(MyStructWithOverriddenEquality other) => Value == other.Value;
public override bool Equals(object obj) => obj is MyStructWithOverriddenEquality other && Equals(other);
public override int GetHashCode() => Value;
public static bool operator ==(MyStructWithOverriddenEquality left, MyStructWithOverriddenEquality right) =>
left.Equals(right);
public static bool operator !=(MyStructWithOverriddenEquality left, MyStructWithOverriddenEquality right) =>
!left.Equals(right);
}
| MyStructWithOverriddenEquality |
csharp | ChilliCream__graphql-platform | src/HotChocolate/Fusion-vnext/test/Fusion.Composition.Tests/SourceSchemaValidationRules/ExternalOnInterfaceRuleTests.cs | {
"start": 1259,
"end": 1454
} | interface ____ {
id: ID! @external
}
"""
],
[
"""
{
"message": "The | Node |
csharp | grpc__grpc-dotnet | src/Grpc.Net.Common/Compression/ICompressionProvider.cs | {
"start": 815,
"end": 1697
} | public interface ____
{
/// <summary>
/// The encoding name used in the 'grpc-encoding' and 'grpc-accept-encoding' request and response headers.
/// </summary>
string EncodingName { get; }
/// <summary>
/// Create a new compression stream.
/// </summary>
/// <param name="stream">The stream that compressed data is written to.</param>
/// <param name="compressionLevel">The compression level.</param>
/// <returns>A stream used to compress data.</returns>
Stream CreateCompressionStream(Stream stream, CompressionLevel? compressionLevel);
/// <summary>
/// Create a new decompression stream.
/// </summary>
/// <param name="stream">The stream that compressed data is copied from.</param>
/// <returns>A stream used to decompress data.</returns>
Stream CreateDecompressionStream(Stream stream);
}
| ICompressionProvider |
csharp | grandnode__grandnode2 | src/Web/Grand.Web.Admin/Interfaces/ICategoryViewModelService.cs | {
"start": 107,
"end": 1423
} | public interface ____
{
Task<CategoryListModel> PrepareCategoryListModel(string storeId);
Task<(IEnumerable<CategoryModel> categoryListModel, int totalCount)> PrepareCategoryListModel(
CategoryListModel model, int pageIndex, int pageSize);
Task<CategoryModel> PrepareCategoryModel(string storeId);
Task<CategoryModel> PrepareCategoryModel(CategoryModel model, Category category, string storeId);
Task<Category> InsertCategoryModel(CategoryModel model);
Task<Category> UpdateCategoryModel(Category category, CategoryModel model);
Task DeleteCategory(Category category);
Task<(IEnumerable<CategoryModel.CategoryProductModel> categoryProductModels, int totalCount)>
PrepareCategoryProductModel(string categoryId, int pageIndex, int pageSize);
Task<ProductCategory> UpdateProductCategoryModel(CategoryModel.CategoryProductModel model);
Task DeleteProductCategoryModel(string id, string productId);
Task<CategoryModel.AddCategoryProductModel> PrepareAddCategoryProductModel(string storeId);
Task InsertCategoryProductModel(CategoryModel.AddCategoryProductModel model);
Task<(IList<ProductModel> products, int totalCount)> PrepareProductModel(
CategoryModel.AddCategoryProductModel model, int pageIndex, int pageSize);
} | ICategoryViewModelService |
csharp | dotnet__efcore | test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs | {
"start": 294597,
"end": 294817
} | public class ____
{
public int Id { get; set; }
public RelatedEntity1353 ParentEntity { get; set; }
public IEnumerable<RelatedEntity1355> ChildEntities { get; set; }
}
| RelatedEntity1354 |
csharp | ServiceStack__ServiceStack | ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/LicenseUsageTests.cs | {
"start": 7889,
"end": 9725
} | public class ____ : IReturn<MegaDto>
{
public T01 T01 { get; set; }
public T02 T02 { get; set; }
public T03 T03 { get; set; }
public T04 T04 { get; set; }
public T05 T05 { get; set; }
public T06 T06 { get; set; }
public T07 T07 { get; set; }
public T08 T08 { get; set; }
public T09 T09 { get; set; }
public T10 T10 { get; set; }
public T11 T11 { get; set; }
public T12 T12 { get; set; }
public T13 T13 { get; set; }
public T14 T14 { get; set; }
public T15 T15 { get; set; }
public T16 T16 { get; set; }
public T17 T17 { get; set; }
public T18 T18 { get; set; }
public T19 T19 { get; set; }
public T20 T20 { get; set; }
public T21 T21 { get; set; }
public static MegaDto Create()
{
return new MegaDto
{
T01 = new T01 { Id = 1 },
T02 = new T02 { Id = 1 },
T03 = new T03 { Id = 1 },
T04 = new T04 { Id = 1 },
T05 = new T05 { Id = 1 },
T06 = new T06 { Id = 1 },
T07 = new T07 { Id = 1 },
T08 = new T08 { Id = 1 },
T09 = new T09 { Id = 1 },
T10 = new T10 { Id = 1 },
T11 = new T11 { Id = 1 },
T12 = new T12 { Id = 1 },
T13 = new T13 { Id = 1 },
T14 = new T14 { Id = 1 },
T15 = new T15 { Id = 1 },
T16 = new T16 { Id = 1 },
T17 = new T17 { Id = 1 },
T18 = new T18 { Id = 1 },
T19 = new T19 { Id = 1 },
T20 = new T20 { Id = 1 },
T21 = new T21 { Id = 1 },
};
}
}
| MegaDto |
csharp | dotnet__aspire | src/Aspire.Hosting/VersionChecking/PackageVersionProvider.cs | {
"start": 217,
"end": 411
} | internal sealed class ____ : IPackageVersionProvider
{
public SemVersion? GetPackageVersion()
{
return PackageUpdateHelpers.GetCurrentPackageVersion();
}
}
| PackageVersionProvider |
csharp | exceptionless__Exceptionless | src/Exceptionless.Core/Pipeline/EventPipeline.cs | {
"start": 271,
"end": 3476
} | public class ____ : PipelineBase<EventContext, EventPipelineActionBase>
{
public EventPipeline(IServiceProvider serviceProvider, AppOptions options, ILoggerFactory loggerFactory) : base(serviceProvider, options, loggerFactory) { }
public Task<EventContext> RunAsync(PersistentEvent ev, Organization organization, Project project, EventPostInfo? epi = null)
{
return RunAsync(new EventContext(ev, organization, project, epi));
}
public Task<ICollection<EventContext>> RunAsync(IEnumerable<PersistentEvent> events, Organization organization, Project project, EventPostInfo? epi = null)
{
return RunAsync(events.Select(ev => new EventContext(ev, organization, project, epi)).ToList());
}
public override async Task<ICollection<EventContext>> RunAsync(ICollection<EventContext> contexts)
{
if (contexts is null || contexts.Count == 0)
return contexts ?? new List<EventContext>();
AppDiagnostics.EventsSubmitted.Add(contexts.Count);
try
{
if (contexts.Any(c => !String.IsNullOrEmpty(c.Event.Id)))
throw new ArgumentException("All Event Ids should not be populated.");
var project = contexts.First().Project;
if (String.IsNullOrEmpty(project.Id))
throw new ArgumentException("All Project Ids must be populated.");
if (contexts.Any(c => c.Event.ProjectId != project.Id))
throw new ArgumentException("All Project Ids must be the same for a batch of events.");
// load organization settings into the context
var organization = contexts.First().Organization;
if (organization.Data is not null)
foreach (string key in organization.Data.Keys)
contexts.ForEach(c => c.SetProperty(key, organization.Data[key]));
// load project settings into the context, overriding any organization settings with the same name
if (project.Data is not null)
foreach (string key in project.Data.Keys)
contexts.ForEach(c => c.SetProperty(key, project.Data[key]));
await AppDiagnostics.EventsProcessingTime.TimeAsync(() => base.RunAsync(contexts));
int cancelled = contexts.Count(c => c.IsCancelled);
if (cancelled > 0)
AppDiagnostics.EventsProcessCancelled.Add(cancelled);
int discarded = contexts.Count(c => c.IsDiscarded);
if (discarded > 0)
AppDiagnostics.EventsDiscarded.Add(discarded);
// TODO: Log the errors out to the events project id.
int errors = contexts.Count(c => c.HasError);
if (errors > 0)
AppDiagnostics.EventsProcessErrors.Add(errors);
}
catch (Exception)
{
AppDiagnostics.EventsProcessErrors.Add(contexts.Count);
throw;
}
return contexts;
}
protected override IList<Type> GetActionTypes()
{
return _actionTypeCache.GetOrAdd(typeof(EventPipelineActionBase), t => TypeHelper.GetDerivedTypes<EventPipelineActionBase>().SortByPriority());
}
}
| EventPipeline |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.