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
AvaloniaUI__Avalonia
src/iOS/Avalonia.iOS/Metal/MetalPlatformSurface.cs
{ "start": 75, "end": 689 }
internal class ____ : IMetalPlatformSurface { private readonly CAMetalLayer _layer; private readonly AvaloniaView _avaloniaView; public MetalPlatformSurface(CAMetalLayer layer, AvaloniaView avaloniaView) { _layer = layer; _avaloniaView = avaloniaView; } public IMetalPlatformSurfaceRenderTarget CreateMetalRenderTarget(IMetalDevice device) { var dev = (MetalDevice)device; _layer.Device = dev.Device; var target = new MetalRenderTarget(_layer, dev); _avaloniaView.SetRenderTarget(target); return target; } }
MetalPlatformSurface
csharp
nunit__nunit
src/NUnitFramework/testdata/ExecutionHooks/TestActionHooksOutcomeFixtures.cs
{ "start": 302, "end": 1836 }
public abstract class ____ : ExecutionHookAttribute { private TestContext.ResultAdapter? _beforeHookTestResult; private static readonly string OutcomeMatched = "Outcome Matched"; private static readonly string OutcomeMismatch = "Outcome Mismatch!!!"; private static readonly string OutcomePropertyKey = "ExpectedOutcome"; protected void BeforeHook(HookData hookData) { _beforeHookTestResult = hookData.Context.Result.Clone(); } protected void AfterHook(HookData hookData) { if (_beforeHookTestResult is null) { return; } string outcomeMatchStatement; var hookedMethodTestResult = hookData.Context.Result.CalculateDeltaWithPrevious(_beforeHookTestResult, hookData.Exception); var expectedOutcome = hookData.Context.Test.Properties.Get(OutcomePropertyKey); if (expectedOutcome is not null && (ResultState)expectedOutcome == hookedMethodTestResult.Outcome) { outcomeMatchStatement = OutcomeMatched; } else { outcomeMatchStatement = OutcomeMismatch; } TestLog.LogMessage( $"{outcomeMatchStatement}: {hookData.Context.Test.FullName} -> {hookData.Context.Result.Outcome}, but expected was {expectedOutcome}"); } } [System.AttributeUsage(System.AttributeTargets.Class)]
OutcomeLoggerBaseAttribute
csharp
getsentry__sentry-dotnet
samples/Sentry.Samples.Maui/Platforms/Windows/App.xaml.cs
{ "start": 321, "end": 703 }
public partial class ____ { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { InitializeComponent(); } protected override MauiApp CreateMauiApp() => MauiProgram.CreateMauiApp(); }
App
csharp
bchavez__Bogus
Source/Bogus/Tokenizer.cs
{ "start": 96, "end": 252 }
public class ____ { public string Name { get; set; } public MethodInfo Method { get; set; } public object[] OptionalArgs { get; set; } }
MustashMethod
csharp
icsharpcode__ILSpy
ICSharpCode.Decompiler.Tests/TestCases/Pretty/DeconstructionTests.cs
{ "start": 1537, "end": 1726 }
public struct ____ { public static implicit operator int(MyInt x) { return 0; } public static implicit operator MyInt(int x) { return default(MyInt); } }
MyInt
csharp
unoplatform__uno
src/Uno.UI.Tests/Windows_UI_XAML_Controls/ListViewBaseTests/Given_ListViewBase.cs
{ "start": 23630, "end": 24094 }
public class ____ : Grid { public static int Count { get; private set; } public static Action CtorCallback = null; public SelfCountingGrid2() { Count++; CtorCallback?.Invoke(); } public static IDisposable RestartCounter() => HookCtor(null); public static IDisposable HookCtor(Action callback) { (Count, CtorCallback) = (0, callback); return new DisposableAction(() => (Count, CtorCallback) = (0, null)); } } } #endif
SelfCountingGrid2
csharp
MassTransit__MassTransit
tests/MassTransit.SignalR.Tests/Utils/IHubManagerConsumerFactory.cs
{ "start": 91, "end": 257 }
public interface ____<THub> where THub : Hub { MassTransitHubLifetimeManager<THub> HubLifetimeManager { get; set; } } }
IHubManagerConsumerFactory
csharp
microsoft__garnet
libs/client/LightEpoch.cs
{ "start": 331, "end": 16242 }
class ____ { /// Size of cache line in bytes public const int kCacheLineBytes = 64; /// <summary> /// Default invalid index entry. /// </summary> const int kInvalidIndex = 0; /// <summary> /// Default number of entries in the entries table /// </summary> static readonly ushort kTableSize = Math.Max((ushort)128, (ushort)(Environment.ProcessorCount * 2)); /// <summary> /// Default drainlist size /// </summary> const int kDrainListSize = 16; /// <summary> /// Thread protection status entries. /// </summary> Entry[] tableRaw; Entry* tableAligned; static readonly Entry[] threadIndex; static readonly Entry* threadIndexAligned; /// <summary> /// List of action, epoch pairs containing actions to performed /// when an epoch becomes safe to reclaim. Marked volatile to /// ensure latest value is seen by the last suspended thread. /// </summary> volatile int drainCount = 0; readonly EpochActionPair[] drainList = new EpochActionPair[kDrainListSize]; /// <summary> /// A thread's entry in the epoch table. /// </summary> [ThreadStatic] static int threadEntryIndex; /// <summary> /// Number of instances using this entry /// </summary> [ThreadStatic] static int threadEntryIndexCount; [ThreadStatic] static int threadId; [ThreadStatic] static ushort startOffset1; [ThreadStatic] static ushort startOffset2; /// <summary> /// Global current epoch value /// </summary> public int CurrentEpoch; /// <summary> /// Cached value of latest epoch that is safe to reclaim /// </summary> public int SafeToReclaimEpoch; /// <summary> /// Local view of current epoch, for an epoch-protected thread /// </summary> public int LocalCurrentEpoch => (*(tableAligned + threadEntryIndex)).localCurrentEpoch; /// <summary> /// Static constructor to setup shared cache-aligned space /// to store per-entry count of instances using that entry /// </summary> static LightEpoch() { // Over-allocate to do cache-line alignment threadIndex = GC.AllocateArray<Entry>(kTableSize + 2, true); long p = (long)Unsafe.AsPointer(ref threadIndex[0]); // Force the pointer to align to 64-byte boundaries long p2 = (p + (kCacheLineBytes - 1)) & ~(kCacheLineBytes - 1); threadIndexAligned = (Entry*)p2; } /// <summary> /// Instantiate the epoch table /// </summary> public LightEpoch() { tableRaw = GC.AllocateArray<Entry>(kTableSize + 2, true); long p = (long)Unsafe.AsPointer(ref tableRaw[0]); // Force the pointer to align to 64-byte boundaries long p2 = (p + (kCacheLineBytes - 1)) & ~(kCacheLineBytes - 1); tableAligned = (Entry*)p2; CurrentEpoch = 1; SafeToReclaimEpoch = 0; for (int i = 0; i < kDrainListSize; i++) drainList[i].epoch = int.MaxValue; drainCount = 0; } /// <summary> /// Clean up epoch table /// </summary> public void Dispose() { CurrentEpoch = 1; SafeToReclaimEpoch = 0; } /// <summary> /// Check whether current epoch instance is protected on this thread /// </summary> /// <returns>Result of the check</returns> public bool ThisInstanceProtected() { int entry = threadEntryIndex; if (kInvalidIndex != entry) { if ((*(tableAligned + entry)).threadId == entry) return true; } return false; } /// <summary> /// Check whether any epoch instance is protected on this thread /// </summary> /// <returns>Result of the check</returns> public static bool AnyInstanceProtected() { int entry = threadEntryIndex; if (kInvalidIndex != entry) { return threadEntryIndexCount > 0; } return false; } /// <summary> /// Enter the thread into the protected code region /// </summary> /// <returns>Current epoch</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public int ProtectAndDrain() { int entry = threadEntryIndex; (*(tableAligned + entry)).threadId = threadEntryIndex; (*(tableAligned + entry)).localCurrentEpoch = CurrentEpoch; if (drainCount > 0) { Drain((*(tableAligned + entry)).localCurrentEpoch); } return (*(tableAligned + entry)).localCurrentEpoch; } /// <summary> /// Thread suspends its epoch entry /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Suspend() { Release(); if (drainCount > 0) SuspendDrain(); } /// <summary> /// Thread resumes its epoch entry /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Resume() { Acquire(); ProtectAndDrain(); } /// <summary> /// Thread resumes its epoch entry /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Resume(out int resumeEpoch) { Acquire(); resumeEpoch = ProtectAndDrain(); } /// <summary> /// Increment current epoch and associate trigger action /// with the prior epoch /// </summary> /// <param name="onDrain">Trigger action</param> /// <returns></returns> public void BumpCurrentEpoch(Action onDrain) { int PriorEpoch = BumpCurrentEpoch() - 1; int i = 0; while (true) { if (drainList[i].epoch == int.MaxValue) { if (Interlocked.CompareExchange(ref drainList[i].epoch, int.MaxValue - 1, int.MaxValue) == int.MaxValue) { drainList[i].action = onDrain; drainList[i].epoch = PriorEpoch; Interlocked.Increment(ref drainCount); break; } } else { var triggerEpoch = drainList[i].epoch; if (triggerEpoch <= SafeToReclaimEpoch) { if (Interlocked.CompareExchange(ref drainList[i].epoch, int.MaxValue - 1, triggerEpoch) == triggerEpoch) { var triggerAction = drainList[i].action; drainList[i].action = onDrain; drainList[i].epoch = PriorEpoch; triggerAction(); break; } } } if (++i == kDrainListSize) { ProtectAndDrain(); i = 0; Thread.Yield(); } } ProtectAndDrain(); } /// <summary> /// Mechanism for threads to mark some activity as completed until /// some version by this thread /// </summary> /// <param name="markerIdx">ID of activity</param> /// <param name="version">Version</param> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Mark(int markerIdx, long version) { (*(tableAligned + threadEntryIndex)).markers[markerIdx] = (int)version; } /// <summary> /// Check if all active threads have completed the some /// activity until given version. /// </summary> /// <param name="markerIdx">ID of activity</param> /// <param name="version">Version</param> /// <returns>Whether complete</returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CheckIsComplete(int markerIdx, long version) { // check if all threads have reported complete for (int index = 1; index <= kTableSize; ++index) { int entry_epoch = (*(tableAligned + index)).localCurrentEpoch; int fc_version = (*(tableAligned + index)).markers[markerIdx]; if (0 != entry_epoch) { if ((fc_version != (int)version) && (entry_epoch < int.MaxValue)) { return false; } } } return true; } /// <summary> /// Increment global current epoch /// </summary> /// <returns></returns> int BumpCurrentEpoch() { int nextEpoch = Interlocked.Add(ref CurrentEpoch, 1); if (drainCount > 0) Drain(nextEpoch); return nextEpoch; } /// <summary> /// Looks at all threads and return the latest safe epoch /// </summary> /// <param name="currentEpoch">Current epoch</param> /// <returns>Safe epoch</returns> int ComputeNewSafeToReclaimEpoch(int currentEpoch) { int oldestOngoingCall = currentEpoch; for (int index = 1; index <= kTableSize; ++index) { int entry_epoch = (*(tableAligned + index)).localCurrentEpoch; if (0 != entry_epoch) { if (entry_epoch < oldestOngoingCall) { oldestOngoingCall = entry_epoch; } } } // The latest safe epoch is the one just before // the earliest unsafe epoch. SafeToReclaimEpoch = oldestOngoingCall - 1; return SafeToReclaimEpoch; } /// <summary> /// Take care of pending drains after epoch suspend /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] void SuspendDrain() { while (drainCount > 0) { // Barrier ensures we see the latest epoch table entries. Ensures // that the last suspended thread drains all pending actions. Thread.MemoryBarrier(); for (int index = 1; index <= kTableSize; ++index) { int entry_epoch = (*(tableAligned + index)).localCurrentEpoch; if (0 != entry_epoch) { return; } } Resume(); Release(); } } /// <summary> /// Check and invoke trigger actions that are ready /// </summary> /// <param name="nextEpoch">Next epoch</param> [MethodImpl(MethodImplOptions.AggressiveInlining)] void Drain(int nextEpoch) { ComputeNewSafeToReclaimEpoch(nextEpoch); for (int i = 0; i < kDrainListSize; i++) { var trigger_epoch = drainList[i].epoch; if (trigger_epoch <= SafeToReclaimEpoch) { if (Interlocked.CompareExchange(ref drainList[i].epoch, int.MaxValue - 1, trigger_epoch) == trigger_epoch) { var trigger_action = drainList[i].action; drainList[i].action = null; drainList[i].epoch = int.MaxValue; Interlocked.Decrement(ref drainCount); trigger_action(); if (drainCount == 0) break; } } } } /// <summary> /// Thread acquires its epoch entry /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] void Acquire() { if (threadEntryIndex == kInvalidIndex) threadEntryIndex = ReserveEntryForThread(); Debug.Assert((*(tableAligned + threadEntryIndex)).localCurrentEpoch == 0, "Trying to acquire protected epoch. Make sure you do not re-enter Tsavorite from callbacks or IDevice implementations. If using tasks, use TaskCreationOptions.RunContinuationsAsynchronously."); threadEntryIndexCount++; } /// <summary> /// Thread releases its epoch entry /// </summary> [MethodImpl(MethodImplOptions.AggressiveInlining)] void Release() { int entry = threadEntryIndex; Debug.Assert((*(tableAligned + entry)).localCurrentEpoch != 0, "Trying to release unprotected epoch. Make sure you do not re-enter Tsavorite from callbacks or IDevice implementations. If using tasks, use TaskCreationOptions.RunContinuationsAsynchronously."); (*(tableAligned + entry)).localCurrentEpoch = 0; (*(tableAligned + entry)).threadId = 0; threadEntryIndexCount--; if (threadEntryIndexCount == 0) { (threadIndexAligned + threadEntryIndex)->threadId = 0; threadEntryIndex = kInvalidIndex; } } /// <summary> /// Reserve entry for thread. This method relies on the fact that no /// thread will ever have ID 0. /// </summary> /// <returns>Reserved entry</returns> static int ReserveEntry() { while (true) { // Try to acquire entry if (0 == (threadIndexAligned + startOffset1)->threadId) { if (0 == Interlocked.CompareExchange( ref (threadIndexAligned + startOffset1)->threadId, threadId, 0)) return startOffset1; } if (startOffset2 > 0) { // Try alternate entry startOffset1 = startOffset2; startOffset2 = 0; } else startOffset1++; // Probe next sequential entry if (startOffset1 > kTableSize) { startOffset1 -= kTableSize; Thread.Yield(); } } } /// <summary> /// Allocate a new entry in epoch table. This is called /// once for a thread. /// </summary> /// <returns>Reserved entry</returns> static int ReserveEntryForThread() { if (threadId == 0) // run once per thread for performance { threadId = Environment.CurrentManagedThreadId; uint code = (uint)Utility.Murmur3(threadId); startOffset1 = (ushort)(1 + (code % kTableSize)); startOffset2 = (ushort)(1 + ((code >> 16) % kTableSize)); } return ReserveEntry(); } /// <summary> /// Epoch table entry (cache line size). /// </summary> [StructLayout(LayoutKind.Explicit, Size = kCacheLineBytes)]
LightEpoch
csharp
getsentry__sentry-dotnet
src/Sentry/Internal/InterlockedBoolean.cs
{ "start": 122, "end": 1595 }
internal struct ____ { private volatile TBool _value; [Browsable(false)] internal TBool ValueForTests => _value; #if NET9_0_OR_GREATER private const TBool True = true; private const TBool False = false; #else private const TBool True = 1; private const TBool False = 0; #endif public InterlockedBoolean() { } [MethodImpl(MethodImplOptions.AggressiveInlining)] public InterlockedBoolean(bool value) { _value = value ? True : False; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator bool(InterlockedBoolean @this) => (@this._value != False); [MethodImpl(MethodImplOptions.AggressiveInlining)] public static implicit operator InterlockedBoolean(bool @this) => new InterlockedBoolean(@this); [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool Exchange(bool newValue) { TBool localNewValue = newValue ? True : False; TBool localReturnValue = Interlocked.Exchange(ref _value, localNewValue); return (localReturnValue != False); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool CompareExchange(bool value, bool comparand) { TBool localValue = value ? True : False; TBool localComparand = comparand ? True : False; TBool localReturnValue = Interlocked.CompareExchange(ref _value, localValue, localComparand); return (localReturnValue != False); } }
InterlockedBoolean
csharp
dotnet__orleans
test/DefaultCluster.Tests/CodeGenTests/IRuntimeCodeGenGrain.cs
{ "start": 5221, "end": 5812 }
public interface ____<T> : IGrainWithGuidKey { /// <summary> /// Sets and returns the grain's state. /// </summary> /// <param name="value">The new state.</param> /// <returns>The current state.</returns> Task<T> SetState(T value); /// <summary> /// Tests that code generation correctly handles methods with reserved keyword identifiers. /// </summary> /// <returns>The current state's event.</returns> Task<@event> @static(); } [Serializable] [GenerateSerializer]
IRuntimeCodeGenGrain
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Ast/Filters/AstNearFilterOperation.cs
{ "start": 767, "end": 2189 }
internal sealed class ____ : AstFilterOperation { private readonly BsonDocument _geometry; private readonly BsonValue _maxDistance; private readonly BsonValue _minDistance; public AstNearFilterOperation( BsonDocument geometry, BsonValue maxDistance = default, BsonValue minDistance = default) { _geometry = Ensure.IsNotNull(geometry, nameof(geometry)); _maxDistance = maxDistance; // optional _minDistance = minDistance; // optional } public BsonDocument Geometry => _geometry; public override AstNodeType NodeType => AstNodeType.NearFilterOperation; public BsonValue MaxDistance => _maxDistance; public BsonValue MinDistance => _minDistance; public override AstNode Accept(AstNodeVisitor visitor) { return visitor.VisitNearFilterOperation(this); } public override BsonValue Render() { return new BsonDocument { { "$near", new BsonDocument { { "$geometry", _geometry }, { "$maxDistance", _maxDistance, _maxDistance != default }, { "$minDistance", _minDistance, _minDistance != default } } } }; } } }
AstNearFilterOperation
csharp
RicoSuter__NSwag
src/NSwag.Sample.Common/WeatherForecast.cs
{ "start": 37, "end": 423 }
public class ____ { public Station Station { get; set; } public string DateFormatted { get; set; } public int TemperatureC { get; set; } public string Summary { get; set; } public int TemperatureF { get { return 32 + (int)(TemperatureC / 0.5556); } } } }
WeatherForecast
csharp
getsentry__sentry-dotnet
benchmarks/Sentry.Benchmarks/TransactionBenchmarks.cs
{ "start": 65, "end": 874 }
public class ____ { private const string Operation = "Operation"; private const string Name = "Name"; [Params(1, 10, 100, 1000)] public int SpanCount; private IDisposable _sdk; [GlobalSetup(Target = nameof(CreateTransaction))] public void EnabledSdk() => _sdk = SentrySdk.Init(Constants.ValidDsn); [GlobalCleanup(Target = nameof(CreateTransaction))] public void DisableDsk() => _sdk.Dispose(); [Benchmark(Description = "Creates a Transaction")] public void CreateTransaction() { var transaction = SentrySdk.StartTransaction(Name, Operation); for (var i = 0; i < SpanCount; i++) { var span = transaction.StartChild(Operation); span.Finish(); } transaction.Finish(); } }
TransactionBenchmarks
csharp
dotnet__orleans
src/Azure/Orleans.Persistence.AzureStorage/Providers/Storage/AzureTableStorage.cs
{ "start": 764, "end": 15173 }
public partial class ____ : IGrainStorage, IRestExceptionDecoder, ILifecycleParticipant<ISiloLifecycle> { private readonly AzureTableStorageOptions options; private readonly ClusterOptions clusterOptions; private readonly IGrainStorageSerializer storageSerializer; private readonly ILogger logger; private readonly IActivatorProvider _activatorProvider; private GrainStateTableDataManager? tableDataManager; // each property can hold 64KB of data and each entity can take 1MB in total, so 15 full properties take // 15 * 64 = 960 KB leaving room for the primary key, timestamp etc private const int MAX_DATA_CHUNK_SIZE = 64 * 1024; private const int MAX_STRING_PROPERTY_LENGTH = 32 * 1024; private const int MAX_DATA_CHUNKS_COUNT = 15; private const string BINARY_DATA_PROPERTY_NAME = "Data"; private const string STRING_DATA_PROPERTY_NAME = "StringData"; private readonly string name; /// <summary> Default constructor </summary> public AzureTableGrainStorage( string name, AzureTableStorageOptions options, IOptions<ClusterOptions> clusterOptions, ILogger<AzureTableGrainStorage> logger, IActivatorProvider activatorProvider) { this.options = options; this.clusterOptions = clusterOptions.Value; this.name = name; this.storageSerializer = options.GrainStorageSerializer; this.logger = logger; _activatorProvider = activatorProvider; } /// <summary> Read state data function for this storage provider. </summary> /// <see cref="IGrainStorage.ReadStateAsync{T}"/> public async Task ReadStateAsync<T>(string grainType, GrainId grainId, IGrainState<T> grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainId); LogTraceReadingGrainState(grainType, pk, grainId, this.options.TableName); string partitionKey = pk; string rowKey = AzureTableUtils.SanitizeTableProperty(grainType); var entity = await tableDataManager.Read(partitionKey, rowKey).ConfigureAwait(false); if (entity is not null) { var loadedState = ConvertFromStorageFormat<T>(entity); grainState.RecordExists = loadedState != null; grainState.State = loadedState ?? CreateInstance<T>(); grainState.ETag = entity.ETag.ToString(); } else { grainState.RecordExists = false; grainState.ETag = null; grainState.State = CreateInstance<T>(); } } /// <summary> Write state data function for this storage provider. </summary> /// <see cref="IGrainStorage.WriteStateAsync{T}"/> public async Task WriteStateAsync<T>(string grainType, GrainId grainId, IGrainState<T> grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainId); LogTraceWritingGrainState(grainType, pk, grainId, grainState.ETag, this.options.TableName); var rowKey = AzureTableUtils.SanitizeTableProperty(grainType); var entity = new TableEntity(pk, rowKey) { ETag = new ETag(grainState.ETag) }; ConvertToStorageFormat(grainState.State, entity); try { await DoOptimisticUpdate(() => tableDataManager.Write(entity), grainType, grainId, this.options.TableName, grainState.ETag).ConfigureAwait(false); grainState.ETag = entity.ETag.ToString(); grainState.RecordExists = true; } catch (Exception exc) { LogErrorWriteGrainState(grainType, grainId, grainState.ETag, this.options.TableName, exc); throw; } } /// <summary> Clear / Delete state data function for this storage provider. </summary> /// <remarks> /// If the <c>DeleteStateOnClear</c> is set to <c>true</c> then the table row /// for this grain will be deleted / removed, otherwise the table row will be /// cleared by overwriting with default / null values. /// </remarks> /// <see cref="IGrainStorage.ClearStateAsync{T}"/> public async Task ClearStateAsync<T>(string grainType, GrainId grainId, IGrainState<T> grainState) { if (tableDataManager == null) throw new ArgumentException("GrainState-Table property not initialized"); string pk = GetKeyString(grainId); LogTraceClearingGrainState(grainType, pk, grainId, grainState.ETag, this.options.DeleteStateOnClear, this.options.TableName); var rowKey = AzureTableUtils.SanitizeTableProperty(grainType); var entity = new TableEntity(pk, rowKey) { ETag = new ETag(grainState.ETag) }; string operation = "Clearing"; try { if (this.options.DeleteStateOnClear) { operation = "Deleting"; await DoOptimisticUpdate(() => tableDataManager.Delete(entity), grainType, grainId, this.options.TableName, grainState.ETag).ConfigureAwait(false); grainState.ETag = null; } else { await DoOptimisticUpdate(() => tableDataManager.Write(entity), grainType, grainId, this.options.TableName, grainState.ETag).ConfigureAwait(false); grainState.ETag = entity.ETag.ToString(); // Update in-memory data to the new ETag } grainState.RecordExists = false; grainState.State = CreateInstance<T>(); } catch (Exception exc) { LogErrorClearingGrainState(operation, grainType, grainId, grainState.ETag!, this.options.TableName, exc); throw; } } private static async Task DoOptimisticUpdate(Func<Task> updateOperation, string grainType, GrainId grainId, string tableName, string currentETag) { try { await updateOperation.Invoke().ConfigureAwait(false); } catch (RequestFailedException ex) when (ex.IsPreconditionFailed() || ex.IsConflict() || ex.IsNotFound()) { throw new TableStorageUpdateConditionNotSatisfiedException(grainType, grainId.ToString(), tableName, "Unknown", currentETag, ex); } } /// <summary> /// Serialize to Azure storage format in either binary or JSON format. /// </summary> /// <param name="grainState">The grain state data to be serialized</param> /// <param name="entity">The Azure table entity the data should be stored in</param> /// <remarks> /// See: /// http://msdn.microsoft.com/en-us/library/system.web.script.serialization.javascriptserializer.aspx /// for more on the JSON serializer. /// </remarks> internal void ConvertToStorageFormat<T>(T grainState, TableEntity entity) { var binaryData = storageSerializer.Serialize<T>(grainState); CheckMaxDataSize(binaryData.ToMemory().Length, MAX_DATA_CHUNK_SIZE * MAX_DATA_CHUNKS_COUNT); if (options.UseStringFormat) { var properties = SplitStringData(binaryData.ToString().AsMemory()); foreach (var keyValuePair in properties.Zip(GetPropertyNames(STRING_DATA_PROPERTY_NAME), (property, name) => new KeyValuePair<string, object>(name, property.ToString()))) { entity[keyValuePair.Key] = keyValuePair.Value; } } else { var properties = SplitBinaryData(binaryData); foreach (var keyValuePair in properties.Zip(GetPropertyNames(BINARY_DATA_PROPERTY_NAME), (property, name) => new KeyValuePair<string, object>(name, property.ToArray()))) { entity[keyValuePair.Key] = keyValuePair.Value; } } } private void CheckMaxDataSize(int dataSize, int maxDataSize) { if (dataSize > maxDataSize) { var msg = string.Format("Data too large to write to Azure table. Size={0} MaxSize={1}", dataSize, maxDataSize); LogErrorDataTooLarge(dataSize, maxDataSize); throw new ArgumentOutOfRangeException("GrainState.Size", msg); } } private static IEnumerable<ReadOnlyMemory<char>> SplitStringData(ReadOnlyMemory<char> stringData) { var startIndex = 0; while (startIndex < stringData.Length) { var chunkSize = Math.Min(MAX_STRING_PROPERTY_LENGTH, stringData.Length - startIndex); yield return stringData.Slice(startIndex, chunkSize); startIndex += chunkSize; } } private static IEnumerable<ReadOnlyMemory<byte>> SplitBinaryData(ReadOnlyMemory<byte> binaryData) { var startIndex = 0; while (startIndex < binaryData.Length) { var chunkSize = Math.Min(MAX_DATA_CHUNK_SIZE, binaryData.Length - startIndex); yield return binaryData.Slice(startIndex, chunkSize); startIndex += chunkSize; } } private static IEnumerable<string> GetPropertyNames(string basePropertyName) { yield return basePropertyName; for (var i = 1; i < MAX_DATA_CHUNKS_COUNT; ++i) { yield return basePropertyName + i; } } private static IEnumerable<byte[]> ReadBinaryDataChunks(TableEntity entity) { foreach (var binaryDataPropertyName in GetPropertyNames(BINARY_DATA_PROPERTY_NAME)) { if (entity.TryGetValue(binaryDataPropertyName, out var dataProperty)) { switch (dataProperty) { // if TablePayloadFormat.JsonNoMetadata is used case string stringValue: if (!string.IsNullOrEmpty(stringValue)) { yield return Convert.FromBase64String(stringValue); } break; // if any payload type providing metadata is used case byte[] binaryValue: if (binaryValue != null && binaryValue.Length > 0) { yield return binaryValue; } break; } } } } private static byte[] ReadBinaryData(TableEntity entity) { var dataChunks = ReadBinaryDataChunks(entity).ToArray(); var dataSize = dataChunks.Select(d => d.Length).Sum(); var result = new byte[dataSize]; var startIndex = 0; foreach (var dataChunk in dataChunks) { Array.Copy(dataChunk, 0, result, startIndex, dataChunk.Length); startIndex += dataChunk.Length; } return result; } private static IEnumerable<string> ReadStringDataChunks(TableEntity entity) { foreach (var stringDataPropertyName in GetPropertyNames(STRING_DATA_PROPERTY_NAME)) { if (entity.TryGetValue(stringDataPropertyName, out var dataProperty)) { if (dataProperty is string { Length: > 0 } data) { yield return data; } } } } private static string ReadStringData(TableEntity entity) { return string.Join(string.Empty, ReadStringDataChunks(entity)); } /// <summary> /// Deserialize from Azure storage format /// </summary> /// <param name="entity">The Azure table entity the stored data</param> internal T? ConvertFromStorageFormat<T>(TableEntity entity) { // Read from both column type for backward compatibility var binaryData = ReadBinaryData(entity); var stringData = ReadStringData(entity); T? dataValue = default; try { var input = binaryData.Length > 0 ? new BinaryData(binaryData) : new BinaryData(stringData); if (input.Length > 0) dataValue = this.storageSerializer.Deserialize<T>(input); } catch (Exception exc) { var sb = new StringBuilder(); if (binaryData.Length > 0) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.Data={0}", binaryData); } else if (!string.IsNullOrEmpty(stringData)) { sb.AppendFormat("Unable to convert from storage format GrainStateEntity.StringData={0}", stringData); } if (dataValue != null) { sb.AppendFormat("Data Value={0} Type={1}", dataValue, dataValue.GetType()); } LogErrorSimpleMessage(sb, exc); throw new AggregateException(sb.ToString(), exc); } return dataValue; } private string GetKeyString(GrainId grainId) { var key = $"{clusterOptions.ServiceId}_{grainId}"; return AzureTableUtils.SanitizeTableProperty(key); }
AzureTableGrainStorage
csharp
ChilliCream__graphql-platform
src/StrawberryShake/Client/src/Transport.WebSockets/ISocketConnectionInterceptor.cs
{ "start": 140, "end": 1354 }
public interface ____ { /// <summary> /// This method is called before the first message is sent to the server. The object /// returned from this message, will be passed to the server as the initial payload. /// </summary> /// <param name="protocol"> /// The protocol over which the connection will be established /// </param> /// <param name="cancellationToken"> /// The cancellation token of this connection /// </param> /// <returns> /// Returns the initial payload of the connection /// </returns> ValueTask<object?> CreateConnectionInitPayload( ISocketProtocol protocol, CancellationToken cancellationToken); /// <summary> /// This method is called when the socket connection is opened. /// </summary> /// <param name="client"> /// The client that opened the connection. /// </param> void OnConnectionOpened(ISocketClient client); /// <summary> /// This method is called when the socket connection is closed. /// </summary> /// <param name="client"> /// The client that closed the connection. /// </param> void OnConnectionClosed(ISocketClient client); }
ISocketConnectionInterceptor
csharp
jellyfin__jellyfin
MediaBrowser.Providers/Plugins/AudioDb/AudioDbAlbumExternalUrlProvider.cs
{ "start": 315, "end": 895 }
public class ____ : IExternalUrlProvider { /// <inheritdoc/> public string Name => "TheAudioDb Album"; /// <inheritdoc/> public IEnumerable<string> GetExternalUrls(BaseItem item) { if (item.TryGetProviderId(MetadataProvider.AudioDbAlbum, out var externalId)) { var baseUrl = "https://www.theaudiodb.com/"; switch (item) { case MusicAlbum: yield return baseUrl + $"album/{externalId}"; break; } } } }
AudioDbAlbumExternalUrlProvider
csharp
grandnode__grandnode2
src/Web/Grand.Web/Features/Models/Courses/GetCheckOrder.cs
{ "start": 121, "end": 250 }
public class ____ : IRequest<bool> { public Customer Customer { get; set; } public Course Course { get; set; } }
GetCheckOrder
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/Middleware/ConsumeContextRetryContext.cs
{ "start": 1744, "end": 3419 }
public class ____<TFilter, TContext> : RetryContext<TFilter> where TFilter : class, CommandContext where TContext : RetryCommandContext, TFilter { readonly TContext _context; readonly RetryContext<TFilter> _retryContext; public ConsumeContextRetryContext(RetryContext<TFilter> retryContext, TContext context) { _retryContext = retryContext; _context = context; _context.RetryAttempt = retryContext.RetryCount; } public TFilter Context => _context; public CancellationToken CancellationToken => _retryContext.CancellationToken; public Exception Exception => _retryContext.Exception; public int RetryCount => _retryContext.RetryCount; public int RetryAttempt => _retryContext.RetryAttempt; public Type ContextType => _retryContext.ContextType; public TimeSpan? Delay => _retryContext.Delay; public async Task PreRetry() { await _retryContext.PreRetry().ConfigureAwait(false); } public async Task RetryFaulted(Exception exception) { await _retryContext.RetryFaulted(exception).ConfigureAwait(false); } public bool CanRetry(Exception exception, out RetryContext<TFilter> retryContext) { var canRetry = _retryContext.CanRetry(exception, out RetryContext<TFilter> policyRetryContext); retryContext = new ConsumeContextRetryContext<TFilter, TContext>(policyRetryContext, canRetry ? _context.CreateNext<TContext>() : _context); return canRetry; } } }
ConsumeContextRetryContext
csharp
duplicati__duplicati
Duplicati/Library/Encryption/Strings.cs
{ "start": 2142, "end": 2336 }
internal static class ____ { public static string DecryptionError(string message) { return LC.L(@"Failed to decrypt data (invalid passphrase?): {0}", message); } }
EncryptionBase
csharp
dotnet__machinelearning
src/Microsoft.ML.Data/Data/BufferBuilder.cs
{ "start": 673, "end": 16351 }
internal sealed class ____<T> { // Don't walk more than this many items when doing an insert. private const int InsertThreshold = 20; private readonly Combiner<T> _comb; // _length is the logical length of the feature set. Valid indices are non-negative // indices less than _length. private int _length; // Whether we're currently using a dense representation. In that case, _indices is not used. private bool _dense; // When we're currently using a sparse representation, this indicates whether the indices are // known to be sorted (increasing, with no duplicates). We'll do a small amount of work on each // AddFeature call to maintain _sorted. private bool _sorted; // When in a sparse representation, _count is the number of active values in _values and _indices. // When dense, _count == _length (see AssertValid). private int _count; // The indices and values. When sparse, these are parallel with _count active entries. When dense, // _indices is not used and the values are stored in the first _length elements of _values. private int[] _indices; private T[] _values; // When invoking a component to add features in a particular range, these can be set to the base // index and length of the component's feature index range. Then the component doesn't need to // know about the rest of the feature index space. private int _ifeatCur; private int _cfeatCur; public bool IsEmpty => _count == 0; public int Length => _length; public BufferBuilder(Combiner<T> comb) { Contracts.AssertValue(comb); _comb = comb; // _values and _indices are resized as needed. This initialization ensures that _values // is never null. Note that _indices starts as null. This is because if we use a dense // representation (specified in ResetImpl), then _indices isn't even needed so no point // pre-allocating. _values = new T[8]; } [Conditional("DEBUG")] private void AssertValid() { #if DEBUG Contracts.Assert(_count >= 0); Contracts.AssertValue(_values); Contracts.Assert(_values.Length >= _count); Contracts.Assert(0 <= _ifeatCur && 0 <= _cfeatCur && _ifeatCur <= _length - _cfeatCur); if (_dense) Contracts.Assert(_count == _length); else { // ResetImpl forces _indices != null and _length > 0. Contracts.Assert(_indices != null || _length == 0); Contracts.Assert(Utils.Size(_indices) >= _count); // If we have no more than InsertThreshold items, we always keep things sorted. Contracts.Assert(_sorted || _count > InsertThreshold); } #endif } public static BufferBuilder<T> CreateDefault() { if (typeof(T) == typeof(ReadOnlyMemory<char>)) return (BufferBuilder<T>)(object)new BufferBuilder<ReadOnlyMemory<char>>(TextCombiner.Instance); if (typeof(T) == typeof(float)) return (BufferBuilder<T>)(object)new BufferBuilder<float>(FloatAdder.Instance); throw Contracts.Except($"Unrecognized type '{typeof(T)}' for default {nameof(BufferBuilder<T>)}"); } /// <summary> /// This resets the FeatureSet to be used again. This functionality is for memory /// efficiency - we can keep pools of these to be re-used. /// Dense indicates whether this should start out dense. It can, of course, /// become dense when it makes sense to do so. /// </summary> private void ResetImpl(int length, bool dense) { Contracts.Assert(length > 0); _length = length; _dense = false; _sorted = true; _count = 0; _ifeatCur = 0; _cfeatCur = 0; if (dense) { if (_values.Length < _length) _values = new T[_length]; else Array.Clear(_values, 0, _length); _dense = true; _count = _length; } else if (_indices == null) _indices = new int[8]; AssertValid(); } /// <summary> /// This sets the active sub-range of the feature index space. For example, when asking /// a feature handler to add features, we call this so the feature handler can use zero-based /// indexing for the features it is generating. This also prohibits the feature handler from /// messing with a different index range. Note that this is protected so a non-abstract derived /// type can choose how to use it, but a feature handler can't directly mess with the active /// range. /// </summary> /// <param name="ifeat">The min feature index of the active range</param> /// <param name="cfeat">The number of feature indices in the active range</param> private void SetActiveRangeImpl(int ifeat, int cfeat) { AssertValid(); Contracts.Assert(0 <= ifeat && 0 <= cfeat && ifeat <= _length - cfeat); _ifeatCur = ifeat; _cfeatCur = cfeat; AssertValid(); } /// <summary> /// Adds a feature to the current active range. If the index is a duplicate, this adds the /// given value to any previously provided value(s). /// </summary> public void AddFeature(int index, T value) { AssertValid(); Contracts.Assert(0 <= index && index < _cfeatCur); // Ignore default values. if (_comb.IsDefault(value)) return; // Adjust the index. index += _ifeatCur; if (_dense) { _comb.Combine(ref _values[index], value); return; } // ResetImpl ensures that _indices is non-null when _dense is false. Contracts.Assert(_indices != null); if (!_sorted) { if (_count < _length) { // Make room. if (_values.Length <= _count) Array.Resize(ref _values, Math.Max(Math.Min(_length, checked(_count * 2)), 8)); if (_indices.Length <= _count) Array.Resize(ref _indices, Math.Max(Math.Min(_length, checked(_count * 2)), 8)); _values[_count] = value; _indices[_count] = index; _count++; return; } SortAndSumDups(); if (_dense) { _comb.Combine(ref _values[index], value); return; } } Contracts.Assert(_sorted); if (_count >= _length / 2 - 1) { MakeDense(); _comb.Combine(ref _values[index], value); return; } // Make room. if (_values.Length <= _count) Array.Resize(ref _values, Math.Max(Math.Min(_length, checked(_count * 2)), 8)); if (_indices.Length <= _count) Array.Resize(ref _indices, Math.Max(Math.Min(_length, checked(_count * 2)), 8)); if (_count >= InsertThreshold && _indices[_count - InsertThreshold] > index) { _values[_count] = value; _indices[_count] = index; _count++; _sorted = false; return; } // Insert this one. Find the right place. // REVIEW: Should we ever use binary search? int ivDst = _count; for (; ; ) { if (--ivDst < 0) break; int diff = _indices[ivDst] - index; if (diff <= 0) { if (diff < 0) break; // entry is found, increment the value _comb.Combine(ref _values[ivDst], value); return; } } Contracts.Assert(ivDst < 0 || _indices[ivDst] < index); ivDst++; Contracts.Assert(ivDst == _count || _indices[ivDst] > index); // Value goes here at ivDst. Shift others up. for (int i = _count; --i >= ivDst;) { _indices[i + 1] = _indices[i]; _values[i + 1] = _values[i]; } _indices[ivDst] = index; _values[ivDst] = value; _count++; } /// <summary> /// Sort the indices/values (by index) and sum the values for duplicate indices. This asserts that /// _sorted is false and _dense is false. It also asserts that _count > 1. /// </summary> private void SortAndSumDups() { AssertValid(); Contracts.Assert(!_sorted); Contracts.Assert(!_dense); Contracts.Assert(_count > 1); // REVIEW: Ideally this would be a stable sort. Array.Sort(_indices, _values, 0, _count); int ivSrc = 0; int ivDst = 0; for (; ; ) { if (ivSrc >= _count) { _count = 0; _sorted = true; AssertValid(); return; } if (!_comb.IsDefault(_values[ivSrc])) break; } Contracts.Assert(ivSrc < _count && !_comb.IsDefault(_values[ivSrc])); _values[ivDst] = _values[ivSrc]; _indices[ivDst++] = _indices[ivSrc]; while (++ivSrc < _count) { Contracts.Assert(ivDst <= ivSrc); if (_indices[ivDst - 1] == _indices[ivSrc]) { _comb.Combine(ref _values[ivDst - 1], _values[ivSrc]); continue; } if (ivDst < ivSrc) { // Copy down _indices[ivDst] = _indices[ivSrc]; _values[ivDst] = _values[ivSrc]; } ivDst++; } Contracts.Assert(0 < ivDst && ivDst <= _count); _count = ivDst; _sorted = true; AssertValid(); if (_count >= _length / 2) MakeDense(); } /// <summary> /// Convert a sorted non-dense representation to dense. /// </summary> private void MakeDense() { AssertValid(); Contracts.Assert(!_dense); Contracts.Assert(_sorted); if (_values.Length < _length) Array.Resize(ref _values, _length); int ivDst = _length; int iivSrc = _count; while (--iivSrc >= 0) { int index = _indices[iivSrc]; Contracts.Assert(ivDst > index); while (--ivDst > index) _values[ivDst] = default(T); Contracts.Assert(ivDst == index); _values[ivDst] = _values[iivSrc]; } while (--ivDst >= 0) _values[ivDst] = default(T); _dense = true; _count = _length; } /// <summary> /// Try to get the value for the given feature. Returns false if the feature index is not found. /// Note that this respects the "active range", just as AddFeature does. /// </summary> public bool TryGetFeature(int index, out T v) { AssertValid(); Contracts.Assert(0 <= index && index < _cfeatCur); int ifeat = index + _ifeatCur; if (_dense) { v = _values[ifeat]; return true; } // Make sure the indices are sorted. if (!_sorted) { SortAndSumDups(); if (_dense) { v = _values[ifeat]; return true; } } int iv = Utils.FindIndexSorted(_indices, 0, _count, ifeat); Contracts.Assert(iv == 0 || ifeat > _indices[iv - 1]); if (iv < _count) { Contracts.Assert(ifeat <= _indices[iv]); if (ifeat == _indices[iv]) { v = _values[iv]; return true; } } v = default(T); return false; } public void Reset(int length, bool dense) { ResetImpl(length, dense); SetActiveRangeImpl(0, length); } public void AddFeatures(int index, in VBuffer<T> buffer) { Contracts.Check(0 <= index && index <= _length - buffer.Length); var values = buffer.GetValues(); int count = values.Length; if (count == 0) return; if (buffer.IsDense) { Contracts.Assert(count == buffer.Length); if (_dense) { for (int i = 0; i < count; i++) _comb.Combine(ref _values[index + i], values[i]); } else { // REVIEW: Optimize this. for (int i = 0; i < count; i++) AddFeature(index + i, values[i]); } } else { // REVIEW: Validate indices! var indices = buffer.GetIndices(); if (_dense) { for (int i = 0; i < count; i++) _comb.Combine(ref _values[index + indices[i]], values[i]); } else { // REVIEW: Optimize this. for (int i = 0; i < count; i++) AddFeature(index + indices[i], values[i]); } } } public void GetResult(ref VBuffer<T> buffer) { if (IsEmpty) { VBufferUtils.Resize(ref buffer, _length, 0); return; } if (!_dense) { if (!_sorted) SortAndSumDups(); if (!_dense && _count >= _length / 2) MakeDense(); } if (_dense) { var editor = VBufferEditor.Create(ref buffer, _length); _values.AsSpan(0, _length).CopyTo(editor.Values); buffer = editor.Commit(); } else { Contracts.Assert(_count < _length); var editor = VBufferEditor.Create(ref buffer, _length, _count); _values.AsSpan(0, _count).CopyTo(editor.Values); _indices.AsSpan(0, _count).CopyTo(editor.Indices); buffer = editor.Commit(); } } } }
BufferBuilder
csharp
PrismLibrary__Prism
tests/Avalonia/Prism.Avalonia.Tests/Modularity/ModuleManagerFixture.cs
{ "start": 19493, "end": 19739 }
internal class ____ : IModuleInitializer { public Action<ModuleInfo> LoadBody; public void Initialize(IModuleInfo moduleInfo) { LoadBody((ModuleInfo)moduleInfo); } } }
MockDelegateModuleInitializer
csharp
dotnet__aspnetcore
src/Mvc/Mvc.ViewFeatures/test/Rendering/HtmlHelperPartialExtensionsTest.cs
{ "start": 22561, "end": 22709 }
private sealed class ____ { public override string ToString() { return "test-model-content"; } } }
TestModel
csharp
simplcommerce__SimplCommerce
src/Modules/SimplCommerce.Module.Contacts/Areas/Contacts/ViewModels/ContactAreaTranslationForm.cs
{ "start": 73, "end": 224 }
public class ____ { public string DefaultCultureName { get; set; } public string Name { get; set; } } }
ContactAreaTranslationForm
csharp
App-vNext__Polly
src/Polly.Core/CircuitBreaker/Health/HealthInfo.cs
{ "start": 57, "end": 419 }
record ____ HealthInfo(int Throughput, double FailureRate, int FailureCount) { public static HealthInfo Create(int successes, int failures) { var total = successes + failures; if (total == 0) { return new HealthInfo(0, 0, failures); } return new(total, failures / (double)total, failures); } }
struct
csharp
FastEndpoints__FastEndpoints
Tests/IntegrationTests/FastEndpoints/MessagingTests/EventBusTests.cs
{ "start": 1968, "end": 2228 }
sealed class ____ : IEventHandler<TestEventBus> { public static int Result; public Task HandleAsync(TestEventBus eventModel, CancellationToken ct) { Result = eventModel.Id + 2; return Task.CompletedTask; } }
AnotherFakeEventHandler
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Controls/BreadcrumbBar/BreadcrumbIterable.cs
{ "start": 355, "end": 729 }
internal partial class ____ : IEnumerable<object?> { public BreadcrumbIterable() { } public BreadcrumbIterable(object? itemsSource) { ItemsSource = itemsSource; } public object? ItemsSource { get; } public IEnumerator<object?> GetEnumerator() => new BreadcrumbIterator(ItemsSource); IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); }
BreadcrumbIterable
csharp
FastEndpoints__FastEndpoints
Web/[Features]/TestCases/Messaging/CommandBusTest/CommandBusTest.cs
{ "start": 1381, "end": 1505 }
public class ____ : ICommand { public string FirstName { get; set; } public string LastName { get; set; } }
VoidCommand
csharp
microsoft__semantic-kernel
dotnet/src/Connectors/Connectors.Google.UnitTests/Core/Gemini/AuthorRoleConverterTests.cs
{ "start": 294, "end": 4655 }
public sealed class ____ { [Fact] public void ReadWhenRoleIsUserReturnsUser() { // Arrange var converter = new AuthorRoleConverter(); var reader = new Utf8JsonReader("\"user\""u8); // Act reader.Read(); var result = converter.Read(ref reader, typeof(AuthorRole?), JsonSerializerOptions.Default); // Assert Assert.Equal(AuthorRole.User, result); } [Fact] public void ReadWhenRoleIsModelReturnsAssistant() { // Arrange var converter = new AuthorRoleConverter(); var reader = new Utf8JsonReader("\"model\""u8); // Act reader.Read(); var result = converter.Read(ref reader, typeof(AuthorRole?), JsonSerializerOptions.Default); // Assert Assert.Equal(AuthorRole.Assistant, result); } [Fact] public void ReadWhenRoleIsFunctionReturnsTool() { // Arrange var converter = new AuthorRoleConverter(); var reader = new Utf8JsonReader("\"function\""u8); // Act reader.Read(); var result = converter.Read(ref reader, typeof(AuthorRole?), JsonSerializerOptions.Default); // Assert Assert.Equal(AuthorRole.Tool, result); } [Fact] public void ReadWhenRoleIsNullReturnsNull() { // Arrange var converter = new AuthorRoleConverter(); var reader = new Utf8JsonReader("null"u8); // Act reader.Read(); var result = converter.Read(ref reader, typeof(AuthorRole?), JsonSerializerOptions.Default); // Assert Assert.Null(result); } [Fact] public void ReadWhenRoleIsUnknownThrows() { // Arrange var converter = new AuthorRoleConverter(); // Act void Act() { var reader = new Utf8JsonReader("\"unknown\""u8); reader.Read(); converter.Read(ref reader, typeof(AuthorRole?), JsonSerializerOptions.Default); } // Assert Assert.Throws<JsonException>(Act); } [Fact] public void WriteWhenRoleIsUserReturnsUser() { // Arrange var converter = new AuthorRoleConverter(); var bufferWriter = new ArrayBufferWriter<byte>(); using var writer = new Utf8JsonWriter(bufferWriter); // Act converter.Write(writer, AuthorRole.User, JsonSerializerOptions.Default); // Assert Assert.Equal("\"user\""u8, bufferWriter.GetSpan().Trim((byte)'\0')); } [Fact] public void WriteWhenRoleIsAssistantReturnsModel() { // Arrange var converter = new AuthorRoleConverter(); var bufferWriter = new ArrayBufferWriter<byte>(); using var writer = new Utf8JsonWriter(bufferWriter); // Act converter.Write(writer, AuthorRole.Assistant, JsonSerializerOptions.Default); // Assert Assert.Equal("\"model\""u8, bufferWriter.GetSpan().Trim((byte)'\0')); } [Fact] public void WriteWhenRoleIsToolReturnsFunction() { // Arrange var converter = new AuthorRoleConverter(); var bufferWriter = new ArrayBufferWriter<byte>(); using var writer = new Utf8JsonWriter(bufferWriter); // Act converter.Write(writer, AuthorRole.Tool, JsonSerializerOptions.Default); // Assert Assert.Equal("\"function\""u8, bufferWriter.GetSpan().Trim((byte)'\0')); } [Fact] public void WriteWhenRoleIsNullReturnsNull() { // Arrange var converter = new AuthorRoleConverter(); var bufferWriter = new ArrayBufferWriter<byte>(); using var writer = new Utf8JsonWriter(bufferWriter); // Act converter.Write(writer, null, JsonSerializerOptions.Default); // Assert Assert.Equal("null"u8, bufferWriter.GetSpan().Trim((byte)'\0')); } [Fact] public void WriteWhenRoleIsNotUserOrAssistantOrToolThrows() { // Arrange var converter = new AuthorRoleConverter(); using var writer = new Utf8JsonWriter(new ArrayBufferWriter<byte>()); // Act void Act() { converter.Write(writer, AuthorRole.System, JsonSerializerOptions.Default); } // Assert Assert.Throws<JsonException>(Act); } }
AuthorRoleConverterTests
csharp
smartstore__Smartstore
src/Smartstore.Core/Common/Configuration/HomePageSettings.cs
{ "start": 128, "end": 711 }
public class ____ : ISettings { /// <summary> /// Gets or sets the homepage meta title. /// </summary> [LocalizedProperty] public string MetaTitle { get; set; } /// <summary> /// Gets or sets the homepage meta description. /// </summary> [LocalizedProperty] public string MetaDescription { get; set; } /// <summary> /// Gets or sets the homepage meta keywords. /// </summary> [LocalizedProperty] public string MetaKeywords { get; set; } } }
HomePageSettings
csharp
microsoft__garnet
libs/common/StreamProvider.cs
{ "start": 1066, "end": 1146 }
class ____ common logic between stream providers /// </summary>
containing
csharp
dotnet__efcore
test/EFCore.Specification.Tests/ModelBuilding/GiantModel.cs
{ "start": 72846, "end": 73063 }
public class ____ { public int Id { get; set; } public RelatedEntity336 ParentEntity { get; set; } public IEnumerable<RelatedEntity338> ChildEntities { get; set; } }
RelatedEntity337
csharp
nopSolutions__nopCommerce
src/Libraries/Nop.Core/Infrastructure/ConcurrentTrie.cs
{ "start": 155, "end": 19032 }
public partial class ____<TValue> : IConcurrentCollection<TValue> { #region Fields protected volatile TrieNode _root = new(); protected readonly StripedReaderWriterLock _locks = new(); protected readonly ReaderWriterLockSlim _structureLock = new(); #endregion #region Ctor /// <summary> /// Initializes a new instance of <see cref="ConcurrentTrie{TValue}" /> /// </summary> protected ConcurrentTrie(TrieNode subtreeRoot) { _root.Children[subtreeRoot.Label[0]] = subtreeRoot; } /// <summary> /// Initializes a new empty instance of <see cref="ConcurrentTrie{TValue}" /> /// </summary> public ConcurrentTrie() { } #endregion #region Utilities [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static int GetCommonPrefixLength(ReadOnlySpan<char> s1, ReadOnlySpan<char> s2) { var i = 0; var minLength = Math.Min(s1.Length, s2.Length); while (i < minLength && s2[i] == s1[i]) i++; return i; } /// <summary> /// Gets a lock on the node's children /// </summary> /// <remarks> /// May return the same lock for two different nodes, so the user needs to check to avoid lock recursion exceptions /// </remarks> protected virtual ReaderWriterLockSlim GetLock(TrieNode node) { return _locks.GetLock(node.Children); } protected virtual bool Find(string key, TrieNode subtreeRoot, out TrieNode node) { node = subtreeRoot; if (key.Length == 0) return true; var suffix = key.AsSpan(); while (true) { var nodeLock = GetLock(node); nodeLock.EnterReadLock(); try { if (!node.Children.TryGetValue(suffix[0], out node)) return false; } finally { nodeLock.ExitReadLock(); } var span = node.Label.AsSpan(); var i = GetCommonPrefixLength(suffix, span); if (i != span.Length) return false; if (i == suffix.Length) return node.HasValue; suffix = suffix[i..]; } } protected virtual TrieNode GetOrAddNode(ReadOnlySpan<char> key, TValue value, bool overwrite = false) { var node = _root; var suffix = key; ReaderWriterLockSlim nodeLock; char c; TrieNode nextNode; _structureLock.EnterReadLock(); try { while (true) { c = suffix[0]; nodeLock = GetLock(node); nodeLock.EnterUpgradeableReadLock(); try { if (node.Children.TryGetValue(c, out nextNode)) { var label = nextNode.Label.AsSpan(); var i = GetCommonPrefixLength(label, suffix); // suffix starts with label if (i == label.Length) { // keys are equal - this is the node we're looking for if (i == suffix.Length) { if (overwrite) nextNode.SetValue(value); else nextNode.GetOrAddValue(value); return nextNode; } // advance the suffix and continue the search from nextNode suffix = suffix[label.Length..]; node = nextNode; continue; } // we need to add a node, but don't want to hold an upgradeable read lock on _structureLock // since only one can be held at a time, so we break, release the lock and reacquire a write lock break; } // if there is no child starting with c, we can just add and return one nodeLock.EnterWriteLock(); try { var suffixNode = new TrieNode(suffix); suffixNode.SetValue(value); return node.Children[c] = suffixNode; } finally { nodeLock.ExitWriteLock(); } } finally { nodeLock.ExitUpgradeableReadLock(); } } } finally { _structureLock.ExitReadLock(); } // if we need to restructure the tree, we do it after releasing and reacquiring the lock. // however, another thread may have restructured around the node we're on in the meantime, // and in that case we need to retry the insertion _structureLock.EnterWriteLock(); nodeLock.EnterUpgradeableReadLock(); try { // we use while instead of if so we can break // and put a recursive call at the end of the method to enable tail-recursion optimization while (!node.IsDeleted && node.Children.TryGetValue(c, out nextNode)) { var label = nextNode.Label.AsSpan(); var i = GetCommonPrefixLength(label, suffix); // suffix starts with label? if (i == label.Length) { // if the keys are equal, the key has already been inserted if (i == suffix.Length) { if (overwrite) nextNode.SetValue(value); return nextNode; } // structure has changed since last; try again break; } var splitNode = new TrieNode(suffix[..i]) { Children = { [label[i]] = new TrieNode(label[i..], nextNode) } }; TrieNode outNode; // label starts with suffix, so we can return splitNode if (i == suffix.Length) outNode = splitNode; // the keys diverge, so we need to branch from splitNode else splitNode.Children[suffix[i]] = outNode = new TrieNode(suffix[i..]); outNode.SetValue(value); nodeLock.EnterWriteLock(); try { node.Children[c] = splitNode; } finally { nodeLock.ExitWriteLock(); } return outNode; } } finally { nodeLock.ExitUpgradeableReadLock(); _structureLock.ExitWriteLock(); } // we failed to add a node, so we have to retry; // the recursive call is placed at the end to enable tail-recursion optimization return GetOrAddNode(key, value, overwrite); } protected virtual void Remove(TrieNode subtreeRoot, ReadOnlySpan<char> key) { TrieNode node = null, grandparent = null; var parent = subtreeRoot; var i = 0; _structureLock.EnterReadLock(); try { while (i < key.Length) { var c = key[i]; var parentLock = GetLock(parent); parentLock.EnterReadLock(); try { if (!parent.Children.TryGetValue(c, out node)) return; } finally { parentLock.ExitReadLock(); } var label = node.Label.AsSpan(); var k = GetCommonPrefixLength(key[i..], label); // is this the node we're looking for? if (k == label.Length && k == key.Length - i) { // this node has to be removed or merged if (node.TryRemoveValue(out _)) break; // the node is either already removed, or it is a branching node return; } if (k < label.Length) return; i += label.Length; grandparent = parent; parent = node; } } finally { _structureLock.ExitReadLock(); } if (node == null) return; // if we need to delete a node, the tree has to be restructured to remove empty leaves or merge // single children with branching node parents, and other threads may be currently on these nodes _structureLock.EnterWriteLock(); try { var nodeLock = GetLock(node); var parentLock = GetLock(parent); var grandparentLock = grandparent != null ? GetLock(grandparent) : null; var lockAlreadyHeld = nodeLock == parentLock || nodeLock == grandparentLock; if (lockAlreadyHeld) nodeLock.EnterUpgradeableReadLock(); else nodeLock.EnterReadLock(); try { // another thread has written a value to the node while we were waiting if (node.HasValue) return; var c = node.Label[0]; var nChildren = node.Children.Count; // if the node has no children, we can just remove it if (nChildren == 0) { parentLock.EnterWriteLock(); try { // was removed or replaced by another thread if (!parent.Children.TryGetValue(c, out var n) || n != node) return; parent.Children.Remove(c); node.Delete(); // since we removed a node, we may be able to merge a lone sibling with the parent if (parent.Children.Count == 1 && grandparent != null && !parent.HasValue) { var grandparentLockAlreadyHeld = grandparentLock == parentLock; if (!grandparentLockAlreadyHeld) grandparentLock.EnterWriteLock(); try { c = parent.Label[0]; if (!grandparent.Children.TryGetValue(c, out n) || n != parent || parent.HasValue) return; var child = parent.Children.First().Value; grandparent.Children[c] = new TrieNode(parent.Label + child.Label, child); parent.Delete(); } finally { if (!grandparentLockAlreadyHeld) grandparentLock.ExitWriteLock(); } } } finally { parentLock.ExitWriteLock(); } } // if there is a single child, we can merge it with node else if (nChildren == 1) { parentLock.EnterWriteLock(); try { // was removed or replaced by another thread if (!parent.Children.TryGetValue(c, out var n) || n != node) return; var child = node.Children.FirstOrDefault().Value; parent.Children[c] = new TrieNode(node.Label + child.Label, child); node.Delete(); } finally { parentLock.ExitWriteLock(); } } } finally { if (lockAlreadyHeld) nodeLock.ExitUpgradeableReadLock(); else nodeLock.ExitReadLock(); } } finally { _structureLock.ExitWriteLock(); } } protected virtual bool SearchOrPrune(string prefix, bool prune, out TrieNode subtreeRoot) { ArgumentNullException.ThrowIfNull(prefix); if (prefix.Length == 0) { subtreeRoot = _root; return true; } subtreeRoot = default; var node = _root; var parent = node; var span = prefix.AsSpan(); var i = 0; while (i < span.Length) { var c = span[i]; var parentLock = GetLock(parent); parentLock.EnterUpgradeableReadLock(); try { if (!parent.Children.TryGetValue(c, out node)) return false; var label = node.Label.AsSpan(); var k = GetCommonPrefixLength(span[i..], label); if (k == span.Length - i) { subtreeRoot = new TrieNode(prefix[..i] + node.Label, node); if (!prune) return true; parentLock.EnterWriteLock(); try { if (parent.Children.Remove(c, out node)) return true; } finally { parentLock.ExitWriteLock(); } // was removed by another thread return false; } if (k < label.Length) return false; i += label.Length; } finally { parentLock.ExitUpgradeableReadLock(); } parent = node; } return false; } #endregion #region Methods /// <summary> /// Attempts to get the value associated with the specified key /// </summary> /// <param name="key">The key of the item to get (case-sensitive)</param> /// <param name="value">The value associated with <paramref name="key"/>, if found</param> /// <returns> /// True if the key was found, otherwise false /// </returns> public virtual bool TryGetValue(string key, out TValue value) { ArgumentNullException.ThrowIfNull(key); value = default; return Find(key, _root, out var node) && node.TryGetValue(out value); } /// <summary> /// Adds a key-value pair to the trie /// </summary> /// <param name="key">The key of the new item (case-sensitive)</param> /// <param name="value">The value to be associated with <paramref name="key"/></param> public virtual void Add(string key, TValue value) { if (string.IsNullOrEmpty(key)) throw new ArgumentException($"'{nameof(key)}' cannot be null or empty.", nameof(key)); GetOrAddNode(key, value, true); } /// <summary> /// Clears the trie /// </summary> public virtual void Clear() { _root = new TrieNode(); } /// <summary> /// Gets all key-value pairs for keys starting with the given prefix /// </summary> /// <param name="prefix">The prefix (case-sensitive) to search for</param> /// <returns> /// All key-value pairs for keys starting with <paramref name="prefix"/> /// </returns> public virtual IEnumerable<KeyValuePair<string, TValue>> Search(string prefix) { ArgumentNullException.ThrowIfNull(prefix); if (!SearchOrPrune(prefix, false, out var node)) return Enumerable.Empty<KeyValuePair<string, TValue>>(); // depth-first traversal IEnumerable<KeyValuePair<string, TValue>> traverse(TrieNode n, string s) { if (n.TryGetValue(out var value)) yield return new KeyValuePair<string, TValue>(s, value); var nLock = GetLock(n); nLock.EnterReadLock(); List<TrieNode> children; try { // we can't know what is done during enumeration, so we need to make a copy of the children children = n.Children.Values.ToList(); } finally { nLock.ExitReadLock(); } foreach (var child in children) foreach (var kv in traverse(child, s + child.Label)) yield return kv; } return traverse(node, node.Label); } /// <summary> /// Removes the item with the given key, if present /// </summary> /// <param name="key">The key (case-sensitive) of the item to be removed</param> public virtual void Remove(string key) { if (string.IsNullOrEmpty(key)) throw new ArgumentException($"'{nameof(key)}' cannot be null or empty.", nameof(key)); Remove(_root, key); } /// <summary> /// Attempts to remove all items with keys starting with the specified prefix /// </summary> /// <param name="prefix">The prefix (case-sensitive) of the items to be deleted</param> /// <param name="subCollection">The sub-collection containing all deleted items, if found</param> /// <returns> /// True if the prefix was successfully removed from the trie, otherwise false /// </returns> public virtual bool Prune(string prefix, out IConcurrentCollection<TValue> subCollection) { var succeeded = SearchOrPrune(prefix, true, out var subtreeRoot); subCollection = succeeded ? new ConcurrentTrie<TValue>(subtreeRoot) : default; return succeeded; } #endregion #region Properties /// <summary> /// Gets a collection that contains the keys in the <see cref="ConcurrentTrie{TValue}" /> /// </summary> public IEnumerable<string> Keys => Search(string.Empty).Select(t => t.Key); #endregion #region Nested classes /// <summary> /// A striped ReaderWriterLock wrapper /// </summary>
ConcurrentTrie
csharp
AutoFixture__AutoFixture
Src/AutoNSubstituteUnitTest/TestTypes/TypeWithIndexer.cs
{ "start": 64, "end": 329 }
public abstract class ____ { private readonly int[] array = new[] { -99, -99, -99 }; public int this[int index] { get { return this.array[index]; } set { this.array[index] = value; } } } }
TypeWithIndexer
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Issues/Bugzilla/Bugzilla35733.cs
{ "start": 197, "end": 1140 }
public class ____ : TestNavigationPage // or TestFlyoutPage, etc ... { protected override void Init() { var thisDoesNotWorkButton = new Button { Text = "This will crash", AutomationId = "btnGo" }; thisDoesNotWorkButton.Clicked += async (object sender, EventArgs e) => await ShowLocation("KÅRA"); Navigation.PushAsync(new ContentPage() { Content = new StackLayout { VerticalOptions = LayoutOptions.Center, Children = { thisDoesNotWorkButton } } }); } async Task ShowLocation(string locationString) { var stringUri = $"https://raw.githubusercontent.com/xamarin/Xamarin.Forms/main/README.md?l=en&px_location={Uri.EscapeDataString(locationString)}"; var uri = new Uri(stringUri); var webPage = new ContentPage { Title = "WebViewTest", Content = new WebView { Source = uri } }; await Navigation.PushAsync(webPage); } } }
Bugzilla35733
csharp
dotnet__aspnetcore
src/Middleware/Rewrite/test/IISUrlRewrite/FileParserTests.cs
{ "start": 379, "end": 9429 }
public class ____ { [Fact] public void RuleParse_ParseTypicalRule() { // arrange var xml = @"<rewrite> <rules> <rule name=""Rewrite to article.aspx""> <match url = ""^article/([0-9]+)/([_0-9a-z-]+)"" /> <action type=""Rewrite"" url =""article.aspx?id={R:1}&amp;title={R:2}"" /> </rule> </rules> </rewrite>"; var expected = new List<IISUrlRewriteRule>(); expected.Add(CreateTestRule(new ConditionCollection(), url: "^article/([0-9]+)/([_0-9a-z-]+)", name: "Rewrite to article.aspx", actionType: ActionType.Rewrite, pattern: "article.aspx?id={R:1}&amp;title={R:2}")); // act var res = new UrlRewriteFileParser().Parse(new StringReader(xml), false); // assert AssertUrlRewriteRuleEquality(expected, res); } [Fact] public void RuleParse_ParseSingleRuleWithSingleCondition() { // arrange var xml = @"<rewrite> <rules> <rule name=""Rewrite to article.aspx""> <match url = ""^article/([0-9]+)/([_0-9a-z-]+)"" /> <conditions> <add input=""{HTTPS}"" pattern=""^OFF$"" /> </conditions> <action type=""Rewrite"" url =""article.aspx?id={R:1}&amp;title={R:2}"" /> </rule> </rules> </rewrite>"; var condList = new ConditionCollection(); condList.Add(new Condition(new InputParser().ParseInputString("{HTTPS}"), new RegexMatch(new Regex("^OFF$"), false))); var expected = new List<IISUrlRewriteRule>(); expected.Add(CreateTestRule(condList, url: "^article/([0-9]+)/([_0-9a-z-]+)", name: "Rewrite to article.aspx", actionType: ActionType.Rewrite, pattern: "article.aspx?id={R:1}&amp;title={R:2}")); // act var res = new UrlRewriteFileParser().Parse(new StringReader(xml), false); // assert AssertUrlRewriteRuleEquality(expected, res); } [Fact] public void RuleParse_ParseMultipleRules() { // arrange var xml = @"<rewrite> <rules> <rule name=""Rewrite to article.aspx""> <match url = ""^article/([0-9]+)/([_0-9a-z-]+)"" /> <conditions> <add input=""{HTTPS}"" pattern=""^OFF$"" /> </conditions> <action type=""Rewrite"" url =""article.aspx?id={R:1}&amp;title={R:2}"" /> </rule> <rule name=""Rewrite to another article.aspx""> <match url = ""^article/([0-9]+)/([_0-9a-z-]+)"" /> <conditions> <add input=""{HTTPS}"" pattern=""^OFF$"" /> </conditions> <action type=""Rewrite"" url =""article.aspx?id={R:1}&amp;title={R:2}"" /> </rule> </rules> </rewrite>"; var condList = new ConditionCollection(); condList.Add(new Condition(new InputParser().ParseInputString("{HTTPS}"), new RegexMatch(new Regex("^OFF$"), false))); var expected = new List<IISUrlRewriteRule>(); expected.Add(CreateTestRule(condList, url: "^article/([0-9]+)/([_0-9a-z-]+)", name: "Rewrite to article.aspx", actionType: ActionType.Rewrite, pattern: "article.aspx?id={R:1}&amp;title={R:2}")); expected.Add(CreateTestRule(condList, url: "^article/([0-9]+)/([_0-9a-z-]+)", name: "Rewrite to another article.aspx", actionType: ActionType.Rewrite, pattern: "article.aspx?id={R:1}&amp;title={R:2}")); // act var res = new UrlRewriteFileParser().Parse(new StringReader(xml), false); // assert AssertUrlRewriteRuleEquality(expected, res); } [Fact] public void Should_parse_global_rules() { // arrange var xml = @"<rewrite> <globalRules> <rule name=""httpsOnly"" patternSyntax=""ECMAScript"" stopProcessing=""true""> <match url="".*"" /> <conditions logicalGrouping=""MatchAll"" trackAllCaptures=""false""> <add input=""{HTTPS}"" pattern=""off"" /> </conditions> <action type=""Redirect"" url=""https://{HTTP_HOST}{REQUEST_URI}"" /> </rule> </globalRules> <rules> <rule name=""Rewrite to article.aspx""> <match url = ""^article/([0-9]+)/([_0-9a-z-]+)"" /> <action type=""Rewrite"" url =""article.aspx?id={R:1}&amp;title={R:2}"" /> </rule> </rules> </rewrite>"; // act var rules = new UrlRewriteFileParser().Parse(new StringReader(xml), false); // assert Assert.Equal(2, rules.Count); Assert.True(rules[0].Global); Assert.False(rules[1].Global); } [Fact] public void Should_skip_empty_conditions() { // arrange var xml = @"<rewrite> <rules> <rule name=""redirect-aspnet-mvc"" enabled=""true"" stopProcessing=""true""> <match url=""^aspnet/Mvc"" /> <conditions logicalGrouping=""MatchAll"" trackAllCaptures=""false"" /> <action type=""Redirect"" url=""https://github.com/dotnet/aspnetcore"" /> </rule> </rules> </rewrite>"; // act var rules = new UrlRewriteFileParser().Parse(new StringReader(xml), false); // assert Assert.Null(rules[0].Conditions); } // Creates a rule with appropriate default values of the url rewrite rule. private static IISUrlRewriteRule CreateTestRule(ConditionCollection conditions, string name = "", bool enabled = true, PatternSyntax patternSyntax = PatternSyntax.ECMAScript, bool stopProcessing = false, string url = "", bool ignoreCase = true, bool negate = false, ActionType actionType = ActionType.None, string pattern = "", bool appendQueryString = false, bool rewrittenUrl = false, bool global = false, UriMatchPart uriMatchPart = UriMatchPart.Path, RedirectType redirectType = RedirectType.Permanent ) { return new IISUrlRewriteRule( name, new RegexMatch(new Regex("^OFF$"), negate), conditions, new RewriteAction(RuleResult.ContinueRules, new InputParser().ParseInputString(url, uriMatchPart), queryStringAppend: false), global); } // TODO make rules comparable? private static void AssertUrlRewriteRuleEquality(IList<IISUrlRewriteRule> actual, IList<IISUrlRewriteRule> expected) { Assert.Equal(actual.Count, expected.Count); for (var i = 0; i < actual.Count; i++) { var r1 = actual[i]; var r2 = expected[i]; Assert.Equal(r1.Name, r2.Name); if (r1.Conditions == null) { Assert.Equal(0, r2.Conditions.Count); } else if (r2.Conditions == null) { Assert.Equal(0, r1.Conditions.Count); } else { Assert.Equal(r1.Conditions.Count, r2.Conditions.Count); for (var j = 0; j < r1.Conditions.Count; j++) { var c1 = r1.Conditions[j]; var c2 = r2.Conditions[j]; Assert.Equal(c1.Input.PatternSegments.Count, c2.Input.PatternSegments.Count); } } Assert.Equal(r1.Action.GetType(), r2.Action.GetType()); Assert.Equal(r1.InitialMatch.GetType(), r2.InitialMatch.GetType()); } } }
FileParserTests
csharp
duplicati__duplicati
LiveTests/Duplicati.Backend.Tests/JottaCloud/JottaCloudTests.cs
{ "start": 1286, "end": 2029 }
public sealed class ____ : BaseTest { [TestMethod] public Task TestJottaCloud() { CheckRequiredEnvironment(["TESTCREDENTIAL_JOTTACLOUD_AUTHID", "TESTCREDENTIAL_JOTTACLOUD_FOLDER"]); var exitCode = CommandLine.BackendTester.Program.Main( new[] { $"jottacloud://{Environment.GetEnvironmentVariable("TESTCREDENTIAL_JOTTACLOUD_FOLDER")}?authid={Uri.EscapeDataString(Environment.GetEnvironmentVariable("TESTCREDENTIAL_IDRIVEE2_ACCESS_KEY")!)}", }.Concat(Parameters.GlobalTestParameters).ToArray()); if (exitCode != 0) Assert.Fail("BackendTester is returning non-zero exit code, check logs for details"); return Task.CompletedTask; } }
JottaCloudTests
csharp
grandnode__grandnode2
src/Business/Grand.Business.Core/Interfaces/Marketing/Newsletters/INewsLetterSubscriptionService.cs
{ "start": 195, "end": 3176 }
public interface ____ { /// <summary> /// Inserts a newsletter subscription /// </summary> /// <param name="newsLetterSubscription">NewsLetter subscription</param> /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param> Task InsertNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true); /// <summary> /// Updates a newsletter subscription /// </summary> /// <param name="newsLetterSubscription">NewsLetter subscription</param> /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param> Task UpdateNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true); /// <summary> /// Deletes a newsletter subscription /// </summary> /// <param name="newsLetterSubscription">NewsLetter subscription</param> /// <param name="publishSubscriptionEvents">if set to <c>true</c> [publish subscription events].</param> Task DeleteNewsLetterSubscription(NewsLetterSubscription newsLetterSubscription, bool publishSubscriptionEvents = true); /// <summary> /// Gets a newsletter subscription by newsletter subscription identifier /// </summary> /// <param name="newsLetterSubscriptionId">The newsletter subscription identifier</param> /// <returns>NewsLetter subscription</returns> Task<NewsLetterSubscription> GetNewsLetterSubscriptionById(string newsLetterSubscriptionId); /// <summary> /// Gets a newsletter subscription by newsletter subscription GUID /// </summary> /// <param name="newsLetterSubscriptionGuid">The newsletter subscription GUID</param> /// <returns>NewsLetter subscription</returns> Task<NewsLetterSubscription> GetNewsLetterSubscriptionByGuid(Guid newsLetterSubscriptionGuid); /// <summary> /// Gets a newsletter subscription by email and store ID /// </summary> /// <param name="email">The newsletter subscription email</param> /// <param name="storeId">Store identifier</param> /// <returns>NewsLetter subscription</returns> Task<NewsLetterSubscription> GetNewsLetterSubscriptionByEmailAndStoreId(string email, string storeId); /// <summary> /// Gets a newsletter subscription by customerId /// </summary> /// <param name="customerId">Customer identifier</param> /// <returns>NewsLetter subscription</returns> Task<NewsLetterSubscription> GetNewsLetterSubscriptionByCustomerId(string customerId); /// <summary> /// Gets the newsletter subscription list /// </summary> /// <param name="email">Email to search or string. Empty to load all records.</param> /// <param name="storeId">Store identifier. "" to load all records.</param> /// <param name="isActive">Value indicating whether subscriber
INewsLetterSubscriptionService
csharp
nopSolutions__nopCommerce
src/Presentation/Nop.Web.Framework/Extensions/CommonExtensions.cs
{ "start": 204, "end": 1778 }
public static class ____ { /// <summary> /// Returns a value indicating whether real selection is not possible /// </summary> /// <param name="items">Items</param> /// <param name="ignoreZeroValue">A value indicating whether we should ignore items with "0" value</param> /// <returns>A value indicating whether real selection is not possible</returns> public static bool SelectionIsNotPossible(this IList<SelectListItem> items, bool ignoreZeroValue = true) { ArgumentNullException.ThrowIfNull(items); //we ignore items with "0" value? Usually it's something like "Select All", "etc return items.Count(x => !ignoreZeroValue || !x.Value.ToString().Equals("0")) < 2; } /// <summary> /// Relative formatting of DateTime (e.g. 2 hours ago, a month ago) /// </summary> /// <param name="source">Source (UTC format)</param> /// <param name="languageCode">Language culture code</param> /// <returns>Formatted date and time string</returns> public static string RelativeFormat(this DateTime source, string languageCode = "en-US") { var ts = new TimeSpan(DateTime.UtcNow.Ticks - source.Ticks); var delta = ts.TotalSeconds; CultureInfo culture; try { culture = new CultureInfo(languageCode); } catch (CultureNotFoundException) { culture = new CultureInfo("en-US"); } return TimeSpan.FromSeconds(delta).Humanize(precision: 1, culture: culture, maxUnit: TimeUnit.Year); } }
CommonExtensions
csharp
OrchardCMS__OrchardCore
src/OrchardCore.Modules/OrchardCore.Workflows/Deployment/AllWorkflowTypeDeploymentStep.cs
{ "start": 76, "end": 229 }
public class ____ : DeploymentStep { public AllWorkflowTypeDeploymentStep() { Name = "AllWorkflowType"; } }
AllWorkflowTypeDeploymentStep
csharp
icsharpcode__AvalonEdit
ICSharpCode.AvalonEdit/Snippets/SnippetReplaceableTextElement.cs
{ "start": 2136, "end": 2431 }
public interface ____ : IActiveElement { /// <summary> /// Gets the current text inside the element. /// </summary> string Text { get; } /// <summary> /// Occurs when the text inside the element changes. /// </summary> event EventHandler TextChanged; }
IReplaceableActiveElement
csharp
JoshClose__CsvHelper
tests/CsvHelper.Tests/Reading/ValidateTests.cs
{ "start": 4932, "end": 5166 }
private class ____ : ClassMap<Test> { public ValidationMessageMap() { Map(m => m.Id); Map(m => m.Name).Validate(args => args.Field == "foo", args => $"Field '{args.Field}' was not foo."); } } } }
ValidationMessageMap
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Serializers/KeyValuePairWrappedValueSerializer.cs
{ "start": 1309, "end": 2257 }
internal class ____<TKey, TValue> : SerializerBase<TValue>, IWrappedValueSerializer { private readonly IBsonSerializer<KeyValuePair<TKey, TValue>> _keyValuePairSerializer; private readonly IBsonSerializer<TValue> _valueSerializer; public KeyValuePairWrappedValueSerializer(IBsonSerializer<TKey> keySerializer, IBsonSerializer<TValue> valueSerializer) { _keyValuePairSerializer = (IBsonSerializer<KeyValuePair<TKey, TValue>>)KeyValuePairSerializer.Create(BsonType.Document, keySerializer, valueSerializer); _valueSerializer = valueSerializer; } public string FieldName => "v"; public IBsonSerializer ValueSerializer => _valueSerializer; public override TValue Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args) { var keyValuePair = _keyValuePairSerializer.Deserialize(context, args); return keyValuePair.Value; } }
KeyValuePairWrappedValueSerializer
csharp
dotnet__aspire
src/Tools/ConfigurationSchemaGenerator/RuntimeSource/Configuration.Binder/Specs/Types/CollectionSpec.cs
{ "start": 1053, "end": 1202 }
internal sealed record ____ : CollectionWithCtorInitSpec { public EnumerableSpec(ITypeSymbol type) : base(type) { } }
EnumerableSpec
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Styling/StyleChildren.cs
{ "start": 98, "end": 1056 }
internal class ____ : Collection<IStyle> { private readonly StyleBase _owner; public StyleChildren(StyleBase owner) => _owner = owner; protected override void InsertItem(int index, IStyle item) { (item as StyleBase)?.SetParent(_owner); base.InsertItem(index, item); } protected override void RemoveItem(int index) { var item = Items[index]; (item as StyleBase)?.SetParent(null); if (_owner.Owner is IResourceHost host) (item as IResourceProvider)?.RemoveOwner(host); base.RemoveItem(index); } protected override void SetItem(int index, IStyle item) { (item as StyleBase)?.SetParent(_owner); base.SetItem(index, item); if (_owner.Owner is IResourceHost host) (item as IResourceProvider)?.AddOwner(host); } } }
StyleChildren
csharp
smartstore__Smartstore
src/Smartstore.Core/Data/SmartDbContext.cs
{ "start": 716, "end": 4216 }
public partial class ____ : HookingDbContext { public SmartDbContext(DbContextOptions<SmartDbContext> options) : base(options) { } protected SmartDbContext(DbContextOptions options) : base(options) { } [SuppressMessage("Performance", "CA1822:Member can be static", Justification = "Seriously?")] public DbQuerySettings QuerySettings { get => EngineContext.Current.Scope.ResolveOptional<DbQuerySettings>() ?? DbQuerySettings.Default; } protected override void OnConfiguring(DbContextOptionsBuilder builder) { // For installation only: // The connection string may change during installation attempts. // Refresh the connection string in the underlying factory in that case. if (!builder.IsConfigured || DataSettings.DatabaseIsInstalled()) { return; } var attemptedConString = DataSettings.Instance.ConnectionString; if (attemptedConString.IsEmpty()) { return; } var extension = builder.Options.FindExtension<DbFactoryOptionsExtension>(); if (extension == null) { return; } var currentConString = extension.ConnectionString; var currentCollation = extension.Collation; var attemptedCollation = DataSettings.Instance.Collation; if (currentConString == null) { // No database creation attempt yet ChangeConnectionString(attemptedConString, attemptedCollation); } else { // At least one database creation attempt if (attemptedConString != currentConString || attemptedCollation != currentCollation) { // ConString changed. Refresh! ChangeConnectionString(attemptedConString, attemptedCollation); } DataSettings.Instance.DbFactory?.ConfigureDbContext(builder, attemptedConString); } void ChangeConnectionString(string conString, string collation) { extension.ConnectionString = conString; extension.Collation = collation.NullEmpty(); ((IDbContextOptionsBuilderInfrastructure)builder).AddOrUpdateExtension(extension); } } protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder) { DataSettings.Instance.DbFactory?.ConfigureModelConventions(configurationBuilder); base.ConfigureConventions(configurationBuilder); } protected override void OnModelCreating(ModelBuilder modelBuilder) { DataSettings.Instance.DbFactory?.CreateModel(modelBuilder); var options = Options.FindExtension<DbFactoryOptionsExtension>(); if (options.DefaultSchema.HasValue()) { modelBuilder.HasDefaultSchema(options.DefaultSchema); } if (options.Collation.HasValue()) { modelBuilder.UseCollation(options.Collation); } CreateModel(modelBuilder, options.ModelAssemblies); base.OnModelCreating(modelBuilder); } } }
SmartDbContext
csharp
dotnet__efcore
test/EFCore.Specification.Tests/TestModels/ManyToManyFieldsModel/ProxyableSharedType.cs
{ "start": 233, "end": 523 }
public class ____ { private readonly Dictionary<string, object> _keyValueStore = new(); public virtual object this[string key] { get => _keyValueStore.TryGetValue(key, out var value) ? value : default; set => _keyValueStore[key] = value; } }
ProxyableSharedType
csharp
ServiceStack__ServiceStack
ServiceStack/tests/CheckWebCore/Startup.cs
{ "start": 9318, "end": 9512 }
public enum ____ { [EnumMember(Value = "No ne")] None = 0, [EnumMember(Value = "Template")] Template = 1, [EnumMember(Value = "Rule")] Rule = 3, }
EnumMemberTest
csharp
abpframework__abp
framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/AspNetCoreApiDescriptionModelProvider.cs
{ "start": 708, "end": 14119 }
public class ____ : IApiDescriptionModelProvider, ITransientDependency { public ILogger<AspNetCoreApiDescriptionModelProvider> Logger { get; set; } private readonly AspNetCoreApiDescriptionModelProviderOptions _options; private readonly IApiDescriptionGroupCollectionProvider _descriptionProvider; private readonly AbpAspNetCoreMvcOptions _abpAspNetCoreMvcOptions; private readonly AbpApiDescriptionModelOptions _modelOptions; public AspNetCoreApiDescriptionModelProvider( IOptions<AspNetCoreApiDescriptionModelProviderOptions> options, IApiDescriptionGroupCollectionProvider descriptionProvider, IOptions<AbpAspNetCoreMvcOptions> abpAspNetCoreMvcOptions, IOptions<AbpApiDescriptionModelOptions> modelOptions) { _options = options.Value; _descriptionProvider = descriptionProvider; _abpAspNetCoreMvcOptions = abpAspNetCoreMvcOptions.Value; _modelOptions = modelOptions.Value; Logger = NullLogger<AspNetCoreApiDescriptionModelProvider>.Instance; } public ApplicationApiDescriptionModel CreateApiModel(ApplicationApiDescriptionModelRequestDto input) { //TODO: Can cache the model? var model = ApplicationApiDescriptionModel.Create(); foreach (var descriptionGroupItem in _descriptionProvider.ApiDescriptionGroups.Items) { foreach (var apiDescription in descriptionGroupItem.Items) { if (!apiDescription.ActionDescriptor.IsControllerAction()) { continue; } AddApiDescriptionToModel(apiDescription, model, input); } } foreach (var (_, module) in model.Modules) { var controllers = module.Controllers.GroupBy(x => x.Value.Type).ToList(); foreach (var controller in controllers.Where(x => x.Count() > 1)) { var removedController = module.Controllers.RemoveAll(x => x.Value.IsRemoteService && controller.OrderBy(c => c.Value.ControllerGroupName).Skip(1).Contains(x)); foreach (var removed in removedController) { Logger.LogInformation($"The controller named '{removed.Value.Type}' was removed from ApplicationApiDescriptionModel because it same with other controller."); } } } model.NormalizeOrder(); return model; } private void AddApiDescriptionToModel( ApiDescription apiDescription, ApplicationApiDescriptionModel applicationModel, ApplicationApiDescriptionModelRequestDto input) { var controllerType = apiDescription .ActionDescriptor .AsControllerActionDescriptor() .ControllerTypeInfo; var setting = FindSetting(controllerType); var moduleModel = applicationModel.GetOrAddModule( GetRootPath(controllerType, apiDescription.ActionDescriptor, setting), GetRemoteServiceName(controllerType, setting) ); var controllerModel = moduleModel.GetOrAddController( _options.ControllerNameGenerator(controllerType, setting), FindGroupName(controllerType) ?? apiDescription.GroupName, apiDescription.IsRemoteService(), apiDescription.IsIntegrationService(), apiDescription.GetProperty<ApiVersion>()?.ToString(), controllerType, _modelOptions.IgnoredInterfaces ); var method = apiDescription.ActionDescriptor.GetMethodInfo(); var uniqueMethodName = _options.ActionNameGenerator(method); if (controllerModel.Actions.ContainsKey(uniqueMethodName)) { Logger.LogWarning( $"Controller '{controllerModel.ControllerName}' contains more than one action with name '{uniqueMethodName}' for module '{moduleModel.RootPath}'. Ignored: " + method); return; } Logger.LogDebug($"ActionApiDescriptionModel.Create: {controllerModel.ControllerName}.{uniqueMethodName}"); bool? allowAnonymous = null; if (apiDescription.ActionDescriptor.EndpointMetadata.Any(x => x is IAllowAnonymous)) { allowAnonymous = true; } else if (apiDescription.ActionDescriptor.EndpointMetadata.Any(x => x is IAuthorizeData)) { allowAnonymous = false; } var implementFrom = controllerType.FullName; var interfaceType = controllerType.GetInterfaces().FirstOrDefault(i => i.GetMethods().Any(x => x.ToString() == method.ToString())); if (interfaceType != null) { implementFrom = TypeHelper.GetFullNameHandlingNullableAndGenerics(interfaceType); } var actionModel = controllerModel.AddAction( uniqueMethodName, ActionApiDescriptionModel.Create( uniqueMethodName, method, apiDescription.RelativePath!, apiDescription.HttpMethod, GetSupportedVersions(controllerType, method, setting), allowAnonymous, implementFrom ) ); if (input.IncludeTypes) { AddCustomTypesToModel(applicationModel, method); } AddParameterDescriptionsToModel(actionModel, method, apiDescription); } private static List<string> GetSupportedVersions(Type controllerType, MethodInfo method, ConventionalControllerSetting? setting) { var supportedVersions = new List<ApiVersion>(); var mapToAttributes = method.GetCustomAttributes<MapToApiVersionAttribute>().ToArray(); if (mapToAttributes.Any()) { supportedVersions.AddRange( mapToAttributes.SelectMany(a => a.Versions) ); } else { supportedVersions.AddRange( controllerType.GetCustomAttributes<ApiVersionAttribute>().SelectMany(a => a.Versions) ); setting?.ApiVersions.ForEach(supportedVersions.Add); } return supportedVersions.Select(v => v.ToString()).Distinct().ToList(); } private void AddCustomTypesToModel(ApplicationApiDescriptionModel applicationModel, MethodInfo method) { foreach (var parameterInfo in method.GetParameters()) { AddCustomTypesToModel(applicationModel, parameterInfo.ParameterType); } AddCustomTypesToModel(applicationModel, method.ReturnType); } private static void AddCustomTypesToModel(ApplicationApiDescriptionModel applicationModel, Type? type) { if (type == null) { return; } if (type.IsGenericParameter) { return; } type = AsyncHelper.UnwrapTask(type); if (type == typeof(object) || type == typeof(void) || type == typeof(Enum) || type == typeof(ValueType) || type == typeof(DateOnly) || type == typeof(TimeOnly) || TypeHelper.IsPrimitiveExtended(type)) { return; } if (TypeHelper.IsDictionary(type, out var keyType, out var valueType)) { AddCustomTypesToModel(applicationModel, keyType); AddCustomTypesToModel(applicationModel, valueType); return; } if (TypeHelper.IsEnumerable(type, out var itemType)) { AddCustomTypesToModel(applicationModel, itemType); return; } if (type.IsGenericType && !type.IsGenericTypeDefinition) { var genericTypeDefinition = type.GetGenericTypeDefinition(); AddCustomTypesToModel(applicationModel, genericTypeDefinition); foreach (var genericArgument in type.GetGenericArguments()) { AddCustomTypesToModel(applicationModel, genericArgument); } return; } var typeName = CalculateTypeName(type); if (applicationModel.Types.ContainsKey(typeName)) { return; } applicationModel.Types[typeName] = TypeApiDescriptionModel.Create(type); AddCustomTypesToModel(applicationModel, type.BaseType); foreach (var propertyInfo in type.GetProperties().Where(p => p.DeclaringType == type)) { AddCustomTypesToModel(applicationModel, propertyInfo.PropertyType); } } private static string CalculateTypeName(Type type) { if (!type.IsGenericTypeDefinition) { return TypeHelper.GetFullNameHandlingNullableAndGenerics(type); } var i = 0; var argumentList = type .GetGenericArguments() .Select(_ => "T" + i++) .JoinAsString(","); return $"{type.FullName!.Left(type.FullName!.IndexOf('`'))}<{argumentList}>"; } private void AddParameterDescriptionsToModel(ActionApiDescriptionModel actionModel, MethodInfo method, ApiDescription apiDescription) { if (!apiDescription.ParameterDescriptions.Any()) { return; } var parameterDescriptionNames = apiDescription .ParameterDescriptions .Select(p => p.Name) .ToArray(); var methodParameterNames = method .GetParameters() .Where(IsNotFromServicesParameter) .Select(GetMethodParamName) .ToArray(); var matchedMethodParamNames = ArrayMatcher.Match( parameterDescriptionNames, methodParameterNames ); for (var i = 0; i < apiDescription.ParameterDescriptions.Count; i++) { var parameterDescription = apiDescription.ParameterDescriptions[i]; var matchedMethodParamName = matchedMethodParamNames.Length > i ? matchedMethodParamNames[i] : parameterDescription.Name; actionModel.AddParameter(ParameterApiDescriptionModel.Create( parameterDescription.Name, _options.ApiParameterNameGenerator?.Invoke(parameterDescription), matchedMethodParamName, parameterDescription.Type, parameterDescription.RouteInfo?.IsOptional ?? false, parameterDescription.RouteInfo?.DefaultValue, parameterDescription.RouteInfo?.Constraints?.Select(c => c.GetType().Name).ToArray(), parameterDescription.Source.Id, parameterDescription.ModelMetadata?.ContainerType != null ? parameterDescription.ParameterDescriptor?.Name ?? string.Empty : string.Empty ) ); } } private static bool IsNotFromServicesParameter(ParameterInfo parameterInfo) { return !parameterInfo.IsDefined(typeof(FromServicesAttribute), true); } public string GetMethodParamName(ParameterInfo parameterInfo) { var modelNameProvider = parameterInfo.GetCustomAttributes() .OfType<IModelNameProvider>() .FirstOrDefault(); if (modelNameProvider == null) { return parameterInfo.Name!; } return (modelNameProvider.Name ?? parameterInfo.Name)!; } private static string GetRootPath( [NotNull] Type controllerType, [NotNull] ActionDescriptor actionDescriptor, ConventionalControllerSetting? setting) { if (setting != null) { return setting.RootPath; } var areaAttr = controllerType.GetCustomAttributes().OfType<AreaAttribute>().FirstOrDefault() ?? actionDescriptor.EndpointMetadata.OfType<AreaAttribute>().FirstOrDefault(); if (areaAttr != null) { return areaAttr.RouteValue; } return ModuleApiDescriptionModel.DefaultRootPath; } private string GetRemoteServiceName(Type controllerType, ConventionalControllerSetting? setting) { if (setting != null) { return setting.RemoteServiceName; } var remoteServiceAttr = controllerType.GetCustomAttributes().OfType<RemoteServiceAttribute>().FirstOrDefault(); if (remoteServiceAttr?.Name != null) { return remoteServiceAttr.Name; } return ModuleApiDescriptionModel.DefaultRemoteServiceName; } private string? FindGroupName(Type controllerType) { var controllerNameAttribute = controllerType.GetCustomAttributes().OfType<ControllerNameAttribute>().FirstOrDefault(); if (controllerNameAttribute?.Name != null) { return controllerNameAttribute.Name; } return null; } private ConventionalControllerSetting? FindSetting(Type controllerType) { foreach (var controllerSetting in _abpAspNetCoreMvcOptions.ConventionalControllers.ConventionalControllerSettings) { if (controllerSetting.ControllerTypes.Contains(controllerType)) { return controllerSetting; } } return null; } }
AspNetCoreApiDescriptionModelProvider
csharp
dotnet__aspnetcore
src/Framework/AspNetCoreAnalyzers/test/Mvc/DetectAmbiguousActionRoutesTest.cs
{ "start": 16429, "end": 16830 }
internal class ____ { static void Main(string[] args) { } } "; // Act & Assert await VerifyCS.VerifyAnalyzerAsync(source); } [Fact] public async Task SameRoutes_SameAction_HostAttribute_HasDiagnostics() { // Arrange var source = @" using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing;
Program
csharp
ChilliCream__graphql-platform
src/HotChocolate/Core/test/Types.Analyzers.Tests/PagingTests.cs
{ "start": 48693, "end": 49124 }
partial class ____ { public static Task<AuthorConnection> GetAuthorsAsync( GreenDonut.Data.PagingArguments pagingArgs, CancellationToken cancellationToken) => default!; } } namespace TestNamespace { [Inaccessible(scoped: true)]
AuthorQueries
csharp
mysql-net__MySqlConnector
src/MySqlConnector/MySqlLoadBalance.cs
{ "start": 27, "end": 602 }
public enum ____ { /// <summary> /// Each new connection opened for a connection pool uses the next host name (sequentially with wraparound). /// </summary> RoundRobin, /// <summary> /// Each new connection tries to connect to the first host; subsequent hosts are used only if connecting to the first one fails. /// </summary> FailOver, /// <summary> /// Servers are tried in random order. /// </summary> Random, /// <summary> /// Servers are tried in ascending order of number of currently-open connections. /// </summary> LeastConnections, }
MySqlLoadBalance
csharp
grandnode__grandnode2
src/Tests/Grand.Business.Messages.Tests/Services/MimeMappingServiceTests.cs
{ "start": 197, "end": 1002 }
public class ____ { private MimeMappingService _service; [TestInitialize] public void Init() { _service = new MimeMappingService(new FileExtensionContentTypeProvider()); } [TestMethod] public void Map_ReturnExpectedValue() { Assert.AreEqual("text/plain", _service.Map("file.txt")); Assert.AreEqual("video/x-msvideo", _service.Map("file.avi")); Assert.AreEqual("application/vnd.microsoft.portable-executable", _service.Map("file.exe")); Assert.AreEqual("image/jpeg", _service.Map("file.jpg")); Assert.AreEqual("image/gif", _service.Map("file.gif")); Assert.AreEqual("image/png", _service.Map("file.png")); Assert.AreEqual("application/octet-stream", _service.Map("file.wirdtype")); } }
MimeMappingServiceTests
csharp
JamesNK__Newtonsoft.Json
Src/Newtonsoft.Json.Tests/TestObjects/MailAddressReadConverter.cs
{ "start": 1301, "end": 2573 }
public class ____ : JsonConverter { public override bool CanConvert(Type objectType) { return objectType == typeof(System.Net.Mail.MailAddress); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { var messageJObject = serializer.Deserialize<JObject>(reader); if (messageJObject == null) { return null; } var address = messageJObject.GetValue("Address", StringComparison.OrdinalIgnoreCase).ToObject<string>(); JToken displayNameToken; string displayName; if (messageJObject.TryGetValue("DisplayName", StringComparison.OrdinalIgnoreCase, out displayNameToken) && !string.IsNullOrEmpty(displayName = displayNameToken.ToObject<string>())) { return new System.Net.Mail.MailAddress(address, displayName); } return new System.Net.Mail.MailAddress(address); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } } #endif }
MailAddressReadConverter
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/PolymorphicFault_Specs.cs
{ "start": 3430, "end": 3592 }
public interface ____ : IMyMessageInterface { string Message { get; } } [ExcludeFromTopology]
IMyGeneralMessageInterface
csharp
NLog__NLog
src/NLog/LayoutRenderers/ProcessIdLayoutRenderer.cs
{ "start": 2207, "end": 3206 }
public class ____ : LayoutRenderer, IRawValue { private readonly int _processId; /// <summary> /// Initializes a new instance of the <see cref="ProcessIdLayoutRenderer" /> class. /// </summary> public ProcessIdLayoutRenderer() : this(LogFactory.DefaultAppEnvironment) { } /// <summary> /// Initializes a new instance of the <see cref="ProcessIdLayoutRenderer" /> class. /// </summary> internal ProcessIdLayoutRenderer(IAppEnvironment appEnvironment) { _processId = appEnvironment.CurrentProcessId; } /// <inheritdoc/> protected override void Append(StringBuilder builder, LogEventInfo logEvent) { builder.AppendInvariant(_processId); } bool IRawValue.TryGetRawValue(LogEventInfo logEvent, out object value) { value = _processId; return true; } } }
ProcessIdLayoutRenderer
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Utilities/AsyncEnumerableHelper.cs
{ "start": 759, "end": 1577 }
private sealed class ____<T> : IAsyncEnumerator<T> { private readonly IEnumerator<T> _enumerator; private readonly CancellationToken _cancellationToken; public EnumeratorAsyncWrapper(IEnumerator<T> enumerator, CancellationToken cancellationToken) { _enumerator = enumerator; _cancellationToken = cancellationToken; } public T Current => _enumerator.Current; public ValueTask<bool> MoveNextAsync() => _cancellationToken.IsCancellationRequested ? new(Task.FromCanceled<bool>(_cancellationToken)) : new(_enumerator.MoveNext()); public ValueTask DisposeAsync() { _enumerator.Dispose(); return default; } } }
EnumeratorAsyncWrapper
csharp
dotnet__maui
src/Controls/src/Core/Interactivity/PlatformBehavior.cs
{ "start": 720, "end": 3467 }
partial class ____<TView, TPlatformView> : Behavior<TView> where TView : Element where TPlatformView : class { TPlatformView? _platformView; /// <inheritdoc /> protected sealed override void OnAttachedTo(BindableObject bindable) { base.OnAttachedTo(bindable); } /// <inheritdoc /> protected sealed override void OnDetachingFrom(BindableObject bindable) { base.OnDetachingFrom(bindable); } /// <inheritdoc /> protected sealed override void OnAttachedTo(TView bindable) { if (bindable is VisualElement ve) { ve.Loaded += OnLoaded; ve.Unloaded += OnUnloaded; } else { if (bindable.Handler != null) FireAttachedTo(bindable); bindable.HandlerChanged += OnHandlerChanged; } } /// <inheritdoc /> protected sealed override void OnDetachingFrom(TView bindable) { if (bindable is VisualElement ve) { ve.Loaded -= OnLoaded; ve.Unloaded -= OnUnloaded; } else { bindable.HandlerChanged -= OnHandlerChanged; } FireDetachedFrom(bindable); } void FireAttachedTo(TView bindable) { if (bindable?.Handler?.PlatformView is TPlatformView platformView) { _platformView = platformView; OnAttachedTo(bindable, platformView); } } void FireDetachedFrom(TView bindable) { if (_platformView != null) { OnDetachedFrom(bindable, _platformView); _platformView = null; } } void OnUnloaded(object? sender, EventArgs e) { if (sender is TView view) { FireDetachedFrom(view); } } void OnLoaded(object? sender, EventArgs e) { if (sender is TView view && view.Handler.PlatformView is TPlatformView platformView) { OnAttachedTo(view, platformView); _platformView = platformView; } } void OnHandlerChanged(object? sender, EventArgs e) { if (sender is not TView visualElement) return; if (visualElement.Handler is not null) FireAttachedTo(visualElement); else FireDetachedFrom(visualElement); } /// <summary> /// This method is called when the bindable is attached to the platform view hierarchy. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> /// <param name="platformView">The platform control connected to the bindable object.</param> protected virtual void OnAttachedTo(TView bindable, TPlatformView platformView) { } /// <summary> /// This method is called when the bindable is detached from the platform view hierarchy. /// </summary> /// <param name="bindable">The bindable object to which the behavior was attached.</param> /// <param name="platformView">The platform control connected to the bindable object.</param> protected virtual void OnDetachedFrom(TView bindable, TPlatformView platformView) { } } /// <summary> /// Base
PlatformBehavior
csharp
dotnet__aspnetcore
src/Mvc/test/Mvc.FunctionalTests/GlobalAuthorizationFilterEndpointRoutingTest.cs
{ "start": 268, "end": 581 }
public class ____ : GlobalAuthorizationFilterTestBase<SecurityWebSite.StartupWithGlobalDenyAnonymousFilter> { public override void ConfigureWebHostBuilder(IWebHostBuilder builder) => builder.UseStartup<SecurityWebSite.StartupWithGlobalDenyAnonymousFilter>(); }
GlobalAuthorizationFilterEndpointRoutingTest
csharp
dotnetcore__FreeSql
Extensions/FreeSql.Extensions.ZeroEntity/Models/SchemaValidationException.cs
{ "start": 69, "end": 211 }
public class ____ : Exception { public SchemaValidationException(string message) : base(message) { } } }
SchemaValidationException
csharp
microsoft__garnet
playground/Embedded.perftest/PerformanceTestLoggerProvider.cs
{ "start": 943, "end": 3372 }
private class ____ : ILogger { private readonly string categoryName; private readonly TextWriter textWriter; public PerformanceTestLogger(string categoryName, TextWriter textWriter) { this.categoryName = categoryName; this.textWriter = textWriter; } public IDisposable BeginScope<TState>(TState state) => default!; public bool IsEnabled(LogLevel logLevel) => true; private static string GetLevelStr(LogLevel ll) => lvl[(int)ll]; /// <summary> /// Specify the log message given the information /// </summary> /// <typeparam name="TState"></typeparam> /// <param name="logLevel"></param> /// <param name="eventId"></param> /// <param name="state"></param> /// <param name="exception"></param> /// <param name="formatter"></param> [MethodImpl(MethodImplOptions.AggressiveInlining)] public void Log<TState>( LogLevel logLevel, EventId eventId, TState state, Exception exception, Func<TState, Exception, string> formatter) { string msg = logLevel switch { LogLevel.Information => string.Format("[{0:D3}.{1}.({2})] |{3}| {4}\n", eventId.Id, DateTime.Now.ToString("hh:mm:ss"), GetLevelStr(logLevel), categoryName, state), _ => string.Format("[{0:D3}.{1}.({2})] |{3}| <{4}> {5}\n", eventId.Id, DateTime.Now.ToString("hh:mm:ss"), GetLevelStr(logLevel), categoryName, exception, state), }; textWriter.Write(msg); } } } }
PerformanceTestLogger
csharp
smartstore__Smartstore
src/Smartstore.Core/Checkout/Permissions.Checkout.cs
{ "start": 2248, "end": 2646 }
public static class ____ { public const string Self = "configuration.paymentmethod"; public const string Read = "configuration.paymentmethod.read"; public const string Update = "configuration.paymentmethod.update"; public const string Activate = "configuration.paymentmethod.activate"; }
PaymentMethod
csharp
AvaloniaUI__Avalonia
src/Linux/Avalonia.LinuxFramebuffer/Input/LibInput/LibInputNativeUnsafeMethods.cs
{ "start": 5007, "end": 7099 }
public enum ____ { LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL = 0, LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL = 1, }; [DllImport(LibInput)] public extern static void libinput_event_destroy(IntPtr ev); [DllImport(LibInput)] public extern static IntPtr libinput_event_get_touch_event(IntPtr ev); [DllImport(LibInput)] public extern static int libinput_event_touch_get_slot(IntPtr ev); [DllImport(LibInput)] public extern static ulong libinput_event_touch_get_time_usec(IntPtr ev); [DllImport(LibInput)] public extern static double libinput_event_touch_get_x_transformed(IntPtr ev, int width); [DllImport(LibInput)] public extern static double libinput_event_touch_get_y_transformed(IntPtr ev, int height); [DllImport(LibInput)] public extern static IntPtr libinput_event_get_pointer_event(IntPtr ev); [DllImport(LibInput)] public extern static ulong libinput_event_pointer_get_time_usec(IntPtr ev); [DllImport(LibInput)] public extern static double libinput_event_pointer_get_absolute_x_transformed(IntPtr ev, int width); [DllImport(LibInput)] public extern static double libinput_event_pointer_get_absolute_y_transformed(IntPtr ev, int height); [DllImport(LibInput)] public extern static int libinput_event_pointer_get_button(IntPtr ev); [DllImport(LibInput)] public extern static int libinput_event_pointer_get_button_state(IntPtr ev); [DllImport(LibInput)] public extern static LibInputPointerAxisSource libinput_event_pointer_get_axis_source(IntPtr ev); [DllImport((LibInput))] public extern static double libinput_event_pointer_get_axis_value_discrete(IntPtr ev, LibInputPointerAxis axis); [DllImport(LibInput)] public extern static double libinput_event_pointer_get_scroll_value_v120(IntPtr ev, LibInputPointerAxis axis); } }
LibInputPointerAxis
csharp
microsoft__PowerToys
src/modules/AdvancedPaste/AdvancedPaste/AdvancedPasteXAML/Pages/MainPage.xaml.cs
{ "start": 713, "end": 8240 }
partial class ____ : Page { private readonly ObservableCollection<ClipboardItem> clipboardHistory; private readonly Microsoft.UI.Dispatching.DispatcherQueue _dispatcherQueue = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); private (VirtualKey Key, DateTime Timestamp) _lastKeyEvent = (VirtualKey.None, DateTime.MinValue); public OptionsViewModel ViewModel { get; private set; } public MainPage() { this.InitializeComponent(); ViewModel = App.GetService<OptionsViewModel>(); clipboardHistory = new ObservableCollection<ClipboardItem>(); LoadClipboardHistoryEvent(null, null); Clipboard.HistoryChanged += LoadClipboardHistoryEvent; } private void LoadClipboardHistoryEvent(object sender, object e) { Task.Run(() => { LoadClipboardHistoryAsync(); }); } public async void LoadClipboardHistoryAsync() { try { Logger.LogTrace(); List<ClipboardItem> items = new(); if (Clipboard.IsHistoryEnabled()) { var historyItems = await Clipboard.GetHistoryItemsAsync(); if (historyItems.Status == ClipboardHistoryItemsResultStatus.Success) { foreach (var item in historyItems.Items) { if (item.Content.Contains(StandardDataFormats.Text)) { string text = await item.Content.GetTextAsync(); items.Add(new ClipboardItem { Content = text, Format = ClipboardFormat.Text, Timestamp = item.Timestamp, Item = item, }); } else if (item.Content.Contains(StandardDataFormats.Bitmap)) { items.Add(new ClipboardItem { Format = ClipboardFormat.Image, Timestamp = item.Timestamp, Item = item, }); } } } } _dispatcherQueue.TryEnqueue(async () => { // Clear to avoid leaks due to Garbage Collection not clearing the bitmap from memory. Fix for https://github.com/microsoft/PowerToys/issues/33423 clipboardHistory.Where(x => x.Image is not null) .ToList() .ForEach(x => x.Image.ClearValue(BitmapImage.UriSourceProperty)); clipboardHistory.Clear(); foreach (var item in items) { if (item.Item.Content.Contains(StandardDataFormats.Bitmap)) { IRandomAccessStreamReference imageReceived = null; imageReceived = await item.Item.Content.GetBitmapAsync(); if (imageReceived != null) { using (var imageStream = await imageReceived.OpenReadAsync()) { var bitmapImage = new BitmapImage(); bitmapImage.SetSource(imageStream); item.Image = bitmapImage; } } } clipboardHistory.Add(item); } }); } catch (Exception ex) { Logger.LogError("Loading clipboard history failed", ex); } } private static MainWindow GetMainWindow() => (App.Current as App)?.GetMainWindow(); private void ClipboardHistoryItemDeleteButton_Click(object sender, RoutedEventArgs e) { Logger.LogTrace(); if (sender is MenuFlyoutItem btn) { ClipboardItem item = btn.CommandParameter as ClipboardItem; Clipboard.DeleteItemFromHistory(item.Item); clipboardHistory.Remove(item); PowerToysTelemetry.Log.WriteEvent(new Telemetry.AdvancedPasteClipboardItemDeletedEvent()); } } private async void PasteFormat_ItemClick(object sender, ItemClickEventArgs e) { if (e.ClickedItem is PasteFormat format) { await ViewModel.ExecutePasteFormatAsync(format, PasteActionSource.ContextMenu); } } private async void KeyboardAccelerator_Invoked(Microsoft.UI.Xaml.Input.KeyboardAccelerator sender, Microsoft.UI.Xaml.Input.KeyboardAcceleratorInvokedEventArgs args) { if (GetMainWindow()?.Visible is false) { return; } Logger.LogTrace(); var thisKeyEvent = (sender.Key, Timestamp: DateTime.Now); if (thisKeyEvent.Key == _lastKeyEvent.Key && (thisKeyEvent.Timestamp - _lastKeyEvent.Timestamp) < TimeSpan.FromMilliseconds(200)) { // Sometimes, multiple keyboard accelerator events are raised for a single Ctrl + VirtualKey press. return; } _lastKeyEvent = thisKeyEvent; switch (sender.Key) { case VirtualKey.Escape: GetMainWindow()?.Close(); break; case VirtualKey.Number1: case VirtualKey.Number2: case VirtualKey.Number3: case VirtualKey.Number4: case VirtualKey.Number5: case VirtualKey.Number6: case VirtualKey.Number7: case VirtualKey.Number8: case VirtualKey.Number9: await ViewModel.ExecutePasteFormatAsync(sender.Key); break; default: break; } } private void Page_KeyDown(object sender, Microsoft.UI.Xaml.Input.KeyRoutedEventArgs e) { if (e.Key == VirtualKey.Escape) { GetMainWindow()?.Close(); } } private async void ClipboardHistory_ItemInvoked(ItemsView sender, ItemsViewItemInvokedEventArgs args) { if (args.InvokedItem is ClipboardItem item) { PowerToysTelemetry.Log.WriteEvent(new Telemetry.AdvancedPasteClipboardItemClicked()); if (!string.IsNullOrEmpty(item.Content)) { ClipboardHelper.SetTextContent(item.Content); } else if (item.Image is not null) { RandomAccessStreamReference image = await item.Item.Content.GetBitmapAsync(); ClipboardHelper.SetImageContent(image); } } } } }
MainPage
csharp
dotnet__maui
src/Controls/src/Core/Items/GroupableItemsView.cs
{ "start": 215, "end": 1963 }
public class ____ : SelectableItemsView { /// <summary>Bindable property for <see cref="IsGrouped"/>.</summary> public static readonly BindableProperty IsGroupedProperty = BindableProperty.Create(nameof(IsGrouped), typeof(bool), typeof(GroupableItemsView), false); /// <include file="../../../docs/Microsoft.Maui.Controls/GroupableItemsView.xml" path="//Member[@MemberName='IsGrouped']/Docs/*" /> public bool IsGrouped { get => (bool)GetValue(IsGroupedProperty); set => SetValue(IsGroupedProperty, value); } /// <summary>Bindable property for <see cref="GroupHeaderTemplate"/>.</summary> public static readonly BindableProperty GroupHeaderTemplateProperty = BindableProperty.Create(nameof(GroupHeaderTemplate), typeof(DataTemplate), typeof(GroupableItemsView), default(DataTemplate)); /// <include file="../../../docs/Microsoft.Maui.Controls/GroupableItemsView.xml" path="//Member[@MemberName='GroupHeaderTemplate']/Docs/*" /> public DataTemplate GroupHeaderTemplate { get => (DataTemplate)GetValue(GroupHeaderTemplateProperty); set => SetValue(GroupHeaderTemplateProperty, value); } /// <summary>Bindable property for <see cref="GroupFooterTemplate"/>.</summary> public static readonly BindableProperty GroupFooterTemplateProperty = BindableProperty.Create(nameof(GroupFooterTemplate), typeof(DataTemplate), typeof(GroupableItemsView), default(DataTemplate)); /// <include file="../../../docs/Microsoft.Maui.Controls/GroupableItemsView.xml" path="//Member[@MemberName='GroupFooterTemplate']/Docs/*" /> public DataTemplate GroupFooterTemplate { get => (DataTemplate)GetValue(GroupFooterTemplateProperty); set => SetValue(GroupFooterTemplateProperty, value); } } }
GroupableItemsView
csharp
ChilliCream__graphql-platform
src/HotChocolate/Data/test/Data.EntityFramework.Tests/Query.cs
{ "start": 3071, "end": 4099 }
public class ____ { public ValueTask<IQueryable<Author>> GetAuthors( BookContext context) => new(context.Authors); [UseOffsetPaging(IncludeTotalCount = true)] [UseFiltering] [UseSorting] public ValueTask<IQueryable<Author>> GetAuthorOffsetPaging( BookContext context) => new(context.Authors); [UseOffsetPaging(IncludeTotalCount = true)] [UseFiltering] [UseSorting] public ValueTask<IExecutable<Author>> GetAuthorOffsetPagingExecutable( BookContext context) => new(context.Authors.AsDbContextExecutable()); [UsePaging(IncludeTotalCount = true)] [UseFiltering] [UseSorting] public ValueTask<IExecutable<Author>> GetAuthorCursorPagingExecutable( BookContext context) => new(context.Authors.AsDbContextExecutable()); [UsePaging(IncludeTotalCount = true)] public ValueTask<IQueryable<Author>> GetAuthorCursorPaging( BookContext context) => new(context.Authors.AsQueryable()); }
QueryValueTask
csharp
dotnet__aspire
tests/Aspire.Hosting.Tests/Orchestrator/ApplicationOrchestratorTests.cs
{ "start": 21972, "end": 22044 }
private sealed class ____(string name) : Resource(name);
CustomResource
csharp
dotnet__maui
src/Controls/tests/TestCases.HostApp/Elements/CollectionView/GroupingGalleries/ViewModel.cs
{ "start": 117, "end": 338 }
class ____ : List<Member> { public Team(string name, List<Member> members) : base(members) { Name = name; } public string Name { get; set; } public override string ToString() { return Name; } }
Team
csharp
moq__moq4
src/Moq.Tests/CaptureFixture.cs
{ "start": 2964, "end": 3148 }
public interface ____ { void DoSomething(string s); void DoSomething(int i, string s); void DoSomething(string s, int i); } } }
IFoo
csharp
protobuf-net__protobuf-net
assorted/SilverlightExtended/Nuxleus.Extension/ExtensionMethods.cs
{ "start": 555, "end": 1761 }
class ____ I have the time. /// </summary> /// <param name="source"></param> /// <param name="value"></param> /// <returns></returns> public static string SubstringAfter(this string source, string value) { if (string.IsNullOrEmpty(value)) { return source; } CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo; int index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal); if (index < 0) { //No such substring return string.Empty; } return source.Substring(index + value.Length); } public static string SubstringBefore(this string source, string value) { if (string.IsNullOrEmpty(value)) { return value; } CompareInfo compareInfo = CultureInfo.InvariantCulture.CompareInfo; int index = compareInfo.IndexOf(source, value, CompareOptions.Ordinal); if (index < 0) { //No such substring return string.Empty; } return source.Substring(0, index); } } }
once
csharp
OrchardCMS__OrchardCore
src/OrchardCore/OrchardCore.Abstractions/Shell/Scope/ShellScopeServices.cs
{ "start": 239, "end": 848 }
public class ____(IServiceProvider services) : IKeyedServiceProvider { private readonly IServiceProvider _services = services; private IServiceProvider Services => ShellScope.Services ?? _services; public object GetKeyedService(Type serviceType, object serviceKey) => Services.GetKeyedService(serviceType, serviceKey); public object GetRequiredKeyedService(Type serviceType, object serviceKey) => Services.GetRequiredKeyedService(serviceType, serviceKey); public object GetService(Type serviceType) => Services?.GetService(serviceType); }
ShellScopeServices
csharp
mongodb__mongo-csharp-driver
src/MongoDB.Bson/Serialization/BsonSerializer.cs
{ "start": 1102, "end": 1193 }
static class ____ represents the BSON serialization functionality. /// </summary>
that
csharp
jellyfin__jellyfin
src/Jellyfin.Database/Jellyfin.Database.Implementations/Enums/MediaSegmentType.cs
{ "start": 218, "end": 700 }
public enum ____ { /// <summary> /// Default media type or custom one. /// </summary> Unknown = 0, /// <summary> /// Commercial. /// </summary> Commercial = 1, /// <summary> /// Preview. /// </summary> Preview = 2, /// <summary> /// Recap. /// </summary> Recap = 3, /// <summary> /// Outro. /// </summary> Outro = 4, /// <summary> /// Intro. /// </summary> Intro = 5 }
MediaSegmentType
csharp
louthy__language-ext
LanguageExt.Core/Immutable Collections/TrackingHashMap/TrackingHashMap.Module.Eq.cs
{ "start": 217, "end": 27334 }
partial class ____ { /// <summary> /// Creates a singleton TrackingHashMap /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> singleton<EqK, K, V>((K, V) value) where EqK : Eq<K> => [value]; /// <summary> /// Creates a singleton TrackingHashMap /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> singleton<EqK, K, V>(K key, V value) where EqK : Eq<K> => [(key, value)]; /// <summary> /// Creates a new empty TrackingHashMap /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> empty<EqK, K, V>() where EqK : Eq<K> => TrackingHashMap<EqK, K, V>.Empty; /// <summary> /// Creates a new empty TrackingHashMap /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> create<EqK, K, V>() where EqK : Eq<K> => TrackingHashMap<EqK, K, V>.Empty; /// <summary> /// Creates a new Map seeded with the keyValues provided /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> create<EqK, K, V>(Tuple<K, V> head, params Tuple<K, V>[] tail) where EqK : Eq<K> => empty<EqK, K, V>().AddRange(head.Cons(tail)); /// <summary> /// Creates a new Map seeded with the keyValues provided /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> create<EqK, K, V>((K, V) head, params (K, V)[] tail) where EqK : Eq<K> => empty<EqK, K, V>().AddRange(head.Cons(tail)); /// <summary> /// Creates a new Map seeded with the keyValues provided /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> create<EqK, K, V>(KeyValuePair<K, V> head, params KeyValuePair<K,V>[] tail) where EqK : Eq<K> => empty<EqK, K, V>().AddRange(head.Cons(tail)); /// <summary> /// Creates a new Map seeded with the keyValues provided /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> createRange<EqK, K, V>(IEnumerable<Tuple<K, V>> keyValues) where EqK : Eq<K> => empty<EqK, K, V>().AddRange(keyValues); /// <summary> /// Creates a new Map seeded with the keyValues provided /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> createRange<EqK, K, V>(IEnumerable<(K, V)> keyValues) where EqK : Eq<K> => new (keyValues); /// <summary> /// Creates a new Map seeded with the keyValues provided /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> createRange<EqK, K, V>(ReadOnlySpan<(K, V)> keyValues) where EqK : Eq<K> => keyValues.IsEmpty ? TrackingHashMap<EqK, K, V>.Empty : new(keyValues); /// <summary> /// Creates a new Map seeded with the keyValues provided /// </summary> [Pure] public static TrackingHashMap<EqK, K, V> createRange<EqK, K, V>(IEnumerable<KeyValuePair<K, V>> keyValues) where EqK : Eq<K> => empty<EqK, K, V>().AddRange(keyValues); /// <summary> /// Atomically adds a new item to the map /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <exception cref="ArgumentException">Throws ArgumentException if the key already exists</exception> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the key or value are null</exception> /// <returns>New Map with the item added</returns> [Pure] public static TrackingHashMap<EqK, K, V> add<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, V value) where EqK : Eq<K> => map.Add(key, value); /// <summary> /// Atomically adds a new item to the map. /// If the key already exists, then the new item is ignored /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the key or value are null</exception> /// <returns>New Map with the item added</returns> [Pure] public static TrackingHashMap<EqK, K, V> tryAdd<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, V value) where EqK : Eq<K> => map.TryAdd(key, value); /// <summary> /// Atomically adds a new item to the map. /// If the key already exists, the new item replaces it. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the key or value are null</exception> /// <returns>New Map with the item added</returns> [Pure] public static TrackingHashMap<EqK, K, V> addOrUpdate<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, V value) where EqK : Eq<K> => map.AddOrUpdate(key, value); /// <summary> /// Retrieve a value from the map by key, map it to a new value, /// put it back. If it doesn't exist, add a new one based on None result. /// </summary> /// <param name="key">Key to find</param> /// <exception cref="Exception">Throws Exception if None returns null</exception> /// <exception cref="Exception">Throws Exception if Some returns null</exception> /// <returns>New map with the mapped value</returns> [Pure] public static TrackingHashMap<EqK, K, V> addOrUpdate<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, Func<V, V> Some, Func<V> None) where EqK : Eq<K> => map.AddOrUpdate(key, Some, None); /// <summary> /// Retrieve a value from the map by key, map it to a new value, /// put it back. If it doesn't exist, add a new one based on None result. /// </summary> /// <param name="key">Key to find</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException if None is null</exception> /// <exception cref="Exception">Throws Exception if Some returns null</exception> /// <returns>New map with the mapped value</returns> [Pure] public static TrackingHashMap<EqK, K, V> addOrUpdate<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, Func<V, V> Some, V None) where EqK : Eq<K> => map.AddOrUpdate(key, Some, None); /// <summary> /// Atomically adds a range of items to the map. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="range">Range of tuples to add</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys already exist</exception> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the keys or values are null</exception> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> addRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<Tuple<K, V>> keyValues) where EqK : Eq<K> => map.AddRange(keyValues); /// <summary> /// Atomically adds a range of items to the map. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="range">Range of tuples to add</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys already exist</exception> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the keys or values are null</exception> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> addRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<(K, V)> keyValues) where EqK : Eq<K> => map.AddRange(keyValues); /// <summary> /// Atomically adds a range of items to the map. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="range">Range of tuples to add</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys already exist</exception> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the keys or values are null</exception> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> addRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<KeyValuePair<K, V>> keyValues) where EqK : Eq<K> => map.AddRange(keyValues); /// <summary> /// Atomically adds a range of items to the map. If any of the keys exist already /// then they're ignored. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="range">Range of tuples to add</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the keys or values are null</exception> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> tryAddRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<Tuple<K, V>> keyValues) where EqK : Eq<K> => map.TryAddRange(keyValues); /// <summary> /// Atomically adds a range of items to the map. If any of the keys exist already /// then they're ignored. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="range">Range of tuples to add</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the keys or values are null</exception> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> tryAddRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<(K, V)> keyValues) where EqK : Eq<K> => map.TryAddRange(keyValues); /// <summary> /// Atomically adds a range of items to the map. If any of the keys exist already /// then they're ignored. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="range">Range of KeyValuePairs to add</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the keys or values are null</exception> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> tryAddRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<KeyValuePair<K, V>> keyValues) where EqK : Eq<K> => map.TryAddRange(keyValues); /// <summary> /// Atomically adds a range of items to the map. If any of the keys exist already /// then they're replaced. /// </summary> /// <param name="range">Range of tuples to add</param> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> addOrUpdateRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<Tuple<K, V>> range) where EqK : Eq<K> => map.AddOrUpdateRange(range); /// <summary> /// Atomically adds a range of items to the map. If any of the keys exist already /// then they're replaced. /// </summary> /// <param name="range">Range of tuples to add</param> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> addOrUpdateRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<(K, V)> range) where EqK : Eq<K> => map.AddOrUpdateRange(range); /// <summary> /// Atomically adds a range of items to the map. If any of the keys exist already /// then they're replaced. /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="range">Range of KeyValuePairs to add</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the keys or values are null</exception> /// <returns>New Map with the items added</returns> [Pure] public static TrackingHashMap<EqK, K, V> addOrUpdateRange<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<KeyValuePair<K, V>> range) where EqK : Eq<K> => map.AddOrUpdateRange(range); /// <summary> /// Atomically removes an item from the map /// If the key doesn't exists, the request is ignored. /// </summary> /// <param name="key">Key</param> /// <returns>New map with the item removed</returns> [Pure] public static TrackingHashMap<EqK, K, V> remove<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key) where EqK : Eq<K> => map.Remove(key); /// <summary> /// Checks for existence of a key in the map /// </summary> /// <param name="key">Key to check</param> /// <returns>True if an item with the key supplied is in the map</returns> [Pure] public static bool containsKey<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key) where EqK : Eq<K> => map.ContainsKey(key); /// <summary> /// Checks for existence of a key in the map /// </summary> /// <param name="key">Key to check</param> /// <returns>True if an item with the key supplied is in the map</returns> [Pure] public static bool contains<EqK, K, V>(TrackingHashMap<EqK, K, V> map, KeyValuePair<K, V> kv) where EqK : Eq<K> => map.Contains(kv.Key, kv.Value); /// <summary> /// Checks for existence of a key in the map /// </summary> /// <param name="key">Key to check</param> /// <returns>True if an item with the key supplied is in the map</returns> [Pure] public static bool contains<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Tuple<K, V> kv) where EqK : Eq<K> => map.Contains(kv.Item1, kv.Item2); /// <summary> /// Checks for existence of a key in the map /// </summary> /// <param name="key">Key to check</param> /// <returns>True if an item with the key supplied is in the map</returns> [Pure] public static bool contains<EqK, K, V>(TrackingHashMap<EqK, K, V> map, (K, V) kv) where EqK : Eq<K> => map.Contains(kv.Item1, kv.Item2); /// <summary> /// Atomically updates an existing item /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the key or value are null</exception> /// <returns>New Map with the item added</returns> [Pure] public static TrackingHashMap<EqK, K, V> setItem<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, V value) where EqK : Eq<K> => map.SetItem(key, value); /// <summary> /// Atomically updates an existing item, unless it doesn't exist, in which case /// it is ignored /// </summary> /// <remarks>Null is not allowed for a Key or a Value</remarks> /// <param name="key">Key</param> /// <param name="value">Value</param> /// <exception cref="ArgumentNullException">Throws ArgumentNullException the value is null</exception> /// <returns>New Map with the item added</returns> [Pure] public static TrackingHashMap<EqK, K, V> trySetItem<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, V value) where EqK : Eq<K> => map.TrySetItem(key, value); /// <summary> /// Atomically sets an item by first retrieving it, applying a map (Some), and then putting /// it back. Silently fails if the value doesn't exist. /// </summary> /// <param name="key">Key to set</param> /// <exception cref="Exception">Throws Exception if Some returns null</exception> /// <param name="Some">delegate to map the existing value to a new one before setting</param> /// <returns>New map with the item set</returns> [Pure] public static TrackingHashMap<EqK, K, V> trySetItem<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, Func<V, V> Some) where EqK : Eq<K> => map.TrySetItem(key, Some); /// <summary> /// Atomically sets a series of items using the Tuples provided /// </summary> /// <param name="items">Items to set</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys aren't in the map</exception> /// <returns>New map with the items set</returns> [Pure] public static TrackingHashMap<EqK, K, V> setItems<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<Tuple<K, V>> items) where EqK : Eq<K> => map.SetItems(items); /// <summary> /// Atomically sets a series of items using the Tuples provided /// </summary> /// <param name="items">Items to set</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys aren't in the map</exception> /// <returns>New map with the items set</returns> [Pure] public static TrackingHashMap<EqK, K, V> setItems<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<(K, V)> items) where EqK : Eq<K> => map.SetItems(items); /// <summary> /// Atomically sets a series of items using the KeyValuePairs provided /// </summary> /// <param name="items">Items to set</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys aren't in the map</exception> /// <returns>New map with the items set</returns> [Pure] public static TrackingHashMap<EqK, K, V> setItems<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<KeyValuePair<K, V>> items) where EqK : Eq<K> => map.SetItems(items); /// <summary> /// Atomically sets a series of items using the Tuples provided. /// </summary> /// <param name="items">Items to set</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys aren't in the map</exception> /// <returns>New map with the items set</returns> [Pure] public static TrackingHashMap<EqK, K, V> trySetItems<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<Tuple<K, V>> items) where EqK : Eq<K> => map.SetItems(items); /// <summary> /// Atomically sets a series of items using the Tuples provided. /// </summary> /// <param name="items">Items to set</param> /// <exception cref="ArgumentException">Throws ArgumentException if any of the keys aren't in the map</exception> /// <returns>New map with the items set</returns> [Pure] public static TrackingHashMap<EqK, K, V> trySetItems<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<(K, V)> items) where EqK : Eq<K> => map.SetItems(items); /// <summary> /// Atomically sets a series of items using the KeyValuePairs provided. If any of the /// items don't exist then they're silently ignored. /// </summary> /// <param name="items">Items to set</param> /// <returns>New map with the items set</returns> [Pure] public static TrackingHashMap<EqK, K, V> trySetItems<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<KeyValuePair<K, V>> items) where EqK : Eq<K> => map.TrySetItems(items); /// <summary> /// Atomically sets a series of items using the keys provided to find the items /// and the Some delegate maps to a new value. If the items don't exist then /// they're silently ignored. /// </summary> /// <param name="keys">Keys of items to set</param> /// <param name="Some">Function map the existing item to a new one</param> /// <returns>New map with the items set</returns> [Pure] public static TrackingHashMap<EqK, K, V> trySetItems<EqK, K, V>(TrackingHashMap<EqK, K, V> map, IEnumerable<K> keys, Func<V, V> Some) where EqK : Eq<K> => map.TrySetItems(keys, Some); /// <summary> /// Retrieve a value from the map by key /// </summary> /// <param name="key">Key to find</param> /// <returns>Found value</returns> [Pure] public static Option<V> find<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key) where EqK : Eq<K> => map.Find(key); /// <summary> /// Retrieve a value from the map by key as an enumerable /// </summary> /// <param name="key">Key to find</param> /// <returns>Found value</returns> [Pure] public static IEnumerable<V> findSeq<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key) where EqK : Eq<K> => map.FindSeq(key); /// <summary> /// Retrieve a value from the map by key and pattern match the /// result. /// </summary> /// <param name="key">Key to find</param> /// <returns>Found value</returns> [Pure] public static R find<EqK, K, V, R>(TrackingHashMap<EqK, K, V> map, K key, Func<V, R> Some, Func<R> None) where EqK : Eq<K> => map.Find(key, Some, None); /// <summary> /// Retrieve a value from the map by key, map it to a new value, /// put it back. /// </summary> /// <param name="key">Key to find</param> /// <returns>New map with the mapped value</returns> [Pure] public static TrackingHashMap<EqK, K, V> setItem<EqK, K, V>(TrackingHashMap<EqK, K, V> map, K key, Func<V, V> mapper) where EqK : Eq<K> => map.SetItem(key, mapper); /// <summary> /// Atomically iterate through all key/value pairs in the map (in order) and execute an /// action on each /// </summary> /// <param name="action">Action to execute</param> /// <returns>Unit</returns> public static Unit iter<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Action<V> action) where EqK : Eq<K> => map.Iter(action); /// <summary> /// Atomically iterate through all key/value pairs in the map (in order) and execute an /// action on each /// </summary> /// <param name="action">Action to execute</param> /// <returns>Unit</returns> public static Unit iter<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Action<K, V> action) where EqK : Eq<K> => map.Iter(action); /// <summary> /// Return true if all items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool forall<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<V, bool> pred) where EqK : Eq<K> => map.ForAll(pred); /// <summary> /// Return true if all items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool forall<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<K, V, bool> pred) where EqK : Eq<K> => map.ForAll(pred); /// <summary> /// Return true if all items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool forall<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<(K Key, V Value), bool> pred) where EqK : Eq<K> => map.ForAll(pred); /// <summary> /// Return true if all items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool forall<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<KeyValuePair<K, V>, bool> pred) where EqK : Eq<K> => map.ForAll(pred); /// <summary> /// Atomically filter out items that return false when a predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>New map with items filtered</returns> [Pure] public static TrackingHashMap<EqK, K, V> filter<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<V, bool> predicate) where EqK : Eq<K> => map.Filter(predicate); /// <summary> /// Atomically filter out items that return false when a predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>New map with items filtered</returns> [Pure] public static TrackingHashMap<EqK, K, V> filter<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<K, V, bool> predicate) where EqK : Eq<K> => map.Filter(predicate); /// <summary> /// Number of items in the map /// </summary> [Pure] public static int length<EqK, K, T>(TrackingHashMap<EqK, K, T> map) where EqK : Eq<K> => map.Count; /// <summary> /// Atomically folds all items in the map (in order) using the folder function provided. /// </summary> /// <typeparam name="S">State type</typeparam> /// <param name="state">Initial state</param> /// <param name="folder">Fold function</param> /// <returns>Folded state</returns> [Pure] public static S fold<EqK, S, K, V>(TrackingHashMap<EqK, K, V> map, S state, Func<S, K, V, S> folder) where EqK : Eq<K> => map.Fold(state, folder); /// <summary> /// Atomically folds all items in the map (in order) using the folder function provided. /// </summary> /// <typeparam name="S">State type</typeparam> /// <param name="state">Initial state</param> /// <param name="folder">Fold function</param> /// <returns>Folded state</returns> [Pure] public static S fold<EqK, S, K, V>(TrackingHashMap<EqK, K, V> map, S state, Func<S, V, S> folder) where EqK : Eq<K> => map.Fold(state, folder); /// <summary> /// Return true if *any* items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool exists<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<K, V, bool> pred) where EqK : Eq<K> => map.Exists(pred); /// <summary> /// Return true if *any* items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool exists<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<(K Key, V Value), bool> pred) where EqK : Eq<K> => map.Exists(pred); /// <summary> /// Return true if *any* items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool exists<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<KeyValuePair<K, V>, bool> pred) where EqK : Eq<K> => map.Exists(pred); /// <summary> /// Return true if *any* items in the map return true when the predicate is applied /// </summary> /// <param name="pred">Predicate</param> /// <returns>True if all items in the map return true when the predicate is applied</returns> [Pure] public static bool exists<EqK, K, V>(TrackingHashMap<EqK, K, V> map, Func<V, bool> pred) where EqK : Eq<K> => map.Exists(pred); }
TrackingHashMap
csharp
Xabaril__AspNetCore.Diagnostics.HealthChecks
src/HealthChecks.Rabbitmq/RabbitMQHealthCheck.cs
{ "start": 182, "end": 1400 }
public class ____ : IHealthCheck { private readonly IConnection? _connection; private readonly IServiceProvider? _serviceProvider; private readonly Func<IServiceProvider, Task<IConnection>>? _factory; public RabbitMQHealthCheck(IConnection connection) { _connection = Guard.ThrowIfNull(connection); } public RabbitMQHealthCheck(IServiceProvider serviceProvider, Func<IServiceProvider, Task<IConnection>> factory) { _serviceProvider = Guard.ThrowIfNull(serviceProvider); _factory = Guard.ThrowIfNull(factory); } /// <inheritdoc /> public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default) { try { var connection = _connection ?? await _factory!(_serviceProvider!).ConfigureAwait(false); await using var model = await connection.CreateChannelAsync(cancellationToken: cancellationToken).ConfigureAwait(false); return HealthCheckResult.Healthy(); } catch (Exception ex) { return new HealthCheckResult(context.Registration.FailureStatus, exception: ex); } } }
RabbitMQHealthCheck
csharp
mongodb__mongo-csharp-driver
tests/MongoDB.Driver.Tests/Linq/Linq3Implementation/Translators/ExpressionToAggregationExpressionTranslators/MethodTranslators/ConvertMethodToAggregationExpressionTranslatorTests.cs
{ "start": 24855, "end": 26979 }
public sealed class ____ : MongoCollectionFixture<TestClass, BsonDocument> { protected override IEnumerable<BsonDocument> InitialData => [ BsonDocument.Parse("{ _id : 0 }"), BsonDocument.Parse("{ _id : 1, BinaryProperty : BinData(0, 'ogIAAA==') }"), BsonDocument.Parse("{ _id : 2, BinaryProperty : BinData(4, 'hn3uUsMxSE6S0cVkebjmfg=='), StringProperty: '867dee52-c331-484e-92d1-c56479b8e67e' }"), BsonDocument.Parse("{ _id : 3, BinaryProperty : BinData(0, 'AAAAAAAA4L8='), DoubleProperty: -0.5, NullableDoubleProperty: -0.5 }"), // LittleEndian BsonDocument.Parse("{ _id : 4, BinaryProperty : BinData(0, 'ogIAAA=='), IntProperty: 674, LongProperty: NumberLong('674'), NullableIntProperty: 674, NullableLongProperty: NumberLong('674') }"), // LittleEndian BsonDocument.Parse("{ _id : 5, BinaryProperty : BinData(0, 'wAQAAAAAAAA='), DoubleProperty: -2.5, NullableDoubleProperty: -2.5 }"), // BigEndian BsonDocument.Parse("{ _id : 6, BinaryProperty : BinData(0, 'AAAAKg=='), IntProperty: 42, LongProperty: NumberLong('42'), NullableIntProperty: 42, NullableLongProperty: NumberLong('42') }"), // BigEndian BsonDocument.Parse("{ _id: 10, DoubleProperty: NumberDecimal('-32768'), IntProperty: NumberDecimal('-32768'), LongProperty: NumberDecimal('-32768'), " + "NullableDoubleProperty: NumberDecimal('-32768'), NullableIntProperty: NumberDecimal('-32768'), NullableLongProperty: NumberDecimal('-32768'), StringProperty: NumberDecimal('-233') }"), // Invalid conversions BsonDocument.Parse("{ _id : 20, StringProperty: 'inValidInt', IntProperty: 22 }"), BsonDocument.Parse("{ _id : 21, StringProperty: '15' }"), BsonDocument.Parse("{ _id : 22, IntProperty: 33 }"), BsonDocument.Parse("{ _id : 23, StringProperty: '2018-03-03' }"), BsonDocument.Parse("{ _id : 24, StringProperty: '5ab9cbfa31c2ab715d42129e' }"), ]; }
ClassFixture
csharp
AvaloniaUI__Avalonia
src/Windows/Avalonia.Win32/DComposition/DirectCompositionConnection.cs
{ "start": 427, "end": 4187 }
internal class ____ : IRenderTimer, IWindowsSurfaceFactory { private static readonly Guid IID_IDCompositionDesktopDevice = Guid.Parse("5f4633fe-1e08-4cb8-8c75-ce24333f5602"); public event Action<TimeSpan>? Tick; public bool RunsInBackground => true; private readonly DirectCompositionShared _shared; public DirectCompositionConnection(DirectCompositionShared shared) { _shared = shared; } private static bool TryCreateAndRegisterCore() { var tcs = new TaskCompletionSource<bool>(); var th = new Thread(() => { DirectCompositionConnection connect; try { var result = NativeMethods.DCompositionCreateDevice2(default, IID_IDCompositionDesktopDevice, out var cDevice); if (result != UnmanagedMethods.HRESULT.S_OK) { throw new Win32Exception((int)result); } using (var device = MicroComRuntime.CreateProxyFor<IDCompositionDesktopDevice>(cDevice, false)) { var shared = new DirectCompositionShared(device); connect = new DirectCompositionConnection(shared); } AvaloniaLocator.CurrentMutable.Bind<IWindowsSurfaceFactory>().ToConstant(connect); AvaloniaLocator.CurrentMutable.Bind<IRenderTimer>().ToConstant(connect); tcs.SetResult(true); } catch (Exception e) { tcs.SetException(e); return; } connect.RunLoop(); }) { IsBackground = true, Name = "DwmRenderTimerLoop" }; th.SetApartmentState(ApartmentState.STA); th.Start(); return tcs.Task.Result; } private void RunLoop() { var cts = new CancellationTokenSource(); AppDomain.CurrentDomain.ProcessExit += (_, _) => cts.Cancel(); var _stopwatch = Stopwatch.StartNew(); var device = _shared.Device.CloneReference(); while (!cts.IsCancellationRequested) { try { device.WaitForCommitCompletion(); Tick?.Invoke(_stopwatch.Elapsed); } catch (Exception ex) { Logger.TryGet(LogEventLevel.Error, LogArea.Win32Platform) ?.Log(this, $"Failed to wait for vblank, Exception: {ex.Message}, HRESULT = {ex.HResult}"); } } device?.Dispose(); } public static bool IsSupported() { return Win32Platform.WindowsVersion >= PlatformConstants.Windows8_1; } public static bool TryCreateAndRegister() { if (IsSupported()) { try { TryCreateAndRegisterCore(); return true; } catch (Exception e) { Logger.TryGet(LogEventLevel.Error, LogArea.Win32Platform) ?.Log(null, "Unable to initialize WinUI compositor: {0}", e); } } else { var osVersionNotice = $"Windows {PlatformConstants.Windows8_1} is required. Your machine has Windows {Win32Platform.WindowsVersion} installed."; Logger.TryGet(LogEventLevel.Warning, LogArea.Win32Platform)?.Log(null, $"Unable to initialize WinUI compositor: {osVersionNotice}"); } return false; } public bool RequiresNoRedirectionBitmap => true; public object CreateSurface(EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo info) => new DirectCompositedWindowSurface(_shared, info); }
DirectCompositionConnection
csharp
MapsterMapper__Mapster
src/Mapster.Core/Attributes/BaseAdaptAttribute.cs
{ "start": 2563, "end": 2753 }
public class ____ : BaseAdaptAttribute { public AdaptToAttribute(Type type) : base(type) { } public AdaptToAttribute(string name) : base(name) { } }
AdaptToAttribute
csharp
dotnet__reactive
Rx.NET/Source/src/System.Reactive/Linq/Observable/Timeout.cs
{ "start": 1174, "end": 4851 }
internal sealed class ____ : IdentitySink<TSource> { private readonly TimeSpan _dueTime; private readonly IObservable<TSource> _other; private readonly IScheduler _scheduler; private long _index; private SingleAssignmentDisposableValue _mainDisposable; private SingleAssignmentDisposableValue _otherDisposable; private IDisposable? _timerDisposable; public _(Relative parent, IObserver<TSource> observer) : base(observer) { _dueTime = parent._dueTime; _other = parent._other; _scheduler = parent._scheduler; } public override void Run(IObservable<TSource> source) { CreateTimer(0L); _mainDisposable.Disposable = source.SubscribeSafe(this); } protected override void Dispose(bool disposing) { if (disposing) { _mainDisposable.Dispose(); _otherDisposable.Dispose(); Disposable.Dispose(ref _timerDisposable); } base.Dispose(disposing); } private void CreateTimer(long idx) { if (Disposable.TrySetMultiple(ref _timerDisposable, null)) { var d = _scheduler.ScheduleAction((idx, instance: this), _dueTime, static state => { state.instance.Timeout(state.idx); }); Disposable.TrySetMultiple(ref _timerDisposable, d); } } private void Timeout(long idx) { if (Volatile.Read(ref _index) == idx && Interlocked.CompareExchange(ref _index, long.MaxValue, idx) == idx) { _mainDisposable.Dispose(); var d = _other.Subscribe(GetForwarder()); _otherDisposable.Disposable = d; } } public override void OnNext(TSource value) { var idx = Volatile.Read(ref _index); if (idx != long.MaxValue && Interlocked.CompareExchange(ref _index, idx + 1, idx) == idx) { // Do not swap in the BooleanDisposable.True here // As we'll need _timerDisposable to store the next timer // BD.True would cancel it immediately and break the operation Volatile.Read(ref _timerDisposable)?.Dispose(); ForwardOnNext(value); CreateTimer(idx + 1); } } public override void OnError(Exception error) { if (Interlocked.Exchange(ref _index, long.MaxValue) != long.MaxValue) { Disposable.Dispose(ref _timerDisposable); ForwardOnError(error); } } public override void OnCompleted() { if (Interlocked.Exchange(ref _index, long.MaxValue) != long.MaxValue) { Disposable.Dispose(ref _timerDisposable); ForwardOnCompleted(); } } } }
_
csharp
MassTransit__MassTransit
src/Persistence/MassTransit.MongoDbIntegration/MongoDbIntegration/NoSessionMongoDbCollectionContext.cs
{ "start": 154, "end": 1799 }
public class ____<T> : MongoDbCollectionContext<T> { static readonly InsertOneOptions _options = new InsertOneOptions(); readonly IMongoCollection<T> _collection; public NoSessionMongoDbCollectionContext(IMongoCollection<T> collection) { _collection = collection; } public IMongoCollection<T> Collection => _collection; public Task InsertOne(T instance, CancellationToken cancellationToken) { return _collection.InsertOneAsync(instance, _options, cancellationToken); } public Task<T> FindOneAndReplace(FilterDefinition<T> filter, T instance, CancellationToken cancellationToken) { return _collection.FindOneAndReplaceAsync(filter, instance, null, cancellationToken); } public Task<DeleteResult> DeleteOne(FilterDefinition<T> filter, CancellationToken cancellationToken) { return _collection.DeleteOneAsync(filter, null, cancellationToken); } public Task<DeleteResult> DeleteMany(FilterDefinition<T> filter, CancellationToken cancellationToken) { return _collection.DeleteManyAsync(filter, null, cancellationToken); } public IFindFluent<T, T> Find(FilterDefinition<T> filter) { return _collection.Find(filter); } public Task<T> Lock(FilterDefinition<T> filter, UpdateDefinition<T> update, CancellationToken cancellationToken) { return _collection.FindOneAndUpdateAsync(filter, update, null, cancellationToken); } } }
NoSessionMongoDbCollectionContext
csharp
dotnet__BenchmarkDotNet
tests/BenchmarkDotNet.Tests/Detectors/Cpu/PowershellWmiCpuInfoParserTests.cs
{ "start": 159, "end": 3536 }
public class ____(ITestOutputHelper output) { private ITestOutputHelper Output { get; } = output; [Fact] public void EmptyTest() { CpuInfo? actual = PowershellWmiCpuInfoParser.Parse(string.Empty); CpuInfo expected = new CpuInfo(); Output.AssertEqual(expected, actual); } [Fact] public void MalformedTest() { CpuInfo? actual = PowershellWmiCpuInfoParser .Parse("malformedkey=malformedvalue\n\nmalformedkey2=malformedvalue2"); CpuInfo expected = new CpuInfo(); Output.AssertEqual(expected, actual); } [Fact] public void RealTwoProcessorEightCoresTest() { const string cpuInfo = """ MaxClockSpeed:2400 Name:Intel(R) Xeon(R) CPU E5-2630 v3 NumberOfCores:8 NumberOfLogicalProcessors:16 MaxClockSpeed:2400 Name:Intel(R) Xeon(R) CPU E5-2630 v3 NumberOfCores:8 NumberOfLogicalProcessors:16 """; CpuInfo? actual = PowershellWmiCpuInfoParser.Parse(cpuInfo); CpuInfo expected = new CpuInfo { ProcessorName = "Intel(R) Xeon(R) CPU E5-2630 v3", PhysicalProcessorCount = 2, PhysicalCoreCount = 16, LogicalCoreCount = 32, NominalFrequencyHz = 2_400_000_000, MaxFrequencyHz = 2_400_000_000, }; Output.AssertEqual(expected, actual); } [Fact] public void RealTwoProcessorEightCoresWithWmicBugTest() { const string cpuInfo = "\r\r\n" + "\r\r\n" + "MaxClockSpeed:3111\r\r\n" + "Name:Intel(R) Xeon(R) CPU E5-2687W 0\r\r\n" + "NumberOfCores:8\r\r\n" + "NumberOfLogicalProcessors:16\r\r\n" + "\r\r\n" + "\r\r\n" + "MaxClockSpeed:3111\r\r\n" + "Name:Intel(R) Xeon(R) CPU E5-2687W 0\r\r\n" + "NumberOfCores:8\r\r\n" + "NumberOfLogicalProcessors:16\r\r\n" + "\r\r\n" + "\r\r\n" + "\r\r\n"; CpuInfo? actual = PowershellWmiCpuInfoParser.Parse(cpuInfo); CpuInfo expected = new CpuInfo { ProcessorName = "Intel(R) Xeon(R) CPU E5-2687W 0", PhysicalProcessorCount = 2, PhysicalCoreCount = 16, LogicalCoreCount = 32, NominalFrequencyHz = 3_111_000_000, MaxFrequencyHz = 3_111_000_000, }; Output.AssertEqual(expected, actual); } [Fact] public void RealOneProcessorFourCoresTest() { const string cpuInfo = """ MaxClockSpeed:2500 Name:Intel(R) Core(TM) i7-4710MQ NumberOfCores:4 NumberOfLogicalProcessors:8 """; CpuInfo? actual = PowershellWmiCpuInfoParser.Parse(cpuInfo); CpuInfo expected = new CpuInfo { ProcessorName = "Intel(R) Core(TM) i7-4710MQ", PhysicalProcessorCount = 1, PhysicalCoreCount = 4, LogicalCoreCount = 8, NominalFrequencyHz = 2_500_000_000, MaxFrequencyHz = 2_500_000_000, }; Output.AssertEqual(expected, actual); } }
PowershellWmiCpuInfoParserTests
csharp
MassTransit__MassTransit
tests/MassTransit.Tests/SagaStateMachineTests/Automatonymous/Visualizer2_Specs.cs
{ "start": 689, "end": 2442 }
public class ____ : MassTransitStateMachine<IngestState> { public SampleStateMachine() { InstanceState(x => x.CurrentState); Request(() => ProcessGetInventory, x => x.InventoryRequestId); Event(() => SubmitOrderEvent, e => { e.CorrelateById(context => context.Message.OrderId); e.InsertOnInitial = true; e.SetSagaFactory(context => new IngestState() { OrderId = context.Message.OrderId, OrderReceivedAt = DateTime.UtcNow }); }); Initially( When(SubmitOrderEvent) .Request(ProcessGetInventory, context => context.Init<ReadInventory>(new { Id = context.Saga.OrderId })) .TransitionTo(ProcessGetInventory.Pending) ); During(ProcessGetInventory.Pending, When(ProcessGetInventory.Completed) .TransitionTo(Completed), When(ProcessGetInventory.TimeoutExpired) .TransitionTo(TimeOutError), When(ProcessGetInventory.Faulted) .TransitionTo(FatalError)); } public State Completed { get; set; } public State FatalError { get; set; } public State TimeOutError { get; set; } public Event<SubmitOrder> SubmitOrderEvent { get; set; } public Request<IngestState, ReadInventory, ReadInventoryResponse> ProcessGetInventory { get; set; } }
SampleStateMachine
csharp
AvaloniaUI__Avalonia
tests/Avalonia.Benchmarks/Base/AvaloniaObject_GetValue.cs
{ "start": 177, "end": 6270 }
public class ____ { private BaselineTestClass _baseline = new(){ StringProperty = "foo" }; private TestClass _target = new(); public AvaloniaObject_GetValue() { RuntimeHelpers.RunClassConstructor(typeof(TestClass).TypeHandle); } [Benchmark(Baseline = true)] public int GetClrPropertyValues() { var target = _baseline; var result = 0; for (var i = 0; i < 100; ++i) { result += target.StringProperty?.Length ?? 0; result += target.Struct1Property.Int1; result += target.Struct2Property.Int1; result += target.Struct3Property.Int1; result += target.Struct4Property.Int1; result += target.Struct5Property.Int1; result += target.Struct6Property.Int1; result += target.Struct7Property.Int1; result += target.Struct8Property.Int1; } return result; } [Benchmark] public int GetDefaultValues() { var target = _target; var result = 0; for (var i = 0; i < 100; ++i) { result += target.GetValue(TestClass.StringProperty)?.Length ?? 0; result += target.GetValue(TestClass.Struct1Property).Int1; result += target.GetValue(TestClass.Struct2Property).Int1; result += target.GetValue(TestClass.Struct3Property).Int1; result += target.GetValue(TestClass.Struct4Property).Int1; result += target.GetValue(TestClass.Struct5Property).Int1; result += target.GetValue(TestClass.Struct6Property).Int1; result += target.GetValue(TestClass.Struct7Property).Int1; result += target.GetValue(TestClass.Struct8Property).Int1; } return result; } [GlobalSetup(Target = nameof(Get_Local_Values))] public void SetupLocalValues() { _target.SetValue(TestClass.StringProperty, "foo"); _target.SetValue(TestClass.Struct1Property, new(1)); _target.SetValue(TestClass.Struct2Property, new(1)); _target.SetValue(TestClass.Struct3Property, new(1)); _target.SetValue(TestClass.Struct4Property, new(1)); _target.SetValue(TestClass.Struct5Property, new(1)); _target.SetValue(TestClass.Struct6Property, new(1)); _target.SetValue(TestClass.Struct7Property, new(1)); _target.SetValue(TestClass.Struct8Property, new(1)); } [Benchmark] public int Get_Local_Values() { var target = _target; var result = 0; for (var i = 0; i < 100; ++i) { result += target.GetValue(TestClass.StringProperty)?.Length ?? 0; result += target.GetValue(TestClass.Struct1Property).Int1; result += target.GetValue(TestClass.Struct2Property).Int1; result += target.GetValue(TestClass.Struct3Property).Int1; result += target.GetValue(TestClass.Struct4Property).Int1; result += target.GetValue(TestClass.Struct5Property).Int1; result += target.GetValue(TestClass.Struct6Property).Int1; result += target.GetValue(TestClass.Struct7Property).Int1; result += target.GetValue(TestClass.Struct8Property).Int1; } return result; } [GlobalSetup(Target = nameof(Get_Local_Values_With_Style_Values))] public void SetupLocalValuesAndStyleValues() { var target = _target; target.SetValue(TestClass.StringProperty, "foo"); target.SetValue(TestClass.Struct1Property, new(1)); target.SetValue(TestClass.Struct2Property, new(1)); target.SetValue(TestClass.Struct3Property, new(1)); target.SetValue(TestClass.Struct4Property, new(1)); target.SetValue(TestClass.Struct5Property, new(1)); target.SetValue(TestClass.Struct6Property, new(1)); target.SetValue(TestClass.Struct7Property, new(1)); target.SetValue(TestClass.Struct8Property, new(1)); target.SetValue(TestClass.StringProperty, "bar", BindingPriority.Style); target.SetValue(TestClass.Struct1Property, new(), BindingPriority.Style); target.SetValue(TestClass.Struct2Property, new(), BindingPriority.Style); target.SetValue(TestClass.Struct3Property, new(), BindingPriority.Style); target.SetValue(TestClass.Struct4Property, new(), BindingPriority.Style); target.SetValue(TestClass.Struct5Property, new(), BindingPriority.Style); target.SetValue(TestClass.Struct6Property, new(), BindingPriority.Style); target.SetValue(TestClass.Struct7Property, new(), BindingPriority.Style); target.SetValue(TestClass.Struct8Property, new(), BindingPriority.Style); } [Benchmark] public int Get_Local_Values_With_Style_Values() { var target = _target; var result = 0; for (var i = 0; i < 100; ++i) { result += target.GetValue(TestClass.StringProperty)?.Length ?? 0; result += target.GetValue(TestClass.Struct1Property).Int1; result += target.GetValue(TestClass.Struct2Property).Int1; result += target.GetValue(TestClass.Struct3Property).Int1; result += target.GetValue(TestClass.Struct4Property).Int1; result += target.GetValue(TestClass.Struct5Property).Int1; result += target.GetValue(TestClass.Struct6Property).Int1; result += target.GetValue(TestClass.Struct7Property).Int1; result += target.GetValue(TestClass.Struct8Property).Int1; } return result; }
AvaloniaObject_GetValue
csharp
SixLabors__ImageSharp
tests/ImageSharp.Benchmarks/Codecs/Jpeg/BlockOperations/Block8x8F_LoadFromInt16.cs
{ "start": 301, "end": 1214 }
public class ____ { private Block8x8 source; private Block8x8F destination; [GlobalSetup] public void Setup() { if (Vector<float>.Count != 8) { throw new NotSupportedException("Vector<float>.Count != 8"); } for (short i = 0; i < Block8x8F.Size; i++) { this.source[i] = i; } } [Benchmark(Baseline = true)] public void Scalar() => this.destination.LoadFromInt16Scalar(ref this.source); [Benchmark] public void ExtendedAvx2() => this.destination.LoadFromInt16ExtendedVector256(ref this.source); // RESULT: // Method | Mean | Error | StdDev | Scaled | // ------------- |---------:|----------:|----------:|-------:| // Scalar | 34.88 ns | 0.3296 ns | 0.3083 ns | 1.00 | // ExtendedAvx2 | 21.58 ns | 0.2125 ns | 0.1884 ns | 0.62 | }
Block8x8F_LoadFromInt16
csharp
dotnet__efcore
src/EFCore.Relational/Migrations/Operations/CreateSequenceOperation.cs
{ "start": 500, "end": 1238 }
public class ____ : SequenceOperation { /// <summary> /// The schema that contains the sequence, or <see langword="null" /> if the default schema should be used. /// </summary> public virtual string? Schema { get; set; } /// <summary> /// The name of the sequence. /// </summary> public virtual string Name { get; set; } = null!; /// <summary> /// The CLR <see cref="Type" /> of values returned from the sequence. /// </summary> public virtual Type ClrType { get; set; } = null!; /// <summary> /// The value at which the sequence will start counting, defaulting to 1. /// </summary> public virtual long StartValue { get; set; } = 1L; }
CreateSequenceOperation
csharp
jbogard__MediatR
src/MediatR/Wrappers/RequestHandlerWrapper.cs
{ "start": 165, "end": 348 }
public abstract class ____ { public abstract Task<object?> Handle(object request, IServiceProvider serviceProvider, CancellationToken cancellationToken); }
RequestHandlerBase
csharp
RicoSuter__NJsonSchema
src/NJsonSchema/ITypeNameGenerator.cs
{ "start": 536, "end": 1028 }
public interface ____ { /// <summary>Generates the type name.</summary> /// <param name="schema">The property.</param> /// <param name="typeNameHint">The type name hint (the property name or definition key).</param> /// <param name="reservedTypeNames">The reserved type names.</param> /// <returns>The new name.</returns> string Generate(JsonSchema schema, string? typeNameHint, IEnumerable<string> reservedTypeNames); } }
ITypeNameGenerator
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/Middleware/Configuration/Send/MessageSendPipeSplitFilterSpecification.cs
{ "start": 260, "end": 879 }
class ____ T : class { readonly ISpecificationPipeSpecification<SendContext<T>> _specification; public MessageSendPipeSplitFilterSpecification(ISpecificationPipeSpecification<SendContext<T>> specification) { _specification = specification; } public void Apply(ISpecificationPipeBuilder<SendContext<TMessage>> builder) { var splitBuilder = new Builder(builder); _specification.Apply(splitBuilder); } public IEnumerable<ValidationResult> Validate() { yield break; }
where
csharp
jellyfin__jellyfin
MediaBrowser.Model/IO/IShortcutHandler.cs
{ "start": 70, "end": 809 }
public interface ____ { /// <summary> /// Gets the extension. /// </summary> /// <value>The extension.</value> string Extension { get; } /// <summary> /// Resolves the specified shortcut path. /// </summary> /// <param name="shortcutPath">The shortcut path.</param> /// <returns>System.String.</returns> string? Resolve(string shortcutPath); /// <summary> /// Creates the specified shortcut path. /// </summary> /// <param name="shortcutPath">The shortcut path.</param> /// <param name="targetPath">The target path.</param> void Create(string shortcutPath, string targetPath); } }
IShortcutHandler
csharp
MassTransit__MassTransit
src/MassTransit/SagaStateMachine/MassTransitStateMachine.cs
{ "start": 66893, "end": 69591 }
class ____ TResponse2 : class { var property = propertyExpression.GetPropertyInfo(); var request = new StateMachineRequest<TRequest, TResponse, TResponse2>(property.Name, settings, requestIdExpression); InitializeRequest(this, property, request); Event(propertyExpression, x => x.Completed, x => { x.CorrelateBy(requestIdExpression, context => context.RequestId); settings.Completed?.Invoke(x); }); Event(propertyExpression, x => x.Completed2, x => { x.CorrelateBy(requestIdExpression, context => context.RequestId); settings.Completed2?.Invoke(x); }); Event(propertyExpression, x => x.Faulted, x => { x.CorrelateBy(requestIdExpression, context => context.RequestId); settings.Faulted?.Invoke(x); }); Event(propertyExpression, x => x.TimeoutExpired, x => { x.CorrelateBy(requestIdExpression, context => context.Message.RequestId); settings.TimeoutExpired?.Invoke(x); }); State(propertyExpression, x => x.Pending); DuringAny( When(request.Completed) .CancelRequestTimeout(request), When(request.Completed2) .CancelRequestTimeout(request), When(request.Faulted) .CancelRequestTimeout(request, false)); } /// <summary> /// Declares a request that is sent by the state machine to a service, and the associated response, fault, and /// timeout handling. The property is initialized with the fully built Request. The request must be declared before /// it is used in the state/event declaration statements. /// Uses the Saga CorrelationId as the RequestId /// </summary> /// <typeparam name="TRequest">The request type</typeparam> /// <typeparam name="TResponse">The response type</typeparam> /// <typeparam name="TResponse2">The alternate response type</typeparam> /// <param name="propertyExpression">The request property on the state machine</param> /// <param name="settings">The request settings (which can be read from configuration, etc.)</param> protected internal void Request<TRequest, TResponse, TResponse2>( Expression<Func<Request<TInstance, TRequest, TResponse, TResponse2>>> propertyExpression, RequestSettings<TInstance, TRequest, TResponse, TResponse2> settings) where TRequest :
where
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Markup/ApplyExtensions.cs
{ "start": 108, "end": 2009 }
public static class ____ { public delegate Binding BindingApplyHandler(Binding binding); public delegate Binding BindingApplyWithParamHandler(Binding binding, object that); /// <summary> /// Executes the provided apply handler on the binding instance. Used by the XAML code generator. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static Binding BindingApply(this Binding instance, BindingApplyHandler apply) { apply(instance); return instance; } /// <summary> /// Executes the provided apply handler on the binding instance. Used by the XAML code generator. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static Binding BindingApply(this Binding instance, object that, BindingApplyWithParamHandler apply) { apply(instance, that); return instance; } /// <summary> /// Executes the provided apply handler on the specified instance. Used by the XAML code generator. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static TType GenericApply<TType>(this TType instance, Action<TType> apply) { apply(instance); return instance; } /// <summary> /// Executes the provided apply handler on the specified instance. Used by the XAML code generator. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static TType GenericApply<TType, TArg1>(this TType instance, TArg1 arg1, Action<TType, TArg1> apply) { apply(instance, arg1); return instance; } /// <summary> /// Executes the provided apply handler on the specified instance. Used by the XAML code generator. /// </summary> [EditorBrowsable(EditorBrowsableState.Never)] public static TType GenericApply<TType, TArg1, TArg2>(this TType instance, TArg1 arg1, TArg2 arg2, Action<TType, TArg1, TArg2> apply) { apply(instance, arg1, arg2); return instance; } } }
ApplyExtensions
csharp
EventStore__EventStore
src/KurrentDB.Core/Services/Transport/Http/UriRouters.cs
{ "start": 3475, "end": 3626 }
private class ____ { public readonly Dictionary<string, RouterNode> Children = new(); public readonly List<HttpRoute> LeafRoutes = []; } }
RouterNode
csharp
dotnet__aspnetcore
src/Components/Endpoints/src/Builder/ResourceCollectionConvention.cs
{ "start": 311, "end": 2406 }
internal class ____(ResourceCollectionResolver resolver) { private string? _collectionUrl; private ImportMapDefinition? _collectionEndpointImportMap; private ResourceAssetCollection? _collection; private ImportMapDefinition? _collectionImportMap; public void OnBeforeCreateEndpoints(RazorComponentEndpointUpdateContext context) { if (resolver.IsRegistered(context.Options.ManifestPath)) { _collection = resolver.ResolveResourceCollection(context.Options.ManifestPath); _collectionImportMap = ImportMapDefinition.FromResourceCollection(_collection); string? url = null; ImportMapDefinition? map = null; foreach (var renderMode in context.Options.ConfiguredRenderModes) { if (renderMode is InteractiveWebAssemblyRenderMode or InteractiveAutoRenderMode) { (map, url) = ResourceCollectionUrlEndpoint.MapResourceCollectionEndpoints( context.Endpoints, "_framework/resource-collection{0}.js{1}", _collection); break; } } if (url != null && map != null) { _collectionUrl = url; _collectionEndpointImportMap = map; } } } public void ApplyConvention(EndpointBuilder eb) { // The user called MapStaticAssets if (_collection != null && _collectionImportMap != null) { eb.Metadata.Add(_collection); eb.Metadata.Add(new ResourcePreloadCollection(_collection)); if (_collectionUrl != null) { eb.Metadata.Add(new ResourceCollectionUrlMetadata(_collectionUrl)); } var importMap = _collectionEndpointImportMap == null ? _collectionImportMap : ImportMapDefinition.Combine(_collectionImportMap, _collectionEndpointImportMap); eb.Metadata.Add(importMap); } } }
ResourceCollectionConvention
csharp
AvaloniaUI__Avalonia
src/Avalonia.Base/Input/PullGestureEventArgs.cs
{ "start": 76, "end": 606 }
public class ____ : RoutedEventArgs { public int Id { get; } public Vector Delta { get; } public PullDirection PullDirection { get; } private static int _nextId = 1; internal static int GetNextFreeId() => _nextId++; public PullGestureEventArgs(int id, Vector delta, PullDirection pullDirection) : base(Gestures.PullGestureEvent) { Id = id; Delta = delta; PullDirection = pullDirection; } }
PullGestureEventArgs
csharp
EventStore__EventStore
src/KurrentDB.Licensing/Keygen/Models.cs
{ "start": 3250, "end": 3452 }
public class ____ : KeygenAttributes { public bool RequireHeartbeat { get; set; } public int HeartbeatDuration { get; set; } public string HeartbeatStatus { get; set; } = null!; }
MachineAttributes
csharp
MassTransit__MassTransit
src/MassTransit.Abstractions/NewId/NewIdParsers/ZBase32Parser.cs
{ "start": 42, "end": 502 }
public class ____ : Base32Parser { const string ConvertChars = "ybndrfg8ejkmcpqxot1uwisza345h769YBNDRFG8EJKMCPQXOT1UWISZA345H769"; const string TransposeChars = "ybndrfg8ejkmcpqx0tlvwis2a345h769YBNDRFG8EJKMCPQX0TLVWIS2A345H769"; public ZBase32Parser(bool handleTransposedCharacters = false) : base(handleTransposedCharacters ? ConvertChars + TransposeChars : ConvertChars) { } } }
ZBase32Parser
csharp
protobuf-net__protobuf-net
src/protobuf-net.Test/Attribs/ProtoContractSurrogate.cs
{ "start": 3168, "end": 4075 }
public class ____ { [ProtoMember(1, IsRequired = true)] public T Value { get; set; } public static implicit operator ImmutableGenericType2<T>(Surrogate surrogate) { return surrogate == null ? null : new ImmutableGenericType2<T>(surrogate.Value); } public static implicit operator Surrogate(ImmutableGenericType2<T> source) { return source == null ? null : new Surrogate { Value = source.Value }; } } } [Fact] public void ImmutableGenericNestedSerialization() { var instance = new ImmutableGenericType2<string>("XYZ!"); var clone = RuntimeTypeModel.Default.DeepClone(instance); Assert.Equal(instance.Value, clone.Value); } } }
Surrogate
csharp
microsoft__garnet
test/Garnet.test.cluster/RedirectTests/BaseCommand.cs
{ "start": 49419, "end": 50490 }
internal class ____ : BaseCommand { public override bool IsArrayCommand => true; public override bool ArrayResponse => true; public override string Command => nameof(LMPOP); public override string[] GetSingleSlotRequest() { var ssk = GetSingleSlotKeys; return ["3", ssk[0], ssk[1], ssk[2], "LEFT"]; } public override string[] GetCrossSlotRequest() { var csk = GetCrossSlotKeys; return ["3", csk[0], csk[1], csk[2], "LEFT"]; } public override ArraySegment<string>[] SetupSingleSlotRequest() { var ssk = GetSingleSlotKeys; var setup = new ArraySegment<string>[3]; setup[0] = new ArraySegment<string>(["LPUSH", ssk[1], "value1", "value2", "value3"]); setup[1] = new ArraySegment<string>(["LPUSH", ssk[2], "value4", "value5", "value6"]); setup[2] = new ArraySegment<string>(["LPUSH", ssk[3], "value7", "value8", "value9"]); return setup; } }
LMPOP
csharp
unoplatform__uno
src/Uno.UWP/Devices/Midi/Internal/MidiMessageValidators.cs
{ "start": 83, "end": 1038 }
internal static class ____ { internal static void VerifyMessageLength(byte[] messageData, int expectedLength, MidiMessageType type) { if (messageData is null) { throw new ArgumentNullException(nameof(messageData)); } if (messageData.Length != expectedLength) { throw new ArgumentException( $"MIDI message of type {type} must have length of {expectedLength} bytes", nameof(messageData)); } } internal static void VerifyMessageType(byte firstByte, MidiMessageType type) { var typeByte = (byte)type; if ((firstByte & typeByte) != typeByte) { throw new ArgumentException( $"The message does not match expected type of {type}"); } } internal static void VerifyRange(int value, MidiMessageParameter parameter) { if (value > (int)parameter) { throw new ArgumentException( $"{parameter} must be a number in the range 0 - {(int)parameter}"); } } } }
MidiMessageValidators
csharp
unoplatform__uno
src/Uno.UWP/Generated/3.0.0.0/Windows.UI.Input.Spatial/SpatialInteractionSource.cs
{ "start": 299, "end": 7472 }
public partial class ____ { #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ internal SpatialInteractionSource() { } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public uint Id { get { throw new global::System.NotImplementedException("The member uint SpatialInteractionSource.Id is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=uint%20SpatialInteractionSource.Id"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.Input.Spatial.SpatialInteractionSourceKind Kind { get { throw new global::System.NotImplementedException("The member SpatialInteractionSourceKind SpatialInteractionSource.Kind is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SpatialInteractionSourceKind%20SpatialInteractionSource.Kind"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.Input.Spatial.SpatialInteractionController Controller { get { throw new global::System.NotImplementedException("The member SpatialInteractionController SpatialInteractionSource.Controller is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SpatialInteractionController%20SpatialInteractionSource.Controller"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public bool IsGraspSupported { get { throw new global::System.NotImplementedException("The member bool SpatialInteractionSource.IsGraspSupported is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20SpatialInteractionSource.IsGraspSupported"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public bool IsMenuSupported { get { throw new global::System.NotImplementedException("The member bool SpatialInteractionSource.IsMenuSupported is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20SpatialInteractionSource.IsMenuSupported"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public bool IsPointingSupported { get { throw new global::System.NotImplementedException("The member bool SpatialInteractionSource.IsPointingSupported is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=bool%20SpatialInteractionSource.IsPointingSupported"); } } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.Input.Spatial.SpatialInteractionSourceHandedness Handedness { get { throw new global::System.NotImplementedException("The member SpatialInteractionSourceHandedness SpatialInteractionSource.Handedness is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SpatialInteractionSourceHandedness%20SpatialInteractionSource.Handedness"); } } #endif // Forced skipping of method Windows.UI.Input.Spatial.SpatialInteractionSource.Id.get // Forced skipping of method Windows.UI.Input.Spatial.SpatialInteractionSource.Kind.get // Forced skipping of method Windows.UI.Input.Spatial.SpatialInteractionSource.IsPointingSupported.get // Forced skipping of method Windows.UI.Input.Spatial.SpatialInteractionSource.IsMenuSupported.get // Forced skipping of method Windows.UI.Input.Spatial.SpatialInteractionSource.IsGraspSupported.get // Forced skipping of method Windows.UI.Input.Spatial.SpatialInteractionSource.Controller.get #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.UI.Input.Spatial.SpatialInteractionSourceState TryGetStateAtTimestamp(global::Windows.Perception.PerceptionTimestamp timestamp) { throw new global::System.NotImplementedException("The member SpatialInteractionSourceState SpatialInteractionSource.TryGetStateAtTimestamp(PerceptionTimestamp timestamp) is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=SpatialInteractionSourceState%20SpatialInteractionSource.TryGetStateAtTimestamp%28PerceptionTimestamp%20timestamp%29"); } #endif // Forced skipping of method Windows.UI.Input.Spatial.SpatialInteractionSource.Handedness.get #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Perception.People.HandMeshObserver TryCreateHandMeshObserver() { throw new global::System.NotImplementedException("The member HandMeshObserver SpatialInteractionSource.TryCreateHandMeshObserver() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=HandMeshObserver%20SpatialInteractionSource.TryCreateHandMeshObserver%28%29"); } #endif #if __ANDROID__ || __IOS__ || __TVOS__ || IS_UNIT_TESTS || __WASM__ || __SKIA__ || __NETSTD_REFERENCE__ [global::Uno.NotImplemented("__ANDROID__", "__IOS__", "__TVOS__", "IS_UNIT_TESTS", "__WASM__", "__SKIA__", "__NETSTD_REFERENCE__")] public global::Windows.Foundation.IAsyncOperation<global::Windows.Perception.People.HandMeshObserver> TryCreateHandMeshObserverAsync() { throw new global::System.NotImplementedException("The member IAsyncOperation<HandMeshObserver> SpatialInteractionSource.TryCreateHandMeshObserverAsync() is not implemented. For more information, visit https://aka.platform.uno/notimplemented#m=IAsyncOperation%3CHandMeshObserver%3E%20SpatialInteractionSource.TryCreateHandMeshObserverAsync%28%29"); } #endif } }
SpatialInteractionSource
csharp
unoplatform__uno
src/Uno.UI/UI/Xaml/Automation/Peers/AutomationNotificationKind.cs
{ "start": 152, "end": 892 }
public enum ____ { /// <summary> /// The current element container has had something added to it that should be presented to the user. /// </summary> ItemAdded = 0, /// <summary> /// The current element has had something removed from inside it that should be presented to the user. /// </summary> ItemRemoved = 1, /// <summary> /// The current element has a notification that an action was completed. /// </summary> ActionCompleted = 2, /// <summary> /// The current element has a notification that an action was abandoned. /// </summary> ActionAborted = 3, /// <summary> /// The current element has a notification not an add, remove, completed, or aborted action. /// </summary> Other = 4, }
AutomationNotificationKind