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
microsoft__semantic-kernel
dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockChatCompletionModelExecutionSettingsTests.cs
{ "start": 525, "end": 27504 }
public class ____ { /// <summary> /// Checks that an invalid prompt execution settings will throw an exception. /// </summary> [Fact] public async Task ShouldThrowExceptionForInvalidPromptExecutionSettingsAsync() { // Arrange string modelId = "amazon.titan-text-lite-v1"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); var invalidSettings = new AmazonTitanExecutionSettings() { Temperature = -1.0f, TopP = -0.5f, MaxTokenCount = -100 }; var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act & Assert await Assert.ThrowsAsync<InvalidOperationException>(() => service.GetChatMessageContentsAsync(chatHistory, invalidSettings)).ConfigureAwait(true); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task ExecutionSettingsExtensionDataShouldOverridePropertyAsync() { // Arrange string modelId = "mistral.mistral-text-lite-v1"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonMistralExecutionSettings() { Temperature = 0.0f, TopP = 0.0f, MaxTokens = 10, ModelId = modelId, ExtensionData = new Dictionary<string, object>() { { "temperature", 0.5f }, { "top_p", 0.9f }, { "max_tokens", 512 } } }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.NotEqual(executionSettings.Temperature, converseRequest?.InferenceConfig.Temperature); Assert.NotEqual(executionSettings.TopP, converseRequest?.InferenceConfig.TopP); Assert.NotEqual(executionSettings.MaxTokens, converseRequest?.InferenceConfig.MaxTokens); Assert.Equal(executionSettings.ExtensionData["temperature"], converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.ExtensionData["top_p"], converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.ExtensionData["max_tokens"], converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task TitanExecutionSettingsShouldSetExtensionDataAsync() { // Arrange string modelId = "amazon.titan-text-lite-v1"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonTitanExecutionSettings() { ModelId = modelId, ExtensionData = new Dictionary<string, object>() { { "temperature", 0.3f }, { "topP", 0.8f }, { "maxTokenCount", 510 } } }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.ExtensionData["temperature"], converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.ExtensionData["topP"], converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.ExtensionData["maxTokenCount"], converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task TitanExecutionSettingsShouldSetPropertiesAsync() { // Arrange string modelId = "amazon.titan-text-lite-v1"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonTitanExecutionSettings() { Temperature = 0.3f, TopP = 0.8f, MaxTokenCount = 510, ModelId = modelId }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.Temperature, converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.TopP, converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.MaxTokenCount, converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task ClaudePromptExecutionSettingsExtensionDataSetsProperlyAsync() { // Arrange string modelId = "anthropic.claude-chat-completion"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonClaudeExecutionSettings() { ModelId = modelId, ExtensionData = new Dictionary<string, object>() { { "temperature", 0.7f }, { "top_p", 0.7f }, { "max_tokens_to_sample", 512 } } }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.ExtensionData["temperature"], converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.ExtensionData["top_p"], converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.ExtensionData["max_tokens_to_sample"], converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task ClaudePromptExecutionSettingsSetsPropertiesAsync() { // Arrange string modelId = "anthropic.claude-chat-completion"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonClaudeExecutionSettings() { Temperature = 0.7f, TopP = 0.7f, MaxTokensToSample = 512, ModelId = modelId }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.Temperature, converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.TopP, converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.MaxTokensToSample, converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task LlamaGetChatMessageContentsAsyncShouldReturnChatMessageWithPromptExecutionSettingsAsync() { // Arrange string modelId = "meta.llama3-text-lite-v1"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new PromptExecutionSettings() { ModelId = modelId, ExtensionData = new Dictionary<string, object>() { { "temperature", 0.7f }, { "top_p", 0.6f }, { "max_gen_len", 256 } } }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.ExtensionData["temperature"], converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.ExtensionData["top_p"], converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.ExtensionData["max_gen_len"], converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task CommandRExecutionSettingsShouldSetExtensionDataAsync() { // Arrange string modelId = "cohere.command-r-chat-stuff"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonCommandRExecutionSettings() { ModelId = modelId, ExtensionData = new Dictionary<string, object>() { { "temperature", 0.7f }, { "p", 0.9f }, { "max_tokens", 202 } } }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.ExtensionData["temperature"], converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.ExtensionData["p"], converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.ExtensionData["max_tokens"], converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task CommandRExecutionSettingsShouldSetPropertiesAsync() { // Arrange string modelId = "cohere.command-r-chat-stuff"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonCommandRExecutionSettings() { Temperature = 0.7f, TopP = 0.9f, MaxTokens = 202, ModelId = modelId, }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.Temperature, converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.TopP, converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.MaxTokens, converseRequest?.InferenceConfig.MaxTokens); } /// <summary> /// Checks that the prompt execution settings are correctly registered for the chat completion call. /// </summary> [Fact] public async Task JambaGetChatMessageContentsAsyncShouldReturnChatMessageWithPromptExecutionSettingsAsync() { // Arrange string modelId = "ai21.jamba-chat-stuff"; var mockBedrockApi = new Mock<IAmazonBedrockRuntime>(); var executionSettings = new AmazonJambaExecutionSettings() { Temperature = 0.7f, ModelId = modelId, ExtensionData = new Dictionary<string, object>() { { "temperature", 0.7f }, { "top_p", 0.9f }, { "max_tokens", 202 } } }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny<ConverseRequest>())) .Returns(new Endpoint("https://bedrock-runtime.us-east-1.amazonaws.com") { URL = "https://bedrock-runtime.us-east-1.amazonaws.com" }); mockBedrockApi.Setup(m => m.ConverseAsync(It.IsAny<ConverseRequest>(), It.IsAny<CancellationToken>())) .ReturnsAsync(new ConverseResponse { Output = new ConverseOutput { Message = new Message { Role = ConversationRole.Assistant, Content = new List<ContentBlock> { new() { Text = "I'm doing well." } } } }, Metrics = new ConverseMetrics(), StopReason = StopReason.Max_tokens, Usage = new TokenUsage() }); var kernel = Kernel.CreateBuilder().AddBedrockChatCompletionService(modelId, mockBedrockApi.Object).Build(); var service = kernel.GetRequiredService<IChatCompletionService>(); var chatHistory = CreateSampleChatHistory(); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, executionSettings).ConfigureAwait(true); // Assert var invocation = mockBedrockApi.Invocations .Where(i => i.Method.Name == "ConverseAsync") .SingleOrDefault(i => i.Arguments.Count > 0 && i.Arguments[0] is ConverseRequest); Assert.NotNull(invocation); ConverseRequest converseRequest = (ConverseRequest)invocation.Arguments[0]; Assert.Single(result); Assert.Equal("I'm doing well.", result[0].Items[0].ToString()); Assert.Equal(executionSettings.ExtensionData["temperature"], converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.Temperature, converseRequest?.InferenceConfig.Temperature); Assert.Equal(executionSettings.ExtensionData["top_p"], converseRequest?.InferenceConfig.TopP); Assert.Equal(executionSettings.ExtensionData["max_tokens"], converseRequest?.InferenceConfig.MaxTokens); } private static ChatHistory CreateSampleChatHistory() { var chatHistory = new ChatHistory(); chatHistory.AddUserMessage("Hello"); chatHistory.AddAssistantMessage("Hi"); chatHistory.AddUserMessage("How are you?"); chatHistory.AddSystemMessage("You are an AI Assistant"); return chatHistory; } }
BedrockChatCompletionModelExecutionSettingsTests
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Media/Animation/LinearDoubleKeyFrame.cs
{ "start": 408, "end": 708 }
class ____ the specified ending value. /// </summary> /// <param name="value">Ending value (also known as "target value") for the key frame.</param> public LinearDoubleKeyFrame(double value) : base(value) { } /// <summary> /// Initializes a new instance of the LinearDoubleKeyFrame
with
csharp
dotnet__reactive
AsyncRx.NET/System.Reactive.Async/Joins/AsyncPlan.Generated.cs
{ "start": 61864, "end": 67917 }
internal abstract class ____<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10, TSource11, TSource12, TResult> : AsyncPlan<TResult> { private readonly AsyncPattern<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10, TSource11, TSource12> _expression; internal AsyncPlanBase(AsyncPattern<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10, TSource11, TSource12> 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, TSource11 arg11, TSource12 arg12); 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 joinObserver11 = AsyncPlan<TResult>.CreateObserver<TSource11>(externalSubscriptions, _expression.Source11, onError); var joinObserver12 = AsyncPlan<TResult>.CreateObserver<TSource12>(externalSubscriptions, _expression.Source12, onError); var activePlan = default(ActiveAsyncPlan<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10, TSource11, TSource12>); activePlan = new ActiveAsyncPlan<TSource1, TSource2, TSource3, TSource4, TSource5, TSource6, TSource7, TSource8, TSource9, TSource10, TSource11, TSource12>( joinObserver1, joinObserver2, joinObserver3, joinObserver4, joinObserver5, joinObserver6, joinObserver7, joinObserver8, joinObserver9, joinObserver10, joinObserver11, joinObserver12, async (arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12) => { var res = default(TResult); try { res = await EvalAsync(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12).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 joinObserver11.RemoveActivePlan(activePlan).ConfigureAwait(false); await joinObserver12.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); joinObserver11.AddActivePlan(activePlan); joinObserver12.AddActivePlan(activePlan); return activePlan; } }
AsyncPlanBase
csharp
nopSolutions__nopCommerce
src/Plugins/Nop.Plugin.Widgets.AccessiBe/Infrastructure/RouteProvider.cs
{ "start": 262, "end": 883 }
public class ____ : IRouteProvider { /// <summary> /// Register routes /// </summary> /// <param name="endpointRouteBuilder">Route builder</param> public void RegisterRoutes(IEndpointRouteBuilder endpointRouteBuilder) { endpointRouteBuilder.MapControllerRoute(name: AccessiBeDefaults.ConfigurationRouteName, pattern: "Plugins/AccessiBe/Configure", defaults: new { controller = "AccessiBe", action = "Configure", area = AreaNames.ADMIN }); } /// <summary> /// Gets a priority of route provider /// </summary> public int Priority => 0; }
RouteProvider
csharp
dotnet__orleans
test/Grains/TestInternalGrains/TestGrain.cs
{ "start": 4873, "end": 6382 }
internal class ____ : Grain, IGuidTestGrain { private readonly string _id = Guid.NewGuid().ToString(); private string label; private readonly ILogger logger; public GuidTestGrain(ILoggerFactory loggerFactory) { this.logger = loggerFactory.CreateLogger($"{this.GetType().Name}-{this.IdentityString}"); } public override Task OnActivateAsync(CancellationToken cancellationToken) { //if (this.GetPrimaryKeyLong() == -2) // throw new ArgumentException("Primary key cannot be -2 for this test case"); label = this.GetPrimaryKey().ToString(); logger.LogInformation("OnActivateAsync"); return Task.CompletedTask; } public Task<Guid> GetKey() { return Task.FromResult(this.GetPrimaryKey()); } public Task<string> GetLabel() { return Task.FromResult(label); } public Task SetLabel(string label) { this.label = label; return Task.CompletedTask; } public Task<string> GetRuntimeInstanceId() { return Task.FromResult(RuntimeIdentity); } public Task<string> GetActivationId() { return Task.FromResult(_id); } public Task<SiloAddress> GetSiloAddress() => Task.FromResult(ServiceProvider.GetRequiredService<ILocalSiloDetails>().SiloAddress); }
GuidTestGrain
csharp
microsoft__semantic-kernel
dotnet/src/Experimental/Process.Runtime.Dapr/Interfaces/IProcess.cs
{ "start": 211, "end": 2399 }
public interface ____ : IActor, IStep { /// <summary> /// Initializes the process with the specified instance of <see cref="DaprProcessInfo"/>. /// </summary> /// <param name="processInfo">Used to initialize the process.</param> /// <param name="parentProcessId">The parent Id of the process if one exists.</param> /// <param name="eventProxyStepId">An optional identifier of an actor requesting to proxy events.</param> /// <returns>A<see cref="Task"/></returns> Task InitializeProcessAsync(DaprProcessInfo processInfo, string? parentProcessId, string? eventProxyStepId); /// <summary> /// Starts an initialized process. /// </summary> /// <param name="keepAlive">Indicates if the process should wait for external events after it's finished processing.</param> /// <returns></returns> Task StartAsync(bool keepAlive); /// <summary> /// Starts the process with an initial event and then waits for the process to finish. In this case the process will not /// keep alive waiting for external events after the internal messages have stopped. /// </summary> /// <param name="processEvent">Required. The <see cref="KernelProcessEvent"/> to start the process with.</param> /// <returns>A <see cref="Task"/></returns> Task RunOnceAsync(string processEvent); /// <summary> /// Stops a running process. This will cancel the process and wait for it to complete before returning. /// </summary> /// <returns>A <see cref="Task"/></returns> Task StopAsync(); /// <summary> /// Sends a message to the process. This does not start the process if it's not already running, in /// this case the message will remain queued until the process is started. /// </summary> /// <param name="processEvent">Required. The <see cref="KernelProcessEvent"/> to start the process with.</param> /// <returns>A <see cref="Task"/></returns> Task SendMessageAsync(string processEvent); /// <summary> /// Gets the process information. /// </summary> /// <returns>An instance of <see cref="KernelProcess"/></returns> Task<DaprProcessInfo> GetProcessInfoAsync(); }
IProcess
csharp
MonoGame__MonoGame
MonoGame.Framework/Design/Byte4TypeConverter.cs
{ "start": 682, "end": 2900 }
public sealed class ____ : TypeConverter { /// <inheritdoc /> public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType) { if (VectorConversion.CanConvertTo(context, destinationType)) return true; if (destinationType == typeof(string)) return true; return base.CanConvertTo(context, destinationType); } /// <inheritdoc /> public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType) { var vec = (Byte4)value; if (VectorConversion.CanConvertTo(context, destinationType)) { var vec4 = vec.ToVector4(); return VectorConversion.ConvertToFromVector4(context, culture, vec4, destinationType); } if (destinationType == typeof(string)) { return vec.PackedValue.ToString(); } return base.ConvertTo(context, culture, value, destinationType); } /// <inheritdoc /> public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType) { if (sourceType == typeof(string)) return true; return base.CanConvertFrom(context, sourceType); } /// <inheritdoc /> public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value) { var sourceType = value.GetType(); if (sourceType == typeof(string)) { var vecx = (float)Convert.ToByte(value.ToString().Substring(6, 2), 16); var vecy = (float)Convert.ToByte(value.ToString().Substring(4, 2), 16); var vecz = (float)Convert.ToByte(value.ToString().Substring(2, 2), 16); var vecw = (float)Convert.ToByte(value.ToString().Substring(0, 2), 16); return new Byte4(vecx, vecy, vecz, vecw); } return base.ConvertFrom(context, culture, value); } } } #pragma warning restore IL2067
Byte4TypeConverter
csharp
dotnet__efcore
src/EFCore/Metadata/IConventionPropertyBase.cs
{ "start": 721, "end": 4641 }
public interface ____ : IReadOnlyPropertyBase, IConventionAnnotatable { /// <summary> /// Gets the type that this property belongs to. /// </summary> new IConventionTypeBase DeclaringType { get; } /// <summary> /// Returns the configuration source for this property. /// </summary> /// <returns>The configuration source.</returns> ConfigurationSource GetConfigurationSource(); /// <summary> /// Sets the <see cref="FieldInfo" /> for the underlying CLR field that this property should use. /// </summary> /// <remarks> /// By default, the backing field, if one is found or has been specified, is used when /// new objects are constructed, typically when entities are queried from the database. /// Properties are used for all other accesses. This can be changed by calling /// <see cref="SetPropertyAccessMode" />. /// </remarks> /// <param name="fieldInfo">The <see cref="FieldInfo" /> for the underlying CLR field to use.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The new <see cref="FieldInfo" />.</returns> FieldInfo? SetFieldInfo(FieldInfo? fieldInfo, bool fromDataAnnotation = false); /// <summary> /// Sets the underlying CLR field that this property should use. /// This may be <see langword="null" /> for shadow properties or if the backing field for the property is not known. /// </summary> /// <remarks> /// <para> /// Backing fields are normally found by convention. /// This method is useful for setting backing fields explicitly in cases where the /// correct field is not found by convention. /// </para> /// <para> /// By default, the backing field, if one is found or has been specified, is used when /// new objects are constructed, typically when entities are queried from the database. /// Properties are used for all other accesses. This can be changed by calling /// <see cref="SetPropertyAccessMode" />. /// </para> /// <para> /// See <see href="https://aka.ms/efcore-docs-backing-fields">Backing fields</see> for more information and examples. /// </para> /// </remarks> /// <param name="fieldName">The name of the field to use.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The new <see cref="FieldInfo" />.</returns> FieldInfo? SetField(string? fieldName, bool fromDataAnnotation = false); /// <summary> /// Returns the configuration source for <see cref="IReadOnlyPropertyBase.FieldInfo" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlyPropertyBase.FieldInfo" />.</returns> ConfigurationSource? GetFieldInfoConfigurationSource(); /// <summary> /// Sets the <see cref="PropertyAccessMode" /> to use for this property. /// </summary> /// <param name="propertyAccessMode">The <see cref="PropertyAccessMode" />, or null to clear the mode set.</param> /// <param name="fromDataAnnotation">Indicates whether the configuration was specified using a data annotation.</param> /// <returns>The configured value.</returns> PropertyAccessMode? SetPropertyAccessMode( PropertyAccessMode? propertyAccessMode, bool fromDataAnnotation = false); /// <summary> /// Returns the configuration source for <see cref="IReadOnlyPropertyBase.GetPropertyAccessMode" />. /// </summary> /// <returns>The configuration source for <see cref="IReadOnlyPropertyBase.GetPropertyAccessMode" />.</returns> ConfigurationSource? GetPropertyAccessModeConfigurationSource(); }
IConventionPropertyBase
csharp
dotnet__aspnetcore
src/Components/Forms/src/ValidationMessageStore.cs
{ "start": 313, "end": 5635 }
public sealed class ____ { private readonly EditContext _editContext; private readonly Dictionary<FieldIdentifier, List<string>> _messages = new Dictionary<FieldIdentifier, List<string>>(); /// <summary> /// Creates an instance of <see cref="ValidationMessageStore"/>. /// </summary> /// <param name="editContext">The <see cref="EditContext"/> with which this store should be associated.</param> public ValidationMessageStore(EditContext editContext) { _editContext = editContext ?? throw new ArgumentNullException(nameof(editContext)); } /// <summary> /// Adds a validation message for the specified field. /// </summary> /// <param name="fieldIdentifier">The identifier for the field.</param> /// <param name="message">The validation message.</param> public void Add(in FieldIdentifier fieldIdentifier, string message) => GetOrCreateMessagesListForField(fieldIdentifier).Add(message); /// <summary> /// Adds a validation message for the specified field. /// </summary> /// <param name="accessor">Identifies the field for which to add the message.</param> /// <param name="message">The validation message.</param> public void Add(Expression<Func<object>> accessor, string message) => Add(FieldIdentifier.Create(accessor), message); /// <summary> /// Adds the messages from the specified collection for the specified field. /// </summary> /// <param name="fieldIdentifier">The identifier for the field.</param> /// <param name="messages">The validation messages to be added.</param> public void Add(in FieldIdentifier fieldIdentifier, IEnumerable<string> messages) => GetOrCreateMessagesListForField(fieldIdentifier).AddRange(messages); /// <summary> /// Adds the messages from the specified collection for the specified field. /// </summary> /// <param name="accessor">Identifies the field for which to add the messages.</param> /// <param name="messages">The validation messages to be added.</param> public void Add(Expression<Func<object>> accessor, IEnumerable<string> messages) => Add(FieldIdentifier.Create(accessor), messages); /// <summary> /// Gets the validation messages within this <see cref="ValidationMessageStore"/> for the specified field. /// /// To get the validation messages across all validation message stores, use <see cref="EditContext.GetValidationMessages(FieldIdentifier)"/> instead /// </summary> /// <param name="fieldIdentifier">The identifier for the field.</param> /// <returns>The validation messages for the specified field within this <see cref="ValidationMessageStore"/>.</returns> public IEnumerable<string> this[FieldIdentifier fieldIdentifier] => _messages.TryGetValue(fieldIdentifier, out var messages) ? messages : Array.Empty<string>(); /// <summary> /// Gets the validation messages within this <see cref="ValidationMessageStore"/> for the specified field. /// /// To get the validation messages across all validation message stores, use <see cref="EditContext.GetValidationMessages(FieldIdentifier)"/> instead /// </summary> /// <param name="accessor">The identifier for the field.</param> /// <returns>The validation messages for the specified field within this <see cref="ValidationMessageStore"/>.</returns> public IEnumerable<string> this[Expression<Func<object>> accessor] => this[FieldIdentifier.Create(accessor)]; /// <summary> /// Removes all messages within this <see cref="ValidationMessageStore"/>. /// </summary> public void Clear() { foreach (var fieldIdentifier in _messages.Keys) { DissociateFromField(fieldIdentifier); } _messages.Clear(); } /// <summary> /// Removes all messages within this <see cref="ValidationMessageStore"/> for the specified field. /// </summary> /// <param name="accessor">Identifies the field for which to remove the messages.</param> public void Clear(Expression<Func<object>> accessor) => Clear(FieldIdentifier.Create(accessor)); /// <summary> /// Removes all messages within this <see cref="ValidationMessageStore"/> for the specified field. /// </summary> /// <param name="fieldIdentifier">The identifier for the field.</param> public void Clear(in FieldIdentifier fieldIdentifier) { DissociateFromField(fieldIdentifier); _messages.Remove(fieldIdentifier); } private List<string> GetOrCreateMessagesListForField(in FieldIdentifier fieldIdentifier) { if (!_messages.TryGetValue(fieldIdentifier, out var messagesForField)) { messagesForField = new List<string>(); _messages.Add(fieldIdentifier, messagesForField); AssociateWithField(fieldIdentifier); } return messagesForField; } private void AssociateWithField(in FieldIdentifier fieldIdentifier) => _editContext.GetOrAddFieldState(fieldIdentifier).AssociateWithValidationMessageStore(this); private void DissociateFromField(in FieldIdentifier fieldIdentifier) => _editContext.GetFieldState(fieldIdentifier)?.DissociateFromValidationMessageStore(this); }
ValidationMessageStore
csharp
dotnet__efcore
src/EFCore/Metadata/Builders/ComplexPropertiesConfigurationBuilder`.cs
{ "start": 776, "end": 1510 }
public class ____<TProperty> : ComplexPropertiesConfigurationBuilder { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [EntityFrameworkInternal] public ComplexPropertiesConfigurationBuilder(ComplexPropertyConfiguration property) : base(property) { } }
ComplexPropertiesConfigurationBuilder
csharp
MassTransit__MassTransit
src/MassTransit/Initializers/PropertyProviders/ToNullablePropertyProvider.cs
{ "start": 111, "end": 241 }
public class ____<TInput, TProperty> : IPropertyProvider<TInput, TProperty?> where TInput :
ToNullablePropertyProvider
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Tests/Types/Relay/NodeFieldSupportTests.cs
{ "start": 9648, "end": 9800 }
public class ____ { public required string Id { get; set; } public static Bar1 GetBar1(string id) => new() { Id = id }; }
Bar1
csharp
louthy__language-ext
LanguageExt.Tests/Transformer/Traverse/Option/Sync/Identity.cs
{ "start": 112, "end": 692 }
public class ____ { [Fact] public void IdentityNoneIsNone() { var ma = new Identity<Option<int>>(None); var mb = ma.Traverse(x => x).As(); var mc = Option<Identity<int>>.None; var mr = mb == mc; Assert.True(mr); } [Fact] public void IdentitySomeIsSomeIdentity() { var ma = new Identity<Option<int>>(1234); var mb = ma.Traverse(x => x).As(); var mc = Some(new Identity<int>(1234)); var mr = mb == mc; Assert.True(mr); } }
IdentityOption
csharp
SixLabors__Fonts
src/SixLabors.Fonts/Tables/AdvancedTypographic/GPos/MarkRecord.cs
{ "start": 439, "end": 2151 }
struct ____ { /// <summary> /// Initializes a new instance of the <see cref="MarkRecord"/> struct. /// </summary> /// <param name="reader">The big endian binary reader.</param> /// <param name="offset">Offset to the beginning of MarkArray table.</param> public MarkRecord(BigEndianBinaryReader reader, long offset) { // +--------------+------------------+--------------------------------------------------------------------------------------+ // | Type | Name | Description | // +==============+==================+======================================================================================+ // | uint16 | markClass | Class defined for the associated mark. | // +--------------+------------------+--------------------------------------------------------------------------------------+ // | Offset16 | markAnchorOffset | Offset to Anchor table, from beginning of MarkArray table. | // +--------------+------------------+--------------------------------------------------------------------------------------+ this.MarkClass = reader.ReadUInt16(); ushort markAnchorOffset = reader.ReadOffset16(); // Reset the reader position after reading the anchor table. long readerPosition = reader.BaseStream.Position; this.MarkAnchorTable = AnchorTable.Load(reader, offset + markAnchorOffset); reader.BaseStream.Seek(readerPosition, SeekOrigin.Begin); } /// <summary> /// Gets the
MarkRecord
csharp
dotnet__aspnetcore
src/Tools/Shared/SecretsHelpers/UserSecretsCreator.cs
{ "start": 300, "end": 3154 }
internal static class ____ { public static string CreateUserSecretsId(IReporter reporter, string project, string workingDirectory, string overrideId = null) { var projectPath = ResolveProjectPath(project, workingDirectory); // Load the project file as XML var projectDocument = XDocument.Load(projectPath, LoadOptions.PreserveWhitespace); // Accept the `--id` CLI option to the main app string newSecretsId = string.IsNullOrWhiteSpace(overrideId) ? Guid.NewGuid().ToString() : overrideId; // Confirm secret ID does not contain invalid characters if (Path.GetInvalidPathChars().Any(newSecretsId.Contains)) { throw new ArgumentException(SecretsHelpersResources.FormatError_InvalidSecretsId(newSecretsId)); } var existingUserSecretsId = projectDocument.XPathSelectElements("//UserSecretsId").FirstOrDefault(); // Check if a UserSecretsId is already set if (existingUserSecretsId is not null) { // Only set the UserSecretsId if the user specified an explicit value if (string.IsNullOrWhiteSpace(overrideId)) { reporter.Output(SecretsHelpersResources.FormatMessage_ProjectAlreadyInitialized(projectPath)); return existingUserSecretsId.Value; } existingUserSecretsId.SetValue(newSecretsId); } else { // Find the first non-conditional PropertyGroup var propertyGroup = projectDocument.Root.DescendantNodes() .FirstOrDefault(node => node is XElement el && el.Name == "PropertyGroup" && el.Attributes().All(attr => attr.Name != "Condition")) as XElement; // No valid property group, create a new one if (propertyGroup == null) { propertyGroup = new XElement("PropertyGroup"); projectDocument.Root.AddFirst(propertyGroup); } // Add UserSecretsId element propertyGroup.Add(" "); propertyGroup.Add(new XElement("UserSecretsId", newSecretsId)); propertyGroup.Add($"{Environment.NewLine} "); } var settings = new XmlWriterSettings { OmitXmlDeclaration = true, }; using var xw = XmlWriter.Create(projectPath, settings); projectDocument.Save(xw); reporter.Output(SecretsHelpersResources.FormatMessage_SetUserSecretsIdForProject(newSecretsId, projectPath)); return newSecretsId; } private static string ResolveProjectPath(string name, string path) { var finder = new MsBuildProjectFinder(path); return finder.FindMsBuildProject(name); } }
UserSecretsCreator
csharp
dotnet__aspnetcore
src/OpenApi/test/Microsoft.AspNetCore.OpenApi.Tests/Services/OpenApiSchemaService/OpenApiSchemaService.ParameterSchemas.cs
{ "start": 38664, "end": 38724 }
public enum ____ { None = 1 }
EnumArrayType
csharp
dotnet__orleans
test/DefaultCluster.Tests/ManagementGrainTests.cs
{ "start": 2888, "end": 3031 }
public class ____ : Grain, IDumbWorker { public Task DoNothing() => Task.CompletedTask; } /// <summary> /// Test
DumbWorker
csharp
smartstore__Smartstore
src/Smartstore.Web.Common/Rendering/Builders/NavigationItemWithContentBuilder.cs
{ "start": 192, "end": 2741 }
public abstract class ____<TItem, TBuilder> : NavigationItemBuilder<TItem, TBuilder>, IHideObjectMembers where TItem : NavigationItemWithContent where TBuilder : NavigationItemtWithContentBuilder<TItem, TBuilder> { public NavigationItemtWithContentBuilder(TItem item, IHtmlHelper htmlHelper) : base(item) { Guard.NotNull(htmlHelper, nameof(htmlHelper)); HtmlHelper = htmlHelper; } protected IHtmlHelper HtmlHelper { get; } /// <summary> /// Specifies whether the content should be loaded per AJAX into the content pane. /// </summary> /// <param name="value">value</param> /// <returns>builder</returns> /// <remarks> /// This setting has no effect when no route is specified OR /// static content was set. /// </remarks> public TBuilder Ajax(bool value = true) { Item.Ajax = value; return (this as TBuilder); } /// <summary> /// Whether item output should be suppressed if result content is empty. /// Has no effect if content is loaded via AJAX. /// </summary> public TBuilder HideIfEmpty(bool value = true) { Item.HideIfEmpty = value; return (this as TBuilder); } public TBuilder Content(string value) { if (value.IsEmpty()) { // do nothing return (this as TBuilder); } return Content(new HtmlString(value)); } public TBuilder Content(IHtmlContent value) { Item.Content = value; return (this as TBuilder); } public TBuilder Content(Widget value) { Item.Widget = value; return (this as TBuilder); } public TBuilder ContentHtmlAttributes(string name, string value, bool condition = true) { if (condition) Item.ContentHtmlAttributes.Merge(name, value); return (this as TBuilder); } public TBuilder ContentHtmlAttributes(object attributes) { return ContentHtmlAttributes(ConvertUtility.ObjectToStringDictionary(attributes)); } public TBuilder ContentHtmlAttributes(IDictionary<string, string> attributes) { Item.ContentHtmlAttributes.Merge(attributes); return (this as TBuilder); } } }
NavigationItemtWithContentBuilder
csharp
dotnet__tye
samples/azure-functions/frontend-backend/frontend/Startup.cs
{ "start": 638, "end": 2986 }
public class ____ { private readonly JsonSerializerOptions options = new JsonSerializerOptions() { PropertyNameCaseInsensitive = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase, }; public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { services.AddHealthChecks(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseRouting(); app.UseEndpoints(endpoints => { var uri = Configuration.GetServiceUri("backend")!; logger.LogInformation("Backend URL: {BackendUrl}", uri); var httpClient = new HttpClient() { BaseAddress = uri }; endpoints.MapGet("/", async context => { var bytes = await httpClient.GetByteArrayAsync("/api/backend"); var backendInfo = JsonSerializer.Deserialize<BackendInfo>(bytes, options); await context.Response.WriteAsync($"Frontend Listening IP: {context.Connection.LocalIpAddress}{Environment.NewLine}"); await context.Response.WriteAsync($"Frontend Hostname: {Dns.GetHostName()}{Environment.NewLine}"); await context.Response.WriteAsync($"EnvVar Configuration value: {Configuration["App:Value"]}{Environment.NewLine}"); await context.Response.WriteAsync($"Backend Listening IP: {backendInfo.IP}{Environment.NewLine}"); await context.Response.WriteAsync($"Backend Hostname: {backendInfo.Hostname}{Environment.NewLine}"); var addresses = await Dns.GetHostAddressesAsync(uri.Host); await context.Response.WriteAsync($"Backend Host Addresses: {string.Join(", ", addresses.Select(a => a.ToString()))}"); }); endpoints.MapHealthChecks("/healthz"); }); }
Startup
csharp
PrismLibrary__Prism
src/Wpf/Prism.Wpf/Modularity/IModuleTypeLoader.cs
{ "start": 66, "end": 122 }
interface ____ moduleTypeLoaders /// </summary>
for
csharp
smartstore__Smartstore
src/Smartstore/Imaging/FormatEnums.cs
{ "start": 7316, "end": 7687 }
public enum ____ { /// <summary> /// The lossless webp format. /// </summary> Lossless, /// <summary> /// The lossy webp format. /// </summary> Lossy, } /// <summary> /// Quality/speed trade-off for the webp encoding process (0=fast, 6=slower-better). /// </summary>
WebpFileFormatType
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Issues/Issue1734.cs
{ "start": 1641, "end": 9878 }
public class ____ { #if !(PORTABLE || PORTABLE40) [Test] public void Test_XmlNode() { XmlDocument xmlDoc = JsonConvert.DeserializeXmlNode(JsonWithoutNamespace, "", true); StringAssert.AreEqual(@"<Test_Service> <fname>mark</fname> <lname>joye</lname> <CarCompany>saab</CarCompany> <CarNumber>9741</CarNumber> <IsInsured>true</IsInsured> <safty>ABS</safty> <safty>AirBags</safty> <safty>childdoorlock</safty> <CarDescription>test Car</CarDescription> <collections json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <XYZ>1</XYZ> <PQR>11</PQR> <contactdetails> <contname>DOM</contname> <contnumber>8787</contnumber> </contactdetails> <contactdetails> <contname>COM</contname> <contnumber>4564</contnumber> <addtionaldetails json:Array=""true""> <description>54657667</description> </addtionaldetails> </contactdetails> <contactdetails> <contname>gf</contname> <contnumber>123</contnumber> <addtionaldetails json:Array=""true""> <description>123</description> </addtionaldetails> </contactdetails> </collections> </Test_Service>", IndentXml(xmlDoc.OuterXml)); xmlDoc = JsonConvert.DeserializeXmlNode(JsonWithNamespace, "", true); StringAssert.AreEqual(@"<ns3:Test_Service xmlns:ns3=""http://www.CCKS.org/XRT/Form""> <ns3:fname>mark</ns3:fname> <ns3:lname>joye</ns3:lname> <ns3:CarCompany>saab</ns3:CarCompany> <ns3:CarNumber>9741</ns3:CarNumber> <ns3:IsInsured>true</ns3:IsInsured> <ns3:safty>ABS</ns3:safty> <ns3:safty>AirBags</ns3:safty> <ns3:safty>childdoorlock</ns3:safty> <ns3:CarDescription>test Car</ns3:CarDescription> <ns3:collections json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <ns3:XYZ>1</ns3:XYZ> <ns3:PQR>11</ns3:PQR> <ns3:contactdetails> <ns3:contname>DOM</ns3:contname> <ns3:contnumber>8787</ns3:contnumber> </ns3:contactdetails> <ns3:contactdetails> <ns3:contname>COM</ns3:contname> <ns3:contnumber>4564</ns3:contnumber> <ns3:addtionaldetails json:Array=""true""> <ns3:description>54657667</ns3:description> </ns3:addtionaldetails> </ns3:contactdetails> <ns3:contactdetails> <ns3:contname>gf</ns3:contname> <ns3:contnumber>123</ns3:contnumber> <ns3:addtionaldetails json:Array=""true""> <ns3:description>123</ns3:description> </ns3:addtionaldetails> </ns3:contactdetails> </ns3:collections> </ns3:Test_Service>", IndentXml(xmlDoc.OuterXml)); } private string IndentXml(string xml) { XmlReader reader = XmlReader.Create(new StringReader(xml)); StringWriter sw = new StringWriter(); XmlWriter writer = XmlWriter.Create(sw, new XmlWriterSettings { Indent = true, OmitXmlDeclaration = true }); while (reader.Read()) { writer.WriteNode(reader, false); } writer.Flush(); return sw.ToString(); } #endif #if !NET20 [Test] public void Test_XNode() { XDocument xmlDoc = JsonConvert.DeserializeXNode(JsonWithoutNamespace, "", true); string xml = xmlDoc.ToString(); StringAssert.AreEqual(@"<Test_Service> <fname>mark</fname> <lname>joye</lname> <CarCompany>saab</CarCompany> <CarNumber>9741</CarNumber> <IsInsured>true</IsInsured> <safty>ABS</safty> <safty>AirBags</safty> <safty>childdoorlock</safty> <CarDescription>test Car</CarDescription> <collections json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <XYZ>1</XYZ> <PQR>11</PQR> <contactdetails> <contname>DOM</contname> <contnumber>8787</contnumber> </contactdetails> <contactdetails> <contname>COM</contname> <contnumber>4564</contnumber> <addtionaldetails json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <description>54657667</description> </addtionaldetails> </contactdetails> <contactdetails> <contname>gf</contname> <contnumber>123</contnumber> <addtionaldetails json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <description>123</description> </addtionaldetails> </contactdetails> </collections> </Test_Service>", xml); xmlDoc = JsonConvert.DeserializeXNode(JsonWithNamespace, "", true); xml = xmlDoc.ToString(); StringAssert.AreEqual(@"<ns3:Test_Service xmlns:ns3=""http://www.CCKS.org/XRT/Form""> <ns3:fname>mark</ns3:fname> <ns3:lname>joye</ns3:lname> <ns3:CarCompany>saab</ns3:CarCompany> <ns3:CarNumber>9741</ns3:CarNumber> <ns3:IsInsured>true</ns3:IsInsured> <ns3:safty>ABS</ns3:safty> <ns3:safty>AirBags</ns3:safty> <ns3:safty>childdoorlock</ns3:safty> <ns3:CarDescription>test Car</ns3:CarDescription> <ns3:collections json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <ns3:XYZ>1</ns3:XYZ> <ns3:PQR>11</ns3:PQR> <ns3:contactdetails> <ns3:contname>DOM</ns3:contname> <ns3:contnumber>8787</ns3:contnumber> </ns3:contactdetails> <ns3:contactdetails> <ns3:contname>COM</ns3:contname> <ns3:contnumber>4564</ns3:contnumber> <ns3:addtionaldetails json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <ns3:description>54657667</ns3:description> </ns3:addtionaldetails> </ns3:contactdetails> <ns3:contactdetails> <ns3:contname>gf</ns3:contname> <ns3:contnumber>123</ns3:contnumber> <ns3:addtionaldetails json:Array=""true"" xmlns:json=""http://james.newtonking.com/projects/json""> <ns3:description>123</ns3:description> </ns3:addtionaldetails> </ns3:contactdetails> </ns3:collections> </ns3:Test_Service>", xml); } #endif private const string JsonWithoutNamespace = @"{ ""Test_Service"": { ""fname"": ""mark"", ""lname"": ""joye"", ""CarCompany"": ""saab"", ""CarNumber"": ""9741"", ""IsInsured"": ""true"", ""safty"": [ ""ABS"", ""AirBags"", ""childdoorlock"" ], ""CarDescription"": ""test Car"", ""collections"": [ { ""XYZ"": ""1"", ""PQR"": ""11"", ""contactdetails"": [ { ""contname"": ""DOM"", ""contnumber"": ""8787"" }, { ""contname"": ""COM"", ""contnumber"": ""4564"", ""addtionaldetails"": [ { ""description"": ""54657667"" } ] }, { ""contname"": ""gf"", ""contnumber"": ""123"", ""addtionaldetails"": [ { ""description"": ""123"" } ] } ] } ] } }"; private const string JsonWithNamespace = @"{ ""ns3:Test_Service"": { ""@xmlns:ns3"": ""http://www.CCKS.org/XRT/Form"", ""ns3:fname"": ""mark"", ""ns3:lname"": ""joye"", ""ns3:CarCompany"": ""saab"", ""ns3:CarNumber"": ""9741"", ""ns3:IsInsured"": ""true"", ""ns3:safty"": [ ""ABS"", ""AirBags"", ""childdoorlock"" ], ""ns3:CarDescription"": ""test Car"", ""ns3:collections"": [ { ""ns3:XYZ"": ""1"", ""ns3:PQR"": ""11"", ""ns3:contactdetails"": [ { ""ns3:contname"": ""DOM"", ""ns3:contnumber"": ""8787"" }, { ""ns3:contname"": ""COM"", ""ns3:contnumber"": ""4564"", ""ns3:addtionaldetails"": [ { ""ns3:description"": ""54657667"" } ] }, { ""ns3:contname"": ""gf"", ""ns3:contnumber"": ""123"", ""ns3:addtionaldetails"": [ { ""ns3:description"": ""123"" } ] } ] } ] } }"; } } #endif
Issue1734
csharp
scriban__scriban
src/Scriban/Runtime/Accessors/TypedObjectAccessor.cs
{ "start": 432, "end": 6816 }
class ____ : IObjectAccessor { private readonly MemberFilterDelegate _filter; private readonly Type _type; private readonly MemberRenamerDelegate _renamer; private readonly Dictionary<string, MemberInfo> _members; private PropertyInfo _indexer; public TypedObjectAccessor(Type targetType, MemberFilterDelegate filter, MemberRenamerDelegate renamer) : this(targetType, null, filter, renamer) { } public TypedObjectAccessor(Type targetType, IEqualityComparer<string> keyComparer, MemberFilterDelegate filter, MemberRenamerDelegate renamer) { _type = targetType ?? throw new ArgumentNullException(nameof(targetType)); _filter = filter; _renamer = renamer ?? StandardMemberRenamer.Default; _members = new Dictionary<string, MemberInfo>(keyComparer); PrepareMembers(); } public Type IndexType { get; private set; } public int GetMemberCount(TemplateContext context, SourceSpan span, object target) { return _members.Count; } public IEnumerable<string> GetMembers(TemplateContext context, SourceSpan span, object target) { return _members.Keys; } public bool HasMember(TemplateContext context, SourceSpan span, object target, string member) { return _members.ContainsKey(member); } public bool TryGetValue(TemplateContext context, SourceSpan span, object target, string member, out object value) { value = null; MemberInfo memberAccessor; if (_members.TryGetValue(member, out memberAccessor)) { var fieldAccessor = memberAccessor as FieldInfo; if (fieldAccessor != null) { value = fieldAccessor.GetValue(target); return true; } var propertyAccessor = (PropertyInfo)memberAccessor; value = propertyAccessor.GetValue(target); return true; } return false; } public bool TryGetItem(TemplateContext context, SourceSpan span, object target, object index, out object value) { if (this._indexer is null) { value = default; return false; } value = this._indexer.GetValue(target, new[] { index }); return true; } public bool TrySetItem(TemplateContext context, SourceSpan span, object target, object index, object value) { if (_indexer is null) { return false; } _indexer.SetValue(target, value, new[] { index }); return true; } public bool HasIndexer => _indexer != null; public bool TrySetValue(TemplateContext context, SourceSpan span, object target, string member, object value) { if (!_members.TryGetValue(member, out MemberInfo memberAccessor)) return false; if (memberAccessor is FieldInfo fieldAccessor) { fieldAccessor.SetValue(target, context.ToObject(span, value, fieldAccessor.FieldType)); return true; } var propertyAccessor = (PropertyInfo)memberAccessor; propertyAccessor.SetValue(target, context.ToObject(span, value, propertyAccessor.PropertyType)); return true; } private void PrepareMembers() { var type = _type; while (type != null) { foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { var keep = field.GetCustomAttribute<ScriptMemberIgnoreAttribute>() == null; if (keep && !field.IsStatic && field.IsPublic && !field.IsLiteral && (_filter == null || _filter(field))) { var newFieldName = Rename(field); if (string.IsNullOrEmpty(newFieldName)) { newFieldName = field.Name; } if (!_members.ContainsKey(newFieldName)) { _members.Add(newFieldName, field); } } } foreach (var property in type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly)) { var keep = property.GetCustomAttribute<ScriptMemberIgnoreAttribute>() == null; // Workaround with .NET Core, extension method is not working (retuning null despite doing property.GetMethod), so we need to inline it here var getMethod = property.GetMethod; if (keep && property.CanRead && !getMethod.IsStatic && getMethod.IsPublic && (_filter == null || _filter(property))) { var indexParameters = property.GetIndexParameters(); if (indexParameters.Length > 0) { IndexType = indexParameters[0].ParameterType; _indexer = property; } else { var newPropertyName = Rename(property); if (string.IsNullOrEmpty(newPropertyName)) { newPropertyName = property.Name; } if (!_members.ContainsKey(newPropertyName)) { _members.Add(newPropertyName, property); } } } } if (type.BaseType == typeof(object)) { break; } type = type.BaseType; } } private string Rename(MemberInfo member) { return _renamer(member); } } }
TypedObjectAccessor
csharp
dotnet__orleans
test/Grains/TestGrains/ImplicitSubscription_NonTransientError_RecoverableStream_CollectorGrain.cs
{ "start": 343, "end": 722 }
public class ____ : Grain<StreamCheckpoint<int>>, IGeneratedEventCollectorGrain { public const string StreamNamespace = "NonTransientError_RecoverableStream"; // grain instance state private readonly ILogger logger; private IAsyncStream<GeneratedEvent> stream;
ImplicitSubscription_NonTransientError_RecoverableStream_CollectorGrain
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler/Util/Win32Resources.cs
{ "start": 5573, "end": 7178 }
public sealed class ____ { private readonly object _name; public bool HasName => _name is string; public bool HasId => _name is ushort; public string Name => (string)_name; public ushort Id => (ushort)_name; public Win32ResourceName(string name) { _name = name ?? throw new ArgumentNullException(nameof(name)); } public Win32ResourceName(int id) : this(checked((ushort)id)) { } public Win32ResourceName(ushort id) { _name = id; } internal unsafe Win32ResourceName(byte* pRoot, IMAGE_RESOURCE_DIRECTORY_ENTRY* pEntry) { _name = (pEntry->Name & 0x80000000) == 0 ? (object)(ushort)pEntry->Name : ReadString(pRoot, (int)(pEntry->Name & 0x7FFFFFFF)); static string ReadString(byte* pRoot, int offset) { var pString = (IMAGE_RESOURCE_DIRECTORY_STRING*)(pRoot + offset); return new string(pString->NameString, 0, pString->Length); } } public static bool operator ==(Win32ResourceName x, Win32ResourceName y) { if (x.HasName) { return y.HasName ? string.Compare(x.Name, y.Name, StringComparison.OrdinalIgnoreCase) == 0 : false; } else { return y.HasId ? x.Id == y.Id : false; } } public static bool operator !=(Win32ResourceName x, Win32ResourceName y) { return !(x == y); } public override int GetHashCode() { return _name.GetHashCode(); } public override bool Equals(object? obj) { if (!(obj is Win32ResourceName name)) return false; return this == name; } public override string ToString() { return HasName ? $"Name: {Name}" : $"Id: {Id}"; } }
Win32ResourceName
csharp
ServiceStack__ServiceStack
ServiceStack.OrmLite/src/ServiceStack.OrmLite.MySql/Converters/MySqlIntegerConverters.cs
{ "start": 460, "end": 573 }
public class ____ : MySqlIntegerConverter { public override DbType DbType => DbType.Int16; }
MySqlInt16Converter
csharp
EventStore__EventStore
src/KurrentDB.Core.Tests/ClientAPI/Security/delete_stream_security.cs
{ "start": 558, "end": 7996 }
public class ____<TLogFormat, TStreamId> : AuthenticationTestBase<TLogFormat, TStreamId> { [Test] public async Task delete_of_all_is_never_allowed() { await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream("$all", null, null)); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream("$all", "user1", "pa$$1")); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream("$all", "adm", "admpa$$")); } [Test] public async Task deleting_normal_no_acl_stream_with_no_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build()); await DeleteStream(streamId, null, null); } [Test] public async Task deleting_normal_no_acl_stream_with_existing_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build()); await DeleteStream(streamId, "user1", "pa$$1"); } [Test] public async Task deleting_normal_no_acl_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build()); await DeleteStream(streamId, "adm", "admpa$$"); } [Test] public async Task deleting_normal_user_stream_with_no_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole("user1")); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, null, null)); } [Test] public async Task deleting_normal_user_stream_with_not_authorized_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole("user1")); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, "user2", "pa$$2")); } [Test] public async Task deleting_normal_user_stream_with_authorized_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole("user1")); await DeleteStream(streamId, "user1", "pa$$1"); } [Test] public async Task deleting_normal_user_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole("user1")); await DeleteStream(streamId, "adm", "admpa$$"); } [Test] public async Task deleting_normal_admin_stream_with_no_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole(SystemRoles.Admins)); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, null, null)); } [Test] public async Task deleting_normal_admin_stream_with_existing_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole(SystemRoles.Admins)); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, "user1", "pa$$1")); } [Test] public async Task deleting_normal_admin_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole(SystemRoles.Admins)); await DeleteStream(streamId, "adm", "admpa$$"); } [Test] public async Task deleting_normal_all_stream_with_no_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole(SystemRoles.All)); await DeleteStream(streamId, null, null); } [Test] public async Task deleting_normal_all_stream_with_existing_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole(SystemRoles.All)); await DeleteStream(streamId, "user1", "pa$$1"); } [Test] public async Task deleting_normal_all_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(StreamMetadata.Build().SetDeleteRole(SystemRoles.All)); await DeleteStream(streamId, "adm", "admpa$$"); } // $-stream [Test] public async Task deleting_system_no_acl_stream_with_no_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build()); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, null, null)); } [Test] public async Task deleting_system_no_acl_stream_with_existing_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build()); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, "user1", "pa$$1")); } [Test] public async Task deleting_system_no_acl_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build()); await DeleteStream(streamId, "adm", "admpa$$"); } [Test] public async Task deleting_system_user_stream_with_no_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole("user1")); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, null, null)); } [Test] public async Task deleting_system_user_stream_with_not_authorized_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole("user1")); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, "user2", "pa$$2")); } [Test] public async Task deleting_system_user_stream_with_authorized_user_is_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole("user1")); await DeleteStream(streamId, "user1", "pa$$1"); } [Test] public async Task deleting_system_user_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole("user1")); await DeleteStream(streamId, "adm", "admpa$$"); } [Test] public async Task deleting_system_admin_stream_with_no_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole(SystemRoles.Admins)); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, null, null)); } [Test] public async Task deleting_system_admin_stream_with_existing_user_is_not_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole(SystemRoles.Admins)); await AssertEx.ThrowsAsync<AccessDeniedException>(() => DeleteStream(streamId, "user1", "pa$$1")); } [Test] public async Task deleting_system_admin_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole(SystemRoles.Admins)); await DeleteStream(streamId, "adm", "admpa$$"); } [Test] public async Task deleting_system_all_stream_with_no_user_is_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole(SystemRoles.All)); await DeleteStream(streamId, null, null); } [Test] public async Task deleting_system_all_stream_with_existing_user_is_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole(SystemRoles.All)); await DeleteStream(streamId, "user1", "pa$$1"); } [Test] public async Task deleting_system_all_stream_with_admin_user_is_allowed() { var streamId = await CreateStreamWithMeta(streamPrefix: "$", metadata: StreamMetadata.Build().SetDeleteRole(SystemRoles.All)); await DeleteStream(streamId, "adm", "admpa$$"); } }
delete_stream_security
csharp
duplicati__duplicati
Duplicati/Library/Common/IO/DefineDosDevice.cs
{ "start": 1422, "end": 1565 }
public class ____ : IDisposable { /// <summary> /// Encapsulation of Win32 calls /// </summary>
DefineDosDevice
csharp
spectreconsole__spectre.console
src/Spectre.Console/Widgets/Grid.cs
{ "start": 80, "end": 3919 }
public sealed class ____ : JustInTimeRenderable, IExpandable, IAlignable { private readonly ListWithCallback<GridColumn> _columns; private readonly ListWithCallback<GridRow> _rows; private bool _expand; private Justify? _alignment; private bool _padRightCell; /// <summary> /// Gets the grid columns. /// </summary> public IReadOnlyList<GridColumn> Columns => _columns; /// <summary> /// Gets the grid rows. /// </summary> public IReadOnlyList<GridRow> Rows => _rows; /// <inheritdoc/> public bool Expand { get => _expand; set => MarkAsDirty(() => _expand = value); } /// <inheritdoc/> [Obsolete("Use the Align widget instead. This property will be removed in a later release.")] public Justify? Alignment { get => _alignment; set => MarkAsDirty(() => _alignment = value); } /// <summary> /// Gets or sets the width of the grid. /// </summary> public int? Width { get; set; } /// <summary> /// Initializes a new instance of the <see cref="Grid"/> class. /// </summary> public Grid() { _expand = false; _alignment = null; _columns = new ListWithCallback<GridColumn>(MarkAsDirty); _rows = new ListWithCallback<GridRow>(MarkAsDirty); } /// <summary> /// Adds a column to the grid. /// </summary> /// <returns>The same instance so that multiple calls can be chained.</returns> public Grid AddColumn() { AddColumn(new GridColumn()); return this; } /// <summary> /// Adds a column to the grid. /// </summary> /// <param name="column">The column to add.</param> /// <returns>The same instance so that multiple calls can be chained.</returns> public Grid AddColumn(GridColumn column) { if (column is null) { throw new ArgumentNullException(nameof(column)); } if (_rows.Count > 0) { throw new InvalidOperationException("Cannot add new columns to grid with existing rows."); } // Only pad the most right cell if we've explicitly set a padding. _padRightCell = column.HasExplicitPadding; _columns.Add(column); return this; } /// <summary> /// Adds a new row to the grid. /// </summary> /// <param name="columns">The columns to add.</param> /// <returns>The same instance so that multiple calls can be chained.</returns> public Grid AddRow(params IRenderable[] columns) { if (columns is null) { throw new ArgumentNullException(nameof(columns)); } if (columns.Length > _columns.Count) { throw new InvalidOperationException("The number of row columns are greater than the number of grid columns."); } _rows.Add(new GridRow(columns)); return this; } /// <inheritdoc/> protected override bool HasDirtyChildren() { return _columns.Any(c => ((IHasDirtyState)c).IsDirty); } /// <inheritdoc/> protected override IRenderable Build() { var table = new Table { Border = TableBorder.None, ShowHeaders = false, IsGrid = true, PadRightCell = _padRightCell, Width = Width, }; foreach (var column in _columns) { table.AddColumn(new TableColumn(string.Empty) { Width = column.Width, NoWrap = column.NoWrap, Padding = column.Padding ?? new Padding(0, 0, 2, 0), Alignment = column.Alignment, }); } foreach (var row in _rows) { table.AddRow(row); } return table; } }
Grid
csharp
dotnet__extensions
test/ProjectTemplates/Infrastructure/TemplateExecutionTestConfiguration.cs
{ "start": 191, "end": 378 }
public sealed class ____ { public required string TemplatePackageName { get; init; } public required string TestOutputFolderPrefix { get; init; } }
TemplateExecutionTestConfiguration
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.StarWars/Types/HumanInputType.cs
{ "start": 57, "end": 285 }
public class ____ : InputObjectGraphType { public HumanInputType() { Name = "HumanInput"; Field<NonNullGraphType<StringGraphType>>("name"); Field<StringGraphType>("homePlanet"); } }
HumanInputType
csharp
dotnetcore__Util
test/Util.Core.Tests.Integration/Samples/TestSample.cs
{ "start": 566, "end": 642 }
public abstract class ____ : IB, IC { } /// <summary> /// 测试类型 /// </summary>
C
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.AI.Evaluation.Console.Tests/ExceptionUtilitiesTests.cs
{ "start": 342, "end": 4760 }
public class ____ { [Fact] public void IsCancellationReturnsFalseForNonCancellationException() { var exception = new InvalidOperationException(); exception.IsCancellation().Should().BeFalse(); } [Fact] public void IsCancellationReturnsTrueForOperationCanceledException() { var exception = new OperationCanceledException(); exception.IsCancellation().Should().BeTrue(); } [Fact] public void IsCancellationReturnsTrueForTaskCanceledException() { var exception = new TaskCanceledException(); exception.IsCancellation().Should().BeTrue(); } [Fact] public void IsCancellationReturnsTrueForAggregateExceptionWithOnlyOperationCanceledExceptions() { var exception = new AggregateException(new OperationCanceledException()); exception.IsCancellation().Should().BeTrue(); } [Fact] public void IsCancellationReturnsTrueForAggregateExceptionWithOnlyTaskCanceledExceptions() { var exception = new AggregateException(new TaskCanceledException()); exception.IsCancellation().Should().BeTrue(); } [Fact] public void IsCancellationReturnsTrueForAggregateExceptionWithMultipleCancellationExceptions() { var exception = new AggregateException( new TaskCanceledException(), new OperationCanceledException(), new OperationCanceledException()); exception.IsCancellation().Should().BeTrue(); } [Fact] public void IsCancellationReturnsFalseForEmptyAggregateException() { var exception = new AggregateException(); exception.IsCancellation().Should().BeFalse(); } [Fact] public void IsCancellationReturnsFalseForAggregateExceptionWithNonCancellationExceptions() { var exception = new AggregateException(new InvalidOperationException(), new ArgumentException()); exception.IsCancellation().Should().BeFalse(); } [Fact] public void IsCancellationReturnsFalseForAggregateExceptionWithCancellationAndNonCancellationExceptions() { var exception = new AggregateException(new OperationCanceledException(), new InvalidOperationException()); exception.IsCancellation().Should().BeFalse(); } [Fact] public void IsCancellationReturnsTrueForNestedAggregateExceptionsContainingOnlyCancellationExceptions() { var exception1 = new AggregateException( new TaskCanceledException(), new OperationCanceledException(), new OperationCanceledException()); var exception2 = new AggregateException(new TaskCanceledException(), exception1); exception2.IsCancellation().Should().BeTrue(); } [Fact] public void IsCancellationReturnsFalseForNestedAggregateExceptionsContainingNonCancellationExceptions() { var exception1 = new AggregateException(new TaskCanceledException(), new InvalidOperationException()); var exception2 = new AggregateException(new TaskCanceledException(), exception1); exception2.IsCancellation().Should().BeFalse(); } [Fact] public void IsCancellationHandlesLoopsInNestedAggregateExceptions1() { var exception1 = new AggregateException(); var exception2 = new AggregateException(exception1); exception2.IsCancellation().Should().BeFalse(); } [Fact] public void IsCancellationHandlesLoopsInNestedAggregateExceptions2() { var exception1 = new AggregateException(new TaskCanceledException(), new OperationCanceledException()); var exception2 = new AggregateException(new OperationCanceledException()); var exception3 = new AggregateException(exception1, exception2, new TaskCanceledException()); exception3.IsCancellation().Should().BeTrue(); } [Fact] public void IsCancellationHandlesLoopsInNestedAggregateExceptions3() { var exception1 = new AggregateException(new TaskCanceledException(), new OperationCanceledException()); var exception2 = new AggregateException(new InvalidOperationException(), new OperationCanceledException()); var exception3 = new AggregateException(exception1, exception2, new TaskCanceledException()); exception3.IsCancellation().Should().BeFalse(); } }
ExceptionUtilitiesTests
csharp
dotnet__maui
src/Essentials/src/Battery/Battery.netstandard.tvos.cs
{ "start": 76, "end": 913 }
partial class ____ : IBattery { void StartBatteryListeners() => throw ExceptionUtils.NotSupportedOrImplementedException; void StopBatteryListeners() => throw ExceptionUtils.NotSupportedOrImplementedException; public double ChargeLevel => throw ExceptionUtils.NotSupportedOrImplementedException; public BatteryState State => throw ExceptionUtils.NotSupportedOrImplementedException; public BatteryPowerSource PowerSource => throw ExceptionUtils.NotSupportedOrImplementedException; void StartEnergySaverListeners() => throw ExceptionUtils.NotSupportedOrImplementedException; void StopEnergySaverListeners() => throw ExceptionUtils.NotSupportedOrImplementedException; public EnergySaverStatus EnergySaverStatus => throw ExceptionUtils.NotSupportedOrImplementedException; } }
BatteryImplementation
csharp
dotnet__efcore
src/EFCore/ChangeTracking/Internal/InternalEntrySubscriber.cs
{ "start": 841, "end": 10961 }
public class ____ : IInternalEntrySubscriber { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool SnapshotAndSubscribe(InternalEntityEntry entry) { var entityType = entry.EntityType; if (entityType.UseEagerSnapshots()) { entry.EnsureOriginalValues(); entry.EnsureRelationshipSnapshot(); } var changeTrackingStrategy = entityType.GetChangeTrackingStrategy(); if (changeTrackingStrategy == ChangeTrackingStrategy.Snapshot) { return false; } foreach (var navigation in entityType .GetNavigations() .Concat<INavigationBase>(entityType.GetSkipNavigations()) .Where(n => n.IsCollection)) { SubscribeCollectionChanged(entry, navigation); } if (changeTrackingStrategy != ChangeTrackingStrategy.ChangedNotifications) { AsINotifyPropertyChanging(entry, entityType, changeTrackingStrategy).PropertyChanging += entry.HandleINotifyPropertyChanging; } AsINotifyPropertyChanged(entry, entityType, changeTrackingStrategy).PropertyChanged += entry.HandleINotifyPropertyChanged; return true; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool SnapshotAndSubscribe(InternalComplexEntry entry) { var complexType = entry.ComplexType; if (complexType.UseEagerSnapshots()) { entry.EnsureOriginalValues(); } var changeTrackingStrategy = complexType.GetChangeTrackingStrategy(); if (changeTrackingStrategy == ChangeTrackingStrategy.Snapshot) { return false; } // TODO: Support complex value type collections. Issue #31411 // INotifyCollectionChanged // TODO: Support complex types with notification change tracking. Issue #36175 // INotifyPropertyChanging, INotifyPropertyChanged throw new InvalidOperationException( CoreStrings.ComplexTypeNotificationChangeTracking(complexType.DisplayName(), changeTrackingStrategy)); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SubscribeCollectionChanged(InternalEntityEntry entry, INavigationBase navigation) => AsINotifyCollectionChanged(entry, navigation, entry.EntityType, entry.EntityType.GetChangeTrackingStrategy()).CollectionChanged += entry.HandleINotifyCollectionChanged; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void SubscribeCollectionChanged(InternalEntryBase entry, IComplexProperty complexProperty) { // TODO: Support complex value type collections. Issue #31411 } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void Unsubscribe(InternalEntityEntry entry) { var entityType = entry.EntityType; var changeTrackingStrategy = entityType.GetChangeTrackingStrategy(); if (changeTrackingStrategy != ChangeTrackingStrategy.Snapshot) { foreach (var navigation in entityType.GetNavigations() .Concat<INavigationBase>(entityType.GetSkipNavigations()) .Where(n => n.IsCollection)) { UnsubscribeCollectionChanged(entry, navigation); } if (changeTrackingStrategy != ChangeTrackingStrategy.ChangedNotifications) { AsINotifyPropertyChanging(entry, entityType, changeTrackingStrategy).PropertyChanging -= entry.HandleINotifyPropertyChanging; } AsINotifyPropertyChanged(entry, entityType, changeTrackingStrategy).PropertyChanged -= entry.HandleINotifyPropertyChanged; } foreach (var complexEntry in entry.GetFlattenedComplexEntries()) { Unsubscribe(complexEntry); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void Unsubscribe(InternalComplexEntry entry) { // TODO: Support complex value type collections. Issue #31411 foreach (var complexEntry in entry.GetFlattenedComplexEntries()) { Unsubscribe(complexEntry); } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void UnsubscribeCollectionChanged( InternalEntityEntry entry, INavigationBase navigation) => AsINotifyCollectionChanged(entry, navigation, entry.EntityType, entry.EntityType.GetChangeTrackingStrategy()).CollectionChanged -= entry.HandleINotifyCollectionChanged; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual void UnsubscribeCollectionChanged(InternalEntryBase entry, IComplexProperty complexProperty) { // TODO: Support complex value type collections. Issue #31411 } private static INotifyCollectionChanged AsINotifyCollectionChanged( InternalEntityEntry entry, INavigationBase navigation, IEntityType entityType, ChangeTrackingStrategy changeTrackingStrategy) { var collection = entry.GetOrCreateCollection(navigation, forMaterialization: false); if (collection is not INotifyCollectionChanged notifyingCollection) { var collectionType = collection.GetType().DisplayName(fullName: false); throw new InvalidOperationException( CoreStrings.NonNotifyingCollection(navigation.Name, entityType.DisplayName(), collectionType, changeTrackingStrategy)); } return notifyingCollection; } private static INotifyPropertyChanged AsINotifyPropertyChanged( InternalEntityEntry entry, IEntityType entityType, ChangeTrackingStrategy changeTrackingStrategy) { if (entry.Entity is not INotifyPropertyChanged changed) { throw new InvalidOperationException( CoreStrings.ChangeTrackingInterfaceMissing( entityType.DisplayName(), changeTrackingStrategy, nameof(INotifyPropertyChanged))); } return changed; } private static INotifyPropertyChanging AsINotifyPropertyChanging( InternalEntityEntry entry, IEntityType entityType, ChangeTrackingStrategy changeTrackingStrategy) { if (entry.Entity is not INotifyPropertyChanging changing) { throw new InvalidOperationException( CoreStrings.ChangeTrackingInterfaceMissing( entityType.DisplayName(), changeTrackingStrategy, nameof(INotifyPropertyChanging))); } return changing; } }
InternalEntrySubscriber
csharp
MonoGame__MonoGame
MonoGame.Framework/Content/ContentReaders/StringReader.cs
{ "start": 379, "end": 653 }
internal class ____ : ContentTypeReader<String> { public StringReader() { } protected internal override string Read(ContentReader input, string existingInstance) { return input.ReadString(); } } }
StringReader
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Microsoft_UI_Xaml_Controls/TreeView/TreeViewNode2.cs
{ "start": 405, "end": 451 }
class ____ : TreeViewNode { } }
TreeViewNode2
csharp
dotnet__extensions
test/Libraries/Microsoft.Extensions.AI.AzureAIInference.Tests/AzureAIInferenceEmbeddingGeneratorTests.cs
{ "start": 475, "end": 39730 }
public class ____ { [Fact] public void AsIEmbeddingGenerator_InvalidArgs_Throws() { Assert.Throws<ArgumentNullException>("embeddingsClient", () => ((EmbeddingsClient)null!).AsIEmbeddingGenerator()); EmbeddingsClient client = new(new("http://somewhere"), new AzureKeyCredential("key")); Assert.Throws<ArgumentException>("defaultModelId", () => client.AsIEmbeddingGenerator(" ")); client.AsIEmbeddingGenerator(null); } [Fact] public void AsIEmbeddingGenerator_AzureAIClient_ProducesExpectedMetadata() { Uri endpoint = new("http://localhost/some/endpoint"); string model = "amazingModel"; EmbeddingsClient client = new(endpoint, new AzureKeyCredential("key")); IEmbeddingGenerator<string, Embedding<float>> embeddingGenerator = client.AsIEmbeddingGenerator(model); var metadata = embeddingGenerator.GetService<EmbeddingGeneratorMetadata>(); Assert.Equal("azure.ai.inference", metadata?.ProviderName); Assert.Equal(endpoint, metadata?.ProviderUri); Assert.Equal(model, metadata?.DefaultModelId); } [Fact] public void GetService_SuccessfullyReturnsUnderlyingClient() { var client = new EmbeddingsClient(new("http://somewhere"), new AzureKeyCredential("key")); var embeddingGenerator = client.AsIEmbeddingGenerator("model"); Assert.Same(embeddingGenerator, embeddingGenerator.GetService<IEmbeddingGenerator<string, Embedding<float>>>()); Assert.Same(client, embeddingGenerator.GetService<EmbeddingsClient>()); using IEmbeddingGenerator<string, Embedding<float>> pipeline = embeddingGenerator .AsBuilder() .UseOpenTelemetry() .UseDistributedCache(new MemoryDistributedCache(Options.Options.Create(new MemoryDistributedCacheOptions()))) .Build(); Assert.NotNull(pipeline.GetService<DistributedCachingEmbeddingGenerator<string, Embedding<float>>>()); Assert.NotNull(pipeline.GetService<CachingEmbeddingGenerator<string, Embedding<float>>>()); Assert.NotNull(pipeline.GetService<OpenTelemetryEmbeddingGenerator<string, Embedding<float>>>()); Assert.Same(client, pipeline.GetService<EmbeddingsClient>()); Assert.IsType<OpenTelemetryEmbeddingGenerator<string, Embedding<float>>>(pipeline.GetService<IEmbeddingGenerator<string, Embedding<float>>>()); } [Fact] public async Task GenerateAsync_ExpectedRequestResponse() { const string Input = """ {"input":["hello, world!","red, white, blue"],"encoding_format":"base64","model":"text-embedding-3-small"} """; const string Output = """ { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": "qjH+vMcj07wP1+U7kbwjOv4cwLyL3iy9DkgpvCkBQD0bthW98o6SvMMwmTrQRQa9r7b1uy4tuLzssJs7jZspPe0JG70KJy89ae4fPNLUwjytoHk9BX/1OlXCfTzc07M8JAMIPU7cibsUJiC8pTNGPWUbJztfwW69oNwOPQIQ+rwm60M7oAfOvDMAsTxb+fM77WIaPIverDqcu5S84f+rvFyr8rxqoB686/4cPVnj9ztLHw29mJqaPAhH8Lz/db86qga/PGh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qm5bDt4vToTmjuGJcg7tmMRO9YEEr3oJAC9THmdPKn607vcJhM8Zj6yvHR5r7ywYmq83fjSO5mLyzshIEU8EWKiuu9eVjw75dk7fzGHvNl+sjwJJOs8YllBPAtheztz7QQ92lDyvDEDozzEKrk7KnZRvG8pbjsdYI+7yky6OfWAVzzjYGk7NX3DOzrNhDyeIaI8joTZvFcMOryYRba8G7iuu893QDw9RyW7za6FvDUJ7rva6YK9D7rBPD1o/zxCLJa65TaKvHsGAT2g6ly8+tCYu+wqy7xeAHu8vZ1nPBv+QzwfVwo8CMYAvM+91TzKTDq8Ueo4u2uvzTsBf8Q8p+uDvKofDz12tj+8wP+yOlkDtTwYyji6ZdPhPGv14rwqdtE8YPf1vLIKy7yFLs28ouFXvO1PBj15pDU83xQJPdfWUTz8x5O64kgUPBQKA72eIaK6A3a/OyzYnLoYnPg4XMNqPdxsqLsKSaY7pfSIvBoshLupKJS8G0TZOu/SqzzFcE47cvaJPA19Mb14dQC8sVllvJmwhjycBey8cvaJOmSWUbvRtFC8WtX0O2r+57twIGm8yeFpvFuG2rzCyO08PUelPK5rbzouFS29uCxMPQAUdDqtma88wqeTu5gge7zH8/O7l067PJdOO7uKxCO8/xx5vKt9+TztTwa8OhOaO+Q/Dzw33w49CZhAvSubjDydttG8IdovPIADR7stHrI7ATmvvOAs3rzL2OQ69K4XvNccZ7zlV2S8c+0EPfNDxzydKqc6LLPhO8YhtDyJhxM9H1eKOaNMKLtOcBg9HPU+PTsrbzvT0Ia8BG26PB2mpDp7TJa8wP8yPVvM77t0ea86eTBgvFurFT1C/tW7CkkmvKOSPT2aPDG9lGDFPAhSq7u5UYc8l5TQPFh3ijz9vg68lGBFO4/vKTxViZS7eQ8GPTNAs7xmsoe8o0yoPJfaZbwlvyA8IazvO0XsS717TJY8flvmOgHFWbyWnVW8mdFgvJbCkDynDF68" } ], "model": "text-embedding-3-small", "usage": { "prompt_tokens": 9, "total_tokens": 9 } } """; using VerbatimHttpHandler handler = new(Input, Output); using HttpClient httpClient = new(handler); using IEmbeddingGenerator<string, Embedding<float>> generator = new EmbeddingsClient(new("http://somewhere"), new AzureKeyCredential("key"), new() { Transport = new HttpClientTransport(httpClient), }).AsIEmbeddingGenerator("text-embedding-3-small"); var response = await generator.GenerateAsync([ "hello, world!", "red, white, blue", ]); Assert.NotNull(response); Assert.Equal(2, response.Count); Assert.NotNull(response.Usage); Assert.Equal(9, response.Usage.InputTokenCount); Assert.Equal(9, response.Usage.TotalTokenCount); foreach (Embedding<float> e in response) { Assert.Equal("text-embedding-3-small", e.ModelId); Assert.NotNull(e.CreatedAt); Assert.Equal(1536, e.Vector.Length); Assert.Contains(e.Vector.ToArray(), f => !f.Equals(0)); } } [Fact] public async Task EmbeddingGenerationOptions_DoNotOverwrite_NotNullPropertiesInRawRepresentation() { const string Input = """ { "input":["hello, world!","red, white, blue"], "dimensions":1536, "encoding_format":"base64", "model":"text-embedding-3-small" } """; const string Output = """ { "object": "list", "data": [ { "object": "embedding", "index": 0, "embedding": "qjH+vMcj07wP1+U7kbwjOv4cwLyL3iy9DkgpvCkBQD0bthW98o6SvMMwmTrQRQa9r7b1uy4tuLzssJs7jZspPe0JG70KJy89ae4fPNLUwjytoHk9BX/1OlXCfTzc07M8JAMIPU7cibsUJiC8pTNGPWUbJztfwW69oNwOPQIQ+rwm60M7oAfOvDMAsTxb+fM77WIaPIverDqcu5S84f+rvFyr8rxqoB686/4cPVnj9ztLHw29mJqaPAhH8Lz/db86qga/PGhnYD1WST28YgWru1AdRTz/db899PIPPBzBE720ie47ujymPbh/Kb0scLs8V1Q7PGIFqzwVMR48xp+UOhNGYTxfwW67CaDvvOeEI7tgc228uQNoPXrLBztd2TI9HRqTvLuVJbytoPm8YVMsOvi6irzweJY7/WpBvI5NKL040ym95ccmPAfj8rxJCZG9bsGYvJkpVzszp7G8wOxcu6/ZN7xXrTo7Q90YvGTtZjz/SgA8RWxVPL/hXjynl8O8ZzGjvHK0Uj0dRVI954QjvaqKfTxmUeS8Abf6O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y7xeAHu8vZ1nPBv+QzwfVwo8CMYAvM+91TzKTDq8Ueo4u2uvzTsBf8Q8p+uDvKofDz12tj+8wP+yOlkDtTwYyji6ZdPhPGv14rwqdtE8YPf1vLIKy7yFLs28ouFXvO1PBj15pDU83xQJPdfWUTz8x5O64kgUPBQKA72eIaK6A3a/OyzYnLoYnPg4XMNqPdxsqLsKSaY7pfSIvBoshLupKJS8G0TZOu/SqzzFcE47cvaJPA19Mb14dQC8sVllvJmwhjycBey8cvaJOmSWUbvRtFC8WtX0O2r+57twIGm8yeFpvFuG2rzCyO08PUelPK5rbzouFS29uCxMPQAUdDqtma88wqeTu5gge7zH8/O7l067PJdOO7uKxCO8/xx5vKt9+TztTwa8OhOaO+Q/Dzw33w49CZhAvSubjDydttG8IdovPIADR7stHrI7ATmvvOAs3rzL2OQ69K4XvNccZ7zlV2S8c+0EPfNDxzydKqc6LLPhO8YhtDyJhxM9H1eKOaNMKLtOcBg9HPU+PTsrbzvT0Ia8BG26PB2mpDp7TJa8wP8yPVvM77t0ea86eTBgvFurFT1C/tW7CkkmvKOSPT2aPDG9lGDFPAhSq7u5UYc8l5TQPFh3ijz9vg68lGBFO4/vKTxViZS7eQ8GPTNAs7xmsoe8o0yoPJfaZbwlvyA8IazvO0XsS717TJY8flvmOgHFWbyWnVW8mdFgvJbCkDynDF68" } ], "model": "text-embedding-3-small" } """; using VerbatimHttpHandler handler = new(Input, Output); using HttpClient httpClient = new(handler); using IEmbeddingGenerator<string, Embedding<float>> generator = new EmbeddingsClient(new("http://somewhere"), new AzureKeyCredential("key"), new() { Transport = new HttpClientTransport(httpClient), }).AsIEmbeddingGenerator("text-embedding-3-large"); var response = await generator.GenerateAsync([ "hello, world!", "red, white, blue", ], new EmbeddingGenerationOptions { Dimensions = 3072, RawRepresentationFactory = (e) => new EmbeddingsOptions(input: []) { Dimensions = 1536, Model = "text-embedding-3-small", EncodingFormat = EmbeddingEncodingFormat.Single, // this will be overwritten, we only support base64. } }); Assert.NotNull(response); foreach (Embedding<float> e in response) { Assert.Equal("text-embedding-3-small", e.ModelId); Assert.NotNull(e.CreatedAt); Assert.Equal(1536, e.Vector.Length); Assert.Contains(e.Vector.ToArray(), f => !f.Equals(0)); } } }
AzureAIInferenceEmbeddingGeneratorTests
csharp
dotnet__aspnetcore
src/Mvc/Mvc.Analyzers/test/AvoidHtmlPartialAnalyzerTest.cs
{ "start": 4589, "end": 6587 }
public class ____ : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<dynamic> { #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { BeginContext(0, 25, true); Write({|#0:Html.Partial(""Some - Partial"")|}); EndContext(); EndContext(); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<dynamic> Html { get; private set; } } } #pragma warning restore 1591"; var diagnosticResult = new DiagnosticResult(DiagnosticDescriptor) .WithLocation(0) .WithArguments("Partial"); return VerifyAnalyzerAsync(source, diagnosticResult); } [Fact] public Task DiagnosticsAreReturned_ForUseOfHtmlPartial_WithAdditionalParameters() { var source = @" namespace AspNetCore { using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures;
DiagnosticsAreReturned_ForUseOfHtmlPartial
csharp
ShareX__ShareX
ShareX.MediaLib/Forms/VideoThumbnailerForm.Designer.cs
{ "start": 33, "end": 3857 }
partial class ____ { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VideoThumbnailerForm)); this.txtMediaPath = new System.Windows.Forms.TextBox(); this.btnStart = new System.Windows.Forms.Button(); this.pgOptions = new System.Windows.Forms.PropertyGrid(); this.btnBrowse = new System.Windows.Forms.Button(); this.pbProgress = new System.Windows.Forms.ProgressBar(); this.SuspendLayout(); // // txtMediaPath // resources.ApplyResources(this.txtMediaPath, "txtMediaPath"); this.txtMediaPath.Name = "txtMediaPath"; // // btnStart // resources.ApplyResources(this.btnStart, "btnStart"); this.btnStart.Name = "btnStart"; this.btnStart.UseVisualStyleBackColor = true; this.btnStart.Click += new System.EventHandler(this.btnStart_Click); // // pgOptions // resources.ApplyResources(this.pgOptions, "pgOptions"); this.pgOptions.Name = "pgOptions"; this.pgOptions.PropertySort = System.Windows.Forms.PropertySort.Categorized; this.pgOptions.ToolbarVisible = false; // // btnBrowse // resources.ApplyResources(this.btnBrowse, "btnBrowse"); this.btnBrowse.Name = "btnBrowse"; this.btnBrowse.UseVisualStyleBackColor = true; this.btnBrowse.Click += new System.EventHandler(this.btnBrowse_Click); // // pbProgress // resources.ApplyResources(this.pbProgress, "pbProgress"); this.pbProgress.Name = "pbProgress"; // // VideoThumbnailerForm // resources.ApplyResources(this, "$this"); this.AutoScaleDimensions = new System.Drawing.SizeF(96F, 96F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Dpi; this.BackColor = System.Drawing.SystemColors.Window; this.Controls.Add(this.btnBrowse); this.Controls.Add(this.pgOptions); this.Controls.Add(this.txtMediaPath); this.Controls.Add(this.btnStart); this.Controls.Add(this.pbProgress); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Name = "VideoThumbnailerForm"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox txtMediaPath; private System.Windows.Forms.Button btnStart; private System.Windows.Forms.PropertyGrid pgOptions; private System.Windows.Forms.Button btnBrowse; private System.Windows.Forms.ProgressBar pbProgress; } }
VideoThumbnailerForm
csharp
icsharpcode__SharpZipLib
src/ICSharpCode.SharpZipLib/Encryption/PkzipClassic.cs
{ "start": 413, "end": 2065 }
public abstract class ____ : SymmetricAlgorithm { /// <summary> /// Generates new encryption keys based on given seed /// </summary> /// <param name="seed">The seed value to initialise keys with.</param> /// <returns>A new key value.</returns> static public byte[] GenerateKeys(byte[] seed) { if (seed == null) { throw new ArgumentNullException(nameof(seed)); } if (seed.Length == 0) { throw new ArgumentException("Length is zero", nameof(seed)); } uint[] newKeys = { 0x12345678, 0x23456789, 0x34567890 }; for (int i = 0; i < seed.Length; ++i) { newKeys[0] = Crc32.ComputeCrc32(newKeys[0], seed[i]); newKeys[1] = newKeys[1] + (byte)newKeys[0]; newKeys[1] = newKeys[1] * 134775813 + 1; newKeys[2] = Crc32.ComputeCrc32(newKeys[2], (byte)(newKeys[1] >> 24)); } byte[] result = new byte[12]; result[0] = (byte)(newKeys[0] & 0xff); result[1] = (byte)((newKeys[0] >> 8) & 0xff); result[2] = (byte)((newKeys[0] >> 16) & 0xff); result[3] = (byte)((newKeys[0] >> 24) & 0xff); result[4] = (byte)(newKeys[1] & 0xff); result[5] = (byte)((newKeys[1] >> 8) & 0xff); result[6] = (byte)((newKeys[1] >> 16) & 0xff); result[7] = (byte)((newKeys[1] >> 24) & 0xff); result[8] = (byte)(newKeys[2] & 0xff); result[9] = (byte)((newKeys[2] >> 8) & 0xff); result[10] = (byte)((newKeys[2] >> 16) & 0xff); result[11] = (byte)((newKeys[2] >> 24) & 0xff); return result; } } /// <summary> /// PkzipClassicCryptoBase provides the low level facilities for encryption /// and decryption using the PkzipClassic algorithm. /// </summary>
PkzipClassic
csharp
rabbitmq__rabbitmq-dotnet-client
projects/RabbitMQ.Client/SslOption.cs
{ "start": 1886, "end": 7422 }
public class ____ { private X509CertificateCollection? _certificateCollection; /// <summary> /// Constructs an <see cref="SslOption"/> specifying both the server canonical name and the client's certificate path. /// </summary> public SslOption(string serverName, string certificatePath = "", bool enabled = false) { Version = SslProtocols.None; AcceptablePolicyErrors = SslPolicyErrors.None; ServerName = serverName; CertPath = certificatePath; Enabled = enabled; CertificateValidationCallback = null; CertificateSelectionCallback = null; } /// <summary> /// Constructs an <see cref="SslOption"/> with no parameters set. /// </summary> public SslOption() : this(string.Empty) { } /// <summary> /// Retrieve or set the set of TLS policy (peer verification) errors that are deemed acceptable. /// </summary> public SslPolicyErrors AcceptablePolicyErrors { get; set; } /// <summary> /// Retrieve or set the client certificate passphrase. /// </summary> public string? CertPassphrase { get; set; } /// <summary> /// Retrieve or set the path to client certificate. /// </summary> public string CertPath { get; set; } /// <summary> /// An optional client TLS certificate selection callback. If this is not specified, /// the first valid certificate found will be used. /// </summary> public LocalCertificateSelectionCallback? CertificateSelectionCallback { get; set; } /// <summary> /// An optional peer verification (TLS certificate validation) callback. If this is not specified, /// the default callback will be used in conjunction with the <see cref="AcceptablePolicyErrors"/> property to /// determine if the peer's (server's) certificate should be considered valid (acceptable). /// </summary> public RemoteCertificateValidationCallback? CertificateValidationCallback { get; set; } /// <summary> /// Retrieve or set the X509CertificateCollection containing the client certificate. /// If no collection is set, the client will attempt to load one from the specified <see cref="CertPath"/>. /// </summary> public X509CertificateCollection? Certs { get { if (_certificateCollection != null) { return _certificateCollection; } if (string.IsNullOrEmpty(CertPath)) { return null; } var collection = new X509CertificateCollection { new X509Certificate2(CertPath, CertPassphrase) }; return collection; } set { _certificateCollection = value; } } /// <summary> /// Attempts to check certificate revocation status. Default is false. /// Set to true to check peer certificate for revocation. /// </summary> /// <remarks> /// Uses the built-in .NET TLS implementation machinery for checking a certificate against /// certificate revocation lists. /// </remarks> public bool CheckCertificateRevocation { get; set; } /// <summary> /// Controls if TLS should indeed be used. Set to false to disable TLS /// on the connection. /// </summary> public bool Enabled { get; set; } /// <summary> /// Retrieve or set server's expected name. /// This MUST match the Subject Alternative Name (SAN) or CN on the peer's (server's) leaf certificate, /// otherwise the TLS connection will fail. /// </summary> public string ServerName { get; set; } /// <summary> /// Retrieve or set the TLS protocol version. /// The client will let the OS pick a suitable version by using <see cref="SslProtocols.None" />. /// If this option is disabled, e.g.see via app context, the client will attempt to fall back /// to TLSv1.2. /// </summary> /// <seealso cref="SslProtocols" /> /// <seealso href="https://www.rabbitmq.com/ssl.html#dotnet-client" /> /// <seealso href="https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls?view=netframework-4.6.2" /> /// <seealso href="https://docs.microsoft.com/en-us/dotnet/api/system.security.authentication.sslprotocols?view=netframework-4.8" /> public SslProtocols Version { get; set; } /// <summary> /// Reconfigures the instance to enable/use TLSv1.2. /// Only used in environments where System.Security.Authentication.SslProtocols.None /// is unavailable or effectively disabled, as reported by System.Net.ServicePointManager. /// </summary> internal SslProtocols UseFallbackTlsVersions() { Version = SslProtocols.Tls12; return Version; } #if NET /// <summary> /// Retrieve or set the <see cref="SslStreamCertificateContext"/> to supply /// a set of certificates used for building a certificate chain. /// </summary> public SslStreamCertificateContext? ClientCertificateContext { get; set; } #endif } }
SslOption
csharp
dotnet__efcore
test/EFCore.Specification.Tests/Query/AdHocNavigationsQueryTestBase.cs
{ "start": 55472, "end": 56174 }
protected class ____(DbContextOptions options) : DbContext(options) { public DbSet<Book> Books { get; set; } public DbSet<Author> Authors { get; set; } public Task SeedAsync() { base.Add( new Author { FirstName = "William", LastName = "Shakespeare", Books = new List<Book> { new() { Title = "Hamlet" }, new() { Title = "Othello" }, new() { Title = "MacBeth" } } }); return SaveChangesAsync(); }
Context26433
csharp
dotnet__maui
src/Controls/tests/DeviceTests/Elements/HybridWebView/HybridWebViewTests_SetInvokeJavaScriptTarget.cs
{ "start": 1182, "end": 3632 }
private class ____ { private static ComputationResult NewComplexResult => new ComputationResult { result = 123, operationName = "Test" }; public string? LastMethodCalled { get; private set; } public void Invoke_NoParam_NoReturn() { UpdateLastMethodCalled(); } public object? Invoke_NoParam_ReturnNull() { UpdateLastMethodCalled(); return null; } public async Task Invoke_NoParam_ReturnTask() { await Task.Delay(1); UpdateLastMethodCalled(); } public async Task<object?> Invoke_NoParam_ReturnTaskNull() { await Task.Delay(1); UpdateLastMethodCalled(); return null; } public async Task<int> Invoke_NoParam_ReturnTaskValueType() { await Task.Delay(1); UpdateLastMethodCalled(); return 2; } public async Task<ComputationResult> Invoke_NoParam_ReturnTaskComplex() { await Task.Delay(1); UpdateLastMethodCalled(); return NewComplexResult; } public int Invoke_OneParam_ReturnValueType(Dictionary<string, int> dict) { Assert.NotNull(dict); Assert.Equal(2, dict.Count); Assert.Equal(111, dict["first"]); Assert.Equal(222, dict["second"]); UpdateLastMethodCalled(); return dict.Count; } public Dictionary<string, int> Invoke_OneParam_ReturnDictionary(Dictionary<string, int> dict) { Assert.NotNull(dict); Assert.Equal(2, dict.Count); Assert.Equal(111, dict["first"]); Assert.Equal(222, dict["second"]); UpdateLastMethodCalled(); dict["third"] = 333; return dict; } public ComputationResult Invoke_NullParam_ReturnComplex(object obj) { Assert.Null(obj); UpdateLastMethodCalled(); return NewComplexResult; } public void Invoke_ManyParams_NoReturn(Dictionary<string, int> dict, string str, object obj, ComputationResult computationResult, int[] arr) { Assert.NotNull(dict); Assert.Equal(2, dict.Count); Assert.Equal(111, dict["first"]); Assert.Equal(222, dict["second"]); Assert.Equal("hello", str); Assert.Null(obj); Assert.NotNull(computationResult); Assert.Equal("invoke_method", computationResult.operationName); Assert.Equal(123.456m, computationResult.result, 6); Assert.NotNull(arr); Assert.Equal(2, arr.Length); Assert.Equal(111, arr[0]); Assert.Equal(222, arr[1]); UpdateLastMethodCalled(); } private void UpdateLastMethodCalled([CallerMemberName] string? methodName = null) { LastMethodCalled = methodName; } }
TestDotNetMethods
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.WebHost.Endpoints.Tests/CorsFeaturePluginTests.cs
{ "start": 140, "end": 224 }
public class ____ { public bool IsSuccess { get; set; } }
CorsFeaturePluginResponse
csharp
open-telemetry__opentelemetry-dotnet
docs/trace/tail-based-sampling-span-level/TailSamplingProcessor.cs
{ "start": 275, "end": 2662 }
internal sealed class ____ : BaseProcessor<Activity> { public TailSamplingProcessor() : base() { } public override void OnEnd(Activity activity) { if (activity.Recorded) { // This means that this activity was included based on head-based sampling, // we continue with that decision and no further change is needed. Console.WriteLine($"Including head-sampled activity with id {activity.Id} and status {activity.Status}"); } else { IncludeForExportIfFailedActivity(activity); } base.OnEnd(activity); } // Note: This is used to filter spans at the end of a span. // This is a basic form of tail-based sampling at a span level. // If a span failed, we always sample it in addition to all head-sampled spans. // In this example, each span is filtered individually without consideration to any other spans. // Tail-sampling this way involves many tradeoffs. A few examples of the tradeoffs: // 1. Performance: Unlike head-based sampling where the sampling decision is made at span creation time, in // tail sampling the decision is made only at the end, so there is additional memory cost. // 2. Traces will not be complete: Since this sampling is at a span level, the generated trace will be partial and won't be complete. // For example, if another part of the call tree is successful, those spans may not be sampled in leading to a partial trace. // 3. If multiple exporters are used, this decision will impact all of them: https://github.com/open-telemetry/opentelemetry-dotnet/issues/3861. private static void IncludeForExportIfFailedActivity(Activity activity) { if (activity.Status == ActivityStatusCode.Error) { // We decide to always include all the failure spans // Set the recorded flag so that this will be exported. activity.ActivityTraceFlags |= ActivityTraceFlags.Recorded; Console.WriteLine($"Including error activity with id {activity.Id} and status {activity.Status}"); } else { // This span is not sampled and exporters won't see this span. Console.WriteLine($"Dropping activity with id {activity.Id} and status {activity.Status}"); } } }
TailSamplingProcessor
csharp
dotnet__orleans
src/Orleans.Transactions/Abstractions/ITransactionalStateStorageFactory.cs
{ "start": 76, "end": 269 }
public interface ____ { ITransactionalStateStorage<TState> Create<TState>(string stateName, IGrainContext context) where TState : class, new(); } }
ITransactionalStateStorageFactory
csharp
dotnet__aspnetcore
src/Http/Http.Extensions/src/RequestDelegateFactory.cs
{ "start": 135968, "end": 137206 }
private static class ____ { public const string RouteAttribute = "Route (Attribute)"; public const string QueryAttribute = "Query (Attribute)"; public const string HeaderAttribute = "Header (Attribute)"; public const string BodyAttribute = "Body (Attribute)"; public const string ServiceAttribute = "Service (Attribute)"; public const string FormFileAttribute = "Form File (Attribute)"; public const string FormAttribute = "Form (Attribute)"; public const string FormBindingAttribute = "Form Binding (Attribute)"; public const string RouteParameter = "Route (Inferred)"; public const string QueryStringParameter = "Query String (Inferred)"; public const string ServiceParameter = "Services (Inferred)"; public const string BodyParameter = "Body (Inferred)"; public const string RouteOrQueryStringParameter = "Route or Query String (Inferred)"; public const string FormFileParameter = "Form File (Inferred)"; public const string FormCollectionParameter = "Form Collection (Inferred)"; public const string PropertyAsParameter = "As Parameter (Attribute)"; } private static
RequestDelegateFactoryConstants
csharp
unoplatform__uno
src/SamplesApp/SamplesApp.UITests/Windows_UI_Xaml_Controls/FlipViewTests/FlipView_Tests.FlipView.cs
{ "start": 320, "end": 4133 }
public partial class ____ : SampleControlUITestBase { // Green, Blue, Red, Fuchsia, Orange const string ButtonColors = "#008000,#0000FF,#FF0000,#FF00FF,#FFA500"; [Test] [AutoRetry] [ActivePlatforms(Platform.Browser)] public void FlipView_WithButtons_FlipForward() { FlipView_WithButtons_BtnNavTest(1, true); } [Test] [AutoRetry(tryCount: 1)] [ActivePlatforms(Platform.Browser)] public void FlipView_WithButtons_FlipBackward() { FlipView_WithButtons_BtnNavTest(0, true, false); } private void FlipView_WithButtons_BtnNavTest(int expectedIndex, params bool[] forwardNavigations) { Run("UITests.Windows_UI_Xaml_Controls.FlipView.FlipView_Buttons"); var flipview = _app.Marked("SUT"); var nextButton = _app.Marked("NextButtonHorizontal"); var previousButton = _app.Marked("PreviousButtonHorizontal"); // using tap to ensure navigation buttons are visible, since we cant mouse-over _app.WaitForElement(flipview); _app.FastTap(flipview); // perform navigations foreach (var navigation in forwardNavigations.Select((x, i) => new { Step = i, Forward = x })) { string GetCurrentNavigationContext() => $"step#{navigation.Step} of" + new string(forwardNavigations .Select(x => x ? 'N' : 'P').ToArray()) .Insert(navigation.Step, "*"); // tap previous or next var targetButton = navigation.Forward ? nextButton : previousButton; _app.WaitForElement(targetButton, $"Timeout waiting for the {(navigation.Forward ? "next" : "previous")} button in {GetCurrentNavigationContext()}"); _app.FastTap(targetButton); } var flipviewRect = _app.GetPhysicalRect(flipview); var navigationContext = new string(forwardNavigations.Select(x => x ? 'N' : 'P').ToArray()); var previousButtonRect = _app.GetPhysicalRect(previousButton); // check for selection index && content Assert.AreEqual(expectedIndex, flipview.GetDependencyPropertyValue<int>("SelectedIndex")); var rect = _app.Query("SUT").Single().Rect; // Get rid of Button hover color so we can assert the actual button background. _app.TapCoordinates(rect.Right + 5, rect.Bottom + 5); using (var screenshot = TakeScreenshot($"Post_{navigationContext}_Navigation", ignoreInSnapshotCompare: true)) { ImageAssert.HasColorAt( screenshot, flipviewRect.X + previousButtonRect.Width + 2, flipviewRect.CenterY, ButtonColors.Split(',').ElementAtOrDefault(expectedIndex) ?? throw new IndexOutOfRangeException($"{nameof(expectedIndex)} is out of range") ); } } [Test] [AutoRetry] [ActivePlatforms(Platform.iOS, Platform.Android)] public void FlipView_WithButtons_FlipForward_Swipe() { Run("UITests.Windows_UI_Xaml_Controls.FlipView.FlipView_Buttons"); var left = _app.GetPhysicalRect("LeftBorder"); QueryEx sut = "SUT"; var sutRect = _app.Query(sut).Single().Rect; _app.WaitForElement("Button1"); _app.DragCoordinates((sutRect.CenterX + sutRect.Right) / 2, sutRect.CenterY, left.CenterX, sutRect.CenterY); _app.WaitForElement("Button2"); } [Test] [AutoRetry] [ActivePlatforms(Platform.iOS, Platform.Android)] public void FlipView_WithButtons_FlipBackward_Swipe() { Run("UITests.Windows_UI_Xaml_Controls.FlipView.FlipView_Buttons"); QueryEx sut = "SUT"; var right = _app.GetPhysicalRect("RightBorder"); var left = _app.GetPhysicalRect("LeftBorder"); var sutRect = _app.Query(sut).Single().Rect; _app.WaitForElement("Button1"); _app.DragCoordinates((sutRect.CenterX + sutRect.Right) / 2, sutRect.CenterY, left.CenterX, sutRect.CenterY); _app.WaitForElement("Button2"); _app.DragCoordinates((sutRect.CenterX + sutRect.X) / 2, sutRect.CenterY, right.CenterX, sutRect.CenterY); _app.WaitForElement("Button1"); } } }
FlipView_Tests
csharp
dotnetcore__Util
src/Util.Domain/Events/EntityChangeType.cs
{ "start": 73, "end": 287 }
public enum ____ { /// <summary> /// 新增 /// </summary> Created, /// <summary> /// 修改 /// </summary> Updated, /// <summary> /// 删除 /// </summary> Deleted }
EntityChangeType
csharp
MassTransit__MassTransit
src/Transports/MassTransit.KafkaIntegration/KafkaIntegration/ProducerContextFactory.cs
{ "start": 230, "end": 2676 }
public class ____ : IPipeContextFactory<ProducerContext> { readonly IClientContextSupervisor _clientContextSupervisor; readonly IHostConfiguration _hostConfiguration; readonly Func<ProducerBuilder<byte[], byte[]>> _producerBuilderFactory; public ProducerContextFactory(IClientContextSupervisor clientContextSupervisor, IHostConfiguration hostConfiguration, Func<ProducerBuilder<byte[], byte[]>> producerBuilderFactory) { _clientContextSupervisor = clientContextSupervisor; _hostConfiguration = hostConfiguration; _producerBuilderFactory = producerBuilderFactory; } public IPipeContextAgent<ProducerContext> CreateContext(ISupervisor supervisor) { IAsyncPipeContextAgent<ProducerContext> asyncContext = supervisor.AddAsyncContext<ProducerContext>(); CreateProducer(asyncContext, supervisor.Stopped); return asyncContext; } public IActivePipeContextAgent<ProducerContext> CreateActiveContext(ISupervisor supervisor, PipeContextHandle<ProducerContext> context, CancellationToken cancellationToken = new CancellationToken()) { return supervisor.AddActiveContext(context, CreateSharedConnection(context.Context, cancellationToken)); } static async Task<ProducerContext> CreateSharedConnection(Task<ProducerContext> context, CancellationToken cancellationToken) { return context.IsCompletedSuccessfully() ? new SharedProducerContext(context.Result, cancellationToken) : new SharedProducerContext(await context.OrCanceled(cancellationToken).ConfigureAwait(false), cancellationToken); } void CreateProducer(IAsyncPipeContextAgent<ProducerContext> asyncContext, CancellationToken cancellationToken) { Task<ProducerContext> Create(ClientContext clientContext, CancellationToken createCancellationToken) { ProducerBuilder<byte[], byte[]> producerBuilder = _producerBuilderFactory(); ProducerContext context = new KafkaProducerContext(producerBuilder, _hostConfiguration, cancellationToken); return Task.FromResult(context); } _clientContextSupervisor.CreateAgent(asyncContext, Create, cancellationToken); } } }
ProducerContextFactory
csharp
SixLabors__ImageSharp
src/ImageSharp/Processing/Processors/Transforms/Linear/GaussianEliminationSolver.cs
{ "start": 268, "end": 571 }
class ____ Gaussian Elimination to transform the matrix into row echelon form and then performs back substitution to find the solution vector. /// This implementation is based on: <see href="https://www.algorithm-archive.org/contents/gaussian_elimination/gaussian_elimination.html"/> /// </summary>
applies
csharp
dotnetcore__Util
test/Util.Ui.Tests/Expressions/ExpressionResolverTest.cs
{ "start": 210, "end": 14998 }
public class ____ { /// <summary> /// 表达式解析器 /// </summary> private readonly ExpressionResolver _resolver; /// <summary> /// 测试初始化 /// </summary> public ExpressionResolverTest() { _resolver = new ExpressionResolver(); } /// <summary> /// 测试解析模型类型 /// </summary> [Fact] public void TestResolve_ModelType() { var expression = ModelExpressionHelper.Create<Customer,string>( "Code",t => t.Code ); var result = _resolver.Resolve( expression ); Assert.Equal( "System.String", result.ModelType?.FullName ); } /// <summary> /// 测试解析原始属性名 /// </summary> [Fact] public void TestResolve_OriginalPropertyName() { var expression = ModelExpressionHelper.Create<Customer>( "a" ); var result = _resolver.Resolve( expression ); Assert.Equal( "a", result.OriginalPropertyName ); } /// <summary> /// 测试解析属性名 /// </summary> [Fact] public void TestResolve_PropertyName_1() { var expression = ModelExpressionHelper.Create<Customer>( "a" ); var result = _resolver.Resolve( expression ); Assert.Equal( "a", result.PropertyName ); } /// <summary> /// 测试解析属性名 - 修正为首字母小写 /// </summary> [Fact] public void TestResolve_PropertyName_2() { var expression = ModelExpressionHelper.Create<Customer>( "CustomerName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "customerName", result.PropertyName ); } /// <summary> /// 测试解析属性名 - 2级对象 /// </summary> [Fact] public void TestResolve_PropertyName_3() { var expression = ModelExpressionHelper.Create<Customer>( "Customer.UserName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "customer.userName", result.PropertyName ); } /// <summary> /// 测试解析属性名 - 3级对象 /// </summary> [Fact] public void TestResolve_PropertyName_4() { var expression = ModelExpressionHelper.Create<Customer>( "Employee.Department.UserName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "employee.department.userName", result.PropertyName ); } /// <summary> /// 测试解析属性名 - 修正缩写大小写 /// </summary> [Fact] public void TestResolve_PropertyName_5() { var expression = ModelExpressionHelper.Create<Customer>( "UIName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "uiName", result.PropertyName ); } /// <summary> /// 测试解析最后一级属性名 /// </summary> [Fact] public void TestResolve_LastPropertyName_1() { var expression = ModelExpressionHelper.Create<Customer,string>( "Code",t => t.Code ); var result = _resolver.Resolve( expression ); Assert.Equal( "code", result.LastPropertyName ); } /// <summary> /// 测试解析最后一级属性名 - 2级对象 /// </summary> [Fact] public void TestResolve_LastPropertyName_2() { var expression = ModelExpressionHelper.Create<Customer, string>( "Employee.Name", t => t.Employee.Name ); var result = _resolver.Resolve( expression ); Assert.Equal( "name", result.LastPropertyName ); } /// <summary> /// 测试解析安全属性名 /// </summary> [Fact] public void TestResolve_GetSafePropertyName_1() { var expression = ModelExpressionHelper.Create<Customer>( "CustomerName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "model.customerName", result.GetSafePropertyName() ); } /// <summary> /// 测试解析安全属性名 - 2级对象 /// </summary> [Fact] public void TestResolve_GetSafePropertyName_2() { var expression = ModelExpressionHelper.Create<Customer>( "Customer.UserName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "a.customer&&a.customer.userName", result.GetSafePropertyName("a") ); } /// <summary> /// 测试解析安全属性名 - 3级对象 /// </summary> [Fact] public void TestResolve_GetSafePropertyName_3() { var expression = ModelExpressionHelper.Create<Customer>( "Employee.Department.UserName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "model.employee&&model.employee.department&&model.employee.department.userName", result.GetSafePropertyName() ); } /// <summary> /// 测试解析安全属性名 - 4级对象 /// </summary> [Fact] public void TestResolve_GetSafePropertyName_4() { var expression = ModelExpressionHelper.Create<Customer>( "Employee.Department.Customer.UserName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "model.employee&&model.employee.department&&model.employee.department.customer&&model.employee.department.customer.userName", result.GetSafePropertyName() ); } /// <summary> /// 测试解析安全属性名 - 转换名称大小写 /// </summary> [Fact] public void TestResolve_GetSafePropertyName_5() { var expression = ModelExpressionHelper.Create<Customer>( "UIName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "model.uiName", result.GetSafePropertyName() ); } /// <summary> /// 测试安全属性名 /// </summary> [Fact] public void TestResolve_SafePropertyName_1() { var expression = ModelExpressionHelper.Create<Customer>( "CustomerName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "model.customerName", result.SafePropertyName ); } /// <summary> /// 测试安全属性名- 2级对象 /// </summary> [Fact] public void TestResolve_SafePropertyName_2() { var expression = ModelExpressionHelper.Create<Customer>( "Customer.UserName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "model.customer&&model.customer.userName", result.SafePropertyName ); } /// <summary> /// 测试安全属性名- 设置模型名称 /// </summary> [Fact] public void TestResolve_SafePropertyName_3() { var expression = ModelExpressionHelper.Create<Employee>( "Customer.UserName" ); var result = _resolver.Resolve( expression ); Assert.Equal( "employee.customer&&employee.customer.userName", result.SafePropertyName ); } /// <summary> /// 测试解析模型名称 - 未设置ModelAttribute /// </summary> [Fact] public void TestResolve_ModelName_1() { var expression = ModelExpressionHelper.Create<Customer>( "a" ); var result = _resolver.Resolve( expression ); Assert.Equal( "model", result.ModelName ); } /// <summary> /// 测试解析模型名称 - 设置ModelAttribute /// </summary> [Fact] public void TestResolve_ModelName_2() { var expression = ModelExpressionHelper.Create<Employee>( "a" ); var result = _resolver.Resolve( expression ); Assert.Equal( "employee", result.ModelName ); } /// <summary> /// 测试解析显示名称 /// </summary> [Fact] public void TestResolve_DisplayName_1() { var expression = ModelExpressionHelper.Create<Customer,string>( "a",t => t.Code ); var result = _resolver.Resolve( expression ); Assert.Equal( "编码", result.DisplayName ); } /// <summary> /// 测试解析是否密码类型 /// </summary> [Fact] public void TestResolve_IsPassword() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Password ); var result = _resolver.Resolve( expression ); Assert.True( result.IsPassword ); } /// <summary> /// 测试解析是否布尔类型 /// </summary> [Fact] public void TestResolve_IsBool() { var expression = ModelExpressionHelper.Create<Customer, bool>( "a", t => t.Enabled ); var result = _resolver.Resolve( expression ); Assert.True( result.IsBool ); } /// <summary> /// 测试解析是否枚举类型 /// </summary> [Fact] public void TestResolve_IsEnum() { var expression = ModelExpressionHelper.Create<Customer, Gender?>( "a", t => t.Gender ); var result = _resolver.Resolve( expression ); Assert.True( result.IsEnum ); } /// <summary> /// 测试解析是否日期类型 /// </summary> [Fact] public void TestResolve_IsDate() { var expression = ModelExpressionHelper.Create<Customer, DateTime?>( "a", t => t.Birthday ); var result = _resolver.Resolve( expression ); Assert.True( result.IsDate ); } /// <summary> /// 测试解析是否整型 /// </summary> [Fact] public void TestResolve_IsInt() { var expression = ModelExpressionHelper.Create<Customer, int>( "a", t => t.Tel ); var result = _resolver.Resolve( expression ); Assert.True( result.IsInt ); } /// <summary> /// 测试解析是否数值类型 /// </summary> [Fact] public void TestResolve_IsNumber() { var expression = ModelExpressionHelper.Create<Customer, double>( "a", t => t.Age ); var result = _resolver.Resolve( expression ); Assert.True( result.IsNumber ); } /// <summary> /// 测试解析是否必填项 /// </summary> [Fact] public void TestResolve_IsRequired_1() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Code ); var result = _resolver.Resolve( expression ); Assert.True( result.IsRequired ); Assert.Equal( "编码不能是空值", result.RequiredMessage ); } /// <summary> /// 测试解析是否必填项 /// </summary> [Fact] public void TestResolve_IsRequired_2() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Name ); var result = _resolver.Resolve( expression ); Assert.False( result.IsRequired ); Assert.Null( result.RequiredMessage ); } /// <summary> /// 测试解析StringLengthAttribute特性 /// </summary> [Fact] public void TestResolve_StringLength() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Code ); var result = _resolver.Resolve( expression ); Assert.Equal( 50,result.MaxLength ); Assert.Equal( 5, result.MinLength ); Assert.Equal( "编码不能超过50位,也不能小于5位", result.MaxLengthMessage ); Assert.Equal( "编码不能超过50位,也不能小于5位", result.MinLengthMessage ); } /// <summary> /// 测试解析MaxLengthAttribute特性 /// </summary> [Fact] public void TestResolve_MaxLength() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Name ); var result = _resolver.Resolve( expression ); Assert.Equal( 200, result.MaxLength ); Assert.Equal( "姓名不能超过200位", result.MaxLengthMessage ); } /// <summary> /// 测试解析MinLengthAttribute特性 /// </summary> [Fact] public void TestResolve_MinLength() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Name ); var result = _resolver.Resolve( expression ); Assert.Equal( 2, result.MinLength ); Assert.Equal( "姓名不能少于2位", result.MinLengthMessage ); } /// <summary> /// 测试解析RangeAttribute特性 /// </summary> [Fact] public void TestResolve_Range() { var expression = ModelExpressionHelper.Create<Customer, double>( "a", t => t.Age ); var result = _resolver.Resolve( expression ); Assert.Equal( 1.1, result.Min ); Assert.Equal( "年龄从1.1到99.99", result.MinMessage ); Assert.Equal( 99.99, result.Max ); Assert.Equal( "年龄从1.1到99.99", result.MaxMessage ); } /// <summary> /// 测试解析EmailAddressAttribute特性 /// </summary> [Fact] public void TestResolve_Email() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Email ); var result = _resolver.Resolve( expression ); Assert.True( result.IsEmail ); Assert.Equal( "电子邮件无效", result.EmailMessage ); } /// <summary> /// 测试解析PhoneAttribute特性 /// </summary> [Fact] public void TestResolve_Phone() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Phone ); var result = _resolver.Resolve( expression ); Assert.True( result.IsPhone ); Assert.Equal( "手机号无效", result.PhoneMessage ); } /// <summary> /// 测试解析IdCardAttribute特性 /// </summary> [Fact] public void TestResolve_IdCard() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.IdCard ); var result = _resolver.Resolve( expression ); Assert.True( result.IsIdCard ); Assert.Equal( "身份证无效", result.IdCardMessage ); } /// <summary> /// 测试解析UrlAttribute特性 /// </summary> [Fact] public void TestResolve_Url() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Url ); var result = _resolver.Resolve( expression ); Assert.True( result.IsUrl ); Assert.Equal( "网址无效", result.UrlMessage ); } /// <summary> /// 测试解析RegularExpressionAttribute特性 /// </summary> [Fact] public void TestResolve_RegularExpression() { var expression = ModelExpressionHelper.Create<Customer, string>( "a", t => t.Regular ); var result = _resolver.Resolve( expression ); Assert.True( result.IsRegularExpression ); Assert.Equal( "a", result.Pattern ); Assert.Equal( "正则表达式无效", result.RegularExpressionMessage ); } } }
ExpressionResolverTest
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.UserDataAccounts/UserDataAccountContentKinds.cs
{ "start": 312, "end": 754 }
public enum ____ : uint { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ Email = 1, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ Contact = 2, #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ Appointment = 4, #endif } #endif }
UserDataAccountContentKinds
csharp
dotnet__aspire
src/Aspire.Hosting.Azure.PostgreSQL/AzurePostgresFlexibleServerDatabaseResource.cs
{ "start": 693, "end": 2625 }
public class ____(string name, string databaseName, AzurePostgresFlexibleServerResource postgresParentResource) : Resource(name), IResourceWithParent<AzurePostgresFlexibleServerResource>, IResourceWithConnectionString { /// <summary> /// Gets the parent Azure PostgresSQL resource. /// </summary> public AzurePostgresFlexibleServerResource Parent { get; } = postgresParentResource ?? throw new ArgumentNullException(nameof(postgresParentResource)); /// <summary> /// Gets the connection string expression for the Postgres database. /// </summary> public ReferenceExpression ConnectionStringExpression => Parent.GetDatabaseConnectionString(Name, databaseName); /// <summary> /// Gets the database name. /// </summary> public string DatabaseName { get; } = ThrowIfNullOrEmpty(databaseName); /// <summary> /// Gets the inner PostgresDatabaseResource resource. /// /// This is set when RunAsContainer is called on the AzurePostgresFlexibleServerResource resource to create a local PostgreSQL container. /// </summary> internal PostgresDatabaseResource? InnerResource { get; private set; } /// <inheritdoc /> public override ResourceAnnotationCollection Annotations => InnerResource?.Annotations ?? base.Annotations; private static string ThrowIfNullOrEmpty([NotNull] string? argument, [CallerArgumentExpression(nameof(argument))] string? paramName = null) { ArgumentException.ThrowIfNullOrEmpty(argument, paramName); return argument; } internal void SetInnerResource(PostgresDatabaseResource innerResource) { // Copy the annotations to the inner resource before making it the inner resource foreach (var annotation in Annotations) { innerResource.Annotations.Add(annotation); } InnerResource = innerResource; } }
AzurePostgresFlexibleServerDatabaseResource
csharp
reactiveui__ReactiveUI
src/ReactiveUI/Bindings/Interaction/InteractionBinderImplementation.cs
{ "start": 2739, "end": 3770 }
class ____ TView : class, IViewFor { propertyName.ArgumentNullExceptionThrowIfNull(nameof(propertyName)); handler.ArgumentNullExceptionThrowIfNull(nameof(handler)); var vmExpression = Reflection.Rewrite(propertyName.Body); var vmNulls = view.WhenAnyValue(x => x.ViewModel).Where(x => x is null).Select(_ => default(IInteraction<TInput, TOutput>)); var source = Reflection.ViewModelWhenAnyValue(viewModel, view, vmExpression) .Cast<IInteraction<TInput, TOutput>?>() .Merge(vmNulls); var interactionDisposable = new SerialDisposable(); return source .Do(x => interactionDisposable.Disposable = x is null ? System.Reactive.Disposables.Disposable.Empty : x.RegisterHandler(handler)) .Finally(() => interactionDisposable.Dispose()) .Subscribe(_ => { }, ex => this.Log().Error(ex, $"{vmExpression} Interaction Binding received an Exception!")); } }
where
csharp
dotnet__maui
src/Essentials/samples/Samples/ViewModel/GeocodingViewModel.cs
{ "start": 162, "end": 3026 }
public class ____ : BaseViewModel { string lat = 47.67398.ToString(); string lon = (-122.121513).ToString(); string address = "Microsoft Building 25 Redmond WA"; string geocodeAddress; string geocodePosition; public GeocodingViewModel() { GetAddressCommand = new Command(OnGetAddress); GetPositionCommand = new Command(OnGetPosition); } public ICommand GetAddressCommand { get; } public ICommand GetPositionCommand { get; } public string Latitude { get => lat; set => SetProperty(ref lat, value); } public string Longitude { get => lon; set => SetProperty(ref lon, value); } public string GeocodeAddress { get => geocodeAddress; set => SetProperty(ref geocodeAddress, value); } public string Address { get => address; set => SetProperty(ref address, value); } public string GeocodePosition { get => geocodePosition; set => SetProperty(ref geocodePosition, value); } async void OnGetPosition() { if (IsBusy) return; IsBusy = true; try { var locations = await Geocoding.GetLocationsAsync(Address); var location = locations?.FirstOrDefault(); if (location == null) { GeocodePosition = "Unable to detect locations"; } else { GeocodePosition = $"{nameof(location.Latitude)}: {location.Latitude}\n" + $"{nameof(location.Longitude)}: {location.Longitude}\n"; } } catch (Exception ex) { GeocodePosition = $"Unable to detect locations: {ex.Message}"; } finally { IsBusy = false; } } async void OnGetAddress() { if (IsBusy) return; IsBusy = true; try { double.TryParse(lat, out var lt); double.TryParse(lon, out var ln); var placemarks = await Geocoding.GetPlacemarksAsync(lt, ln); var placemark = placemarks?.FirstOrDefault(); if (placemark == null) { GeocodeAddress = "Unable to detect placemarks."; } else { GeocodeAddress = $"{nameof(placemark.AdminArea)}: {placemark.AdminArea}\n" + $"{nameof(placemark.CountryCode)}: {placemark.CountryCode}\n" + $"{nameof(placemark.CountryName)}: {placemark.CountryName}\n" + $"{nameof(placemark.FeatureName)}: {placemark.FeatureName}\n" + $"{nameof(placemark.Locality)}: {placemark.Locality}\n" + $"{nameof(placemark.PostalCode)}: {placemark.PostalCode}\n" + $"{nameof(placemark.SubAdminArea)}: {placemark.SubAdminArea}\n" + $"{nameof(placemark.SubLocality)}: {placemark.SubLocality}\n" + $"{nameof(placemark.SubThoroughfare)}: {placemark.SubThoroughfare}\n" + $"{nameof(placemark.Thoroughfare)}: {placemark.Thoroughfare}\n"; } } catch (Exception ex) { GeocodeAddress = $"Unable to detect placemarks: {ex.Message}"; } finally { IsBusy = false; } } } }
GeocodingViewModel
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Animation/Easings/QuinticEaseIn.cs
{ "start": 161, "end": 394 }
public class ____ : Easing { /// <inheritdoc/> public override double Ease(double progress) { double p2 = progress * progress; return p2 * p2 * progress; } } }
QuinticEaseIn
csharp
ChilliCream__graphql-platform
src/GreenDonut/test/GreenDonut.Tests/DataLoaderTests.cs
{ "start": 32556, "end": 33411 }
private class ____ : DataLoaderBase<int, Entity> { public TestDataLoader2( IBatchScheduler batchScheduler, DataLoaderOptions options) : base(batchScheduler, options) { PromiseCacheObserver .Create(value => value.OtherId, this) .Accept(this); } protected internal override ValueTask FetchAsync( IReadOnlyList<int> keys, Memory<Result<Entity?>> results, DataLoaderFetchContext<Entity> context, CancellationToken cancellationToken) { for (var i = 0; i < keys.Count; i++) { var key = keys[i]; results.Span[i] = new Entity { Id = key + 1, OtherId = key }; } return default; } }
TestDataLoader2
csharp
jbogard__MediatR
test/MediatR.Tests/MicrosoftExtensionsDI/Handlers.cs
{ "start": 6553, "end": 6814 }
class ____<T> : IRequestHandler<OpenGenericVoidRequest<T>> where T : class, ITypeArgument { public Task Handle(OpenGenericVoidRequest<T> request, CancellationToken cancellationToken) => Task.CompletedTask; }
OpenGenericVoidRequestHandler
csharp
dotnet__orleans
src/api/Orleans.Core.Abstractions/Orleans.Core.Abstractions.cs
{ "start": 49901, "end": 51224 }
partial class ____ { public static object AsReference(this Runtime.IAddressable grain, System.Type interfaceType) { throw null; } public static TGrainInterface AsReference<TGrainInterface>(this Runtime.IAddressable grain) { throw null; } public static object Cast(this Runtime.IAddressable grain, System.Type interfaceType) { throw null; } public static TGrainInterface Cast<TGrainInterface>(this Runtime.IAddressable grain) { throw null; } public static Runtime.GrainId GetGrainId(this Runtime.IAddressable grain) { throw null; } public static System.Guid GetPrimaryKey(this Runtime.IAddressable grain, out string? keyExt) { throw null; } public static System.Guid GetPrimaryKey(this Runtime.IAddressable grain) { throw null; } public static long GetPrimaryKeyLong(this Runtime.IAddressable grain, out string? keyExt) { throw null; } public static long GetPrimaryKeyLong(this Runtime.IAddressable grain) { throw null; } public static string GetPrimaryKeyString(this Runtime.IAddressable grain) { throw null; } public static bool IsPrimaryKeyBasedOnLong(this Runtime.IAddressable grain) { throw null; } } [System.AttributeUsage(System.AttributeTargets.Class, AllowMultiple = false)] public sealed
GrainExtensions
csharp
dotnet__efcore
test/EFCore.Tests/ChangeTracking/Internal/ShadowFkFixupTest.cs
{ "start": 59631, "end": 62005 }
private class ____ : DbContext { public FixupContext() // ReSharper disable once VirtualMemberCallInConstructor => ChangeTracker.AutoDetectChangesEnabled = false; protected internal override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Product>() .HasMany(e => e.SpecialOffers) .WithOne(e => e.Product) .HasForeignKey("ProductId"); modelBuilder.Entity<Category>() .HasMany(e => e.Products) .WithOne(e => e.Category) .HasForeignKey("CategoryId"); modelBuilder.Entity<CategoryPN>() .HasMany(e => e.Products) .WithOne() .HasForeignKey("CategoryId"); modelBuilder.Entity<ProductDN>() .HasOne(e => e.Category) .WithMany() .HasForeignKey("CategoryId"); modelBuilder.Entity<ProductNN>() .HasOne<CategoryNN>() .WithMany() .HasForeignKey("CategoryId"); modelBuilder.Entity<Parent>() .HasOne(e => e.Child) .WithOne(e => e.Parent) .HasForeignKey<Child>("ParentId"); modelBuilder.Entity<ParentPN>() .HasOne(e => e.Child) .WithOne() .HasForeignKey<ChildPN>("ParentId"); modelBuilder.Entity<ChildDN>() .HasOne(e => e.Parent) .WithOne() .HasForeignKey<ChildDN>("ParentId"); modelBuilder.Entity<ParentNN>() .HasOne<ChildNN>() .WithOne() .HasForeignKey<ChildNN>("ParentId"); } protected internal override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseInternalServiceProvider(InMemoryFixture.DefaultServiceProvider) .UseInMemoryDatabase(nameof(FixupContext)); } private void AssertFixup(DbContext context, Action asserts) { asserts(); context.ChangeTracker.DetectChanges(); asserts(); context.ChangeTracker.DetectChanges(); asserts(); context.ChangeTracker.DetectChanges(); asserts(); } }
FixupContext
csharp
dotnet__aspnetcore
src/Mvc/test/Mvc.FunctionalTests/CorsTests.cs
{ "start": 281, "end": 924 }
public class ____ : CorsTestsBase<CorsWebSite.StartupWithoutEndpointRouting> { [Fact] public override async Task PreflightRequestOnNonCorsEnabledController_DoesNotMatchTheAction() { // Arrange var request = new HttpRequestMessage(new HttpMethod("OPTIONS"), "http://localhost/NonCors/Post"); request.Headers.Add(CorsConstants.Origin, "http://example.com"); request.Headers.Add(CorsConstants.AccessControlRequestMethod, "POST"); // Act var response = await Client.SendAsync(request); // Assert Assert.Equal(HttpStatusCode.NotFound, response.StatusCode); } }
CorsTests
csharp
Humanizr__Humanizer
src/Humanizer/TupleizeExtensions.cs
{ "start": 292, "end": 2095 }
public static class ____ { /// <summary> /// Converts an integer to its corresponding tuple name (e.g., 'single', 'double', 'triple'). /// </summary> /// <param name="input">The integer value to convert to a tuple name.</param> /// <returns> /// A string representing the tuple name: /// - 1 returns "single" /// - 2 returns "double" /// - 3 returns "triple" /// - 4 returns "quadruple" /// - 5 returns "quintuple" /// - 6 returns "sextuple" /// - 7 returns "septuple" /// - 8 returns "octuple" /// - 9 returns "nonuple" /// - 10 returns "decuple" /// - 100 returns "centuple" /// - 1000 returns "milluple" /// - Any other value returns "{value}-tuple" (e.g., "42-tuple") /// </returns> /// <remarks> /// Only values 1-10, 100, and 1000 have specific named tuples. All other values return /// a generic n-tuple format. Negative values and zero will return in the format "{value}-tuple". /// </remarks> /// <example> /// <code> /// 1.Tupleize() => "single" /// 2.Tupleize() => "double" /// 3.Tupleize() => "triple" /// 10.Tupleize() => "decuple" /// 100.Tupleize() => "centuple" /// 42.Tupleize() => "42-tuple" /// (-5).Tupleize() => "-5-tuple" /// </code> /// </example> public static string Tupleize(this int input) => input switch { 1 => "single", 2 => "double", 3 => "triple", 4 => "quadruple", 5 => "quintuple", 6 => "sextuple", 7 => "septuple", 8 => "octuple", 9 => "nonuple", 10 => "decuple", 100 => "centuple", 1000 => "milluple", _ => $"{input}-tuple" }; }
TupleizeExtensions
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Windows_UI_Xaml_Controls/FrameTests/Frame_PageStacking.xaml.cs
{ "start": 346, "end": 1131 }
partial class ____ : Page { public Frame_PageStacking() { this.InitializeComponent(); } private void NavigateBack(object sender, RoutedEventArgs e) => MyFrame.GoBack(new SuppressNavigationTransitionInfo()); private void NavigateRed(object sender, RoutedEventArgs e) => MyFrame.Navigate(typeof(FrameTests_RedPage), default, new SuppressNavigationTransitionInfo()); private void NavigateTransparent(object sender, RoutedEventArgs e) => MyFrame.Navigate(typeof(FrameTests_TransparentPage), default, new SuppressNavigationTransitionInfo()); /// <inheritdoc /> protected override void OnTapped(TappedRoutedEventArgs e) => TappedResult.Text = "tapped"; private void HandleTappedOnNavBar(object sender, TappedRoutedEventArgs e) => e.Handled = true; }
Frame_PageStacking
csharp
MonoGame__MonoGame
MonoGame.Framework.Content.Pipeline/VideoContent.cs
{ "start": 451, "end": 1960 }
public class ____ : ContentItem, IDisposable { private bool _disposed; private int _bitsPerSecond; private TimeSpan _duration; private float _framesPerSecond; private int _height; private int _width; /// <summary> /// Gets the bit rate for this video. /// </summary> public int BitsPerSecond { get { return _bitsPerSecond; } } /// <summary> /// Gets the duration of this video. /// </summary> public TimeSpan Duration { get { return _duration; } } /// <summary> /// Gets or sets the file name for this video. /// </summary> [ContentSerializerAttribute] public string Filename { get; set; } /// <summary> /// Gets the frame rate for this video. /// </summary> public float FramesPerSecond { get { return _framesPerSecond; } } /// <summary> /// Gets the height of this video. /// </summary> public int Height { get { return _height; } } /// <summary> /// Gets or sets the type of soundtrack accompanying the video. /// </summary> [ContentSerializerAttribute] public VideoSoundtrackType VideoSoundtrackType { get; set; } /// <summary> /// Gets the width of this video. /// </summary> public int Width { get { return _width; } } /// <summary> /// Initializes a new copy of the VideoContent
VideoContent
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Tests/Running/JobRuntimePropertiesComparerTests.cs
{ "start": 316, "end": 1050 }
public class ____ { [Fact] public void SingleJobLeadsToNoGrouping() { var benchmarks1 = BenchmarkConverter.TypeToBenchmarks(typeof(Plain1)); var benchmarks2 = BenchmarkConverter.TypeToBenchmarks(typeof(Plain2)); var grouped = benchmarks1.BenchmarksCases.Union(benchmarks2.BenchmarksCases) .GroupBy(benchmark => benchmark, new BenchmarkPartitioner.BenchmarkRuntimePropertiesComparer()) .ToArray(); Assert.Single(grouped); // we should have single exe! Assert.Equal(benchmarks1.BenchmarksCases.Length + benchmarks2.BenchmarksCases.Length, grouped.Single().Count()); }
JobRuntimePropertiesComparerTests
csharp
unoplatform__uno
src/SamplesApp/UITests.Shared/Microsoft_UI_Xaml_Controls/NumberBoxTests/NumberBox_Header.xaml.cs
{ "start": 166, "end": 280 }
partial class ____ : Page { public NumberBox_Header() { this.InitializeComponent(); } } }
NumberBox_Header
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/DemoTests.cs
{ "start": 15459, "end": 21766 }
public class ____ { [JsonProperty("address", Order = 2)] public string StreetAddress { get; set; } public int Bedrooms { get; set; } public decimal FloorArea { get; set; } [JsonProperty("buildDate", Order = 1)] [JsonConverter(typeof(JavaScriptDateTimeConverter))] public DateTime BuildDate { get; set; } } [Test] public void SerializeAttributes() { var house = new House3(); house.StreetAddress = "221B Baker Street"; house.Bedrooms = 2; house.FloorArea = 100m; house.BuildDate = new DateTime(1890, 1, 1); string json = JsonConvert.SerializeObject(house, Formatting.Indented); // { // "StreetAddress": "221B Baker Street", // "Bedrooms": 2, // "FloorArea": 100.0, // "BuildDate": "1890-01-01T00:00:00" // } // { // "StreetAddress": "221B Baker Street" // } // { // "address": "221B Baker Street" // } // { // "buildDate": "1890-01-01T00:00:00", // "address": "221B Baker Street" // } // { // "buildDate": new Date(-2524568400000), // "address": "221B Baker Street" // } } [Test] public void MergeJson() { JObject o1 = JObject.Parse(@"{ 'FirstName': 'John', 'LastName': 'Smith', 'Enabled': false, 'Roles': [ 'User' ] }"); JObject o2 = JObject.Parse(@"{ 'Enabled': true, 'Roles': [ 'User', 'Admin' ] }"); o1.Merge(o2, new JsonMergeSettings { // union arrays together to avoid duplicates MergeArrayHandling = MergeArrayHandling.Union }); string json = o1.ToString(); // { // "FirstName": "John", // "LastName": "Smith", // "Enabled": true, // "Roles": [ // "User", // "Admin" // ] // } StringAssert.AreEqual(@"{ ""FirstName"": ""John"", ""LastName"": ""Smith"", ""Enabled"": true, ""Roles"": [ ""User"", ""Admin"" ] }", json); } #if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void ArrayPooling() { IList<int> value; JsonSerializer serializer = new JsonSerializer(); using (JsonTextReader reader = new JsonTextReader(new StringReader(@"[1,2,3,4]"))) { reader.ArrayPool = JsonArrayPool.Instance; value = serializer.Deserialize<IList<int>>(reader); } Assert.AreEqual(4, value.Count); } #endif #if !(PORTABLE || DNXCORE50 || PORTABLE40) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public void SerializeDataTable() { DataTable dt = new DataTable(); dt.Columns.Add("PackageId", typeof(string)); dt.Columns.Add("Version", typeof(string)); dt.Columns.Add("ReleaseDate", typeof(DateTime)); dt.Rows.Add("Newtonsoft.Json", "11.0.1", new DateTime(2018, 2, 17)); dt.Rows.Add("Newtonsoft.Json", "10.0.3", new DateTime(2017, 6, 18)); string json = JsonConvert.SerializeObject(dt, Formatting.Indented); Console.WriteLine(json); // [ // { // "PackageId": "Newtonsoft.Json", // "Version": "11.0.1", // "ReleaseDate": "2018-02-17T00:00:00" // }, // { // "PackageId": "Newtonsoft.Json", // "Version": "10.0.3", // "ReleaseDate": "2017-06-18T00:00:00" // } // ] StringAssert.AreEqual(@"[ { ""PackageId"": ""Newtonsoft.Json"", ""Version"": ""11.0.1"", ""ReleaseDate"": ""2018-02-17T00:00:00"" }, { ""PackageId"": ""Newtonsoft.Json"", ""Version"": ""10.0.3"", ""ReleaseDate"": ""2017-06-18T00:00:00"" } ]", json); } #endif [Test] public void JsonPathRegex() { JArray packages = JArray.Parse(@"[ { ""PackageId"": ""Newtonsoft.Json"", ""Version"": ""11.0.1"", ""ReleaseDate"": ""2018-02-17T00:00:00"" }, { ""PackageId"": ""NUnit"", ""Version"": ""3.9.0"", ""ReleaseDate"": ""2017-11-10T00:00:00"" } ]"); List<JToken> newtonsoftPackages = packages.SelectTokens(@"$.[?(@.PackageId =~ /^Newtonsoft\.(.*)$/)]").ToList(); Console.WriteLine(newtonsoftPackages.Count); // 1 Assert.AreEqual(1, newtonsoftPackages.Count); } #if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER [Test] public async Task AsyncDemo() { JArray largeJson; // read asynchronously from a file using (TextReader textReader = new StreamReader(new FileStream(ResolvePath(@"large.json"), FileMode.Open, FileAccess.Read, FileShare.Read, 4096, true))) { largeJson = await JArray.LoadAsync(new JsonTextReader(textReader)); } JToken user = largeJson.SelectToken("$[?(@.name == 'Woodard Caldwell')]"); user["isActive"] = false; // write asynchronously to a file using (TextWriter textWriter = new StreamWriter(new FileStream(ResolvePath(@"large.json"), FileMode.Open, FileAccess.Write, FileShare.Write, 4096, true))) { await largeJson.WriteToAsync(new JsonTextWriter(textWriter)); } } #endif } #if !(NET20 || NET35 || NET40 || PORTABLE || PORTABLE40 || DNXCORE50) || NETSTANDARD2_0 || NET6_0_OR_GREATER
House5
csharp
dotnet__aspnetcore
src/DataProtection/DataProtection/src/AuthenticatedEncryption/ConfigurationModel/IInternalAlgorithmConfiguration.cs
{ "start": 617, "end": 1082 }
internal interface ____ { /// <summary> /// Creates a new <see cref="IAuthenticatedEncryptorDescriptor"/> instance from this configuration /// given specific secret key material. /// </summary> IAuthenticatedEncryptorDescriptor CreateDescriptorFromSecret(ISecret secret); /// <summary> /// Performs a self-test of the algorithm specified by the configuration object. /// </summary> void Validate(); }
IInternalAlgorithmConfiguration
csharp
unoplatform__uno
src/Uno.UI.Tests/Windows_UI_Xaml_Data/BindingTests/Controls/Binding_TemplateBinding_AttachedDP.xaml.cs
{ "start": 719, "end": 861 }
partial class ____ : Page { public Binding_TemplateBinding_AttachedDP() { this.InitializeComponent(); } }
Binding_TemplateBinding_AttachedDP
csharp
dotnet__aspire
tests/Aspire.Hosting.Milvus.Tests/MilvusFunctionalTests.cs
{ "start": 374, "end": 7134 }
public class ____(ITestOutputHelper testOutputHelper) { private const string CollectionName = "book"; [Fact] [RequiresDocker] public async Task VerifyMilvusResource() { using var builder = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper); var milvus = builder.AddMilvus("milvus"); var db = milvus.AddDatabase("milvusdb", "db1"); using var app = builder.Build(); await app.StartAsync(); await app.WaitForTextAsync("Milvus Proxy successfully initialized and ready to serve", milvus.Resource.Name); var hb = Host.CreateApplicationBuilder(); hb.Configuration[$"ConnectionStrings:{db.Resource.Name}"] = await db.Resource.ConnectionStringExpression.GetValueAsync(default); hb.AddMilvusClient(db.Resource.Name); using var host = hb.Build(); await host.StartAsync(); var milvusClient = host.Services.GetRequiredService<MilvusClient>(); await milvusClient.CreateDatabaseAsync("db1"); await CreateTestDataAsync(milvusClient, default); } private static async Task CreateTestDataAsync(MilvusClient milvusClient, CancellationToken token) { var collection = await milvusClient.CreateCollectionAsync( CollectionName, [ FieldSchema.Create<long>("book_id", isPrimaryKey:true), FieldSchema.Create<long>("word_count"), FieldSchema.CreateVarchar("book_name", 256), FieldSchema.CreateFloatVector("book_intro", 2) ] , cancellationToken: token); var collections = await milvusClient.ListCollectionsAsync(cancellationToken: token); Assert.Single(collections, c => c.Name == CollectionName); } [Theory] [InlineData(false)] [InlineData(true)] [RequiresDocker] public async Task WithDataShouldPersistStateBetweenUsages(bool useVolume) { var dbname = "milvusdbtest"; string? volumeName = null; string? bindMountPath = null; try { using var builder1 = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper); var milvus1 = builder1.AddMilvus("milvus1"); #pragma warning disable CS0618 // Type or member is obsolete var password = milvus1.Resource.ApiKeyParameter.Value; #pragma warning restore CS0618 // Type or member is obsolete var db1 = milvus1.AddDatabase("milvusdb1", dbname); if (useVolume) { // Use a deterministic volume name to prevent them from exhausting the machines if deletion fails volumeName = VolumeNameGenerator.Generate(milvus1, nameof(WithDataShouldPersistStateBetweenUsages)); // if the volume already exists (because of a crashing previous run), delete it DockerUtils.AttemptDeleteDockerVolume(volumeName, throwOnFailure: true); milvus1.WithDataVolume(volumeName); } else { // Milvus container runs as root and will create the directory. bindMountPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); milvus1.WithDataBindMount(bindMountPath); } using (var app = builder1.Build()) { await app.StartAsync(); await app.WaitForTextAsync("Milvus Proxy successfully initialized and ready to serve", milvus1.Resource.Name); try { var hb = Host.CreateApplicationBuilder(); hb.Configuration[$"ConnectionStrings:{db1.Resource.Name}"] = await db1.Resource.ConnectionStringExpression.GetValueAsync(default); hb.AddMilvusClient(db1.Resource.Name); using (var host = hb.Build()) { await host.StartAsync(); var milvusClient = host.Services.GetRequiredService<MilvusClient>(); await milvusClient.CreateDatabaseAsync(dbname); await CreateTestDataAsync(milvusClient, default); } } finally { // Stops the container, or the Volume would still be in use await app.StopAsync(); } } using var builder2 = TestDistributedApplicationBuilder.CreateWithTestContainerRegistry(testOutputHelper); var passwordParameter = builder2.AddParameter("pwd", password); var milvus2 = builder2.AddMilvus("milvus2", passwordParameter); var db2 = milvus2.AddDatabase("milvusdb2", dbname); if (useVolume) { milvus2.WithDataVolume(volumeName); } else { milvus2.WithDataBindMount(bindMountPath!); } using (var app = builder2.Build()) { await app.StartAsync(); await app.WaitForTextAsync("Milvus Proxy successfully initialized and ready to serve", milvus2.Resource.Name); try { var hb = Host.CreateApplicationBuilder(); hb.Configuration[$"ConnectionStrings:{db2.Resource.Name}"] = await db2.Resource.ConnectionStringExpression.GetValueAsync(default); hb.AddMilvusClient(db2.Resource.Name); using (var host = hb.Build()) { await host.StartAsync(); var milvusClient = host.Services.GetRequiredService<MilvusClient>(); var collections = await milvusClient.ListCollectionsAsync(); Assert.Single(collections, c => c.Name == CollectionName); } } finally { // Stops the container, or the Volume would still be in use await app.StopAsync(); } } } finally { if (volumeName is not null) { DockerUtils.AttemptDeleteDockerVolume(volumeName); } if (bindMountPath is not null) { try { Directory.Delete(bindMountPath, recursive: true); } catch { // Don't fail test if we can't clean the temporary folder } } } } }
MilvusFunctionalTests
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Utilities/LateboundReflectionDelegateFactoryTests.cs
{ "start": 1331, "end": 4334 }
public class ____ : TestFixtureBase { [Test] public void ConstructorWithInString() { ConstructorInfo constructor = TestReflectionUtils.GetConstructors(typeof(InTestClass)).Single(c => c.GetParameters().Count() == 1); var creator = LateBoundReflectionDelegateFactory.Instance.CreateParameterizedConstructor(constructor); object[] args = new object[] { "Value" }; InTestClass o = (InTestClass)creator(args); Assert.IsNotNull(o); Assert.AreEqual("Value", o.Value); } [Test] public void ConstructorWithInStringAndBool() { ConstructorInfo constructor = TestReflectionUtils.GetConstructors(typeof(InTestClass)).Single(c => c.GetParameters().Count() == 2); var creator = LateBoundReflectionDelegateFactory.Instance.CreateParameterizedConstructor(constructor); object[] args = new object[] { "Value", true }; InTestClass o = (InTestClass)creator(args); Assert.IsNotNull(o); Assert.AreEqual("Value", o.Value); Assert.AreEqual(true, o.B1); } [Test] public void ConstructorWithRefString() { ConstructorInfo constructor = TestReflectionUtils.GetConstructors(typeof(OutAndRefTestClass)).Single(c => c.GetParameters().Count() == 1); var creator = LateBoundReflectionDelegateFactory.Instance.CreateParameterizedConstructor(constructor); object[] args = new object[] { "Input" }; OutAndRefTestClass o = (OutAndRefTestClass)creator(args); Assert.IsNotNull(o); Assert.AreEqual("Input", o.Input); } [Test] public void ConstructorWithRefStringAndOutBool() { ConstructorInfo constructor = TestReflectionUtils.GetConstructors(typeof(OutAndRefTestClass)).Single(c => c.GetParameters().Count() == 2); var creator = LateBoundReflectionDelegateFactory.Instance.CreateParameterizedConstructor(constructor); object[] args = new object[] { "Input", null }; OutAndRefTestClass o = (OutAndRefTestClass)creator(args); Assert.IsNotNull(o); Assert.AreEqual("Input", o.Input); } [Test] public void ConstructorWithRefStringAndRefBoolAndRefBool() { ConstructorInfo constructor = TestReflectionUtils.GetConstructors(typeof(OutAndRefTestClass)).Single(c => c.GetParameters().Count() == 3); var creator = LateBoundReflectionDelegateFactory.Instance.CreateParameterizedConstructor(constructor); object[] args = new object[] { "Input", true, null }; OutAndRefTestClass o = (OutAndRefTestClass)creator(args); Assert.IsNotNull(o); Assert.AreEqual("Input", o.Input); Assert.AreEqual(true, o.B1); Assert.AreEqual(false, o.B2); } }
LateboundReflectionDelegateFactoryTests
csharp
MassTransit__MassTransit
tests/MassTransit.EntityFrameworkIntegration.Tests/PreInsert_Specs.cs
{ "start": 8821, "end": 10241 }
class ____ : MassTransitStateMachine<Instance> { public TestStateMachine() { InstanceState(x => x.CurrentState); Event(() => WarmedUp, x => { x.InsertOnInitial = true; x.SetSagaFactory(context => new Instance { // the CorrelationId header is the value that should be used CorrelationId = context.CorrelationId.Value, CreateTimestamp = context.Message.Timestamp, Name = context.Message.Name }); }); Initially( When(WarmedUp) .Then(context => { }), When(Started) .Publish(context => new StartupComplete { TransactionId = context.Data.CorrelationId }) .TransitionTo(Running)); } public State Running { get; private set; } public Event<Start> Started { get; private set; } public Event<WarmUp> WarmedUp { get; private set; } } } #endregion EntityFramework } }
TestStateMachine
csharp
dotnet__aspnetcore
src/Components/Server/test/Circuits/RemoteRendererTest.cs
{ "start": 29211, "end": 30735 }
private class ____ : IComponent, IHandleAfterRender { private RenderHandle _renderHandle; private readonly RenderFragment _renderFragment = (builder) => { builder.OpenElement(0, "my element"); builder.AddContent(1, "some text"); builder.CloseElement(); }; public TestComponent() { } internal TestComponent(RenderFragment renderFragment) { _renderFragment = renderFragment; } public Action OnAfterRenderComplete { get; set; } public void Attach(RenderHandle renderHandle) { _renderHandle = renderHandle; } public Task OnAfterRenderAsync() { OnAfterRenderComplete?.Invoke(); return Task.CompletedTask; } public Task SetParametersAsync(ParameterView parameters) { TriggerRender(); return Task.CompletedTask; } public void TriggerRender() { var task = _renderHandle.Dispatcher.InvokeAsync(() => _renderHandle.Render(_renderFragment)); // Log the task state for debugging purposes. var status = task.Status; var innerException = task.Exception?.InnerException; var message = $"Render task should succeed synchronously.\nStatus: '{status}'\nInner exception: '{innerException}'"; Assert.True(task.IsCompletedSuccessfully, message); } }
TestComponent
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding101OneToOneTestBase.cs
{ "start": 46718, "end": 47571 }
public class ____ { public int Id { get; set; } [InverseProperty("Header"), ForeignKey("BlogId"), Required] public Blog Blog { get; set; } } public DbSet<Blog> Blogs => Set<Blog>(); public DbSet<BlogHeader> BlogHeaders => Set<BlogHeader>(); protected override void OnModelCreating(ModelBuilder modelBuilder) => modelBuilder.Entity<Blog>() .HasOne(e => e.Header) .WithOne(e => e.Blog) .HasPrincipalKey<Blog>(e => e.AlternateId); } } [ConditionalFact] public virtual void OneToOneOptionalWithShadowFkWithAlternateKeyTest() => Assert.Throws<EqualException>(() => Model101Test()); // Issue #30346
BlogHeader
csharp
kgrzybek__modular-monolith-with-ddd
src/Modules/Administration/Infrastructure/Configuration/EventsBus/EventsBusModule.cs
{ "start": 187, "end": 810 }
internal class ____ : Autofac.Module { private readonly IEventsBus _eventsBus; public EventsBusModule(IEventsBus eventsBus) { _eventsBus = eventsBus; } protected override void Load(ContainerBuilder builder) { if (_eventsBus != null) { builder.RegisterInstance(_eventsBus).SingleInstance(); } else { builder.RegisterType<InMemoryEventBusClient>() .As<IEventsBus>() .SingleInstance(); } } } }
EventsBusModule
csharp
bitwarden__server
src/Core/Dirt/Reports/ReportFeatures/GetPasswordHealthReportApplicationQuery.cs
{ "start": 197, "end": 1006 }
public class ____ : IGetPasswordHealthReportApplicationQuery { private IPasswordHealthReportApplicationRepository _passwordHealthReportApplicationRepo; public GetPasswordHealthReportApplicationQuery( IPasswordHealthReportApplicationRepository passwordHealthReportApplicationRepo) { _passwordHealthReportApplicationRepo = passwordHealthReportApplicationRepo; } public async Task<IEnumerable<PasswordHealthReportApplication>> GetPasswordHealthReportApplicationAsync(Guid organizationId) { if (organizationId == Guid.Empty) { throw new BadRequestException("OrganizationId is required."); } return await _passwordHealthReportApplicationRepo.GetByOrganizationIdAsync(organizationId); } }
GetPasswordHealthReportApplicationQuery
csharp
EventStore__EventStore
src/KurrentDB.Projections.Core.Tests/Services/core_coordinator/when_starting_with_projection_type_all.cs
{ "start": 502, "end": 1356 }
public class ____ { private FakePublisher[] queues; private FakePublisher publisher; private ProjectionCoreCoordinator _coordinator; [SetUp] public void Setup() { queues = new List<FakePublisher>() { new FakePublisher() }.ToArray(); publisher = new FakePublisher(); _coordinator = new ProjectionCoreCoordinator(ProjectionType.All, queues, publisher); _coordinator.Handle(new ProjectionSubsystemMessage.StartComponents(Guid.NewGuid())); } [Test] public void should_publish_start_reader_messages() { Assert.AreEqual(1, queues[0].Messages.FindAll(x => x is ReaderCoreServiceMessage.StartReader).Count); } [Test] public void should_publish_start_core_messages() { Assert.AreEqual(1, queues[0].Messages.FindAll(x => x.GetType() == typeof(ProjectionCoreServiceMessage.StartCore)).Count); } }
when_starting_with_projection_type_all
csharp
MonoGame__MonoGame
Tools/MonoGame.Tools.Tests/EffectProcessorTests.cs
{ "start": 344, "end": 2181 }
class ____ : ContentImporterContext { public override string IntermediateDirectory { get { throw new NotImplementedException(); } } public override ContentBuildLogger Logger { get { throw new NotImplementedException(); } } public override string OutputDirectory { get { throw new NotImplementedException(); } } public override void AddDependency(string filename) { throw new NotImplementedException(); } } #if DIRECTX [Test] public void TestPreprocessor() { var effectFile = "Assets/Effects/PreprocessorTest.fx"; var effectCode = File.ReadAllText(effectFile); var fullPath = Path.GetFullPath(effectFile); // Preprocess. var mgDependencies = new List<string>(); var mgPreprocessed = Preprocessor.Preprocess(effectCode, fullPath, new Dictionary<string, string> { { "TEST2", "1" } }, mgDependencies, new TestEffectCompilerOutput()); Assert.That(mgDependencies, Has.Count.EqualTo(1)); Assert.That(Path.GetFileName(mgDependencies[0]), Is.EqualTo("PreprocessorInclude.fxh")); Assert.That(mgPreprocessed, Does.Not.Contain("Foo")); Assert.That(mgPreprocessed, Does.Contain("Bar")); Assert.That(mgPreprocessed, Does.Not.Contain("Baz")); Assert.That(mgPreprocessed, Does.Contain("FOO")); Assert.That(mgPreprocessed, Does.Not.Contain("BAR")); // Check that we can actually compile this file. BuildEffect(effectFile, TargetPlatform.Windows); }
ImporterContext
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Validation.Tests/Types/CatType.cs
{ "start": 69, "end": 625 }
public class ____ : ObjectType<Cat> { protected override void Configure(IObjectTypeDescriptor<Cat> descriptor) { descriptor.Implements<PetType>(); descriptor.Implements<BeingType>(); descriptor.Implements<MammalType>(); descriptor.Field(t => t.Name).Type<NonNullType<StringType>>(); descriptor.Field(t => t.DoesKnowCommand(default)) .Argument("catCommand", a => a.Type<NonNullType<EnumType<CatCommand>>>()); descriptor.Field("furColor").Type<FurColor>().Resolve(() => null!); } }
CatType
csharp
dotnet__machinelearning
src/Microsoft.ML.AutoML/API/BinaryClassificationExperiment.cs
{ "start": 4705, "end": 16364 }
public sealed class ____ : ExperimentBase<BinaryClassificationMetrics, BinaryExperimentSettings> { private AutoMLExperiment _experiment; private const string Features = "__Features__"; private SweepablePipeline _pipeline; internal BinaryClassificationExperiment(MLContext context, BinaryExperimentSettings settings) : base(context, new BinaryMetricsAgent(context, settings.OptimizingMetric), new OptimizingMetricInfo(settings.OptimizingMetric), settings, TaskKind.BinaryClassification, TrainerExtensionUtil.GetTrainerNames(settings.Trainers)) { _experiment = context.Auto().CreateExperiment(); if (settings.MaximumMemoryUsageInMegaByte is double d) { _experiment.SetMaximumMemoryUsageInMegaByte(d); } _experiment.SetMaxModelToExplore(settings.MaxModels); _experiment.SetTrainingTimeInSeconds(settings.MaxExperimentTimeInSeconds); } public override ExperimentResult<BinaryClassificationMetrics> Execute(IDataView trainData, ColumnInformation columnInformation, IEstimator<ITransformer> preFeaturizer = null, IProgress<RunDetail<BinaryClassificationMetrics>> progressHandler = null) { var label = columnInformation.LabelColumnName; _experiment.SetBinaryClassificationMetric(Settings.OptimizingMetric, label); // Cross val threshold for # of dataset rows -- // If dataset has < threshold # of rows, use cross val. // Else, run experiment using train-validate split. const int crossValRowCountThreshold = 15000; var rowCount = DatasetDimensionsUtil.CountRows(trainData, crossValRowCountThreshold); // TODO // split cross validation result according to sample key as well. if (rowCount < crossValRowCountThreshold) { const int numCrossValFolds = 10; _experiment.SetDataset(trainData, numCrossValFolds); } else { var splitData = Context.Data.TrainTestSplit(trainData); _experiment.SetDataset(splitData.TrainSet, splitData.TestSet); } _pipeline = CreateBinaryClassificationPipeline(trainData, columnInformation, preFeaturizer); _experiment.SetPipeline(_pipeline); // set monitor TrialResultMonitor<BinaryClassificationMetrics> monitor = null; _experiment.SetMonitor((provider) => { var channel = provider.GetService<IChannel>(); var pipeline = provider.GetService<SweepablePipeline>(); monitor = new TrialResultMonitor<BinaryClassificationMetrics>(channel, pipeline); monitor.OnTrialCompleted += (o, e) => { var detail = BestResultUtil.ToRunDetail(Context, e, _pipeline); progressHandler?.Report(detail); }; return monitor; }); _experiment = PostConfigureAutoMLExperiment(_experiment); _experiment.Run(); var runDetails = monitor.RunDetails.Select(e => BestResultUtil.ToRunDetail(Context, e, _pipeline)); var bestRun = BestResultUtil.ToRunDetail(Context, monitor.BestRun, _pipeline); var result = new ExperimentResult<BinaryClassificationMetrics>(runDetails, bestRun); return result; } public override ExperimentResult<BinaryClassificationMetrics> Execute(IDataView trainData, IDataView validationData, ColumnInformation columnInformation, IEstimator<ITransformer> preFeaturizer = null, IProgress<RunDetail<BinaryClassificationMetrics>> progressHandler = null) { var label = columnInformation.LabelColumnName; _experiment.SetBinaryClassificationMetric(Settings.OptimizingMetric, label); _experiment.SetDataset(trainData, validationData); _pipeline = CreateBinaryClassificationPipeline(trainData, columnInformation, preFeaturizer); _experiment.SetPipeline(_pipeline); // set monitor TrialResultMonitor<BinaryClassificationMetrics> monitor = null; _experiment.SetMonitor((provider) => { var channel = provider.GetService<IChannel>(); var pipeline = provider.GetService<SweepablePipeline>(); monitor = new TrialResultMonitor<BinaryClassificationMetrics>(channel, pipeline); monitor.OnTrialCompleted += (o, e) => { var detail = BestResultUtil.ToRunDetail(Context, e, _pipeline); progressHandler?.Report(detail); }; return monitor; }); _experiment = PostConfigureAutoMLExperiment(_experiment); _experiment.Run(); var runDetails = monitor.RunDetails.Select(e => BestResultUtil.ToRunDetail(Context, e, _pipeline)); var bestRun = BestResultUtil.ToRunDetail(Context, monitor.BestRun, _pipeline); var result = new ExperimentResult<BinaryClassificationMetrics>(runDetails, bestRun); return result; } public override ExperimentResult<BinaryClassificationMetrics> Execute(IDataView trainData, IDataView validationData, string labelColumnName = "Label", IEstimator<ITransformer> preFeaturizer = null, IProgress<RunDetail<BinaryClassificationMetrics>> progressHandler = null) { var columnInformation = new ColumnInformation() { LabelColumnName = labelColumnName, }; return Execute(trainData, validationData, columnInformation, preFeaturizer, progressHandler); } public override ExperimentResult<BinaryClassificationMetrics> Execute(IDataView trainData, string labelColumnName = "Label", string samplingKeyColumn = null, IEstimator<ITransformer> preFeaturizer = null, IProgress<RunDetail<BinaryClassificationMetrics>> progressHandler = null) { var columnInformation = new ColumnInformation() { LabelColumnName = labelColumnName, SamplingKeyColumnName = samplingKeyColumn, }; return Execute(trainData, columnInformation, preFeaturizer, progressHandler); } public override CrossValidationExperimentResult<BinaryClassificationMetrics> Execute(IDataView trainData, uint numberOfCVFolds, ColumnInformation columnInformation = null, IEstimator<ITransformer> preFeaturizer = null, IProgress<CrossValidationRunDetail<BinaryClassificationMetrics>> progressHandler = null) { var label = columnInformation.LabelColumnName; _experiment.SetBinaryClassificationMetric(Settings.OptimizingMetric, label); _experiment.SetDataset(trainData, (int)numberOfCVFolds); _pipeline = CreateBinaryClassificationPipeline(trainData, columnInformation, preFeaturizer); _experiment.SetPipeline(_pipeline); // set monitor TrialResultMonitor<BinaryClassificationMetrics> monitor = null; _experiment.SetMonitor((provider) => { var channel = provider.GetService<IChannel>(); var pipeline = provider.GetService<SweepablePipeline>(); monitor = new TrialResultMonitor<BinaryClassificationMetrics>(channel, pipeline); monitor.OnTrialCompleted += (o, e) => { var detail = BestResultUtil.ToCrossValidationRunDetail(Context, e, _pipeline); progressHandler?.Report(detail); }; return monitor; }); _experiment = PostConfigureAutoMLExperiment(_experiment); _experiment.Run(); var runDetails = monitor.RunDetails.Select(e => BestResultUtil.ToCrossValidationRunDetail(Context, e, _pipeline)); var bestResult = BestResultUtil.ToCrossValidationRunDetail(Context, monitor.BestRun, _pipeline); var result = new CrossValidationExperimentResult<BinaryClassificationMetrics>(runDetails, bestResult); return result; } public override CrossValidationExperimentResult<BinaryClassificationMetrics> Execute(IDataView trainData, uint numberOfCVFolds, string labelColumnName = "Label", string samplingKeyColumn = null, IEstimator<ITransformer> preFeaturizer = null, IProgress<CrossValidationRunDetail<BinaryClassificationMetrics>> progressHandler = null) { var columnInformation = new ColumnInformation() { LabelColumnName = labelColumnName, SamplingKeyColumnName = samplingKeyColumn, }; return Execute(trainData, numberOfCVFolds, columnInformation, preFeaturizer, progressHandler); } private protected override RunDetail<BinaryClassificationMetrics> GetBestRun(IEnumerable<RunDetail<BinaryClassificationMetrics>> results) { return BestResultUtil.GetBestRun(results, MetricsAgent, OptimizingMetricInfo.IsMaximizing); } private protected override CrossValidationRunDetail<BinaryClassificationMetrics> GetBestCrossValRun(IEnumerable<CrossValidationRunDetail<BinaryClassificationMetrics>> results) { return BestResultUtil.GetBestRun(results, MetricsAgent, OptimizingMetricInfo.IsMaximizing); } private SweepablePipeline CreateBinaryClassificationPipeline(IDataView trainData, ColumnInformation columnInformation, IEstimator<ITransformer> preFeaturizer = null) { var useSdca = Settings.Trainers.Contains(BinaryClassificationTrainer.SdcaLogisticRegression); var uselbfgs = Settings.Trainers.Contains(BinaryClassificationTrainer.LbfgsLogisticRegression); var useLgbm = Settings.Trainers.Contains(BinaryClassificationTrainer.LightGbm); var useFastForest = Settings.Trainers.Contains(BinaryClassificationTrainer.FastForest); var useFastTree = Settings.Trainers.Contains(BinaryClassificationTrainer.FastTree); if (preFeaturizer != null) { return preFeaturizer.Append(Context.Auto().Featurizer(trainData, columnInformation, Features)) .Append(Context.Auto().BinaryClassification(labelColumnName: columnInformation.LabelColumnName, useSdcaLogisticRegression: useSdca, useFastTree: useFastTree, useLgbm: useLgbm, useLbfgsLogisticRegression: uselbfgs, useFastForest: useFastForest, featureColumnName: Features)); } else { return Context.Auto().Featurizer(trainData, columnInformation, Features) .Append(Context.Auto().BinaryClassification(labelColumnName: columnInformation.LabelColumnName, useSdcaLogisticRegression: useSdca, useFastTree: useFastTree, useLgbm: useLgbm, useLbfgsLogisticRegression: uselbfgs, useFastForest: useFastForest, featureColumnName: Features)); } } private AutoMLExperiment PostConfigureAutoMLExperiment(AutoMLExperiment experiment) { experiment.SetTrialRunner<BinaryClassificationRunner>(); if (Settings.UseAutoZeroTuner) { experiment.SetTuner<AutoZeroTuner>(); } return experiment; } }
BinaryClassificationExperiment
csharp
dotnet__efcore
test/EFCore.Specification.Tests/TestModels/MonsterModel.cs
{ "start": 8467, "end": 8873 }
public interface ____ { string Username { get; set; } string AlternateUsername { get; set; } int CustomerId { get; set; } ICustomer Customer { get; set; } ILastLogin LastLogin { get; set; } ICollection<IMessage> SentMessages { get; set; } ICollection<IMessage> ReceivedMessages { get; set; } ICollection<IAnOrder> Orders { get; set; } void InitializeCollections(); }
ILogin
csharp
dotnet__aspnetcore
src/Shared/test/Shared.Tests/PropertyHelperTest.cs
{ "start": 23611, "end": 23859 }
public class ____ : BaseClassWithVirtual { private string _value = "Newed"; public new string PropB { get { return _value; } set { _value = "Newed" + value; } } }
DerivedClassWithNew
csharp
microsoft__semantic-kernel
dotnet/src/Agents/Orchestration/Concurrent/ConcurrentOrchestration.cs
{ "start": 563, "end": 3325 }
public class ____<TInput, TOutput> : AgentOrchestration<TInput, TOutput> { /// <summary> /// Initializes a new instance of the <see cref="ConcurrentOrchestration{TInput, TOutput}"/> class. /// </summary> /// <param name="agents">The agents participating in the orchestration.</param> public ConcurrentOrchestration(params Agent[] agents) : base(agents) { } /// <inheritdoc /> protected override ValueTask StartAsync(IAgentRuntime runtime, TopicId topic, IEnumerable<ChatMessageContent> input, AgentType? entryAgent) { return runtime.PublishMessageAsync(input.AsInputMessage(), topic); } /// <inheritdoc /> protected override async ValueTask<AgentType?> RegisterOrchestrationAsync(IAgentRuntime runtime, OrchestrationContext context, RegistrationContext registrar, ILogger logger) { AgentType outputType = await registrar.RegisterResultTypeAsync<ConcurrentMessages.Result[]>(response => [.. response.Select(r => r.Message)]).ConfigureAwait(false); // Register result actor AgentType resultType = this.FormatAgentType(context.Topic, "Results"); await runtime.RegisterOrchestrationAgentAsync( resultType, (agentId, runtime) => { ConcurrentResultActor actor = new(agentId, runtime, context, outputType, this.Members.Count, context.LoggerFactory.CreateLogger<ConcurrentResultActor>()); #if !NETCOREAPP return actor.AsValueTask<IHostableAgent>(); #else return ValueTask.FromResult<IHostableAgent>(actor); #endif }).ConfigureAwait(false); logger.LogRegisterActor(this.OrchestrationLabel, resultType, "RESULTS"); // Register member actors - All agents respond to the same message. int agentCount = 0; foreach (Agent agent in this.Members) { ++agentCount; AgentType agentType = await runtime.RegisterAgentFactoryAsync( this.FormatAgentType(context.Topic, $"Agent_{agentCount}"), (agentId, runtime) => { ConcurrentActor actor = new(agentId, runtime, context, agent, resultType, context.LoggerFactory.CreateLogger<ConcurrentActor>()); #if !NETCOREAPP return actor.AsValueTask<IHostableAgent>(); #else return ValueTask.FromResult<IHostableAgent>(actor); #endif }).ConfigureAwait(false); logger.LogRegisterActor(this.OrchestrationLabel, agentType, "MEMBER", agentCount); await runtime.SubscribeAsync(agentType, context.Topic).ConfigureAwait(false); } return null; } }
ConcurrentOrchestration
csharp
microsoft__garnet
libs/server/Storage/Functions/EtagState.cs
{ "start": 429, "end": 2168 }
public struct ____ { public EtagState() { } /// <summary> /// Offset used accounting space for an etag during allocation /// </summary> public byte etagOffsetForVarlen { get; set; } = 0; /// <summary> /// Gives an offset used to opaquely work with Etag in a payload. By calling this you can skip past the etag if it is present. /// </summary> public byte etagSkippedStart { get; private set; } = 0; /// <summary> /// Resp response methods depend on the value for end being -1 or length of the payload. This field lets you work with providing the end opaquely. /// </summary> public int etagAccountedLength { get; private set; } = -1; /// <summary> /// Field provides access to getting an Etag from a record, hiding whether it is actually present or not. /// </summary> public long etag { get; set; } = EtagConstants.NoETag; /// <summary> /// Sets the values to indicate the presence of an Etag as a part of the payload value /// </summary> public static void SetValsForRecordWithEtag(ref EtagState curr, ref SpanByte value) { curr.etagOffsetForVarlen = EtagConstants.EtagSize; curr.etagSkippedStart = EtagConstants.EtagSize; curr.etagAccountedLength = value.LengthWithoutMetadata; curr.etag = value.GetEtagInPayload(); } public static void ResetState(ref EtagState curr) { curr.etagOffsetForVarlen = 0; curr.etagSkippedStart = 0; curr.etag = EtagConstants.NoETag; curr.etagAccountedLength = -1; } } }
EtagState
csharp
SixLabors__ImageSharp
src/ImageSharp/Formats/Webp/Lossy/Vp8MacroBlockType.cs
{ "start": 130, "end": 196 }
internal enum ____ { I4X4 = 0, I16X16 = 1 }
Vp8MacroBlockType
csharp
ServiceStack__ServiceStack
ServiceStack/tests/ServiceStack.ServiceHost.Tests/AppData/NorthwindHelpers.cs
{ "start": 109, "end": 747 }
public class ____ { public string OrderTotal(List<OrderDetail> orderDetails) { var total = 0m; if (!orderDetails.IsEmpty()) total += orderDetails.Sum(item => item.Quantity * item.UnitPrice); return FormatHelpers.Instance.Money(total); } public string CustomerOrderTotal(List<CustomerOrder> customerOrders) { var total = customerOrders .Sum(x => x.OrderDetails.Sum(item => item.Quantity * item.UnitPrice)); return FormatHelpers.Instance.Money(total); } } }
NorthwindHelpers
csharp
dotnet__aspnetcore
src/Mvc/Mvc.ViewFeatures/test/PageRemoteAttributeTest.cs
{ "start": 768, "end": 6773 }
public class ____ { [Fact] public void GetUrl_CallsUrlHelperWithExpectedValues() { // Arrange var testableAttribute = new TestablePageRemoteAttribute { PageName = "Foo", PageHandler = "Bar" }; var ambientValues = new RouteValueDictionary() { ["page"] = "/Foo" }; var routeData = new RouteData(ambientValues) { Routers = { Mock.Of<IRouter>() } }; var urlHelper = new MockUrlHelper(url: "/Foo?handler=Bar") { ActionContext = GetActionContext(new ServiceCollection().BuildServiceProvider(), routeData) }; var validationContext = GetValidationContext(urlHelper); // Act testableAttribute.InvokeGetUrl(validationContext); // Assert var routeDictionary = Assert.IsType<RouteValueDictionary>(urlHelper.RouteValues); Assert.Equal(2, routeDictionary.Count); Assert.Equal("/Foo", routeDictionary["page"] as string); Assert.Equal("Bar", routeDictionary["handler"] as string); } [Fact] public void GetUrl_WhenUrlHelperReturnsNull_Throws() { // Arrange var testableAttribute = new TestablePageRemoteAttribute { PageName = "Foo", PageHandler = "Bar" }; var ambientValues = new RouteValueDictionary { ["page"] = "/Page" }; var routeData = new RouteData(ambientValues) { Routers = { Mock.Of<IRouter>() } }; var urlHelper = new MockUrlHelper(url: null) { ActionContext = GetActionContext(new ServiceCollection().BuildServiceProvider(), routeData) }; var validationContext = GetValidationContext(urlHelper); // Act && Assert ExceptionAssert.Throws<InvalidOperationException>( () => testableAttribute.InvokeGetUrl(validationContext), Resources.RemoteAttribute_NoUrlFound); } [Fact] public void GetUrl_WhenPageNameIsNotSet_WillUsePageNameFromAmbientValues() { // Arrange var testableAttribute = new TestablePageRemoteAttribute() { PageHandler = "Handler" }; var ambientValues = new RouteValueDictionary { ["page"] = "/Page" }; var routeData = new RouteData(ambientValues) { Routers = { Mock.Of<IRouter>() } }; var urlHelper = new MockUrlHelper(url: "/Page?handler=Handler") { ActionContext = GetActionContext(new ServiceCollection().BuildServiceProvider(), routeData) }; var validationContext = GetValidationContext(urlHelper); // Act var actualUrl = testableAttribute.InvokeGetUrl(validationContext); // Assert Assert.Equal("/Page?handler=Handler", actualUrl); } [Fact] public void GetUrl_WhenPageNameAndPageHandlerIsNotSet_WillUseAmbientValues() { // Arrange var testableAttribute = new TestablePageRemoteAttribute(); var ambientValues = new RouteValueDictionary { ["page"] = "/Page", ["handler"] = "Handler" }; var routeData = new RouteData(ambientValues) { Routers = { Mock.Of<IRouter>() } }; var urlHelper = new MockUrlHelper(url: "/Page?handler=Handler") { ActionContext = GetActionContext(new ServiceCollection().BuildServiceProvider(), routeData) }; var validationContext = GetValidationContext(urlHelper); // Act var actualUrl = testableAttribute.InvokeGetUrl(validationContext); // Assert Assert.Equal("/Page?handler=Handler", actualUrl); } private static ClientModelValidationContext GetValidationContext(IUrlHelper urlHelper, RouteData routeData = null) { var serviceCollection = GetServiceCollection(); var factory = new Mock<IUrlHelperFactory>(MockBehavior.Strict); serviceCollection.AddSingleton<IUrlHelperFactory>(factory.Object); var serviceProvider = serviceCollection.BuildServiceProvider(); var actionContext = GetActionContext(serviceProvider, routeData); factory .Setup(f => f.GetUrlHelper(actionContext)) .Returns(urlHelper); var metadataProvider = new EmptyModelMetadataProvider(); var metadata = metadataProvider.GetMetadataForProperty( containerType: typeof(string), propertyName: nameof(string.Length)); return new ClientModelValidationContext( actionContext, metadata, metadataProvider, new AttributeDictionary()); } private static ServiceCollection GetServiceCollection() { var serviceCollection = new ServiceCollection(); serviceCollection .AddSingleton<ILoggerFactory>(new NullLoggerFactory()); serviceCollection.AddOptions(); serviceCollection.AddRouting(); serviceCollection.AddSingleton<IInlineConstraintResolver>( provider => new DefaultInlineConstraintResolver(provider.GetRequiredService<IOptions<RouteOptions>>(), provider)); return serviceCollection; } private static ActionContext GetActionContext(IServiceProvider serviceProvider, RouteData routeData) { // Set IServiceProvider properties because TemplateRoute gets services (e.g. an ILoggerFactory instance) // through the HttpContext. var httpContext = new DefaultHttpContext { RequestServices = serviceProvider, }; if (routeData == null) { routeData = new RouteData { Routers = { Mock.Of<IRouter>(), }, }; } return new ActionContext(httpContext, routeData, new ActionDescriptor()); }
PageRemoteAttributeTest
csharp
Humanizr__Humanizer
src/Humanizer.Tests/Localisation/uk-UA/OrdinalizeTests.cs
{ "start": 40, "end": 3476 }
public class ____ { [Theory] [InlineData("0", "0-й")] [InlineData("1", "1-й")] [InlineData("2", "2-й")] [InlineData("3", "3-й")] [InlineData("4", "4-й")] [InlineData("5", "5-й")] [InlineData("6", "6-й")] [InlineData("23", "23-й")] [InlineData("100", "100-й")] [InlineData("101", "101-й")] [InlineData("102", "102-й")] [InlineData("103", "103-й")] [InlineData("1001", "1001-й")] public void OrdinalizeString(string number, string ordinalized) => Assert.Equal(number.Ordinalize(GrammaticalGender.Masculine), ordinalized); [Theory] [InlineData("0", "0-а")] [InlineData("1", "1-а")] [InlineData("2", "2-а")] [InlineData("3", "3-я")] [InlineData("4", "4-а")] [InlineData("5", "5-а")] [InlineData("6", "6-а")] [InlineData("23", "23-я")] [InlineData("100", "100-а")] [InlineData("101", "101-а")] [InlineData("102", "102-а")] [InlineData("103", "103-я")] [InlineData("1001", "1001-а")] public void OrdinalizeStringFeminine(string number, string ordinalized) => Assert.Equal(number.Ordinalize(GrammaticalGender.Feminine), ordinalized); [Theory] [InlineData("0", "0-е")] [InlineData("1", "1-е")] [InlineData("2", "2-е")] [InlineData("3", "3-є")] [InlineData("4", "4-е")] [InlineData("5", "5-е")] [InlineData("6", "6-е")] [InlineData("23", "23-є")] [InlineData("100", "100-е")] [InlineData("101", "101-е")] [InlineData("102", "102-е")] [InlineData("103", "103-є")] [InlineData("1001", "1001-е")] public void OrdinalizeStringNeuter(string number, string ordinalized) => Assert.Equal(number.Ordinalize(GrammaticalGender.Neuter), ordinalized); [Theory] [InlineData(0, "0-й")] [InlineData(1, "1-й")] [InlineData(2, "2-й")] [InlineData(3, "3-й")] [InlineData(4, "4-й")] [InlineData(5, "5-й")] [InlineData(6, "6-й")] [InlineData(10, "10-й")] [InlineData(23, "23-й")] [InlineData(100, "100-й")] [InlineData(101, "101-й")] [InlineData(102, "102-й")] [InlineData(103, "103-й")] [InlineData(1001, "1001-й")] public void OrdinalizeNumber(int number, string ordinalized) => Assert.Equal(number.Ordinalize(GrammaticalGender.Masculine), ordinalized); [Theory] [InlineData(0, "0-а")] [InlineData(1, "1-а")] [InlineData(2, "2-а")] [InlineData(3, "3-я")] [InlineData(4, "4-а")] [InlineData(5, "5-а")] [InlineData(6, "6-а")] [InlineData(10, "10-а")] [InlineData(23, "23-я")] [InlineData(100, "100-а")] [InlineData(101, "101-а")] [InlineData(102, "102-а")] [InlineData(103, "103-я")] [InlineData(1001, "1001-а")] public void OrdinalizeNumberFeminine(int number, string ordinalized) => Assert.Equal(number.Ordinalize(GrammaticalGender.Feminine), ordinalized); [Theory] [InlineData(0, "0-е")] [InlineData(1, "1-е")] [InlineData(2, "2-е")] [InlineData(3, "3-є")] [InlineData(4, "4-е")] [InlineData(5, "5-е")] [InlineData(6, "6-е")] [InlineData(23, "23-є")] [InlineData(100, "100-е")] [InlineData(101, "101-е")] [InlineData(102, "102-е")] [InlineData(103, "103-є")] [InlineData(1001, "1001-е")] public void OrdinalizeNumberNeuter(int number, string ordinalized) => Assert.Equal(number.Ordinalize(GrammaticalGender.Neuter), ordinalized); }
OrdinalizeTests
csharp
FastEndpoints__FastEndpoints
Src/AspVersioning/VersionSets.cs
{ "start": 238, "end": 898 }
public static class ____ { internal static readonly ConcurrentDictionary<string, ApiVersionSet> Container = new(); internal static string VersionFormat = null!; /// <summary> /// creates a api/group/swagger-tag with an associated version set /// </summary> /// <param name="apiName">the name of the api (swagger tag)</param> /// <param name="builder">version set builder action</param> public static void CreateApi(string apiName, Action<ApiVersionSetBuilder> builder) { var setBuilder = new ApiVersionSetBuilder(apiName); builder(setBuilder); Container[apiName] = setBuilder.Build(); } }
VersionSets
csharp
Xabaril__AspNetCore.Diagnostics.HealthChecks
test/HealthChecks.Aws.Sns.Tests/DependencyInjection/RegistrationTests.cs
{ "start": 96, "end": 6688 }
public class ____ { [Fact] public void add_health_check_with_topics_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(setup => { setup.Credentials = new BasicAWSCredentials("access-key", "secret-key"); setup.AddTopicAndSubscriptions("topic1"); }); using var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("aws sns subs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); } [Fact] public void add_health_check_with_topics_and_subscriptions_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(setup => { setup.Credentials = new BasicAWSCredentials("access-key", "secret-key"); setup.AddTopicAndSubscriptions("topic1", ["subscription1-arn", "subscription2-arn"]); }); using var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("aws sns subs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); } [Fact] public void add_health_check_with_topics_assumerole_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(setup => { setup.Credentials = new AssumeRoleAWSCredentials(null, "role-arn", "session-name"); setup.AddTopicAndSubscriptions("topic1"); }); using var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("aws sns subs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); } [Fact] public void add_health_check_with_topics_and_subscriptions_assumerole_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(setup => { setup.Credentials = new AssumeRoleAWSCredentials(null, "role-arn", "session-name"); setup.AddTopicAndSubscriptions("topic1", ["subscription1-arn", "subscription2-arn"]); }); using var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("aws sns subs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); } [Fact] public void add_named_health_with_topics_and_subscriptions_check_when_properly_configured() { var services = new ServiceCollection(); services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(setup => setup.Credentials = new BasicAWSCredentials("access-key", "secret-key"), name: "awssnssubs"); using var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("awssnssubs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); } [Fact] public void add_health_check_with_topics_and_subscriptions_when_no_credentials_provided() { var services = new ServiceCollection(); var setupCalled = false; services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(_ => setupCalled = true, name: "awssnssubs"); using var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("awssnssubs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); setupCalled.ShouldBeTrue(); } [Fact] public void add_health_check_with_topics_and_subscriptions_when_no_credentials_but_region_provided() { var services = new ServiceCollection(); services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(setup => setup.RegionEndpoint = RegionEndpoint.EUCentral1); using var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("aws sns subs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); } [Fact] public void add_health_check_with_topics_and_subscriptions_when_credentials_and_region_provided() { var services = new ServiceCollection(); services.AddHealthChecks() .AddSnsTopicsAndSubscriptions(setup => { setup.Credentials = new BasicAWSCredentials("access-key", "secret-key"); setup.RegionEndpoint = RegionEndpoint.EUCentral1; }); var serviceProvider = services.BuildServiceProvider(); var options = serviceProvider.GetRequiredService<IOptions<HealthCheckServiceOptions>>(); var registration = options.Value.Registrations.First(); var check = registration.Factory(serviceProvider); registration.Name.ShouldBe("aws sns subs"); check.ShouldBeOfType<SnsTopicAndSubscriptionHealthCheck>(); } }
aws_sns_registration_should
csharp
AutoFixture__AutoFixture
Src/AutoFixture/Kernel/Postprocessor.cs
{ "start": 1909, "end": 5146 }
class ____ the supplied /// parameters. /// </summary> /// <param name="builder">The <see cref="ISpecimenBuilder"/> to decorate.</param> /// <param name="action">The action to perform on the created specimen.</param> /// <param name="specification"> /// A specification which is used to determine whether postprocessing should be performed /// for a request. /// </param> [Obsolete("Use Postprocessor(ISpecimenBuilder, ISpecimenCommand, IRequestSpecification) instead", true)] public Postprocessor(ISpecimenBuilder builder, Action<object, ISpecimenContext> action, IRequestSpecification specification) : base(builder, action, specification) { } /// <summary> /// Initializes a new instance of the <see cref="Postprocessor" /> /// class. /// </summary> /// <param name="builder"> /// The <see cref="ISpecimenBuilder"/> to decorate. /// </param> /// <param name="command"> /// The command to apply to the created specimen. /// </param> public Postprocessor(ISpecimenBuilder builder, ISpecimenCommand command) : base(builder, command) { } /// <summary> /// Initializes a new instance of the <see cref="Postprocessor" /> /// class. /// </summary> /// <param name="builder"> /// The <see cref="ISpecimenBuilder"/> to decorate. /// </param> /// <param name="command"> /// The command to apply to the created specimen. /// </param> /// A specification which is used to determine whether postprocessing /// should be performed /// <param name="specification"> /// </param> public Postprocessor( ISpecimenBuilder builder, ISpecimenCommand command, IRequestSpecification specification) : base(builder, command, specification) { } /// <summary>Composes the supplied builders.</summary> /// <param name="builders">The builders to compose.</param> /// <returns> /// A new <see cref="ISpecimenBuilderNode" /> instance containing /// <paramref name="builders" /> as child nodes. /// </returns> public override ISpecimenBuilderNode Compose(IEnumerable<ISpecimenBuilder> builders) { if (builders == null) throw new ArgumentNullException(nameof(builders)); var composedBuilder = CompositeSpecimenBuilder.ComposeIfMultiple(builders); var pp = new Postprocessor(composedBuilder, this.Command, this.Specification); #pragma warning disable 618 ObsoletedMemberShims.Postprocessor_SetAction(pp, ObsoletedMemberShims.Postprocessor_GetAction(this)); #pragma warning restore 618 return pp; } } /// <summary> /// Performs post-processing on a created specimen. /// </summary> /// <typeparam name="T">The type of specimen.</typeparam> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "The main responsibility of this
with
csharp
microsoft__FASTER
cs/src/core/Index/Interfaces/IFunctions.cs
{ "start": 21496, "end": 21606 }
public interface ____<Key, Value, Context> : IFunctions<Key, Value, Value, Value, Context> { } }
IFunctions
csharp
DuendeSoftware__IdentityServer
identity-server/src/IdentityServer/ResponseHandling/IAuthorizeResponseGenerator.cs
{ "start": 289, "end": 567 }
public interface ____ { /// <summary> /// Creates the response /// </summary> /// <param name="request">The request.</param> /// <returns></returns> Task<AuthorizeResponse> CreateResponseAsync(ValidatedAuthorizeRequest request); }
IAuthorizeResponseGenerator
csharp
EventStore__EventStore
src/KurrentDB.Core/Services/Gossip/GossipServiceBase.cs
{ "start": 530, "end": 16206 }
public abstract class ____ : IHandle<SystemMessage.SystemInit>, IHandle<GossipMessage.RetrieveGossipSeedSources>, IHandle<GossipMessage.GotGossipSeedSources>, IHandle<GossipMessage.Gossip>, IHandle<GossipMessage.GossipReceived>, IHandle<GossipMessage.ReadGossip>, IHandle<GossipMessage.ClientGossip>, IHandle<SystemMessage.StateChangeMessage>, IHandle<GossipMessage.GossipSendFailed>, IHandle<SystemMessage.VNodeConnectionLost>, IHandle<SystemMessage.VNodeConnectionEstablished>, IHandle<GossipMessage.GetGossipReceived>, IHandle<GossipMessage.GetGossipFailed>, IHandle<ElectionMessage.ElectionsDone> { public const int GossipRoundStartupThreshold = 20; public static readonly TimeSpan DnsRetryTimeout = TimeSpan.FromMilliseconds(1000); public static readonly TimeSpan GossipStartupInterval = TimeSpan.FromMilliseconds(100); private readonly TimeSpan _deadMemberRemovalPeriod; private static readonly ILogger Log = Serilog.Log.ForContext<GossipServiceBase>(); protected readonly MemberInfo MemberInfo; protected VNodeState CurrentRole = VNodeState.Initializing; private MemberInfo _currentLeader; private readonly TimeSpan _gossipInterval; private readonly TimeSpan _allowedTimeDifference; private readonly TimeSpan _gossipTimeout; private readonly IPublisher _bus; private readonly int _clusterSize; private readonly IEnvelope _publishEnvelope; private readonly IGossipSeedSource _gossipSeedSource; private GossipState _state; private ClusterInfo _cluster; private readonly Random _rnd = new Random(Math.Abs(Environment.TickCount)); private readonly ITimeProvider _timeProvider; private readonly Func<MemberInfo[], MemberInfo> _getNodeToGossipTo; protected GossipServiceBase(IPublisher bus, int clusterSize, IGossipSeedSource gossipSeedSource, MemberInfo memberInfo, TimeSpan gossipInterval, TimeSpan allowedTimeDifference, TimeSpan gossipTimeout, TimeSpan deadMemberRemovalPeriod, ITimeProvider timeProvider, Func<MemberInfo[], MemberInfo> getNodeToGossipTo = null) { _bus = Ensure.NotNull(bus); _clusterSize = clusterSize; _publishEnvelope = bus; _gossipSeedSource = Ensure.NotNull(gossipSeedSource); MemberInfo = Ensure.NotNull(memberInfo); _gossipInterval = gossipInterval; _allowedTimeDifference = allowedTimeDifference; _gossipTimeout = gossipTimeout; _deadMemberRemovalPeriod = deadMemberRemovalPeriod; _state = GossipState.Startup; _timeProvider = Ensure.NotNull(timeProvider); _getNodeToGossipTo = getNodeToGossipTo ?? GetNodeToGossipTo; } protected abstract MemberInfo GetInitialMe(); protected abstract MemberInfo GetUpdatedMe(MemberInfo me); public void Handle(SystemMessage.SystemInit message) { if (_state != GossipState.Startup) return; _cluster = new ClusterInfo(GetInitialMe()); Handle(new GossipMessage.RetrieveGossipSeedSources()); } public void Handle(GossipMessage.RetrieveGossipSeedSources message) { _state = GossipState.RetrievingGossipSeeds; try { _gossipSeedSource.BeginGetHostEndpoints(OnGotGossipSeedSources, null); } catch (Exception ex) { Log.Error(ex, "Error while retrieving cluster members through DNS."); _bus.Publish(TimerMessage.Schedule.Create(DnsRetryTimeout, _publishEnvelope, new GossipMessage.RetrieveGossipSeedSources())); } } private void OnGotGossipSeedSources(IAsyncResult ar) { try { var entries = _gossipSeedSource.EndGetHostEndpoints(ar); _bus.Publish(new GossipMessage.GotGossipSeedSources(entries)); } catch (Exception ex) { Log.Error(ex, "Error while retrieving cluster members through DNS."); _bus.Publish(TimerMessage.Schedule.Create(DnsRetryTimeout, _publishEnvelope, new GossipMessage.RetrieveGossipSeedSources())); } } public void Handle(GossipMessage.GotGossipSeedSources message) { var now = _timeProvider.UtcNow; var dnsCluster = new ClusterInfo(message.GossipSeeds.Select(x => MemberInfo.ForManager(Guid.Empty, now, true, x)).ToArray()); var oldCluster = _cluster; _cluster = MergeClusters(_cluster, dnsCluster, null, x => x, _timeProvider.UtcNow, MemberInfo, _currentLeader?.InstanceId, _allowedTimeDifference, _deadMemberRemovalPeriod); LogClusterChange(oldCluster, _cluster, null); _state = GossipState.Working; Handle(new GossipMessage.Gossip(0)); } public void Handle(GossipMessage.Gossip message) { if (_state != GossipState.Working) return; TimeSpan interval; int gossipRound; if (_clusterSize == 1) { _cluster = UpdateCluster(_cluster, x => x.InstanceId == MemberInfo.InstanceId ? GetUpdatedMe(x) : x, _timeProvider, _deadMemberRemovalPeriod, CurrentRole); interval = _gossipInterval; gossipRound = Math.Min(int.MaxValue - 1, message.GossipRound + 1); } else { var node = _getNodeToGossipTo(_cluster.Members); if (node != null) { _cluster = UpdateCluster(_cluster, x => x.InstanceId == MemberInfo.InstanceId ? GetUpdatedMe(x) : x, _timeProvider, _deadMemberRemovalPeriod, CurrentRole); _bus.Publish(new GrpcMessage.SendOverGrpc(node.HttpEndPoint, new GossipMessage.SendGossip(_cluster, MemberInfo.HttpEndPoint), _timeProvider.LocalTime.Add(_gossipTimeout))); } interval = message.GossipRound < GossipRoundStartupThreshold ? GossipStartupInterval : _gossipInterval; gossipRound = Math.Min(int.MaxValue - 1, node == null ? message.GossipRound : message.GossipRound + 1); } _bus.Publish(TimerMessage.Schedule.Create(interval, _publishEnvelope, new GossipMessage.Gossip(gossipRound))); } private MemberInfo GetNodeToGossipTo(MemberInfo[] members) { if (members.Length == 0) return null; for (int i = 0; i < 5; ++i) { var node = members[_rnd.Next(members.Length)]; if (node.InstanceId != MemberInfo.InstanceId) return node; } return null; } public void Handle(GossipMessage.GossipReceived message) { if (_state != GossipState.Working) return; var oldCluster = _cluster; _cluster = MergeClusters(_cluster, message.ClusterInfo, message.Server, x => x.InstanceId == MemberInfo.InstanceId ? GetUpdatedMe(x) : x, _timeProvider.UtcNow, MemberInfo, _currentLeader?.InstanceId, _allowedTimeDifference, _deadMemberRemovalPeriod); message.Envelope.ReplyWith(new GossipMessage.SendGossip(_cluster, MemberInfo.HttpEndPoint)); if (_cluster.HasChangedSince(oldCluster)) LogClusterChange(oldCluster, _cluster, $"gossip received from [{message.Server}]"); _bus.Publish(new GossipMessage.GossipUpdated(_cluster)); } public void Handle(GossipMessage.ReadGossip message) { if (_cluster != null) { message.Envelope.ReplyWith(new GossipMessage.SendGossip(_cluster, MemberInfo.HttpEndPoint)); } } public void Handle(GossipMessage.ClientGossip message) { if (_cluster == null) return; var advertisedAddress = string.IsNullOrEmpty(MemberInfo.AdvertiseHostToClientAs) ? MemberInfo.HttpEndPoint.GetHost() : MemberInfo.AdvertiseHostToClientAs; var advertisedPort = MemberInfo.AdvertiseHttpPortToClientAs == 0 ? MemberInfo.HttpEndPoint.GetPort() : MemberInfo.AdvertiseHttpPortToClientAs; message.Envelope.ReplyWith(new GossipMessage.SendClientGossip(new(_cluster, advertisedAddress, advertisedPort))); } public void Handle(SystemMessage.StateChangeMessage message) { CurrentRole = message.State; _currentLeader = message is not SystemMessage.ReplicaStateMessage replicaState ? null : replicaState.Leader; if (_cluster is null) return; _cluster = UpdateCluster(_cluster, x => x.InstanceId == MemberInfo.InstanceId ? GetUpdatedMe(x) : x, _timeProvider, _deadMemberRemovalPeriod, CurrentRole); _bus.Publish(new GossipMessage.GossipUpdated(_cluster)); } public void Handle(GossipMessage.GossipSendFailed message) { var node = _cluster.Members.FirstOrDefault(x => x.Is(message.Recipient)); if (node is not { IsAlive: true }) return; if (node.InstanceId == _currentLeader?.InstanceId) { Log.Information( "Leader [{leaderEndPoint}, {instanceId:B}] appears to be DEAD (Gossip send failed); wait for TCP to decide.", message.Recipient, node.InstanceId); return; } Log.Information("Looks like node [{nodeEndPoint}] is DEAD (Gossip send failed).", message.Recipient); var oldCluster = _cluster; _cluster = UpdateCluster(_cluster, x => x.Is(message.Recipient) ? x.Updated(_timeProvider.UtcNow, isAlive: false) : x, _timeProvider, _deadMemberRemovalPeriod, CurrentRole); if (_cluster.HasChangedSince(oldCluster)) LogClusterChange(oldCluster, _cluster, $"gossip send failed to [{message.Recipient}]"); _bus.Publish(new GossipMessage.GossipUpdated(_cluster)); } public void Handle(SystemMessage.VNodeConnectionLost message) { var node = _cluster.Members.FirstOrDefault(x => x.Is(message.VNodeEndPoint)); if (node is not { IsAlive: true }) return; Log.Information("Looks like node [{nodeEndPoint}] is DEAD (TCP connection lost). Issuing a gossip to confirm.", message.VNodeEndPoint); _bus.Publish(new GrpcMessage.SendOverGrpc(node.HttpEndPoint, new GossipMessage.GetGossip(), _timeProvider.LocalTime.Add(_gossipTimeout))); } public void Handle(GossipMessage.GetGossipReceived message) { if (_state != GossipState.Working) return; Log.Information("Gossip Received, The node [{nodeEndpoint}] is not DEAD.", message.Server); var oldCluster = _cluster; _cluster = MergeClusters(_cluster, message.ClusterInfo, message.Server, x => x.InstanceId == MemberInfo.InstanceId ? GetUpdatedMe(x) : x, _timeProvider.UtcNow, MemberInfo, _currentLeader?.InstanceId, _allowedTimeDifference, _deadMemberRemovalPeriod); if (_cluster.HasChangedSince(oldCluster)) LogClusterChange(oldCluster, _cluster, $"gossip received from [{message.Server}]"); _bus.Publish(new GossipMessage.GossipUpdated(_cluster)); } public void Handle(GossipMessage.GetGossipFailed message) { if (_state != GossipState.Working) return; Log.Information("Gossip Failed, The node [{nodeEndpoint}] is being marked as DEAD. Reason: {reason}", message.Recipient, message.Reason); var oldCluster = _cluster; _cluster = UpdateCluster(_cluster, x => x.Is(message.Recipient) ? x.Updated(_timeProvider.UtcNow, isAlive: false) : x, _timeProvider, _deadMemberRemovalPeriod, CurrentRole); if (_cluster.HasChangedSince(oldCluster)) LogClusterChange(oldCluster, _cluster, $"TCP connection lost to [{message.Recipient}]"); _bus.Publish(new GossipMessage.GossipUpdated(_cluster)); } public void Handle(SystemMessage.VNodeConnectionEstablished message) { var oldCluster = _cluster; _cluster = UpdateCluster(_cluster, x => x.Is(message.VNodeEndPoint) ? x.Updated(_timeProvider.UtcNow, isAlive: true) : x, _timeProvider, _deadMemberRemovalPeriod, CurrentRole); if (_cluster.HasChangedSince(oldCluster)) LogClusterChange(oldCluster, _cluster, $"TCP connection established to [{message.VNodeEndPoint}]"); _bus.Publish(new GossipMessage.GossipUpdated(_cluster)); } public void Handle(ElectionMessage.ElectionsDone message) { var oldCluster = _cluster; _cluster = UpdateCluster(_cluster, x => x.InstanceId == message.Leader.InstanceId ? x.Updated(_timeProvider.UtcNow, VNodeState.Leader) : x.Updated(_timeProvider.UtcNow, VNodeState.Unknown), _timeProvider, _deadMemberRemovalPeriod, CurrentRole); if (_cluster.HasChangedSince(oldCluster)) LogClusterChange(oldCluster, _cluster, "Elections Done"); _bus.Publish(new GossipMessage.GossipUpdated(_cluster)); } public static ClusterInfo MergeClusters(ClusterInfo myCluster, ClusterInfo othersCluster, EndPoint peerEndPoint, Func<MemberInfo, MemberInfo> update, DateTime utcNow, MemberInfo me, Guid? currentLeaderInstanceId, TimeSpan allowedTimeDifference, TimeSpan deadMemberRemovalTimeout) { var members = myCluster.Members.ToDictionary(member => member.HttpEndPoint, new EndPointEqualityComparer()); MemberInfo peerNode = peerEndPoint != null ? othersCluster.Members.SingleOrDefault(member => member.Is(peerEndPoint), null) : null; bool isPeerOld = peerNode?.ESVersion == null; foreach (var member in othersCluster.Members) { if (member.InstanceId == me.InstanceId || member.Is(me.HttpEndPoint)) // we know about ourselves better continue; if (member.Equals(peerNode)) // peer knows about itself better { if ((utcNow - member.TimeStamp).Duration() > allowedTimeDifference) { Log.Error("Time difference between us and [{peerEndPoint}] is too great! " + "UTC now: {dateTime:yyyy-MM-dd HH:mm:ss.fff}, peer's time stamp: {peerTimestamp:yyyy-MM-dd HH:mm:ss.fff}.", peerEndPoint, utcNow, member.TimeStamp); } members[member.HttpEndPoint] = member.Updated(utcNow: member.TimeStamp, esVersion: isPeerOld ? VersionInfo.OldVersion : member.ESVersion); } else { // if there is no data about this member or data is stale -- update if (!members.TryGetValue(member.HttpEndPoint, out var existingMem) || IsMoreUpToDate(member, existingMem)) { // we do not trust leader's alive status and state to come from outside if (currentLeaderInstanceId != null && existingMem != null && member.InstanceId == currentLeaderInstanceId) members[member.HttpEndPoint] = member.Updated(utcNow: utcNow, isAlive: existingMem.IsAlive, state: existingMem.State); else members[member.HttpEndPoint] = member; } if (peerNode != null && isPeerOld) { MemberInfo newInfo = members[member.HttpEndPoint]; // if we don't have past information about es version of the node, es version is unknown because old peer won't be sending version info in gossip members[member.HttpEndPoint] = newInfo.Updated(newInfo.TimeStamp, esVersion: existingMem?.ESVersion ?? VersionInfo.UnknownVersion); } } } var newMembers = members.Values.Select(update).Where(x => KeepNodeInGossip(x, utcNow, deadMemberRemovalTimeout, me.State)); return new ClusterInfo(newMembers); } private static bool IsMoreUpToDate(MemberInfo member, MemberInfo existingMem) { if (member.EpochNumber != existingMem.EpochNumber) return member.EpochNumber > existingMem.EpochNumber; if (member.WriterCheckpoint != existingMem.WriterCheckpoint) return member.WriterCheckpoint > existingMem.WriterCheckpoint; return member.TimeStamp > existingMem.TimeStamp; } public static ClusterInfo UpdateCluster(ClusterInfo cluster, Func<MemberInfo, MemberInfo> update, ITimeProvider timeProvider, TimeSpan deadMemberRemovalTimeout, VNodeState currentRole) { var newMembers = cluster.Members.Select(update) .Where(x => KeepNodeInGossip(x, timeProvider.UtcNow, deadMemberRemovalTimeout, currentRole)); return new ClusterInfo(newMembers); } private static bool KeepNodeInGossip(MemberInfo m, DateTime utcNow, TimeSpan deadMemberRemovalTimeout, VNodeState currentRole) { // remove dead timed-out members, if there are any, and if we are not in an unknown/initializing/leaderless state return m.IsAlive || utcNow - m.TimeStamp < deadMemberRemovalTimeout || currentRole <= VNodeState.Unknown || currentRole == VNodeState.ReadOnlyLeaderless; } private static void LogClusterChange(ClusterInfo oldCluster, ClusterInfo newCluster, string source) { var endPointComparer = new EndPointComparer(); var oldMembers = oldCluster.Members.OrderByDescending(x => x.HttpEndPoint, endPointComparer).ToList(); var newMembers = newCluster.Members.OrderByDescending(x => x.HttpEndPoint, endPointComparer).ToList(); Log.Information( "CLUSTER HAS CHANGED {source}" + "\nOld:" + "\n{oldMembers}" + "\nNew:" + "\n{newMembers}" , source.IsNotEmptyString() ? source : string.Empty , oldMembers , newMembers ); } }
GossipServiceBase
csharp
ServiceStack__ServiceStack
ServiceStack/src/ServiceStack.Client/JsonApiClientUtils.cs
{ "start": 780, "end": 4765 }
public static class ____ { public static Dictionary<string, string> ToDictionary(this HttpResponseHeaders headers) { var to = new Dictionary<string, string>(); foreach (var header in headers) { to[header.Key] = string.Join(", ", header.Value); } return to; } public static WebHeaderCollection ToWebHeaderCollection(this HttpResponseHeaders headers) { var to = new WebHeaderCollection(); foreach (var header in headers) { to[header.Key] = string.Join(", ", header.Value); } return to; } public static string? GetContentType(this HttpResponseMessage httpRes) { return httpRes.Headers.TryGetValues(HttpHeaders.ContentType, out var values) ? values.FirstOrDefault() : null; } public static void AddBasicAuth(this HttpRequestMessage request, string userName, string password) { request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(userName + ":" + password))); } public static void AddApiKeyAuth(this HttpRequestMessage request, string apiKey) { request.Headers.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(Encoding.UTF8.GetBytes(apiKey + ":"))); } public static void AddBearerToken(this HttpRequestMessage request, string bearerToken) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearerToken); } public static IHttpClientBuilder AddJsonApiClient(this IServiceCollection services, string baseUrl) { return services.AddHttpClient<JsonApiClient>(client => client.BaseAddress = new Uri(baseUrl)); } public static IHttpClientBuilder AddJsonApiClient(this IServiceCollection services, string baseUrl, Action<HttpClient> configureClient) { return services.AddHttpClient<JsonApiClient>(client => { client.BaseAddress = new Uri(baseUrl); configureClient(client); }); } public static async Task<ApiResult<TResponse>> ApiAsync<TResponse>(this IHasJsonApiClient instance, IReturn<TResponse> request) => await instance.Client!.ApiAsync(request); public static async Task<ApiResult<EmptyResponse>> ApiAsync(this IHasJsonApiClient instance, IReturnVoid request) => await instance.Client!.ApiAsync(request); public static async Task<IHasErrorStatus> ApiAsync<Model>(this JsonApiClient client, object request) { if (request is IReturn<Model> modelRequest) return await client.ApiAsync(modelRequest); if (request is IReturn<IdResponse> idRequest) return await client.ApiAsync(idRequest); if (request is IReturn<EmptyResponse> emptyRequest) return await client.ApiAsync(emptyRequest); if (request is IReturnVoid voidRequest) return await client.ApiAsync(voidRequest); throw new NotSupportedException($"{request.GetType().Name} must implement IReturn<{typeof(Model).Name}>, IReturn<{nameof(IdResponse)}>, IReturn<{nameof(EmptyResponse)}> or IReturnVoid"); } public static async Task<ApiResult<TResponse>> ApiFormAsync<TResponse>(this IHasJsonApiClient instance, string method, string relativeOrAbsoluteUrl, MultipartFormDataContent request) => await instance.Client!.ApiFormAsync<TResponse>(method, relativeOrAbsoluteUrl, request); public static async Task<ApiResult<TResponse>> ApiFormAsync<TResponse>(this IHasJsonApiClient instance, string relativeOrAbsoluteUrl, MultipartFormDataContent request) => await instance.Client!.ApiFormAsync<TResponse>(relativeOrAbsoluteUrl, request); public static async Task<TResponse> SendAsync<TResponse>(this IHasJsonApiClient instance, IReturn<TResponse> request) => await instance.Client!.SendAsync(request);
JsonApiClientUtils
csharp
mysql-net__MySqlConnector
src/MySqlConnector/Core/ResultSetState.cs
{ "start": 32, "end": 135 }
internal enum ____ { None, ReadResultSetHeader, ReadingRows, HasMoreData, NoMoreData, }
ResultSetState
csharp
ChilliCream__graphql-platform
src/HotChocolate/Fusion-vnext/src/Fusion.Composition/PostMergeValidationRules/EmptyMergedEnumTypeRule.cs
{ "start": 319, "end": 501 }
enum ____ only exists in /// one source schema, it has to be marked as <c>@inaccessible</c>. Enum members that are marked as /// <c>@inaccessible</c> are not included in the merged
value
csharp
graphql-dotnet__graphql-dotnet
src/GraphQL.Tests/Bugs/Bug4078.cs
{ "start": 775, "end": 953 }
public class ____ : ObjectGraphType { public QueryGraphType() { Field<StringGraphType>("test").Resolve(ctx => "abc"); } } }
QueryGraphType