content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StreamEndpoint.cs" company="Sitecore A/S">
// Copyright (C) 2015 by Sitecore
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace KomfoSharp.Configuration.Endpoints
{
using System;
using System.ComponentModel.DataAnnotations;
using System.Xml.Serialization;
/// <summary>
/// Represents the "stream" endpoint.
/// </summary>
[Serializable]
public class StreamEndpoint : EndpointBase
{
/// <summary>
/// Gets or sets the maximum twitter handles per call.
/// </summary>
/// <value>
/// The maximum twitter handles per call.
/// </value>
[XmlAttribute("maxTwitterHandlesPerCall")]
[Range(1, int.MaxValue)]
public int MaxTwitterHandlesPerCall { get; set; }
/// <summary>
/// Gets or sets the maximum results per call.
/// </summary>
/// <value>
/// The maximum results per call.
/// </value>
[XmlAttribute("maxResultsPerCall")]
[Range(1, int.MaxValue)]
public int MaxResultsPerCall { get; set; }
}
}
| 31.435897 | 120 | 0.51876 | [
"MIT"
] | Sitecore/KomfoSharp | KomfoSharp/Configuration/Endpoints/StreamEndpoint.cs | 1,228 | C# |
using DbFramework.DbCommands;
using DbFramework.Interfaces.Invokers;
namespace DbFramework.Interfaces.Factories
{
public interface IDbInvokerFactory
{
INonQueryCommandInvoker Create(INonQueryCommand serviceCommand);
IDoesResultExistCommandInvoker Create(IDoesResultExistCommand serviceCommand);
IManyResultCommandInvoker<TResult> Create<TResult>(IManyResultsCommand<TResult> serviceCommand);
INonQueryCommandInvoker<TResult> Create<TResult>(INonQueryCommand<TResult> serviceCommand);
IScalarCommandInvoker<TResult> Create<TResult>(IScalarCommand<TResult> serviceCommand);
ISingleResultCommandInvoker<TResult> Create<TResult>(ISingleResultCommand<TResult> serviceCommand);
ISingleResultOrDefaultCommandInvoker<TResult> Create<TResult>(ISingleResultOrDefaultCommand<TResult> serviceCommand);
IFirstResultCommandInvoker<TResult> Create<TResult>(IFirstResultCommand<TResult> serviceCommand);
IFirstResultOrDefaultCommandInvoker<TResult> Create<TResult>(IFirstResultOrDefaultCommand<TResult> serviceCommand);
}
} | 57.222222 | 119 | 0.862136 | [
"MIT"
] | christoff85/DbFramework | src/DbFramework/Interfaces/Factories/IDbInvokerFactory.cs | 1,032 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
[assembly: AssemblyTitle("Ninject ASP.NET Framework")]
[assembly: Guid("2dafe407-a883-46fb-b13d-3263716ca817")]
#if !NO_PARTIAL_TRUST
[assembly: AllowPartiallyTrustedCallers]
#endif | 25.818182 | 56 | 0.809859 | [
"Apache-2.0"
] | ninject/ninject1 | src/Framework/Web/Properties/AssemblyInfo.cs | 286 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.ChangeTracking;
using Microsoft.EntityFrameworkCore.ChangeTracking.Internal;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Internal;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors;
using Microsoft.EntityFrameworkCore.Query.ExpressionVisitors.Internal;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.EntityFrameworkCore.ValueGeneration;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ReLinq = Remotion.Linq.Parsing.ExpressionVisitors.TreeEvaluation;
namespace Microsoft.EntityFrameworkCore.Infrastructure
{
/// <summary>
/// <para>
/// A builder API designed for database providers to use when registering services.
/// </para>
/// <para>
/// Providers should create an instance of this class, use its methods to register
/// services, and then call <see cref="TryAddCoreServices" /> to fill out the remaining Entity
/// Framework services.
/// </para>
/// <para>
/// Relational providers should use 'EntityFrameworkRelationalServicesBuilder instead.
/// </para>
/// <para>
/// Entity Framework ensures that services are registered with the appropriate scope. In some cases a provider
/// may register a service with a different scope, but great care must be taken that all its dependencies
/// can handle the new scope, and that it does not cause issue for services that depend on it.
/// </para>
/// </summary>
public class EntityFrameworkServicesBuilder
{
/// <summary>
/// <para>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </para>
/// <para>
/// This dictionary is exposed for testing and provider-validation only.
/// It should not be used from application code.
/// </para>
/// </summary>
public static readonly IDictionary<Type, ServiceCharacteristics> CoreServices
= new Dictionary<Type, ServiceCharacteristics>
{
{ typeof(IDatabaseProvider), new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) },
{ typeof(IDbSetFinder), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IDbSetInitializer), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IDbSetSource), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IEntityFinderSource), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IEntityMaterializerSource), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(ICoreConventionSetBuilder), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(ITypeMappingSource), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IModelCustomizer), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IModelCacheKeyFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IModelSource), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IInternalEntityEntryFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IInternalEntityEntrySubscriber), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IEntityEntryGraphIterator), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IValueGeneratorCache), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(INodeTypeProviderFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(ISingletonOptionsInitializer), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(ILoggingOptions), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(ICoreSingletonOptions), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IModelValidator), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(ICompiledQueryCache), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IQueryAnnotationExtractor), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IEntityTrackingInfoFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(ITaskBlockingExpressionVisitor), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IMemberAccessBindingExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(INavigationRewritingExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IEagerLoadingExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IQuerySourceTracingExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IProjectionExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IValueConverterSelector), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IConstructorBindingFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IRegisteredServices), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IPropertyParameterBindingFactory), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IParameterBindingFactories), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IMemberClassifier), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IMemoryCache), new ServiceCharacteristics(ServiceLifetime.Singleton) },
{ typeof(IDiagnosticsLogger<>), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(ILoggerFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IEntityGraphAttacher), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IKeyPropagator), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(INavigationFixer), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(ILocalViewListener), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IStateManager), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(Func<IStateManager>), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IConcurrencyDetector), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IInternalEntityEntryNotifier), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IValueGenerationManager), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IChangeTrackerFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IChangeDetector), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IDbContextServices), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IValueGeneratorSelector), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IExpressionPrinter), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IExecutionStrategyFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IAsyncQueryProvider), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IQueryCompiler), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IQueryModelGenerator), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IQueryOptimizer), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IEntityResultFindingExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IRequiresMaterializationExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IQueryCompilationContextFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(ICompiledQueryCacheKeyGenerator), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IResultOperatorHandler), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IModel), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(ICurrentDbContext), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IDbContextDependencies), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IDbContextOptions), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IDatabase), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IDatabaseCreator), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IDbContextTransactionManager), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IQueryContextFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IEntityQueryableExpressionVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IEntityQueryModelVisitorFactory), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(ReLinq.IEvaluatableExpressionFilter), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(IEvaluatableExpressionFilter), new ServiceCharacteristics(ServiceLifetime.Scoped) },
{ typeof(ILazyLoader), new ServiceCharacteristics(ServiceLifetime.Transient) },
{ typeof(IParameterBindingFactory), new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) },
{ typeof(ITypeMappingSourcePlugin), new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) },
{ typeof(ISingletonOptions), new ServiceCharacteristics(ServiceLifetime.Singleton, multipleRegistrations: true) },
{ typeof(IConventionSetBuilder), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) },
{ typeof(IEntityStateListener), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) },
{ typeof(INavigationListener), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) },
{ typeof(IKeyListener), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) },
{ typeof(IQueryTrackingListener), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) },
{ typeof(IPropertyListener), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) },
{ typeof(IResettableService), new ServiceCharacteristics(ServiceLifetime.Scoped, multipleRegistrations: true) }
};
/// <summary>
/// Used by database providers to create a new <see cref="EntityFrameworkServicesBuilder" /> for
/// registration of provider services. Relational providers should use
/// 'EntityFrameworkRelationalServicesBuilder'.
/// </summary>
/// <param name="serviceCollection"> The collection to which services will be registered. </param>
public EntityFrameworkServicesBuilder([NotNull] IServiceCollection serviceCollection)
{
Check.NotNull(serviceCollection, nameof(serviceCollection));
ServiceCollectionMap = new ServiceCollectionMap(serviceCollection);
}
/// <summary>
/// Access to the underlying <see cref="ServiceCollectionMap" />.
/// </summary>
protected virtual ServiceCollectionMap ServiceCollectionMap { get; }
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
protected virtual ServiceCharacteristics GetServiceCharacteristics([NotNull] Type serviceType)
{
if (!CoreServices.TryGetValue(serviceType, out var characteristics))
{
throw new InvalidOperationException(CoreStrings.NotAnEFService(serviceType.Name));
}
return characteristics;
}
/// <summary>
/// Database providers should call this method for access to the underlying
/// <see cref="ServiceCollectionMap" /> such that provider-specific services can be registered.
/// Note that implementations of Entity Framework services should be registered directly on the
/// <see cref="EntityFrameworkServicesBuilder" /> and not through this method.
/// </summary>
/// <param name="serviceMap"> The underlying map to which provider services should be added.</param>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAddProviderSpecificServices([NotNull] Action<ServiceCollectionMap> serviceMap)
{
Check.NotNull(serviceMap, nameof(serviceMap));
serviceMap(ServiceCollectionMap);
return this;
}
/// <summary>
/// Registers default implementations of all services not already registered by the provider.
/// Database providers must call this method as the last step of service registration--that is,
/// after all provider services have been registered.
/// </summary>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAddCoreServices()
{
TryAdd<IDbSetFinder, DbSetFinder>();
TryAdd<IDbSetInitializer, DbSetInitializer>();
TryAdd<IDbSetSource, DbSetSource>();
TryAdd<IEntityFinderSource, EntityFinderSource>();
TryAdd<IEntityMaterializerSource, EntityMaterializerSource>();
TryAdd<ICoreConventionSetBuilder, CoreConventionSetBuilder>();
TryAdd<IModelCustomizer, ModelCustomizer>();
TryAdd<IModelCacheKeyFactory, ModelCacheKeyFactory>();
TryAdd<ILoggerFactory>(p => ScopedLoggerFactory.Create(p, null));
TryAdd<IModelSource, ModelSource>();
TryAdd<IInternalEntityEntryFactory, InternalEntityEntryFactory>();
TryAdd<IInternalEntityEntrySubscriber, InternalEntityEntrySubscriber>();
TryAdd<IEntityEntryGraphIterator, EntityEntryGraphIterator>();
TryAdd<IEntityGraphAttacher, EntityGraphAttacher>();
TryAdd<IValueGeneratorCache, ValueGeneratorCache>();
TryAdd<INodeTypeProviderFactory, DefaultMethodInfoBasedNodeTypeRegistryFactory>();
TryAdd<IKeyPropagator, KeyPropagator>();
TryAdd<INavigationFixer, NavigationFixer>();
TryAdd<ILocalViewListener, LocalViewListener>();
TryAdd<IStateManager, StateManager>();
TryAdd<IConcurrencyDetector, ConcurrencyDetector>();
TryAdd<IInternalEntityEntryNotifier, InternalEntityEntryNotifier>();
TryAdd<IValueGenerationManager, ValueGenerationManager>();
TryAdd<IChangeTrackerFactory, ChangeTrackerFactory>();
TryAdd<IChangeDetector, ChangeDetector>();
TryAdd<IDbContextServices, DbContextServices>();
TryAdd<IDbContextDependencies, DbContextDependencies>();
TryAdd<IValueGeneratorSelector, ValueGeneratorSelector>();
TryAdd<IConventionSetBuilder, NullConventionSetBuilder>();
TryAdd<IModelValidator, ModelValidator>();
TryAdd<IExecutionStrategyFactory, ExecutionStrategyFactory>();
TryAdd<ICompiledQueryCache, CompiledQueryCache>();
TryAdd<IAsyncQueryProvider, EntityQueryProvider>();
TryAdd<IQueryCompiler, QueryCompiler>();
TryAdd<IQueryModelGenerator, QueryModelGenerator>();
TryAdd<IQueryAnnotationExtractor, QueryAnnotationExtractor>();
TryAdd<IQueryOptimizer, QueryOptimizer>();
TryAdd<IEntityTrackingInfoFactory, EntityTrackingInfoFactory>();
TryAdd<ITaskBlockingExpressionVisitor, TaskBlockingExpressionVisitor>();
TryAdd<IEntityResultFindingExpressionVisitorFactory, EntityResultFindingExpressionVisitorFactory>();
TryAdd<IMemberAccessBindingExpressionVisitorFactory, MemberAccessBindingExpressionVisitorFactory>();
TryAdd<INavigationRewritingExpressionVisitorFactory, NavigationRewritingExpressionVisitorFactory>();
TryAdd<IEagerLoadingExpressionVisitorFactory, EagerLoadingExpressionVisitorFactory>();
TryAdd<IQuerySourceTracingExpressionVisitorFactory, QuerySourceTracingExpressionVisitorFactory>();
TryAdd<IRequiresMaterializationExpressionVisitorFactory, RequiresMaterializationExpressionVisitorFactory>();
TryAdd<IExpressionPrinter, ExpressionPrinter>();
TryAdd<IQueryCompilationContextFactory, QueryCompilationContextFactory>();
TryAdd<ICompiledQueryCacheKeyGenerator, CompiledQueryCacheKeyGenerator>();
TryAdd<IResultOperatorHandler, ResultOperatorHandler>();
TryAdd<IProjectionExpressionVisitorFactory, ProjectionExpressionVisitorFactory>();
TryAdd<ISingletonOptionsInitializer, SingletonOptionsInitializer>();
TryAdd(typeof(IDiagnosticsLogger<>), typeof(DiagnosticsLogger<>));
TryAdd<ILoggingOptions, LoggingOptions>();
TryAdd<ICoreSingletonOptions, CoreSingletonOptions>();
TryAdd<ISingletonOptions, ILoggingOptions>(p => p.GetService<ILoggingOptions>());
TryAdd<ISingletonOptions, ICoreSingletonOptions>(p => p.GetService<ICoreSingletonOptions>());
TryAdd(p => GetContextServices(p).Model);
TryAdd(p => GetContextServices(p).CurrentContext);
TryAdd(p => GetContextServices(p).ContextOptions);
TryAdd<IEntityStateListener, INavigationFixer>(p => p.GetService<INavigationFixer>());
TryAdd<INavigationListener, INavigationFixer>(p => p.GetService<INavigationFixer>());
TryAdd<IKeyListener, INavigationFixer>(p => p.GetService<INavigationFixer>());
TryAdd<IQueryTrackingListener, INavigationFixer>(p => p.GetService<INavigationFixer>());
TryAdd<IPropertyListener, IChangeDetector>(p => p.GetService<IChangeDetector>());
TryAdd<IEntityStateListener, ILocalViewListener>(p => p.GetService<ILocalViewListener>());
TryAdd<IResettableService, IStateManager>(p => p.GetService<IStateManager>());
TryAdd<IResettableService, IDbContextTransactionManager>(p => p.GetService<IDbContextTransactionManager>());
TryAdd<Func<IStateManager>>(p => p.GetService<IStateManager>);
TryAdd<ReLinq.IEvaluatableExpressionFilter, ReLinqEvaluatableExpressionFilter>();
TryAdd<IEvaluatableExpressionFilter, EvaluatableExpressionFilter>();
TryAdd<IValueConverterSelector, ValueConverterSelector>();
TryAdd<IConstructorBindingFactory, ConstructorBindingFactory>();
TryAdd<ILazyLoader, LazyLoader>();
TryAdd<IParameterBindingFactories, ParameterBindingFactories>();
TryAdd<IMemberClassifier, MemberClassifier>();
TryAdd<IPropertyParameterBindingFactory, PropertyParameterBindingFactory>();
TryAdd<IParameterBindingFactory, LazyLoaderParameterBindingFactory>();
TryAdd<IParameterBindingFactory, ContextParameterBindingFactory>();
TryAdd<IParameterBindingFactory, EntityTypeParameterBindingFactory>();
TryAdd<IMemoryCache>(p => new MemoryCache(new MemoryCacheOptions()));
ServiceCollectionMap
.TryAddSingleton<DiagnosticSource>(new DiagnosticListener(DbLoggerCategory.Name));
ServiceCollectionMap.GetInfrastructure()
.AddDependencySingleton<DatabaseProviderDependencies>()
.AddDependencySingleton<ResultOperatorHandlerDependencies>()
.AddDependencySingleton<ModelSourceDependencies>()
.AddDependencySingleton<ValueGeneratorCacheDependencies>()
.AddDependencySingleton<ModelValidatorDependencies>()
.AddDependencySingleton<CoreConventionSetBuilderDependencies>()
.AddDependencySingleton<TypeMappingSourceDependencies>()
.AddDependencySingleton<ModelCustomizerDependencies>()
.AddDependencySingleton<ModelCacheKeyFactoryDependencies>()
.AddDependencySingleton<ValueConverterSelectorDependencies>()
.AddDependencyScoped<StateManagerDependencies>()
.AddDependencyScoped<ExecutionStrategyDependencies>()
.AddDependencyScoped<CompiledQueryCacheKeyGeneratorDependencies>()
.AddDependencyScoped<QueryContextDependencies>()
.AddDependencyScoped<ValueGeneratorSelectorDependencies>()
.AddDependencyScoped<EntityQueryModelVisitorDependencies>()
.AddDependencyScoped<DatabaseDependencies>()
.AddDependencyScoped<QueryCompilationContextDependencies>();
ServiceCollectionMap.TryAddSingleton<IRegisteredServices>(
new RegisteredServices(ServiceCollectionMap.ServiceCollection.Select(s => s.ServiceType)));
return this;
}
private static IDbContextServices GetContextServices(IServiceProvider serviceProvider)
=> serviceProvider.GetRequiredService<IDbContextServices>();
/// <summary>
/// Adds an implementation of an Entity Framework service only if one has not already been registered.
/// The scope of the service is automatically defined by Entity Framework.
/// </summary>
/// <typeparam name="TService"> The contract for the service. </typeparam>
/// <typeparam name="TImplementation"> The concrete type that implements the service. </typeparam>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAdd<TService, TImplementation>()
where TService : class
where TImplementation : class, TService
=> TryAdd(typeof(TService), typeof(TImplementation));
/// <summary>
/// Adds an implementation of an Entity Framework service only if one has not already been registered.
/// The scope of the service is automatically defined by Entity Framework.
/// </summary>
/// <param name="serviceType"> The contract for the service. </param>
/// <param name="implementationType"> The concrete type that implements the service. </param>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAdd([NotNull] Type serviceType, [NotNull] Type implementationType)
{
Check.NotNull(serviceType, nameof(serviceType));
Check.NotNull(implementationType, nameof(implementationType));
var characteristics = GetServiceCharacteristics(serviceType);
if (characteristics.MultipleRegistrations)
{
ServiceCollectionMap.TryAddEnumerable(serviceType, implementationType, characteristics.Lifetime);
}
else
{
ServiceCollectionMap.TryAdd(serviceType, implementationType, characteristics.Lifetime);
}
return this;
}
/// <summary>
/// Adds a factory for an Entity Framework service only if one has not already been registered.
/// The scope of the service is automatically defined by Entity Framework.
/// </summary>
/// <typeparam name="TService"> The contract for the service. </typeparam>
/// <param name="factory"> The factory that will create the service instance. </param>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAdd<TService>([NotNull] Func<IServiceProvider, TService> factory)
where TService : class
=> TryAdd(typeof(TService), typeof(TService), factory);
/// <summary>
/// Adds a factory for an Entity Framework service only if one has not already been registered.
/// The scope of the service is automatically defined by Entity Framework.
/// </summary>
/// <typeparam name="TService"> The contract for the service. </typeparam>
/// <typeparam name="TImplementation"> The concrete type that implements the service. </typeparam>
/// <param name="factory"> The factory that will create the service instance. </param>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAdd<TService, TImplementation>(
[NotNull] Func<IServiceProvider, TImplementation> factory)
where TService : class
where TImplementation : class, TService
=> TryAdd(typeof(TService), typeof(TImplementation), factory);
/// <summary>
/// Adds a factory for an Entity Framework service only if one has not already been registered.
/// The scope of the service is automatically defined by Entity Framework.
/// </summary>
/// <param name="serviceType"> The contract for the service. </param>
/// <param name="implementationType"> The concrete type that implements the service. </param>
/// <param name="factory"> The factory that will create the service instance. </param>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAdd(
[NotNull] Type serviceType,
[NotNull] Type implementationType,
[NotNull] Func<IServiceProvider, object> factory)
{
Check.NotNull(serviceType, nameof(serviceType));
Check.NotNull(implementationType, nameof(implementationType));
Check.NotNull(factory, nameof(factory));
var characteristics = GetServiceCharacteristics(serviceType);
if (characteristics.MultipleRegistrations)
{
if (implementationType == serviceType
|| implementationType == typeof(object))
{
throw new InvalidOperationException(CoreStrings.ImplementationTypeRequired(serviceType.Name));
}
ServiceCollectionMap.TryAddEnumerable(serviceType, implementationType, factory, characteristics.Lifetime);
}
else
{
ServiceCollectionMap.TryAdd(serviceType, factory, characteristics.Lifetime);
}
return this;
}
/// <summary>
/// Adds an implementation of an Entity Framework service only if one has not already been registered.
/// This method can only be used for singleton services.
/// </summary>
/// <typeparam name="TService"> The contract for the service. </typeparam>
/// <param name="implementation"> The implementation of the service. </param>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAdd<TService>([CanBeNull] TService implementation)
where TService : class
=> TryAdd(typeof(TService), implementation);
/// <summary>
/// Adds an implementation of an Entity Framework service only if one has not already been registered.
/// This method can only be used for singleton services.
/// </summary>
/// <param name="serviceType"> The contract for the service. </param>
/// <param name="implementation"> The implementation of the service. </param>
/// <returns> This builder, such that further calls can be chained. </returns>
public virtual EntityFrameworkServicesBuilder TryAdd(
[NotNull] Type serviceType,
[CanBeNull] object implementation)
{
Check.NotNull(serviceType, nameof(serviceType));
var characteristics = GetServiceCharacteristics(serviceType);
if (characteristics.Lifetime != ServiceLifetime.Singleton)
{
throw new InvalidOperationException(CoreStrings.SingletonRequired(characteristics.Lifetime, serviceType.Name));
}
if (characteristics.MultipleRegistrations)
{
if (implementation == null)
{
throw new InvalidOperationException(CoreStrings.ImplementationTypeRequired(serviceType.Name));
}
ServiceCollectionMap.TryAddSingletonEnumerable(serviceType, implementation);
}
else
{
ServiceCollectionMap.TryAddSingleton(serviceType, implementation);
}
return this;
}
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public readonly struct ServiceCharacteristics
{
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public ServiceLifetime Lifetime { get; }
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public bool MultipleRegistrations { get; }
/// <summary>
/// This API supports the Entity Framework Core infrastructure and is not intended to be used
/// directly from your code. This API may change or be removed in future releases.
/// </summary>
public ServiceCharacteristics(ServiceLifetime lifetime, bool multipleRegistrations = false)
{
Lifetime = lifetime;
MultipleRegistrations = multipleRegistrations;
}
}
}
}
| 64.856 | 137 | 0.685765 | [
"Apache-2.0"
] | csoulioti/EntityFrameworkCore | src/EFCore/Infrastructure/EntityFrameworkServicesBuilder.cs | 32,428 | C# |
public Pen estilizarLinha(float[] estiloLinha, Color cor, int espessuraReta)
{
Pen caneta = new Pen(cor, espessuraReta);
caneta.DashPattern = estiloLinha;
return caneta;
}
| 32 | 76 | 0.598214 | [
"MIT"
] | AndreyPradoAP/Computacao_Grafica | Funcoes_e_Procedimentos/Funcao_estilizarReta.cs | 224 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequest.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading;
/// <summary>
/// The type WorkbookFunctionsMidbRequest.
/// </summary>
public partial class WorkbookFunctionsMidbRequest : BaseRequest, IWorkbookFunctionsMidbRequest
{
/// <summary>
/// Constructs a new WorkbookFunctionsMidbRequest.
/// </summary>
public WorkbookFunctionsMidbRequest(
string requestUrl,
IBaseClient client,
IEnumerable<Option> options)
: base(requestUrl, client, options)
{
this.ContentType = CoreConstants.MimeTypeNames.Application.Json;
this.RequestBody = new WorkbookFunctionsMidbRequestBody();
}
/// <summary>
/// Gets the request body.
/// </summary>
public WorkbookFunctionsMidbRequestBody RequestBody { get; private set; }
/// <summary>
/// Issues the POST request.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The task to await for async call.</returns>
public System.Threading.Tasks.Task<WorkbookFunctionResult> PostAsync(
CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.POST;
return this.SendAsync<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Issues the POST request and returns a <see cref="GraphResponse"/> object.
/// </summary>
/// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param>
/// <returns>The <see cref="GraphResponse"/> object of the request</returns>
public System.Threading.Tasks.Task<GraphResponse<WorkbookFunctionResult>> PostResponseAsync(CancellationToken cancellationToken = default)
{
this.Method = HttpMethods.POST;
return this.SendAsyncWithGraphResponse<WorkbookFunctionResult>(this.RequestBody, cancellationToken);
}
/// <summary>
/// Adds the specified expand value to the request.
/// </summary>
/// <param name="value">The expand value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsMidbRequest Expand(string value)
{
this.QueryOptions.Add(new QueryOption("$expand", value));
return this;
}
/// <summary>
/// Adds the specified select value to the request.
/// </summary>
/// <param name="value">The select value.</param>
/// <returns>The request object to send.</returns>
public IWorkbookFunctionsMidbRequest Select(string value)
{
this.QueryOptions.Add(new QueryOption("$select", value));
return this;
}
}
}
| 38.88764 | 153 | 0.602138 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/WorkbookFunctionsMidbRequest.cs | 3,461 | C# |
using System.Threading.Tasks;
namespace Azure.Functions.Cli.Interfaces
{
public interface IHostingPlatform
{
Task DeployContainerizedFunction(string functionName, string image, string nameSpace, int min, int max, double cpu, int memory, string port, string pullSecret);
}
} | 32.666667 | 168 | 0.758503 | [
"MIT"
] | AnnMerlyn/azure-functions-core-tools | src/Azure.Functions.Cli/Interfaces/IHostingPlatform.cs | 294 | C# |
using DotNetBlog.Core.Model.Comment;
using DotNetBlog.Core.Model.Topic;
using System.Collections.Generic;
namespace DotNetBlog.Web.ViewModels.Home
{
public class TopicPageViewModel
{
public bool AllowComment { get; set; }
public CommentFormModel CommentForm { get; set; }
public TopicModel Topic { get; set; }
public TopicModel PrevTopic { get; set; }
public TopicModel NextTopic { get; set; }
public List<TopicModel> RelatedTopicList { get; set; }
public List<CommentModel> CommentList { get; set; }
}
}
| 24.208333 | 62 | 0.672978 | [
"MIT"
] | OmidID/DotNetBlog | src/DotNetBlog.Web/ViewModels/Home/TopicPageViewModel.cs | 583 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using BasicTestApp;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure;
using Microsoft.AspNetCore.Components.E2ETest.Infrastructure.ServerFixtures;
using Microsoft.AspNetCore.E2ETesting;
using OpenQA.Selenium;
using OpenQA.Selenium.Support.UI;
using TestServer;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.AspNetCore.Components.E2ETest.ServerExecutionTests
{
// For now this is limited to server-side execution because we don't have the ability to set the
// culture in client-side Blazor.
public class LocalizationTest : ServerTestBase<BasicTestAppServerSiteFixture<InternationalizationStartup>>
{
public LocalizationTest(
BrowserFixture browserFixture,
BasicTestAppServerSiteFixture<InternationalizationStartup> serverFixture,
ITestOutputHelper output)
: base(browserFixture, serverFixture, output)
{
}
protected override void InitializeAsyncCore()
{
Navigate(ServerPathBase);
Browser.MountTestComponent<CulturePicker>();
Browser.Exists(By.Id("culture-selector"));
}
[Theory]
[InlineData("en-US", "Hello!")]
[InlineData("fr-FR", "Bonjour!")]
public void CanSetCultureAndReadLocalizedResources(string culture, string message)
{
var selector = new SelectElement(Browser.FindElement(By.Id("culture-selector")));
selector.SelectByValue(culture);
// Click the link to return back to the test page
Browser.Exists(By.ClassName("return-from-culture-setter")).Click();
// That should have triggered a page load, so wait for the main test selector to come up.
Browser.MountTestComponent<LocalizedText>();
var cultureDisplay = Browser.Exists(By.Id("culture-name-display"));
Assert.Equal($"Culture is: {culture}", cultureDisplay.Text);
var messageDisplay = Browser.FindElement(By.Id("message-display"));
Assert.Equal(message, messageDisplay.Text);
}
}
}
| 39.736842 | 111 | 0.690066 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Components/test/E2ETest/ServerExecutionTests/LocalizationTest.cs | 2,265 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AntChain.SDK.TWC.Models
{
// 签字人
public class ContractFlowSigner : TeaModel {
// 签署顺序
[NameInMap("sign_order")]
[Validation(Required=false)]
public long? SignOrder { get; set; }
// 签署状态, 0-待签, 1-未签, 2-已签 3-待审批 4-拒签
[NameInMap("sign_status")]
[Validation(Required=false)]
public long? SignStatus { get; set; }
// 签署人账号id
[NameInMap("signer_account_id")]
[Validation(Required=false)]
public string SignerAccountId { get; set; }
// 签署人名称
[NameInMap("signer_name")]
[Validation(Required=false)]
public string SignerName { get; set; }
// 签署人是否已实名
[NameInMap("signer_real_name")]
[Validation(Required=false)]
public bool? SignerRealName { get; set; }
// 签约主体的账号id(个人/企业);如签署人本签署,则返回签署人账号id;如签署人代机构签署,则返回机构账号id
[NameInMap("signer_authorized_account_id")]
[Validation(Required=false)]
public string SignerAuthorizedAccountId { get; set; }
// 签约主体名称
[NameInMap("signer_authorized_account_name")]
[Validation(Required=false)]
public string SignerAuthorizedAccountName { get; set; }
// 签署主体是否已实名
[NameInMap("signer_authorized_account_real_name")]
[Validation(Required=false)]
public bool? SignerAuthorizedAccountRealName { get; set; }
// 签署主体类型, 0-个人, 1-机构
[NameInMap("signer_authorized_account_type")]
[Validation(Required=false)]
public long? SignerAuthorizedAccountType { get; set; }
// 本次签署任务对应指定的第三方业务流水号id,当存在多个第三方业务流水号id时,返回多个,并逗号隔开
[NameInMap("third_order_no")]
[Validation(Required=false)]
public string ThirdOrderNo { get; set; }
}
}
| 29.090909 | 66 | 0.628125 | [
"MIT"
] | alipay/antchain-openapi-prod-sdk | twc/csharp/core/Models/ContractFlowSigner.cs | 2,236 | C# |
using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using SharpMap.Utilities;
namespace SharpMap.Rendering.Decoration
{
/// <summary>
/// North arrow map decoration
/// </summary>
[Serializable]
public class NorthArrow : MapDecoration
{
private static readonly object _lockObject = new object();
private static readonly Bitmap DefaultNorthArrowBitmap;
static NorthArrow()
{
lock(_lockObject)
{
DefaultNorthArrowBitmap = new Bitmap(120, 120);
using (var g = Graphics.FromImage(DefaultNorthArrowBitmap))
{
g.Clear(Color.Transparent);
var b = new SolidBrush(Color.Black);
var p = new Pen(new SolidBrush(Color.Black), 10) {LineJoin = LineJoin.Miter};
g.FillEllipse(b, new RectangleF(50, 50, 20, 20));
g.DrawLine(p, 60, 110, 60, 40);
var pts = new[] {new PointF(45, 40), new PointF(60, 10), new PointF(75, 40), new PointF(45, 40)};
g.FillPolygon(b, pts);
g.DrawPolygon(p, pts);
b = new SolidBrush(Color.White);
g.DrawString("N", new Font("Arial", 20, FontStyle.Bold, GraphicsUnit.Pixel), b, new RectangleF(50, 25, 20, 20),
new StringFormat
{LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center});
}
}
}
/// <summary>
/// Creates an instance of this class
/// </summary>
public NorthArrow()
{
Size = new Size(45, 45);
ForeColor = Color.Silver;
Location = new Point(5, 5);
Anchor = MapDecorationAnchor.LeftTop;
}
/// <summary>
/// Gets or sets the NorthArrowImage
/// </summary>
public Image NorthArrowImage { get; set; }
/// <summary>
/// Gets or sets the size of the North arrow Bitmap
/// </summary>
public Size Size { get; set; }
/// <summary>
/// Gets or sets the fore color
/// </summary>
public Color ForeColor { get; set; }
#region MapDecoration overrides
/// <summary>
/// Function to compute the required size for rendering the map decoration object
/// <para>This is just the size of the decoration object, border settings are excluded</para>
/// </summary>
/// <param name="g">The graphics object</param>
/// <param name="map">The map</param>
/// <returns>The size of the map decoration</returns>
protected override Size InternalSize(Graphics g, Map map)
{
return Size;
}
/// <summary>
/// Function to render the actual map decoration
/// </summary>
/// <param name="g"></param>
/// <param name="map"></param>
protected override void OnRender(Graphics g, Map map)
{
var image = NorthArrowImage ?? DefaultNorthArrowBitmap;
var mapSize = map.Size;
//Get rotation
var ptTop = map.ImageToWorld(new PointF(mapSize.Width/2f, 0f),true);
var ptBottom = map.ImageToWorld(new PointF(mapSize.Width / 2f, mapSize.Height * 0.5f), true);
var dx = ptTop.X - ptBottom.X;
var dy = ptBottom.Y - ptTop.Y;
var length = Math.Sqrt(dx*dx + dy*dy);
var cos = dx/length;
var rot = -90 + (dy > 0 ? -1 : 1) * Math.Acos(cos) / GeoSpatialMath.DegToRad;
var halfSize = new Size((int)(0.5f*Size.Width), (int)(0.5f*Size.Height));
var oldTransform = g.Transform;
var clip = g.ClipBounds;
var newTransform = new Matrix(1f, 0f, 0f, 1f,
clip.Left + halfSize.Width,
clip.Top + halfSize.Height);
newTransform.Rotate((float)rot);
// Setup image attributes
var ia = new ImageAttributes();
var cmap = new [] {
new ColorMap { OldColor = Color.Transparent, NewColor = OpacityColor(BackgroundColor) },
new ColorMap { OldColor = Color.Black, NewColor = OpacityColor(ForeColor) }
};
ia.SetRemapTable( cmap );
g.Transform = newTransform;
var rect = new Rectangle(-halfSize.Width, -halfSize.Height, Size.Width, Size.Height);
g.DrawImage(image, rect, 0, 0, image.Size.Width, image.Size.Height, GraphicsUnit.Pixel, ia);
g.Transform = oldTransform;
}
#endregion
}
} | 36.681818 | 131 | 0.532425 | [
"BSD-2-Clause"
] | zffp/ObjectProcessTool | SharpMap/Rendering/Decoration/NorthArrow.cs | 4,844 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Buffers;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading;
using Microsoft.Win32.SafeHandles;
using SYSTEM_PROCESS_INFORMATION = Interop.NtDll.SYSTEM_PROCESS_INFORMATION;
using SYSTEM_THREAD_INFORMATION = Interop.NtDll.SYSTEM_THREAD_INFORMATION;
namespace System.Diagnostics
{
internal static partial class ProcessManager
{
public static IntPtr GetMainWindowHandle(int processId)
{
return new MainWindowFinder().FindMainWindow(processId);
}
}
internal sealed class MainWindowFinder
{
private const int GW_OWNER = 4;
private IntPtr _bestHandle;
private int _processId;
public IntPtr FindMainWindow(int processId)
{
_bestHandle = IntPtr.Zero;
_processId = processId;
Interop.User32.EnumWindows(EnumWindowsCallback, IntPtr.Zero);
return _bestHandle;
}
private bool IsMainWindow(IntPtr handle)
{
if (Interop.User32.GetWindow(handle, GW_OWNER) != IntPtr.Zero || !Interop.User32.IsWindowVisible(handle))
return false;
return true;
}
private bool EnumWindowsCallback(IntPtr handle, IntPtr extraParameter)
{
int processId;
Interop.User32.GetWindowThreadProcessId(handle, out processId);
if (processId == _processId)
{
if (IsMainWindow(handle))
{
_bestHandle = handle;
return false;
}
}
return true;
}
}
internal static partial class NtProcessManager
{
private static ProcessModuleCollection GetModules(int processId, bool firstModuleOnly)
{
// preserving Everett behavior.
if (processId == SystemProcessID || processId == IdleProcessID)
{
// system process and idle process doesn't have any modules
throw new Win32Exception(HResults.E_FAIL, SR.EnumProcessModuleFailed);
}
SafeProcessHandle processHandle = SafeProcessHandle.InvalidHandle;
try
{
processHandle = ProcessManager.OpenProcess(processId, Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION | Interop.Advapi32.ProcessOptions.PROCESS_VM_READ, true);
bool succeeded = Interop.Kernel32.EnumProcessModules(processHandle, null, 0, out int needed);
// The API we need to use to enumerate process modules differs on two factors:
// 1) If our process is running in WOW64.
// 2) The bitness of the process we wish to introspect.
//
// If we are not running in WOW64 or we ARE in WOW64 but want to inspect a 32 bit process
// we can call psapi!EnumProcessModules.
//
// If we are running in WOW64 and we want to inspect the modules of a 64 bit process then
// psapi!EnumProcessModules will return false with ERROR_PARTIAL_COPY (299). In this case we can't
// do the enumeration at all. So we'll detect this case and bail out.
if (!succeeded)
{
SafeProcessHandle hCurProcess = SafeProcessHandle.InvalidHandle;
try
{
hCurProcess = ProcessManager.OpenProcess((int)Interop.Kernel32.GetCurrentProcessId(), Interop.Advapi32.ProcessOptions.PROCESS_QUERY_INFORMATION, true);
if (!Interop.Kernel32.IsWow64Process(hCurProcess, out bool sourceProcessIsWow64))
{
throw new Win32Exception();
}
if (!Interop.Kernel32.IsWow64Process(processHandle, out bool targetProcessIsWow64))
{
throw new Win32Exception();
}
if (sourceProcessIsWow64 && !targetProcessIsWow64)
{
// Wow64 isn't going to allow this to happen, the best we can do is give a descriptive error to the user.
throw new Win32Exception(Interop.Errors.ERROR_PARTIAL_COPY, SR.EnumProcessModuleFailedDueToWow);
}
}
finally
{
if (hCurProcess != SafeProcessHandle.InvalidHandle)
{
hCurProcess.Dispose();
}
}
EnumProcessModulesUntilSuccess(processHandle, null, 0, out needed);
}
int modulesCount = needed / IntPtr.Size;
IntPtr[] moduleHandles = new IntPtr[modulesCount];
while (true)
{
int size = needed;
EnumProcessModulesUntilSuccess(processHandle, moduleHandles, size, out needed);
if (size == needed)
{
break;
}
if (needed > size && needed / IntPtr.Size > modulesCount)
{
modulesCount = needed / IntPtr.Size;
moduleHandles = new IntPtr[modulesCount];
}
}
var modules = new ProcessModuleCollection(firstModuleOnly ? 1 : modulesCount);
char[] chars = ArrayPool<char>.Shared.Rent(1024);
try
{
for (int i = 0; i < modulesCount; i++)
{
if (i > 0)
{
// If the user is only interested in the main module, break now.
// This avoid some waste of time. In addition, if the application unloads a DLL
// we will not get an exception.
if (firstModuleOnly)
{
break;
}
}
IntPtr moduleHandle = moduleHandles[i];
Interop.Kernel32.NtModuleInfo ntModuleInfo;
if (!Interop.Kernel32.GetModuleInformation(processHandle, moduleHandle, out ntModuleInfo))
{
HandleLastWin32Error();
continue;
}
var module = new ProcessModule()
{
ModuleMemorySize = ntModuleInfo.SizeOfImage,
EntryPointAddress = ntModuleInfo.EntryPoint,
BaseAddress = ntModuleInfo.BaseOfDll
};
int length = Interop.Kernel32.GetModuleBaseName(processHandle, moduleHandle, chars, chars.Length);
if (length == 0)
{
HandleLastWin32Error();
continue;
}
module.ModuleName = new string(chars, 0, length);
length = Interop.Kernel32.GetModuleFileNameEx(processHandle, moduleHandle, chars, chars.Length);
if (length == 0)
{
HandleLastWin32Error();
continue;
}
module.FileName = (length >= 4 && chars[0] == '\\' && chars[1] == '\\' && chars[2] == '?' && chars[3] == '\\') ?
new string(chars, 4, length - 4) :
new string(chars, 0, length);
modules.Add(module);
}
}
finally
{
ArrayPool<char>.Shared.Return(chars);
}
return modules;
}
finally
{
if (!processHandle.IsInvalid)
{
processHandle.Dispose();
}
}
}
private static void EnumProcessModulesUntilSuccess(SafeProcessHandle processHandle, IntPtr[]? modules, int size, out int needed)
{
// When called on a running process, EnumProcessModules may fail with ERROR_PARTIAL_COPY
// if the target process is not yet initialized or if the module list changes during the function call.
// We just try to avoid the race by retring 50 (an arbitrary number) times.
int i = 0;
while (true)
{
if (Interop.Kernel32.EnumProcessModules(processHandle, modules, size, out needed))
{
return;
}
if (i++ > 50)
{
throw new Win32Exception();
}
Thread.Sleep(1);
}
}
private static void HandleLastWin32Error()
{
int lastError = Marshal.GetLastWin32Error();
switch (lastError)
{
case Interop.Errors.ERROR_INVALID_HANDLE:
case Interop.Errors.ERROR_PARTIAL_COPY:
// It's possible that another thread caused this module to become
// unloaded (e.g FreeLibrary was called on the module). Ignore it and
// move on.
break;
default:
throw new Win32Exception(lastError);
}
}
}
internal static class NtProcessInfoHelper
{
// Cache a single buffer for use in GetProcessInfos().
private static long[]? CachedBuffer;
// Use a smaller buffer size on debug to ensure we hit the retry path.
#if DEBUG
private const int DefaultCachedBufferSize = 1024;
#else
private const int DefaultCachedBufferSize = 128 * 1024;
#endif
internal static ProcessInfo[] GetProcessInfos(Predicate<int>? processIdFilter = null)
{
ProcessInfo[] processInfos;
// Start with the default buffer size.
int bufferSize = DefaultCachedBufferSize;
// Get the cached buffer.
long[]? buffer = Interlocked.Exchange(ref CachedBuffer, null);
try
{
while (true)
{
if (buffer == null)
{
// Allocate buffer of longs since some platforms require the buffer to be 64-bit aligned.
buffer = new long[(bufferSize + 7) / 8];
}
uint requiredSize = 0;
unsafe
{
// Note that the buffer will contain pointers to itself and it needs to be pinned while it is being processed
// by GetProcessInfos below
fixed (long* bufferPtr = buffer)
{
uint status = Interop.NtDll.NtQuerySystemInformation(
Interop.NtDll.SystemProcessInformation,
bufferPtr,
(uint)(buffer.Length * sizeof(long)),
&requiredSize);
if (status != Interop.NtDll.STATUS_INFO_LENGTH_MISMATCH)
{
// see definition of NT_SUCCESS(Status) in SDK
if ((int)status < 0)
{
throw new InvalidOperationException(SR.CouldntGetProcessInfos, new Win32Exception((int)status));
}
// Parse the data block to get process information
processInfos = GetProcessInfos(MemoryMarshal.AsBytes<long>(buffer), processIdFilter);
break;
}
}
}
buffer = null;
bufferSize = GetNewBufferSize(bufferSize, (int)requiredSize);
}
}
finally
{
// Cache the final buffer for use on the next call.
Interlocked.Exchange(ref CachedBuffer, buffer);
}
return processInfos;
}
private static int GetNewBufferSize(int existingBufferSize, int requiredSize)
{
int newSize;
if (requiredSize == 0)
{
//
// On some old OS like win2000, requiredSize will not be set if the buffer
// passed to NtQuerySystemInformation is not enough.
//
newSize = existingBufferSize * 2;
}
else
{
// allocating a few more kilo bytes just in case there are some new process
// kicked in since new call to NtQuerySystemInformation
newSize = requiredSize + 1024 * 10;
}
if (newSize < 0)
{
// In reality, we should never overflow.
// Adding the code here just in case it happens.
throw new OutOfMemoryException();
}
return newSize;
}
private static unsafe ProcessInfo[] GetProcessInfos(ReadOnlySpan<byte> data, Predicate<int>? processIdFilter)
{
// Use a dictionary to avoid duplicate entries if any
// 60 is a reasonable number for processes on a normal machine.
Dictionary<int, ProcessInfo> processInfos = new Dictionary<int, ProcessInfo>(60);
int processInformationOffset = 0;
while (true)
{
ref readonly SYSTEM_PROCESS_INFORMATION pi = ref MemoryMarshal.AsRef<SYSTEM_PROCESS_INFORMATION>(data.Slice(processInformationOffset));
// Process ID shouldn't overflow. OS API GetCurrentProcessID returns DWORD.
int processInfoProcessId = pi.UniqueProcessId.ToInt32();
if (processIdFilter == null || processIdFilter(processInfoProcessId))
{
// get information for a process
ProcessInfo processInfo = new ProcessInfo((int)pi.NumberOfThreads)
{
ProcessId = processInfoProcessId,
SessionId = (int)pi.SessionId,
PoolPagedBytes = (long)pi.QuotaPagedPoolUsage,
PoolNonPagedBytes = (long)pi.QuotaNonPagedPoolUsage,
VirtualBytes = (long)pi.VirtualSize,
VirtualBytesPeak = (long)pi.PeakVirtualSize,
WorkingSetPeak = (long)pi.PeakWorkingSetSize,
WorkingSet = (long)pi.WorkingSetSize,
PageFileBytesPeak = (long)pi.PeakPagefileUsage,
PageFileBytes = (long)pi.PagefileUsage,
PrivateBytes = (long)pi.PrivatePageCount,
BasePriority = pi.BasePriority,
HandleCount = (int)pi.HandleCount,
};
if (pi.ImageName.Buffer == IntPtr.Zero)
{
if (processInfo.ProcessId == NtProcessManager.SystemProcessID)
{
processInfo.ProcessName = "System";
}
else if (processInfo.ProcessId == NtProcessManager.IdleProcessID)
{
processInfo.ProcessName = "Idle";
}
else
{
// for normal process without name, using the process ID.
processInfo.ProcessName = processInfo.ProcessId.ToString(CultureInfo.InvariantCulture);
}
}
else
{
string processName = GetProcessShortName(new ReadOnlySpan<char>(pi.ImageName.Buffer.ToPointer(), pi.ImageName.Length / sizeof(char)));
processInfo.ProcessName = processName;
}
// get the threads for current process
processInfos[processInfo.ProcessId] = processInfo;
int threadInformationOffset = processInformationOffset + sizeof(SYSTEM_PROCESS_INFORMATION);
for (int i = 0; i < pi.NumberOfThreads; i++)
{
ref readonly SYSTEM_THREAD_INFORMATION ti = ref MemoryMarshal.AsRef<SYSTEM_THREAD_INFORMATION>(data.Slice(threadInformationOffset));
ThreadInfo threadInfo = new ThreadInfo
{
_processId = (int)ti.ClientId.UniqueProcess,
_threadId = (ulong)ti.ClientId.UniqueThread,
_basePriority = ti.BasePriority,
_currentPriority = ti.Priority,
_startAddress = ti.StartAddress,
_threadState = (ThreadState)ti.ThreadState,
_threadWaitReason = NtProcessManager.GetThreadWaitReason((int)ti.WaitReason),
};
processInfo._threadInfoList.Add(threadInfo);
threadInformationOffset += sizeof(SYSTEM_THREAD_INFORMATION);
}
}
if (pi.NextEntryOffset == 0)
{
break;
}
processInformationOffset += (int)pi.NextEntryOffset;
}
ProcessInfo[] temp = new ProcessInfo[processInfos.Values.Count];
processInfos.Values.CopyTo(temp, 0);
return temp;
}
// This function generates the short form of process name.
//
// This is from GetProcessShortName in NT code base.
// Check base\screg\winreg\perfdlls\process\perfsprc.c for details.
internal static string GetProcessShortName(ReadOnlySpan<char> name)
{
if (name.IsEmpty)
{
return string.Empty;
}
int slash = -1;
int period = -1;
for (int i = 0; i < name.Length; i++)
{
if (name[i] == '\\')
slash = i;
else if (name[i] == '.')
period = i;
}
if (period == -1)
period = name.Length - 1; // set to end of string
else
{
// if a period was found, then see if the extension is
// .EXE, if so drop it, if not, then use end of string
// (i.e. include extension in name)
ReadOnlySpan<char> extension = name.Slice(period);
if (extension.Equals(".exe", StringComparison.OrdinalIgnoreCase))
period--; // point to character before period
else
period = name.Length - 1; // set to end of string
}
if (slash == -1)
slash = 0; // set to start of string
else
slash++; // point to character next to slash
// copy characters between period (or end of string) and
// slash (or start of string) to make image name
return name.Slice(slash, period - slash + 1).ToString();
}
}
}
| 40.66 | 185 | 0.493212 | [
"MIT"
] | VFLashM/runtime | src/libraries/System.Diagnostics.Process/src/System/Diagnostics/ProcessManager.Win32.cs | 20,330 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using Bing.Applications.Aspects;
using Bing.Applications.Dtos;
using Bing.Validations.Aspects;
namespace Bing.Applications.Operations
{
/// <summary>
/// 创建操作
/// </summary>
/// <typeparam name="TCreateRequest">创建参数类型</typeparam>
public interface ICreateAsync<in TCreateRequest> where TCreateRequest : IRequest, new()
{
/// <summary>
/// 创建
/// </summary>
/// <param name="request">请求参数</param>
/// <returns></returns>
[UnitOfWork]
Task<string> CreateAsync([Valid] TCreateRequest request);
}
}
| 26.038462 | 91 | 0.649926 | [
"MIT"
] | hanabi1224/Bing.NetCore | src/Bing.Applications/Operations/ICreateAsync.cs | 711 | C# |
namespace ClassLibraryTvShows
{
public class Links
{
public Self self { get; set; }
public Previousepisode previousepisode { get; set; }
public Nextepisode nextepisode { get; set; }
}
}
| 22.3 | 60 | 0.627803 | [
"MIT"
] | jurajperic/oop_zadace | DZ6/TvShows/ClassLibraryTvShows/Links.cs | 225 | C# |
namespace Identity.Business.Mappers.Abstractions
{
using System.Collections.Generic;
using AlbedoTeam.Identity.Contracts.Common;
using AlbedoTeam.Identity.Contracts.Requests;
using AlbedoTeam.Identity.Contracts.Responses;
using AlbedoTeam.Sdk.DataLayerAccess.Utils.Query;
using Models;
using Models.SubDocuments;
public interface IAuthServerMapper
{
AuthServer MapRequestToModel(CreateAuthServer request);
CommunicationRules MapRequestToModel(ICommunicationRules request);
AuthServerResponse MapModelToResponse(AuthServer model);
List<AuthServerResponse> MapModelToResponse(List<AuthServer> models);
QueryParams RequestToQuery(ListAuthServers request);
}
} | 38.842105 | 77 | 0.772358 | [
"MIT"
] | albedoteam/wrk-identity | src/Mappers/Abstractions/IAuthServerMapper.cs | 740 | C# |
using System;
using System.Activities;
using System.IO;
using System.Linq;
using Capgemini.Pipefy.Attachment;
using Capgemini.Pipefy.TableRecord;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
namespace Capgemini.Pipefy.Test
{
[TestClass]
public class AttachmentTest
{
private static TestConfiguration testConfig;
private static Helper.Table attachmentTable;
[ClassInitialize]
public static void AttachmentTestInitialize(TestContext context)
{
testConfig = TestConfiguration.Instance;
attachmentTable = Helper.Table.CreateTable("AtachmentTable");
var attachmentField = new Helper.CustomField("File", "attachment");
attachmentTable.CreateField(attachmentField);
}
[ClassCleanup]
public static void AttachmentTestCleanup()
{
attachmentTable.Delete();
}
[TestMethod]
public void UploadFile_TableRecordFileInfo_Success()
{
// Create
var dict = testConfig.GetDefaultActivityArguments();
dict["TableID"] = attachmentTable.Id;
dict["Title"] = "Upload TextFile Test Record";
var act = new CreateTableRecord();
var result = WorkflowInvoker.Invoke(act, dict);
Assert.IsTrue((bool)result["Success"]);
var recordId = (long)result["TableRecordID"];
Assert.IsTrue(recordId > 0);
// Upload file
var fileInfo = new FileInfo("TestFiles/simple-text.txt");
dict = testConfig.GetDefaultActivityArguments();
dict["OrganizationID"] = testConfig.GetCustomConfig("OrganizationID");
dict["FileInfo"] = fileInfo;
var act2 = new UploadAttachment();
result = WorkflowInvoker.Invoke(act2, dict);
var uploadedUrl = (string)result["FileUrl"];
Assert.IsTrue((bool)result["Success"]);
Assert.IsFalse(string.IsNullOrWhiteSpace(uploadedUrl));
// Update TableRecord field
dict = testConfig.GetDefaultActivityArguments();
dict["TableRecordID"] = recordId;
dict["FieldID"] = "file";
dict["Value"] = new string[]{ uploadedUrl };
var act3 = new SetTableRecordFieldValue();
result = WorkflowInvoker.Invoke(act3, dict);
Assert.IsTrue((bool)result["Success"]);
// Get
dict = testConfig.GetDefaultActivityArguments();
dict["TableRecordID"] = recordId;
var act4 = new GetTableRecord();
result = WorkflowInvoker.Invoke(act4, dict);
Assert.IsTrue((bool)result["Success"]);
var tableRecord = (JObject)result["TableRecord"];
var valuesJArray = tableRecord["record_fields"] as JArray;
var valuesDict = Helper.TableRecord.FieldsJArrayToJObjectDictionary(valuesJArray);
Assert.AreEqual(uploadedUrl, valuesDict["file"]["array_value"].First.Value<string>());
// Delete
dict = testConfig.GetDefaultActivityArguments();
dict["TableRecordID"] = recordId;
var act5 = new DeleteTableRecord();
result = WorkflowInvoker.Invoke(act5, dict);
Assert.IsTrue((bool)result["Success"]);
Assert.AreEqual(act5.SuccessMessage, result["Status"].ToString());
}
}
} | 34.62 | 98 | 0.617562 | [
"MIT"
] | mghextreme/pipefy-uipath-activities | Capgemini.Pipefy.Test/AttachmentTest.cs | 3,462 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace StrawberryShake.CodeGeneration.CSharp {
using System;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
[System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class ServerResources {
private static System.Resources.ResourceManager resourceMan;
private static System.Globalization.CultureInfo resourceCulture;
[System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal ServerResources() {
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static System.Resources.ResourceManager ResourceManager {
get {
if (object.Equals(null, resourceMan)) {
System.Resources.ResourceManager temp = new System.Resources.ResourceManager("StrawberryShake.CodeGeneration.CSharp.ServerResources", typeof(ServerResources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
internal static System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
internal static string Main_No_Arguments {
get {
return ResourceManager.GetString("Main_No_Arguments", resourceCulture);
}
}
internal static string Main_Request_File_Does_Not_Exist {
get {
return ResourceManager.GetString("Main_Request_File_Does_Not_Exist", resourceCulture);
}
}
internal static string CSharpGeneratorServer_ClientName_Invalid {
get {
return ResourceManager.GetString("CSharpGeneratorServer_ClientName_Invalid", resourceCulture);
}
}
}
}
| 39.238806 | 188 | 0.600609 | [
"MIT"
] | ChilliCream/prometheus | src/StrawberryShake/CodeGeneration/src/CodeGeneration.CSharp.Server/ServerResources.Designer.cs | 2,631 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using Apache.NMS.Policies;
using NUnit.Framework;
namespace Apache.NMS.Test
{
[TestFixture]
public class RedeliveryPolicyTest
{
[Test]
public void Executes_redelivery_policy_with_backoff_enabled_correctly()
{
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.BackOffMultiplier = 2;
policy.InitialRedeliveryDelay = 5;
policy.UseExponentialBackOff = true;
// simulate a retry of 10 times
Assert.IsTrue(policy.RedeliveryDelay(0) == 0, "redelivery delay not 5 is " + policy.RedeliveryDelay(0));
Assert.IsTrue(policy.RedeliveryDelay(1) == 5, "redelivery delay not 10 is " + policy.RedeliveryDelay(1));
Assert.IsTrue(policy.RedeliveryDelay(2) == 10, "redelivery delay not 20 is " + policy.RedeliveryDelay(2));
Assert.IsTrue(policy.RedeliveryDelay(3) == 20, "redelivery delay not 40 is " + policy.RedeliveryDelay(3));
Assert.IsTrue(policy.RedeliveryDelay(4) == 40, "redelivery delay not 80 is " + policy.RedeliveryDelay(4));
Assert.IsTrue(policy.RedeliveryDelay(5) == 80, "redelivery delay not 160 is " + policy.RedeliveryDelay(5));
Assert.IsTrue(policy.RedeliveryDelay(6) == 160, "redelivery delay not 320 is " + policy.RedeliveryDelay(6));
Assert.IsTrue(policy.RedeliveryDelay(7) == 320, "redelivery delay not 640 is " + policy.RedeliveryDelay(7));
Assert.IsTrue(policy.RedeliveryDelay(8) == 640, "redelivery delay not 1280 is " + policy.RedeliveryDelay(8));
Assert.IsTrue(policy.RedeliveryDelay(9) == 1280, "redelivery delay not 2560 is " + policy.RedeliveryDelay(9));
}
[Test]
public void Executes_redelivery_policy_with_backoff_of_3_enabled_correctly()
{
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.BackOffMultiplier = 3;
policy.InitialRedeliveryDelay = 3;
policy.UseExponentialBackOff = true;
// simulate a retry of 10 times
Assert.IsTrue(policy.RedeliveryDelay(0) == 0, "redelivery delay not 5 is " + policy.RedeliveryDelay(0));
Assert.IsTrue(policy.RedeliveryDelay(1) == 3, "redelivery delay not 10 is " + policy.RedeliveryDelay(1));
Assert.IsTrue(policy.RedeliveryDelay(2) == 9, "redelivery delay not 20 is " + policy.RedeliveryDelay(2));
Assert.IsTrue(policy.RedeliveryDelay(3) == 27, "redelivery delay not 40 is " + policy.RedeliveryDelay(3));
Assert.IsTrue(policy.RedeliveryDelay(4) == 81, "redelivery delay not 80 is " + policy.RedeliveryDelay(4));
Assert.IsTrue(policy.RedeliveryDelay(5) == 243, "redelivery delay not 160 is " + policy.RedeliveryDelay(5));
Assert.IsTrue(policy.RedeliveryDelay(6) == 729, "redelivery delay not 320 is " + policy.RedeliveryDelay(6));
Assert.IsTrue(policy.RedeliveryDelay(7) == 2187, "redelivery delay not 640 is " + policy.RedeliveryDelay(7));
Assert.IsTrue(policy.RedeliveryDelay(8) == 6561, "redelivery delay not 1280 is " + policy.RedeliveryDelay(8));
Assert.IsTrue(policy.RedeliveryDelay(9) == 19683, "redelivery delay not 2560 is " + policy.RedeliveryDelay(9));
}
[Test]
public void Executes_redelivery_policy_without_backoff_enabled_correctly()
{
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.InitialRedeliveryDelay = 5;
// simulate a retry of 10 times
Assert.IsTrue(policy.RedeliveryDelay(0) == 0, "redelivery delay not 0 is " + policy.RedeliveryDelay(0));
Assert.IsTrue(policy.RedeliveryDelay(1) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(1));
Assert.IsTrue(policy.RedeliveryDelay(2) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(2));
Assert.IsTrue(policy.RedeliveryDelay(3) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(3));
Assert.IsTrue(policy.RedeliveryDelay(4) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(4));
Assert.IsTrue(policy.RedeliveryDelay(5) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(5));
Assert.IsTrue(policy.RedeliveryDelay(6) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(6));
Assert.IsTrue(policy.RedeliveryDelay(7) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(7));
Assert.IsTrue(policy.RedeliveryDelay(8) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(8));
Assert.IsTrue(policy.RedeliveryDelay(9) == 5, "redelivery delay not 5 is " + policy.RedeliveryDelay(9));
}
[Test]
public void Should_get_collision_percent_correctly()
{
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.CollisionAvoidancePercent = 45;
Assert.IsTrue(policy.CollisionAvoidancePercent == 45);
}
[Test]
public void Executes_redelivery_policy_with_collision_enabled_correctly()
{
RedeliveryPolicy policy = new RedeliveryPolicy();
policy.BackOffMultiplier = 2;
policy.InitialRedeliveryDelay = 5;
policy.UseExponentialBackOff = true;
policy.UseCollisionAvoidance = true;
policy.CollisionAvoidancePercent = 10;
// simulate a retry of 10 times
int delay = policy.RedeliveryDelay(0);
Assert.IsTrue(delay == 0, "not zero is " + policy.RedeliveryDelay(0));
delay = policy.RedeliveryDelay(1);
Assert.IsTrue(delay >= 4.5 && delay <= 5.5, "not delay >= 4.5 && delay <= 5.5 is " + policy.RedeliveryDelay(1));
delay = policy.RedeliveryDelay(2);
Assert.IsTrue(delay >= 9 && delay <= 11, "not delay >= 9 && delay <= 11 is " + policy.RedeliveryDelay(2));
delay = policy.RedeliveryDelay(3);
Assert.IsTrue(delay >= 18 && delay <= 22, "not delay >= 18 && delay <= 22 is " + policy.RedeliveryDelay(3));
delay = policy.RedeliveryDelay(4);
Assert.IsTrue(delay >= 36 && delay <= 44, "not delay >= 36 && delay <= 44 is " + policy.RedeliveryDelay(4));
delay = policy.RedeliveryDelay(5);
Assert.IsTrue(delay >= 72 && delay <= 88, "not delay >= 72 && delay <= 88 is " + policy.RedeliveryDelay(5));
delay = policy.RedeliveryDelay(6);
Assert.IsTrue(delay >= 144 && delay <= 176, "not delay >= 144 && delay <= 176 is " + policy.RedeliveryDelay(6));
delay = policy.RedeliveryDelay(7);
Assert.IsTrue(delay >= 288 && delay <= 352, "not delay >= 288 && delay <= 352 is " + policy.RedeliveryDelay(7));
delay = policy.RedeliveryDelay(8);
Assert.IsTrue(delay >= 576 && delay <= 704, "not delay >= 576 && delay <= 704 is " + policy.RedeliveryDelay(8));
delay = policy.RedeliveryDelay(9);
Assert.IsTrue(delay >= 1152 && delay <= 1408, "not delay >= 1152 && delay <= 1408 is " + policy.RedeliveryDelay(9));
delay = policy.RedeliveryDelay(10);
Assert.IsTrue(delay >= 2304 && delay <= 2816, "not delay >= 2304 && delay <= 2816 is " + policy.RedeliveryDelay(10));
}
}
}
| 59.233577 | 129 | 0.643993 | [
"Apache-2.0"
] | Havret/activemq-nms-api | test/nms-api-test/RedeliveryPolicyTest.cs | 8,117 | C# |
namespace CrossJob.Web
{
using System;
using System.Linq;
using System.Web.UI;
using Ninject;
using Services.Contracts;
public partial class Projects : Page
{
[Inject]
public IProjectsService ProjectsService { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
}
public IQueryable<CrossJob.Models.Project> GridViewProjects_GetData()
{
return this.ProjectsService.GetAll().Where(p => p.FinishOn > DateTime.Now);
}
}
} | 22.708333 | 87 | 0.618349 | [
"MIT"
] | Team-Katana-WebForms/CrossJob | CrossJob/Web/CrossJob.Web/Projects.aspx.cs | 547 | C# |
using System.Text;
namespace MSPack.Processor.Core
{
public static class NoBomUtf8Encoder
{
public static readonly Encoding Encoding = new UTF8Encoding(false);
}
}
| 19.5 | 76 | 0.676923 | [
"MIT"
] | pCYSl5EDgo/MSPack-Processor | src/Core/Generator/NoBomUtf8Encoder.cs | 197 | C# |
namespace SchoolManager.Service.Responses
{
public interface IResponse
{
string Message { get; set; }
bool DidError { get; set; }
string ErrorMessage { get; set; }
}
}
| 20.4 | 41 | 0.602941 | [
"MIT"
] | LissetteIbnz/aspnetcore-efcore-api | SchoolManager.Service/Responses/IResponse.cs | 204 | C# |
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class DetectionManager : MonoBehaviour {
public int maxDetection;
public static int currentDetection;
public Slider detectionBar;
public LevelManager levelManager;
public float invisWait;
private float invisCount;
public PlayerController player;
// Use this for initialization
void Start () {
//detectionBar = GetComponent<Slider> ();
currentDetection = 0;
levelManager = GameObject.FindObjectOfType<LevelManager> ();
player = FindObjectOfType<PlayerController> ();
}
// Update is called once per frame
void Update () {
detectionBar.value = currentDetection;
if (player.isInvisible ()) {
if (invisCount <= 0) {
addDetection (-1);
invisCount = invisWait;
}else
invisCount -= Time.deltaTime;
}
}
public static void addDetection(int value){
if (value > 0) {
if (currentDetection >= 100) {
currentDetection = 100;
} else {
currentDetection += value;
}
} else {
if (currentDetection <= 0) {
currentDetection = 0;
} else {
currentDetection += value;
}
}
}
public static int getDetection(){
return currentDetection;
}
}
| 19.85 | 62 | 0.691016 | [
"MIT"
] | NguX0530/ufoabduction | Assets/Scripts/DetectionManager.cs | 1,193 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.Logic
{
public static class ListIntegrationAccountKeyVaultKeys
{
/// <summary>
/// Collection of key vault keys.
/// API Version: 2019-05-01.
/// </summary>
public static Task<ListIntegrationAccountKeyVaultKeysResult> InvokeAsync(ListIntegrationAccountKeyVaultKeysArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<ListIntegrationAccountKeyVaultKeysResult>("azure-native:logic:listIntegrationAccountKeyVaultKeys", args ?? new ListIntegrationAccountKeyVaultKeysArgs(), options.WithVersion());
}
public sealed class ListIntegrationAccountKeyVaultKeysArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The integration account name.
/// </summary>
[Input("integrationAccountName", required: true)]
public string IntegrationAccountName { get; set; } = null!;
/// <summary>
/// The key vault reference.
/// </summary>
[Input("keyVault", required: true)]
public Inputs.KeyVaultReferenceArgs KeyVault { get; set; } = null!;
/// <summary>
/// The resource group name.
/// </summary>
[Input("resourceGroupName", required: true)]
public string ResourceGroupName { get; set; } = null!;
/// <summary>
/// The skip token.
/// </summary>
[Input("skipToken")]
public string? SkipToken { get; set; }
public ListIntegrationAccountKeyVaultKeysArgs()
{
}
}
[OutputType]
public sealed class ListIntegrationAccountKeyVaultKeysResult
{
/// <summary>
/// The skip token.
/// </summary>
public readonly string? SkipToken;
/// <summary>
/// The key vault keys.
/// </summary>
public readonly ImmutableArray<Outputs.KeyVaultKeyResponseResult> Value;
[OutputConstructor]
private ListIntegrationAccountKeyVaultKeysResult(
string? skipToken,
ImmutableArray<Outputs.KeyVaultKeyResponseResult> value)
{
SkipToken = skipToken;
Value = value;
}
}
}
| 32.051282 | 230 | 0.6316 | [
"Apache-2.0"
] | pulumi-bot/pulumi-azure-native | sdk/dotnet/Logic/ListIntegrationAccountKeyVaultKeys.cs | 2,500 | C# |
using Xunit;
using Shouldly;
namespace AutoMapper.UnitTests.Bug
{
public class NullableEnums : AutoMapperSpecBase
{
public class Src { public EnumType? A { get; set; } }
public class Dst { public EnumType? A { get; set; } }
public enum EnumType { One, Two }
protected override MapperConfiguration Configuration { get; } = new MapperConfiguration(cfg =>
{
cfg.CreateMap<Src, Dst>();
});
[Fact]
public void TestNullableEnum()
{
var d = Mapper.Map(new Src { A = null }, new Dst { A = EnumType.One });
d.A.ShouldBeNull();
}
}
} | 25.307692 | 102 | 0.56383 | [
"MIT"
] | AutoMapper/AutoMapper | src/UnitTests/Bug/NullableEnums.cs | 660 | C# |
using FluentAssertions;
using FluentAssertions.Execution;
using FluentAssertions.Primitives;
using Tensorflow.NumPy;
using System;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using Tensorflow;
namespace TensorFlowNET.UnitTest
{
[DebuggerStepThrough]
public static class FluentExtension
{
public static ShapeAssertions Should(this Shape shape)
{
return new ShapeAssertions(shape);
}
public static NDArrayAssertions Should(this NDArray arr)
{
return new NDArrayAssertions(arr);
}
public static string ToString(this Array arr, bool flat)
{
// return new NDArray(arr).ToString(flat);
throw new NotImplementedException("");
}
}
[DebuggerStepThrough]
public class ShapeAssertions : ReferenceTypeAssertions<Shape, ShapeAssertions>
{
public ShapeAssertions(Shape instance)
{
Subject = instance;
}
protected override string Identifier => "shape";
public AndConstraint<ShapeAssertions> BeOfSize(int size, string because = null, params object[] becauseArgs)
{
Subject.size.Should().Be(size, because, becauseArgs);
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> NotBeOfSize(int size, string because = null, params object[] becauseArgs)
{
Subject.size.Should().NotBe(size, because, becauseArgs);
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> BeShaped(params int[] dimensions)
{
if (dimensions == null)
throw new ArgumentNullException(nameof(dimensions));
if (dimensions.Length == 0)
throw new ArgumentException("Value cannot be an empty collection.", nameof(dimensions));
Subject.dims.Should().BeEquivalentTo(dimensions);
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> Be(Shape shape, string because = null, params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(Subject.Equals(shape))
.FailWith($"Expected shape to be {shape.ToString()} but got {Subject.ToString()}");
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> BeEquivalentTo(int? size = null, int? ndim = null, ITuple shape = null)
{
if (size.HasValue)
{
BeOfSize(size.Value, null);
}
if (ndim.HasValue)
HaveNDim(ndim.Value);
if (shape != null)
for (int i = 0; i < shape.Length; i++)
{
Subject.dims[i].Should().Be((int)shape[i]);
}
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> NotBe(Shape shape, string because = null, params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(!Subject.Equals(shape))
.FailWith($"Expected shape to be {shape.ToString()} but got {Subject.ToString()}");
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> HaveNDim(int ndim)
{
Subject.dims.Length.Should().Be(ndim);
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> BeScalar()
{
Subject.IsScalar.Should().BeTrue();
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> NotBeScalar()
{
Subject.IsScalar.Should().BeFalse();
return new AndConstraint<ShapeAssertions>(this);
}
public AndConstraint<ShapeAssertions> BeNDim(int ndim)
{
Subject.dims.Length.Should().Be(ndim);
return new AndConstraint<ShapeAssertions>(this);
}
}
//[DebuggerStepThrough]
public class NDArrayAssertions : ReferenceTypeAssertions<NDArray, NDArrayAssertions>
{
public NDArrayAssertions(NDArray instance)
{
Subject = instance;
}
protected override string Identifier => "shape";
public AndConstraint<NDArrayAssertions> BeOfSize(int size, string because = null, params object[] becauseArgs)
{
Subject.size.Should().Be((ulong)size, because, becauseArgs);
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> BeShaped(params int[] dimensions)
{
if (dimensions == null)
throw new ArgumentNullException(nameof(dimensions));
if (dimensions.Length == 0)
throw new ArgumentException("Value cannot be an empty collection.", nameof(dimensions));
Subject.dims.Should().BeEquivalentTo(dimensions);
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> BeShaped(int? size = null, int? ndim = null, ITuple shape = null)
{
if (size.HasValue)
{
BeOfSize(size.Value, null);
}
if (ndim.HasValue)
HaveNDim(ndim.Value);
if (shape != null)
for (int i = 0; i < shape.Length; i++)
{
Subject.dims[i].Should().Be((int)shape[i]);
}
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> NotBeShaped(Shape shape, string because = null, params object[] becauseArgs)
{
Execute.Assertion
.BecauseOf(because, becauseArgs)
.ForCondition(!Subject.dims.Equals(shape.dims))
.FailWith($"Expected shape to be {shape} but got {Subject}");
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> HaveNDim(int ndim)
{
Subject.ndim.Should().Be(ndim);
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> BeScalar()
{
Subject.shape.IsScalar.Should().BeTrue();
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> BeScalar(object value)
{
Subject.shape.IsScalar.Should().BeTrue();
Subject.GetValue().Should().Be(value);
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> BeOfType(Type typeCode)
{
Subject.dtype.Should().Be(typeCode);
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> NotBeScalar()
{
Subject.shape.IsScalar.Should().BeFalse();
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> BeNDim(int ndim)
{
Subject.ndim.Should().Be(ndim);
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> Be(NDArray expected)
{
Execute.Assertion
.ForCondition(np.array_equal(Subject, expected))
.FailWith($"Expected the subject and other ndarray to be equals.\n------- Subject -------\n{Subject}\n------- Expected -------\n{expected}");
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> AllValuesBe(object val)
{
#region Compute
/*switch (Subject.typecode)
{
case NPTypeCode.Boolean:
{
var iter = Subject.AsIterator<bool>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToBoolean(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Byte:
{
var iter = Subject.AsIterator<byte>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToByte(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Byte).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Int16:
{
var iter = Subject.AsIterator<short>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToInt16(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Int16).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.UInt16:
{
var iter = Subject.AsIterator<ushort>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToUInt16(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: UInt16).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Int32:
{
var iter = Subject.AsIterator<int>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToInt32(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Int32).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.UInt32:
{
var iter = Subject.AsIterator<uint>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToUInt32(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: UInt32).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Int64:
{
var iter = Subject.AsIterator<long>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToInt64(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Int64).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.UInt64:
{
var iter = Subject.AsIterator<ulong>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToUInt64(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: UInt64).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Char:
{
var iter = Subject.AsIterator<char>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToChar(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Char).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Double:
{
var iter = Subject.AsIterator<double>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToDouble(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Double).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Single:
{
var iter = Subject.AsIterator<float>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToSingle(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Single).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
case NPTypeCode.Decimal:
{
var iter = Subject.AsIterator<decimal>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
var expected = Convert.ToDecimal(val);
for (int i = 0; hasnext(); i++)
{
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {2}th value to be {0}, but found {1} (dtype: Decimal).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n{val}", expected, nextval, i);
}
break;
}
default:
throw new NotSupportedException();
}*/
#endregion
return new AndConstraint<NDArrayAssertions>(this);
}
public AndConstraint<NDArrayAssertions> BeOfValuesApproximately(double sensitivity, params object[] values)
{
if (values == null)
throw new ArgumentNullException(nameof(values));
Subject.size.Should().Be((ulong)values.Length, "the method BeOfValuesApproximately also confirms the sizes are matching with given values.");
#region Compute
/*switch (Subject.typecode)
{
case NPTypeCode.Boolean:
{
var iter = Subject.AsIterator<bool>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToBoolean(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(expected == nextval)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Byte:
{
var iter = Subject.AsIterator<byte>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToByte(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Int16:
{
var iter = Subject.AsIterator<short>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToInt16(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.UInt16:
{
var iter = Subject.AsIterator<ushort>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToUInt16(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Int32:
{
var iter = Subject.AsIterator<int>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToInt32(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.UInt32:
{
var iter = Subject.AsIterator<uint>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToUInt32(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Int64:
{
var iter = Subject.AsIterator<long>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToInt64(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.UInt64:
{
var iter = Subject.AsIterator<ulong>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToUInt64(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs((double)(expected - nextval)) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Char:
{
var iter = Subject.AsIterator<char>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToChar(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Double:
{
var iter = Subject.AsIterator<double>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToDouble(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Single:
{
var iter = Subject.AsIterator<float>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToSingle(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
case NPTypeCode.Decimal:
{
var iter = Subject.AsIterator<decimal>();
var next = iter.MoveNext;
var hasnext = iter.HasNext;
for (int i = 0; i < values.Length; i++)
{
Execute.Assertion
.ForCondition(hasnext())
.FailWith($"Expected the NDArray to have atleast {values.Length} but in fact it has size of {i}.");
var expected = Convert.ToDecimal(values[i]);
var nextval = next();
Execute.Assertion
.ForCondition(Math.Abs(expected - nextval) <= (decimal)sensitivity)
.FailWith($"Expected NDArray's {{2}}th value to be {{0}}, but found {{1}} (dtype: Boolean).\n------- Subject -------\n{Subject.ToString(false)}\n------- Expected -------\n[{string.Join(", ", values.Select(v => v.ToString()))}]", expected, nextval, i);
}
break;
}
default:
throw new NotSupportedException();
}*/
#endregion
return new AndConstraint<NDArrayAssertions>(this);
}
}
} | 44.266312 | 283 | 0.443268 | [
"Apache-2.0"
] | Hallupa/TensorFlow.NET | test/TensorFlowNET.UnitTest/Utilities/FluentExtension.cs | 33,246 | C# |
using System.Collections.Generic;
using ZMachineLib.Content;
namespace ZMachineLib.Operations.OP2
{
/// <summary>
/// 2OP:5 5 inc_chk (variable) value ?(label)
/// Increment variable, and branch if now greater than value.
/// </summary>
public sealed class IncCheck : ZMachineOperationBase
{
public IncCheck(IZMemory memory)
: base((ushort)OpCodes.IncCheck, memory)
{
}
public override void Execute(List<ushort> args)
{
var variableManager = Memory.VariableManager;
var val = (short)variableManager.GetUShort((byte)args[0]);
val++;
ushort value = (ushort)val;
variableManager.Store((byte)args[0], value);
Memory.Jump(val > (short)args[1]);
}
}
} | 29.925926 | 70 | 0.597772 | [
"MIT"
] | Chrislee187/ZMachineLib | ZMachineLib/Operations/OP2/IncCheck.cs | 810 | C# |
// Copyright (c) 2012-2015 Sharpex2D - Kevin Scholz (ThuCommix)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using Sharpex2D.Math;
namespace Sharpex2D.Rendering
{
[Developer("ThuCommix", "developer@sharpex2d.de")]
[TestState(TestState.Tested)]
public interface IRenderer
{
/// <summary>
/// Gets or sets the SmoothingMode.
/// </summary>
SmoothingMode SmoothingMode { get; set; }
/// <summary>
/// Gets or sets the InterpolationMode.
/// </summary>
InterpolationMode InterpolationMode { get; set; }
/// <summary>
/// Initializes the renderer.
/// </summary>
void Initialize();
/// <summary>
/// Begins the draw operation.
/// </summary>
void Begin();
/// <summary>
/// Ends the draw operation.
/// </summary>
void End();
/// <summary>
/// Draws a string.
/// </summary>
/// <param name="text">The Text.</param>
/// <param name="font">The Font.</param>
/// <param name="rectangle">The Rectangle.</param>
/// <param name="color">The Color.</param>
void DrawString(string text, IFont font, Rectangle rectangle, Color color);
/// <summary>
/// Draws a string.
/// </summary>
/// <param name="text">The Text.</param>
/// <param name="font">The Font.</param>
/// <param name="position">The Position.</param>
/// <param name="color">The Color.</param>
void DrawString(string text, IFont font, Vector2 position, Color color);
/// <summary>
/// Draws a Texture.
/// </summary>
/// <param name="texture">The Texture.</param>
/// <param name="position">The Position.</param>
/// <param name="opacity">The Opacity.</param>
/// <param name="color">The Color.</param>
void DrawTexture(ITexture texture, Vector2 position, Color color, float opacity = 1f);
/// <summary>
/// Draws a Texture.
/// </summary>
/// <param name="texture">The Texture.</param>
/// <param name="rectangle">The Rectangle.</param>
/// <param name="opacity">The Opacity.</param>
/// <param name="color">The Color.</param>
void DrawTexture(ITexture texture, Rectangle rectangle, Color color, float opacity = 1f);
/// <summary>
/// Draws a Texture.
/// </summary>
/// <param name="texture">The Texture.</param>
/// <param name="spriteSheet">The SpriteSheet.</param>
/// <param name="position">The Position.</param>
/// <param name="color">The Color.</param>
/// <param name="opacity">The Opacity.</param>
void DrawTexture(ITexture texture, SpriteSheet spriteSheet, Vector2 position, Color color, float opacity = 1f);
/// <summary>
/// Draws a Texture.
/// </summary>
/// <param name="texture">The Texture.</param>
/// <param name="spriteSheet">The SpriteSheet.</param>
/// <param name="rectangle">The Rectangle.</param>
/// <param name="color">The Color.</param>
/// <param name="opacity">The Opacity.</param>
void DrawTexture(ITexture texture, SpriteSheet spriteSheet, Rectangle rectangle, Color color, float opacity = 1f);
/// <summary>
/// Draws a Texture.
/// </summary>
/// <param name="texture">The Texture.</param>
/// <param name="source">The SourceRectangle.</param>
/// <param name="destination">The DestinationRectangle.</param>
/// <param name="color">The Color.</param>
/// <param name="opacity">The Opacity.</param>
void DrawTexture(ITexture texture, Rectangle source, Rectangle destination, Color color,
float opacity = 1f);
/// <summary>
/// Measures the string.
/// </summary>
/// <param name="text">The String.</param>
/// <param name="font">The Font.</param>
/// <returns>Vector2.</returns>
Vector2 MeasureString(string text, IFont font);
/// <summary>
/// Sets the Transform.
/// </summary>
/// <param name="matrix">The Matrix.</param>
void SetTransform(Matrix2x3 matrix);
/// <summary>
/// Resets the Transform.
/// </summary>
void ResetTransform();
/// <summary>
/// Creates a new Resource.
/// </summary>
/// <param name="fontFamily">The FontFamily.</param>
/// <param name="size">The Size.</param>
/// <param name="accessoire">The TextAccessoire.</param>
/// <returns>IFont.</returns>
IFont CreateResource(string fontFamily, float size, TextAccessoire accessoire);
/// <summary>
/// Creates a new Resource.
/// </summary>
/// <param name="path">The Path.</param>
/// <returns>ITexture.</returns>
ITexture CreateResource(string path);
/// <summary>
/// Creates a new Resource.
/// </summary>
/// <param name="width">The Width.</param>
/// <param name="height">The Height.</param>
/// <returns>ITexture.</returns>
ITexture CreateResource(int width, int height);
}
} | 38.521212 | 122 | 0.590308 | [
"MIT"
] | ThuCommix/Sharpex2D | Sharpex2D/Rendering/IRenderer.cs | 6,358 | C# |
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using Thinktecture.IdentityModel.Owin.ResourceAuthorization;
namespace Owin.ResourceAuthorization.Tests
{
public static class ResourceAuthorizationContextExtensions
{
public static bool HasClaim(this IEnumerable<Claim> claims, string claimType)
{
return claims.Any(c => c.Type == claimType);
}
public static string ClaimValue(this IEnumerable<Claim> claims, string claimType)
{
return claims.Single(c => c.Type == claimType).Value;
}
public static IEnumerable<string> ClaimValues(this IEnumerable<Claim> claims, string claimType)
{
return claims.Where(c => c.Type == claimType).Select(c => c.Value);
}
public static IEnumerable<string> NameClaims(this IEnumerable<Claim> claims)
{
return claims.ClaimValues("name");
}
public static IEnumerable<string> ActionNames(this ResourceAuthorizationContext context)
{
return context.Action.NameClaims();
}
public static IEnumerable<string> ResourceNames(this ResourceAuthorizationContext context)
{
return context.Resource.NameClaims();
}
}
} | 32.525 | 104 | 0.659493 | [
"BSD-3-Clause"
] | BadriL/Thinktecture.IdentityModel | source/Owin.ResourceAuthorization.Tests/ResourceAuthorizationContextExtensions.cs | 1,301 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Threading.Tasks;
namespace MonuGuardaApp.Models
{
public class PontosdeInteresse
{
public int PontosdeInteresseId { get; set; }
[Required(ErrorMessage = "É necessário colocar nome")]
[StringLength(40)]
public string Nome { get; set; }
public int FreguesiaId { get; set; }
public Freguesia Freguesia { get; set; }
public int ConcelhoId { get; set; }
public Concelho Concelho { get; set; }
[Required(ErrorMessage = "É necessário colocar morada")]
[StringLength(100)]
public string Morada { get; set; }
[Required(ErrorMessage = "É necessário colocar coordenadas")]
[StringLength(100)]
public string Coordenadas { get; set; }
}
}
| 27.5625 | 69 | 0.64966 | [
"MIT"
] | Greatbisca/MonuGuardaApp | MonuGuardaApp/Models/PontosdeInteresse.cs | 890 | C# |
using UnityEngine;
public class KeyPointsHandler : MonoBehaviour {
public GameObject MainMenuCamPoint;
public GameObject LevelCamPoint;
public GameObject DropdownAreaPoint;
public GameObject EntryPoint;
public GameObject EntryLandingPoint;
public GameObject MainMenuExitPoint;
public GameObject LevelEntryPoint;
public GameObject LevelMenuMidPoint;
public GameObject LevelMenuEndPoint;
public GameObject LevelMapStart;
private void Start()
{
foreach(SpriteRenderer kp in transform.GetComponentsInChildren<SpriteRenderer>())
{
kp.GetComponent<SpriteRenderer>().enabled = false;
}
}
}
| 25.259259 | 89 | 0.725806 | [
"Apache-2.0"
] | Aspekt1024/ClumsyBat | Assets/Scripts/Menu/MainMenu/Components/KeyPointsHandler.cs | 684 | C# |
using System.Collections.Generic;
using Essensoft.Paylink.Alipay.Response;
namespace Essensoft.Paylink.Alipay.Request
{
/// <summary>
/// alipay.open.app.test.test.create
/// </summary>
public class AlipayOpenAppTestTestCreateRequest : IAlipayRequest<AlipayOpenAppTestTestCreateResponse>
{
/// <summary>
/// 验收测试SPI接口
/// </summary>
public string BizContent { get; set; }
#region IAlipayRequest Members
private bool needEncrypt = false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AlipayObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt)
{
this.needEncrypt = needEncrypt;
}
public bool GetNeedEncrypt()
{
return needEncrypt;
}
public void SetNotifyUrl(string notifyUrl)
{
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl()
{
return notifyUrl;
}
public void SetReturnUrl(string returnUrl)
{
this.returnUrl = returnUrl;
}
public string GetReturnUrl()
{
return returnUrl;
}
public void SetTerminalType(string terminalType)
{
this.terminalType = terminalType;
}
public string GetTerminalType()
{
return terminalType;
}
public void SetTerminalInfo(string terminalInfo)
{
this.terminalInfo = terminalInfo;
}
public string GetTerminalInfo()
{
return terminalInfo;
}
public void SetProdCode(string prodCode)
{
this.prodCode = prodCode;
}
public string GetProdCode()
{
return prodCode;
}
public string GetApiName()
{
return "alipay.open.app.test.test.create";
}
public void SetApiVersion(string apiVersion)
{
this.apiVersion = apiVersion;
}
public string GetApiVersion()
{
return apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if (udfParams == null)
{
udfParams = new Dictionary<string, string>();
}
udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
var parameters = new AlipayDictionary
{
{ "biz_content", BizContent }
};
if (udfParams != null)
{
parameters.AddAll(udfParams);
}
return parameters;
}
public AlipayObject GetBizModel()
{
return bizModel;
}
public void SetBizModel(AlipayObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.463768 | 105 | 0.537369 | [
"MIT"
] | Frunck8206/payment | src/Essensoft.Paylink.Alipay/Request/AlipayOpenAppTestTestCreateRequest.cs | 3,252 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
namespace Google.Cloud.Monitoring.V3.Snippets
{
using Google.Api.Gax;
using Google.Cloud.Monitoring.V3;
public sealed partial class GeneratedAlertPolicyServiceClientStandaloneSnippets
{
/// <summary>Snippet for GetAlertPolicy</summary>
/// <remarks>
/// This snippet has been automatically generated for illustrative purposes only.
/// It may require modifications to work in your environment.
/// </remarks>
public void GetAlertPolicyResourceNames2()
{
// Create client
AlertPolicyServiceClient alertPolicyServiceClient = AlertPolicyServiceClient.Create();
// Initialize request argument(s)
IResourceName name = new UnparsedResourceName("a/wildcard/resource");
// Make the request
AlertPolicy response = alertPolicyServiceClient.GetAlertPolicy(name);
}
}
}
| 38.425 | 98 | 0.698764 | [
"Apache-2.0"
] | googleapis/googleapis-gen | google/monitoring/v3/google-cloud-monitoring-v3-csharp/Google.Cloud.Monitoring.V3.StandaloneSnippets/AlertPolicyServiceClient.GetAlertPolicyResourceNames2Snippet.g.cs | 1,537 | C# |
using UnityEditor;
using UnityEngine;
namespace LoneTower.SRP {
public class SRPGUIDrawer {
SRPController srp;
VisibilityButton visibility;
PaintButton paintButton;
public SRPGUIDrawer(SRPController srp) {
this.srp = srp;
visibility = new VisibilityButton();
paintButton = new PaintButton();
visibility.OnEnable += srp.VisibilityOff;
visibility.OnDisable += srp.VisibilityOn;
paintButton.OnEnable += srp.PaintOn;
paintButton.OnDisable += srp.PaintOff;
}
public Rect InspectorDraw(Rect position, string label) {
visibility.state = !srp.State.visible;
paintButton.state = srp.State.enabled;
position = EditorGUI.PrefixLabel(position, UnityEngine.GUIUtility.GetControlID(FocusType.Passive), new GUIContent(label));
GUITools.ColorField(position, srp.drawer.color);
position = paintButton.PropertyDraw(position);
position = visibility.PropertyDraw(position);
return position;
}
~SRPGUIDrawer() {
visibility.OnEnable -= srp.VisibilityOff;
visibility.OnDisable -= srp.VisibilityOn;
paintButton.OnEnable -= srp.PaintOn;
paintButton.OnDisable -= srp.PaintOff;
}
}
} | 24.361702 | 125 | 0.739738 | [
"MIT"
] | MLopusiewicz/SceneReferencePicker | Assets/SRP/Editor/GUI/SRPGUIDrawer.cs | 1,147 | C# |
using System;
using System.Text;
namespace Sharp.Xmpp.Core.Sasl.Mechanisms
{
/// <summary>
/// Implements the Sasl Plain authentication method as described in
/// RFC 4616.
/// </summary>
internal class SaslPlain : SaslMechanism
{
private bool Completed = false;
/// <summary>
/// True if the authentication exchange between client and server
/// has been completed.
/// </summary>
public override bool IsCompleted
{
get
{
return Completed;
}
}
/// <summary>
/// Sasl Plain just sends one initial response.
/// </summary>
public override bool HasInitial
{
get
{
return true;
}
}
/// <summary>
/// The IANA name for the Plain authentication mechanism as described
/// in RFC 4616.
/// </summary>
public override string Name
{
get
{
return "PLAIN";
}
}
/// <summary>
/// The username to authenticate with.
/// </summary>
private string Username
{
get
{
return Properties.ContainsKey("Username") ?
Properties["Username"] as string : null;
}
set
{
Properties["Username"] = value;
}
}
/// <summary>
/// The plain-text password to authenticate with.
/// </summary>
private string Password
{
get
{
return Properties.ContainsKey("Password") ?
Properties["Password"] as string : null;
}
set
{
Properties["Password"] = value;
}
}
/// <summary>
/// Private constructor for use with Sasl.SaslFactory.
/// </summary>
private SaslPlain()
{
// Nothing to do here.
}
/// <summary>
/// Creates and initializes a new instance of the SaslPlain class
/// using the specified username and password.
/// </summary>
/// <param name="username">The username to authenticate with.</param>
/// <param name="password">The plaintext password to authenticate
/// with.</param>
/// <exception cref="ArgumentNullException">The username or the
/// password parameter is null.</exception>
/// <exception cref="ArgumentException">The username parameter
/// is empty.</exception>
public SaslPlain(string username, string password)
{
username.ThrowIfNull("username");
if (username == string.Empty)
throw new ArgumentException("The username must not be empty.");
password.ThrowIfNull("password");
Username = username;
Password = password;
}
/// <summary>
/// Computes the client response for a plain-challenge.
/// </summary>
/// <param name="challenge">The challenge sent by the server. For the
/// "plain" mechanism this will usually be empty.</param>
/// <returns>The response for the "plain"-challenge.</returns>
/// <exception cref="SaslException">The response could not be
/// computed.</exception>
protected override byte[] ComputeResponse(byte[] challenge)
{
// Precondition: Ensure username and password are not null and
// username is not empty.
if (string.IsNullOrEmpty(Username) || Password == null)
{
throw new SaslException("The username must not be null or empty and " +
"the password must not be null.");
}
// Sasl Plain does not involve another roundtrip.
Completed = true;
// Username and password are delimited by a NUL (U+0000) character
// and the response shall be encoded as UTF-8.
return Encoding.UTF8.GetBytes("\0" + Username + "\0" + Password);
}
}
} | 30.941606 | 87 | 0.515688 | [
"MIT"
] | REPLDigital/Sharp.Xmpp | Core/Sasl/Mechanisms/SaslPlain.cs | 4,241 | C# |
namespace Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Extensions;
/// <summary>Dictionary of <string></summary>
public partial class ServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json erialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <see "returnNow" /> output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Models.Api20170401Preview.IServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns FromJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json ? new ServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject into a new instance of <see cref="ServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns"
/// />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject instance to deserialize from.</param>
/// <param name="exclusions"></param>
internal ServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject json, global::System.Collections.Generic.HashSet<string> exclusions = null)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.JsonSerializable.FromJson( json, ((Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.IAssociativeArray<string>)this).AdditionalProperties, null ,exclusions );
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="ServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns" /> into a <see
/// cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="ServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode"
/// />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.JsonSerializable.ToJson( ((Microsoft.Azure.PowerShell.Cmdlets.StreamAnalytics.Runtime.IAssociativeArray<string>)this).AdditionalProperties, container);
AfterToJson(ref container);
return container;
}
}
} | 70.72381 | 277 | 0.707918 | [
"MIT"
] | Agazoth/azure-powershell | src/StreamAnalytics/generated/api/Models/Api20170401Preview/ServiceBusQueueOutputDataSourcePropertiesSystemPropertyColumns.json.cs | 7,322 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.Compute.V20200601.Outputs
{
[OutputType]
public sealed class VirtualMachineScaleSetDataDiskResponse
{
/// <summary>
/// Specifies the caching requirements. <br><br> Possible values are: <br><br> **None** <br><br> **ReadOnly** <br><br> **ReadWrite** <br><br> Default: **None for Standard storage. ReadOnly for Premium storage**
/// </summary>
public readonly string? Caching;
/// <summary>
/// The create option.
/// </summary>
public readonly string CreateOption;
/// <summary>
/// Specifies the Read-Write IOPS for the managed disk. Should be used only when StorageAccountType is UltraSSD_LRS. If not specified, a default value would be assigned based on diskSizeGB.
/// </summary>
public readonly int? DiskIOPSReadWrite;
/// <summary>
/// Specifies the bandwidth in MB per second for the managed disk. Should be used only when StorageAccountType is UltraSSD_LRS. If not specified, a default value would be assigned based on diskSizeGB.
/// </summary>
public readonly int? DiskMBpsReadWrite;
/// <summary>
/// Specifies the size of an empty data disk in gigabytes. This element can be used to overwrite the size of the disk in a virtual machine image. <br><br> This value cannot be larger than 1023 GB
/// </summary>
public readonly int? DiskSizeGB;
/// <summary>
/// Specifies the logical unit number of the data disk. This value is used to identify data disks within the VM and therefore must be unique for each data disk attached to a VM.
/// </summary>
public readonly int Lun;
/// <summary>
/// The managed disk parameters.
/// </summary>
public readonly Outputs.VirtualMachineScaleSetManagedDiskParametersResponse? ManagedDisk;
/// <summary>
/// The disk name.
/// </summary>
public readonly string? Name;
/// <summary>
/// Specifies whether writeAccelerator should be enabled or disabled on the disk.
/// </summary>
public readonly bool? WriteAcceleratorEnabled;
[OutputConstructor]
private VirtualMachineScaleSetDataDiskResponse(
string? caching,
string createOption,
int? diskIOPSReadWrite,
int? diskMBpsReadWrite,
int? diskSizeGB,
int lun,
Outputs.VirtualMachineScaleSetManagedDiskParametersResponse? managedDisk,
string? name,
bool? writeAcceleratorEnabled)
{
Caching = caching;
CreateOption = createOption;
DiskIOPSReadWrite = diskIOPSReadWrite;
DiskMBpsReadWrite = diskMBpsReadWrite;
DiskSizeGB = diskSizeGB;
Lun = lun;
ManagedDisk = managedDisk;
Name = name;
WriteAcceleratorEnabled = writeAcceleratorEnabled;
}
}
}
| 39.929412 | 278 | 0.63789 | [
"Apache-2.0"
] | test-wiz-sec/pulumi-azure-nextgen | sdk/dotnet/Compute/V20200601/Outputs/VirtualMachineScaleSetDataDiskResponse.cs | 3,394 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO.Pipelines;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Infrastructure;
namespace Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http
{
public class HttpParser<TRequestHandler> : IHttpParser<TRequestHandler> where TRequestHandler : IHttpHeadersHandler, IHttpRequestLineHandler
{
private bool _showErrorDetails;
public HttpParser() : this(showErrorDetails: true)
{
}
public HttpParser(bool showErrorDetails)
{
_showErrorDetails = showErrorDetails;
}
// byte types don't have a data type annotation so we pre-cast them; to avoid in-place casts
private const byte ByteCR = (byte)'\r';
private const byte ByteLF = (byte)'\n';
private const byte ByteColon = (byte)':';
private const byte ByteSpace = (byte)' ';
private const byte ByteTab = (byte)'\t';
private const byte ByteQuestionMark = (byte)'?';
private const byte BytePercentage = (byte)'%';
public unsafe bool ParseRequestLine(TRequestHandler handler, ReadableBuffer buffer, out ReadCursor consumed, out ReadCursor examined)
{
consumed = buffer.Start;
examined = buffer.End;
// Prepare the first span
var span = buffer.First.Span;
var lineIndex = span.IndexOf(ByteLF);
if (lineIndex >= 0)
{
consumed = buffer.Move(consumed, lineIndex + 1);
span = span.Slice(0, lineIndex + 1);
}
else if (buffer.IsSingleSpan)
{
// No request line end
return false;
}
else if (TryGetNewLine(ref buffer, out var found))
{
span = buffer.Slice(consumed, found).ToSpan();
consumed = found;
}
else
{
// No request line end
return false;
}
// Fix and parse the span
fixed (byte* data = &span.DangerousGetPinnableReference())
{
ParseRequestLine(handler, data, span.Length);
}
examined = consumed;
return true;
}
private unsafe void ParseRequestLine(TRequestHandler handler, byte* data, int length)
{
int offset;
Span<byte> customMethod = default(Span<byte>);
// Get Method and set the offset
var method = HttpUtilities.GetKnownMethod(data, length, out offset);
if (method == HttpMethod.Custom)
{
customMethod = GetUnknownMethod(data, length, out offset);
}
// Skip space
offset++;
byte ch = 0;
// Target = Path and Query
var pathEncoded = false;
var pathStart = -1;
for (; offset < length; offset++)
{
ch = data[offset];
if (ch == ByteSpace)
{
if (pathStart == -1)
{
// Empty path is illegal
RejectRequestLine(data, length);
}
break;
}
else if (ch == ByteQuestionMark)
{
if (pathStart == -1)
{
// Empty path is illegal
RejectRequestLine(data, length);
}
break;
}
else if (ch == BytePercentage)
{
if (pathStart == -1)
{
// Path starting with % is illegal
RejectRequestLine(data, length);
}
pathEncoded = true;
}
else if (pathStart == -1)
{
pathStart = offset;
}
}
if (pathStart == -1)
{
// Start of path not found
RejectRequestLine(data, length);
}
var pathBuffer = new Span<byte>(data + pathStart, offset - pathStart);
// Query string
var queryStart = offset;
if (ch == ByteQuestionMark)
{
// We have a query string
for (; offset < length; offset++)
{
ch = data[offset];
if (ch == ByteSpace)
{
break;
}
}
}
// End of query string not found
if (offset == length)
{
RejectRequestLine(data, length);
}
var targetBuffer = new Span<byte>(data + pathStart, offset - pathStart);
var query = new Span<byte>(data + queryStart, offset - queryStart);
// Consume space
offset++;
// Version
var httpVersion = HttpUtilities.GetKnownVersion(data + offset, length - offset);
if (httpVersion == HttpVersion.Unknown)
{
if (data[offset] == ByteCR || data[length - 2] != ByteCR)
{
// If missing delimiter or CR before LF, reject and log entire line
RejectRequestLine(data, length);
}
else
{
// else inform HTTP version is unsupported.
RejectUnknownVersion(data + offset, length - offset - 2);
}
}
// After version's 8 bytes and CR, expect LF
if (data[offset + 8 + 1] != ByteLF)
{
RejectRequestLine(data, length);
}
handler.OnStartLine(method, httpVersion, targetBuffer, pathBuffer, query, customMethod, pathEncoded);
}
public unsafe bool ParseHeaders(TRequestHandler handler, ReadableBuffer buffer, out ReadCursor consumed, out ReadCursor examined, out int consumedBytes)
{
consumed = buffer.Start;
examined = buffer.End;
consumedBytes = 0;
var bufferEnd = buffer.End;
var reader = new ReadableBufferReader(buffer);
var start = default(ReadableBufferReader);
var done = false;
try
{
while (!reader.End)
{
var span = reader.Span;
var remaining = span.Length - reader.Index;
fixed (byte* pBuffer = &span.DangerousGetPinnableReference())
{
while (remaining > 0)
{
var index = reader.Index;
int ch1;
int ch2;
// Fast path, we're still looking at the same span
if (remaining >= 2)
{
ch1 = pBuffer[index];
ch2 = pBuffer[index + 1];
}
else
{
// Store the reader before we look ahead 2 bytes (probably straddling
// spans)
start = reader;
// Possibly split across spans
ch1 = reader.Take();
ch2 = reader.Take();
}
if (ch1 == ByteCR)
{
// Check for final CRLF.
if (ch2 == -1)
{
// Reset the reader so we don't consume anything
reader = start;
return false;
}
else if (ch2 == ByteLF)
{
// If we got 2 bytes from the span directly so skip ahead 2 so that
// the reader's state matches what we expect
if (index == reader.Index)
{
reader.Skip(2);
}
done = true;
return true;
}
// Headers don't end in CRLF line.
RejectRequest(RequestRejectionReason.InvalidRequestHeadersNoCRLF);
}
// We moved the reader so look ahead 2 bytes so reset both the reader
// and the index
if (index != reader.Index)
{
reader = start;
index = reader.Index;
}
var endIndex = new Span<byte>(pBuffer + index, remaining).IndexOf(ByteLF);
var length = 0;
if (endIndex != -1)
{
length = endIndex + 1;
var pHeader = pBuffer + index;
TakeSingleHeader(pHeader, length, handler);
}
else
{
var current = reader.Cursor;
// Split buffers
if (ReadCursorOperations.Seek(current, bufferEnd, out var lineEnd, ByteLF) == -1)
{
// Not there
return false;
}
// Make sure LF is included in lineEnd
lineEnd = buffer.Move(lineEnd, 1);
var headerSpan = buffer.Slice(current, lineEnd).ToSpan();
length = headerSpan.Length;
fixed (byte* pHeader = &headerSpan.DangerousGetPinnableReference())
{
TakeSingleHeader(pHeader, length, handler);
}
// We're going to the next span after this since we know we crossed spans here
// so mark the remaining as equal to the headerSpan so that we end up at 0
// on the next iteration
remaining = length;
}
// Skip the reader forward past the header line
reader.Skip(length);
remaining -= length;
}
}
}
return false;
}
finally
{
consumed = reader.Cursor;
consumedBytes = reader.ConsumedBytes;
if (done)
{
examined = consumed;
}
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe int FindEndOfName(byte* headerLine, int length)
{
var index = 0;
var sawWhitespace = false;
for (; index < length; index++)
{
var ch = headerLine[index];
if (ch == ByteColon)
{
break;
}
if (ch == ByteTab || ch == ByteSpace || ch == ByteCR)
{
sawWhitespace = true;
}
}
if (index == length || sawWhitespace)
{
RejectRequestHeader(headerLine, length);
}
return index;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private unsafe void TakeSingleHeader(byte* headerLine, int length, TRequestHandler handler)
{
// Skip CR, LF from end position
var valueEnd = length - 3;
var nameEnd = FindEndOfName(headerLine, length);
if (headerLine[valueEnd + 2] != ByteLF)
{
RejectRequestHeader(headerLine, length);
}
if (headerLine[valueEnd + 1] != ByteCR)
{
RejectRequestHeader(headerLine, length);
}
// Skip colon from value start
var valueStart = nameEnd + 1;
// Ignore start whitespace
for (; valueStart < valueEnd; valueStart++)
{
var ch = headerLine[valueStart];
if (ch != ByteTab && ch != ByteSpace && ch != ByteCR)
{
break;
}
else if (ch == ByteCR)
{
RejectRequestHeader(headerLine, length);
}
}
// Check for CR in value
var valueBuffer = new Span<byte>(headerLine + valueStart, valueEnd - valueStart + 1);
if (valueBuffer.IndexOf(ByteCR) >= 0)
{
RejectRequestHeader(headerLine, length);
}
// Ignore end whitespace
var lengthChanged = false;
for (; valueEnd >= valueStart; valueEnd--)
{
var ch = headerLine[valueEnd];
if (ch != ByteTab && ch != ByteSpace)
{
break;
}
lengthChanged = true;
}
if (lengthChanged)
{
// Length changed
valueBuffer = new Span<byte>(headerLine + valueStart, valueEnd - valueStart + 1);
}
var nameBuffer = new Span<byte>(headerLine, nameEnd);
handler.OnHeader(nameBuffer, valueBuffer);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private static bool TryGetNewLine(ref ReadableBuffer buffer, out ReadCursor found)
{
var start = buffer.Start;
if (ReadCursorOperations.Seek(start, buffer.End, out found, ByteLF) != -1)
{
// Move 1 byte past the \n
found = buffer.Move(found, 1);
return true;
}
return false;
}
[MethodImpl(MethodImplOptions.NoInlining)]
private unsafe Span<byte> GetUnknownMethod(byte* data, int length, out int methodLength)
{
methodLength = 0;
for (var i = 0; i < length; i++)
{
var ch = data[i];
if (ch == ByteSpace)
{
if (i == 0)
{
RejectRequestLine(data, length);
}
methodLength = i;
break;
}
else if (!IsValidTokenChar((char)ch))
{
RejectRequestLine(data, length);
}
}
return new Span<byte>(data, methodLength);
}
private static bool IsValidTokenChar(char c)
{
// Determines if a character is valid as a 'token' as defined in the
// HTTP spec: https://tools.ietf.org/html/rfc7230#section-3.2.6
return
(c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'Z') ||
(c >= 'a' && c <= 'z') ||
c == '!' ||
c == '#' ||
c == '$' ||
c == '%' ||
c == '&' ||
c == '\'' ||
c == '*' ||
c == '+' ||
c == '-' ||
c == '.' ||
c == '^' ||
c == '_' ||
c == '`' ||
c == '|' ||
c == '~';
}
private void RejectRequest(RequestRejectionReason reason)
=> throw BadHttpRequestException.GetException(reason);
private unsafe void RejectRequestLine(byte* requestLine, int length)
=> throw GetInvalidRequestException(RequestRejectionReason.InvalidRequestLine, requestLine, length);
private unsafe void RejectRequestHeader(byte* headerLine, int length)
=> throw GetInvalidRequestException(RequestRejectionReason.InvalidRequestHeader, headerLine, length);
private unsafe void RejectUnknownVersion(byte* version, int length)
=> throw GetInvalidRequestException(RequestRejectionReason.UnrecognizedHTTPVersion, version, length);
private unsafe BadHttpRequestException GetInvalidRequestException(RequestRejectionReason reason, byte* detail, int length)
=> BadHttpRequestException.GetException(
reason,
_showErrorDetails
? new Span<byte>(detail, length).GetAsciiStringEscaped(Constants.MaxExceptionDetailSize)
: string.Empty);
}
}
| 35.829659 | 160 | 0.427373 | [
"Apache-2.0"
] | benaadams/KestrelHttpServer | src/Kestrel.Core/Internal/Http/HttpParser.cs | 17,879 | C# |
using System.Xml.Serialization;
namespace Alipay.AopSdk.Core.Response
{
/// <summary>
/// AlipayCommerceCityfacilitatorVoucherGenerateResponse.
/// </summary>
public class AlipayCommerceCityfacilitatorVoucherGenerateResponse : AopResponse
{
/// <summary>
/// 核销码过期时间
/// </summary>
[XmlElement("expired_date")]
public string ExpiredDate { get; set; }
/// <summary>
/// 地铁购票二维码编码,可自定义
/// </summary>
[XmlElement("qr_code_no")]
public string QrCodeNo { get; set; }
/// <summary>
/// 地铁购票的核销码
/// </summary>
[XmlElement("ticket_no")]
public string TicketNo { get; set; }
}
}
| 24.793103 | 83 | 0.573018 | [
"MIT"
] | leixf2005/Alipay.AopSdk.Core | Alipay.AopSdk.Core/Response/AlipayCommerceCityfacilitatorVoucherGenerateResponse.cs | 777 | C# |
using System;
using LanguageExt.ClassInstances;
namespace LanguageExt
{
/// <summary>
/// A proxy for `Ref`, returned by `commute`. This allows the transaction system to know that the
/// result is a commutative and therefore give you a result based on the live state rather than
/// the transaction.
/// </summary>
/// <remarks>
/// See the [concurrency section](https://github.com/louthy/language-ext/wiki/Concurrency) of the wiki for more info.
/// </remarks>
public readonly struct CommuteRef<A>
{
internal CommuteRef(Ref<A> r) => Ref = r;
internal readonly Ref<A> Ref;
public A Value
{
get => Ref.Value;
set => Ref.Value = value;
}
public static implicit operator A(CommuteRef<A> r) => r.Value;
public override string ToString() => Value?.ToString() ?? "[null]";
public override int GetHashCode() => Value?.GetHashCode() ?? 0;
public override bool Equals(object obj) => obj is A val && Equals(val);
public bool Equals(A other) => default(EqDefault<A>).Equals(other, Value);
public A Swap(Func<A, A> f) => Ref.Swap(f);
public A Swap<X>(X x, Func<X, A, A> f) => Ref.Swap(x, f);
public A Swap<X, Y>(X x, Y y, Func<X, Y, A, A> f) => Ref.Swap(x, y, f);
public CommuteRef<A> Commute(Func<A, A> f) => Ref.Commute(f);
public A Commute<X>(X x, Func<X, A, A> f) => Ref.Commute(x, f);
public A Commute<X, Y>(X x, Y y, Func<X, Y, A, A> f) => Ref.Commute(x, y, f);
}
}
| 43.388889 | 121 | 0.587068 | [
"MIT"
] | CK-LinoPro/language-ext | LanguageExt.Core/Concurrency/STM/CommuteRef.cs | 1,564 | C# |
using System;
using System.Collections.Generic;
namespace DurandalAuth.Domain.Models
{
public partial class rf_activity
{
public string bl_id { get; set; }
public Nullable<System.DateTime> date_activity { get; set; }
public Nullable<int> direction { get; set; }
public Nullable<decimal> epoch_time { get; set; }
public string fl_id { get; set; }
public Nullable<int> geo_objectid { get; set; }
public Nullable<decimal> lat { get; set; }
public Nullable<decimal> lon { get; set; }
public string reader_id { get; set; }
public string rm_id { get; set; }
public string site_id { get; set; }
public string tag_id { get; set; }
public Nullable<System.DateTime> time_activity { get; set; }
public int rf_act_id { get; set; }
public virtual bl bl { get; set; }
public virtual Fl fl { get; set; }
public virtual rf_reader rf_reader { get; set; }
public virtual Rm rm { get; set; }
public virtual site site { get; set; }
}
}
| 37.275862 | 68 | 0.612396 | [
"MIT"
] | benitazz/AlcmSolutions | DurandalAuth.Domain/Models/rf_activity.cs | 1,081 | C# |
/*
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
/*
* Do not modify this file. This file is generated from the license-manager-2018-08-01.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using System.Xml.Serialization;
using Amazon.LicenseManager.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.LicenseManager.Model.Internal.MarshallTransformations
{
/// <summary>
/// CreateLicense Request Marshaller
/// </summary>
public class CreateLicenseRequestMarshaller : IMarshaller<IRequest, CreateLicenseRequest> , IMarshaller<IRequest,AmazonWebServiceRequest>
{
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public IRequest Marshall(AmazonWebServiceRequest input)
{
return this.Marshall((CreateLicenseRequest)input);
}
/// <summary>
/// Marshaller the request object to the HTTP request.
/// </summary>
/// <param name="publicRequest"></param>
/// <returns></returns>
public IRequest Marshall(CreateLicenseRequest publicRequest)
{
IRequest request = new DefaultRequest(publicRequest, "Amazon.LicenseManager");
string target = "AWSLicenseManager.CreateLicense";
request.Headers["X-Amz-Target"] = target;
request.Headers["Content-Type"] = "application/x-amz-json-1.1";
request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2018-08-01";
request.HttpMethod = "POST";
request.ResourcePath = "/";
request.MarshallerVersion = 2;
using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
{
JsonWriter writer = new JsonWriter(stringWriter);
writer.WriteObjectStart();
var context = new JsonMarshallerContext(request, writer);
if(publicRequest.IsSetBeneficiary())
{
context.Writer.WritePropertyName("Beneficiary");
context.Writer.Write(publicRequest.Beneficiary);
}
if(publicRequest.IsSetClientToken())
{
context.Writer.WritePropertyName("ClientToken");
context.Writer.Write(publicRequest.ClientToken);
}
if(publicRequest.IsSetConsumptionConfiguration())
{
context.Writer.WritePropertyName("ConsumptionConfiguration");
context.Writer.WriteObjectStart();
var marshaller = ConsumptionConfigurationMarshaller.Instance;
marshaller.Marshall(publicRequest.ConsumptionConfiguration, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetEntitlements())
{
context.Writer.WritePropertyName("Entitlements");
context.Writer.WriteArrayStart();
foreach(var publicRequestEntitlementsListValue in publicRequest.Entitlements)
{
context.Writer.WriteObjectStart();
var marshaller = EntitlementMarshaller.Instance;
marshaller.Marshall(publicRequestEntitlementsListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetHomeRegion())
{
context.Writer.WritePropertyName("HomeRegion");
context.Writer.Write(publicRequest.HomeRegion);
}
if(publicRequest.IsSetIssuer())
{
context.Writer.WritePropertyName("Issuer");
context.Writer.WriteObjectStart();
var marshaller = IssuerMarshaller.Instance;
marshaller.Marshall(publicRequest.Issuer, context);
context.Writer.WriteObjectEnd();
}
if(publicRequest.IsSetLicenseMetadata())
{
context.Writer.WritePropertyName("LicenseMetadata");
context.Writer.WriteArrayStart();
foreach(var publicRequestLicenseMetadataListValue in publicRequest.LicenseMetadata)
{
context.Writer.WriteObjectStart();
var marshaller = MetadataMarshaller.Instance;
marshaller.Marshall(publicRequestLicenseMetadataListValue, context);
context.Writer.WriteObjectEnd();
}
context.Writer.WriteArrayEnd();
}
if(publicRequest.IsSetLicenseName())
{
context.Writer.WritePropertyName("LicenseName");
context.Writer.Write(publicRequest.LicenseName);
}
if(publicRequest.IsSetProductName())
{
context.Writer.WritePropertyName("ProductName");
context.Writer.Write(publicRequest.ProductName);
}
if(publicRequest.IsSetProductSKU())
{
context.Writer.WritePropertyName("ProductSKU");
context.Writer.Write(publicRequest.ProductSKU);
}
if(publicRequest.IsSetValidity())
{
context.Writer.WritePropertyName("Validity");
context.Writer.WriteObjectStart();
var marshaller = DatetimeRangeMarshaller.Instance;
marshaller.Marshall(publicRequest.Validity, context);
context.Writer.WriteObjectEnd();
}
writer.WriteObjectEnd();
string snippet = stringWriter.ToString();
request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
}
return request;
}
private static CreateLicenseRequestMarshaller _instance = new CreateLicenseRequestMarshaller();
internal static CreateLicenseRequestMarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static CreateLicenseRequestMarshaller Instance
{
get
{
return _instance;
}
}
}
} | 38.445 | 142 | 0.55898 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/LicenseManager/Generated/Model/Internal/MarshallTransformations/CreateLicenseRequestMarshaller.cs | 7,689 | C# |
using WellEngineered.CruiseControl.PrivateBuild.NetReflector.Attributes;
using WellEngineered.CruiseControl.WebDashboard.Dashboard;
using WellEngineered.CruiseControl.WebDashboard.Dashboard.Actions;
using WellEngineered.CruiseControl.WebDashboard.Dashboard.GenericPlugins;
namespace WellEngineered.CruiseControl.WebDashboard.Plugins.BuildReport
{
// ToDo - Refactor to inherit from XslMultiReportBuildPlugin at some point
/// <summary>
/// Shows an overview of the build. This overview is generated by using xslt transformations over the build log.
/// These xslt transformations can be changed at will via the xslFileNames property.
/// <para>
/// Handy information : modifications, compile warnings or errors, amount of tests ok or failed, ...
/// </para>
/// <para>
/// LinkDescription : Build Report
/// </para>
/// <example>
/// <code>
/// <buildReportBuildPlugin>
/// <xslFileNames>
/// <xslFile>xsl\header.xsl</xslFile>
/// <xslFile>xsl\modifications.xsl</xslFile>
/// <xslFile>xsl\unittests.xsl</xslFile>
/// <xslFile>xsl\MsTestSummary2008.xsl</xslFile>
/// <xslFile>xsl\compile-msbuild.xsl</xslFile>
/// <xslFile>xsl\SimianSummary.xsl</xslFile>
/// </xslFileNames>
/// </buildReportBuildPlugin>
/// </code>
/// </example>
/// </summary>
/// <title>Build Report Plugin</title>
[ReflectorType("buildReportBuildPlugin")]
public class BuildReportBuildPlugin : ProjectConfigurableBuildPlugin
{
public static readonly string ACTION_NAME = "ViewBuildReport";
private readonly IActionInstantiator actionInstantiator;
public BuildReportBuildPlugin(IActionInstantiator actionInstantiator)
{
this.actionInstantiator = actionInstantiator;
}
public override string LinkDescription
{
get { return "Build Report"; }
}
/// <summary>
/// The xsl files to use to transform the build log. Location is relative to the web.config file.
/// Standard installation places the xsl files in the xsl folder.
/// </summary>
/// <default>
/// <xslFileNames>
/// <xslFile>xsl\header.xsl</xslFile>
/// <xslFile>xsl\modifications.xsl</xslFile>
/// </xslFileNames>
/// </default>
/// <version>1.0</version>
[ReflectorProperty("xslFileNames", typeof(BuildReportXslFilenameSerialiserFactory))]
public BuildReportXslFilename[] XslFileNames { get; set; }
public override INamedAction[] NamedActions
{
get
{
MultipleXslReportBuildAction buildAction = (MultipleXslReportBuildAction) this.actionInstantiator.InstantiateAction(typeof (MultipleXslReportBuildAction));
buildAction.XslFileNames = this.XslFileNames;
return new INamedAction[] {new ImmutableNamedAction(ACTION_NAME, buildAction)};
}
}
}
} | 39.52 | 159 | 0.70108 | [
"MIT"
] | wellengineered-us/cruisecontrol | src/WellEngineered.CruiseControl.Dashboard.Web/Plugins/BuildReport/BuildReportBuildPlugin.cs | 2,964 | C# |
using FluentValidation.Results;
using System;
using System.Collections.Generic;
using System.Linq;
namespace Ordering.Application.Exceptions
{
//Exception layer
public class ValidationException : ApplicationException
{
//Error
public ValidationException()
: base("One or more validation failures have occurred.")
{
Errors = new Dictionary<string, string[]>();
}
//Constructor for any Command Validator files.
//FluentValidation will throw an error that will be captured here and processed into the Errors Disctionary
public ValidationException(IEnumerable<ValidationFailure> failures)
:this()
{
Errors = failures
.GroupBy(e => e.PropertyName, e => e.ErrorMessage)
.ToDictionary(failureGroup => failureGroup.Key, failureGroup => failureGroup.ToArray());
}
//Error Dictionary
public IDictionary<string, string[]> Errors { get; set; }
}
}
| 32 | 115 | 0.641602 | [
"MIT"
] | Arniox/AspnetMicroservices | src/Services/Ordering/Ordering.Application/Exceptions/ValidationException.cs | 1,026 | C# |
using JetBrains.Annotations;
namespace ITGlobal.CommandLine.Parsing
{
/// <summary>
/// Command line parser that supports subcommands
/// </summary>
[PublicAPI]
public interface ITreeCliParser : ICliCommandRoot, ICliParser
{
}
} | 21.75 | 65 | 0.678161 | [
"MIT"
] | ITGlobal/CLI | src/CLI.Parser/ITreeCliParser.cs | 261 | C# |
using System.Collections.Generic;
using System.Linq;
/*
Нужна таблица свежести:
для каждой свежей туда класть минимум через сколько заразится (минимум)
какое дефолное значение там хранить? сейчас максимум
*/
public class Solution {
public int OrangesRotting(int[][] grid) {
var queue = new Queue<int[]>();
var freshCount = 0;
for (int i = 0; i < grid.Length; i++) {
for (int j = 0; j < grid[0].Length; j++) {
if (grid[i][j] == 2) {
queue.Enqueue(new int[] {i,j});
} else if (grid[i][j] == 1) {
freshCount++;
}
}
}
int X = grid.Length;
int Y = grid[0].Length;
int level = 0;
if (freshCount == 0) {
return 0;
}
while (queue.Any()) {
int size = queue.Count;
for (int i = 0; i < size; i++) {
var cur = queue.Dequeue();
var curX = cur[0];
var curY = cur[1];
if (curX < X -1 && grid[curX+1][curY] == 1) {
grid[curX+1][curY] = 2;
freshCount--;
queue.Enqueue(new int[] {curX + 1,curY});
}
if (curX > 0 && grid[curX-1][curY] == 1) {
grid[curX-1][curY] = 2;
freshCount--;
queue.Enqueue(new int[] {curX - 1,curY});
}
if (curY < Y -1 && grid[curX][curY+1] == 1) {
grid[curX][curY + 1] = 2;
freshCount--;
queue.Enqueue(new int[] {curX,curY + 1});
}
if (curY > 0 && grid[curX][curY-1] == 1) {
grid[curX][curY-1] = 2;
freshCount--;
queue.Enqueue(new int[] {curX,curY - 1});
}
}
level++;
}
if (freshCount > 0) {
return -1;
}
return level - 1;
}
} | 29.386667 | 79 | 0.368875 | [
"MIT"
] | DiscoDancer/LeetCode | Algorithm/BFS DFS/rotting-oranges_1.cs | 2,329 | C# |
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using org.mariuszgromada.math.mxparser;
namespace Calculator.Models
{
public interface IOperations
{
void Insert(string digit);
void InsertOperation(Operations operation);
}
public enum Operations
{
Clear,
Equal,
Backspace,
Bracket,
Percentage
}
public class CalculatorModel : IOperations
{
public string Expression { get; private set; } = string.Empty;
public string Result { get; private set; } = string.Empty;
private const string OpenBracketSign = "(";
private const string EncloseBracketSign = ")";
private readonly Stack<string> _encloseBracketStack;
public CalculatorModel()
{
_encloseBracketStack = new Stack<string>();
}
private void Clear()
{
Expression = string.Empty;
Result = string.Empty;
}
private void Equal()
{
Expression = Result;
}
private void Backspace()
{
if (string.IsNullOrEmpty(Expression)) return;
if (Regex.IsMatch(Expression, $@"\{EncloseBracketSign}$"))
_encloseBracketStack.Push(EncloseBracketSign);
else if (Regex.IsMatch(Expression, $@"\{OpenBracketSign}$"))
_encloseBracketStack.Pop();
Expression = Expression.Remove(Expression.Length - 1, 1);
Result = CalculateExpression();
}
private void AddBracket()
{
if (!_encloseBracketStack.Any())
{
Expression += Regex.IsMatch(Expression.Last().ToString(), @"\d") ? $"*{OpenBracketSign}" : OpenBracketSign;
_encloseBracketStack.Push(EncloseBracketSign);
Result = string.Empty;
}
else
{
Expression += _encloseBracketStack.Pop();
Result = CalculateExpression();
}
}
public void Insert(string element)
{
if (Regex.IsMatch(element, @"[+\-*/%,]"))
Expression += string.IsNullOrEmpty(Expression) || Regex.IsMatch(Expression, @"[+\-*/%]$") ? string.Empty : element;
else
Expression += element;
Result = CalculateExpression();
}
public void InsertOperation(Operations operation)
{
switch (operation)
{
case Operations.Backspace:
Backspace();
break;
case Operations.Clear:
Clear();
break;
case Operations.Bracket:
AddBracket();
break;
case Operations.Equal:
Equal();
break;
}
}
string CalculateExpression()
{
if (string.IsNullOrEmpty(Expression) || !Regex.IsMatch(Expression.Last().ToString(), @"(\d|\))") || _encloseBracketStack.Any())
return string.Empty;
Expression expression = new Expression(Expression);
#region MyRegion
//var listOfDigits = Regex.Split(Expression, @"\D").Select(Convert.ToDouble).ToList();
//var listOfOperations = Regex.Split(Expression, @"((\d*\,\d+)|\d+)").Select(sign =>
//{
// switch (sign)
// {
// case "+":
// return Operations.Add;
// case "-":
// return Operations.Substruct;
// case "*":
// return Operations.Multiply;
// default:
// return Operations.Divide;
// }
//}).ToList();
//if (listOfDigits.Count > listOfOperations.Count)
//{
// CurrentOperation = Operations.Add;
// var result = 0.0;
// for (int index = 0; index < listOfDigits.Count; index++)
// {
// var digit = listOfDigits[index];
// switch (CurrentOperation)
// {
// case Operations.Add:
// result += digit;
// break;
// case Operations.Substruct:
// result -= digit;
// break;
// case Operations.Multiply:
// result *= digit;
// break;
// case Operations.Divide:
// result /= digit;
// break;
// default:
// throw new ArgumentOutOfRangeException();
// }
// if (index > listOfOperations.Count)
// {
// }
// else
// {
// CurrentOperation = listOfOperations[index];
// }
// }
// return result.ToString(CultureInfo.InvariantCulture);
//}
//return string.Empty;
#endregion
return expression.calculate().ToString(CultureInfo.InvariantCulture);
}
}
}
| 30.988827 | 139 | 0.459528 | [
"MIT"
] | dariuszdbr/CalculatorWpfMVVM | Calculator/Models/CalculatorModel.cs | 5,549 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="FolderApi.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Viewer.Cloud.Sdk.Api
{
using System.Collections.Generic;
using System.Text.RegularExpressions;
using GroupDocs.Viewer.Cloud.Sdk.Client;
using GroupDocs.Viewer.Cloud.Sdk.Client.RequestHandlers;
using GroupDocs.Viewer.Cloud.Sdk.Model;
using GroupDocs.Viewer.Cloud.Sdk.Model.Requests;
/// <summary>
/// GroupDocs.Viewer Cloud API.
/// </summary>
public class FolderApi
{
private readonly ApiInvoker apiInvoker;
private readonly Configuration configuration;
/// <summary>
/// Initializes a new instance of the <see cref="FolderApi"/> class.
/// </summary>
/// <param name="appSid">Application identifier (App SID)</param>
/// <param name="appKey">Application private key (App Key)</param>
public FolderApi(string appSid, string appKey)
: this(new Configuration(appSid, appKey))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="FolderApi"/> class.
/// </summary>
/// <param name="configuration">Configuration settings</param>
public FolderApi(Configuration configuration)
{
this.configuration = configuration;
var requestHandlers = new List<IRequestHandler>();
requestHandlers.Add(new AuthRequestHandler(this.configuration));
requestHandlers.Add(new DebugLogRequestHandler(this.configuration));
requestHandlers.Add(new ApiExceptionRequestHandler());
this.apiInvoker = new ApiInvoker(requestHandlers, this.configuration.Timeout);
}
/// <summary>
/// Copy folder
/// </summary>
/// <param name="request">Request. <see cref="CopyFolderRequest" /></param>
public void CopyFolder(CopyFolderRequest request)
{
// verify the required parameter 'srcPath' is set
if (request.srcPath == null)
{
throw new ApiException(400, "Missing required parameter 'srcPath' when calling CopyFolder");
}
// verify the required parameter 'destPath' is set
if (request.destPath == null)
{
throw new ApiException(400, "Missing required parameter 'destPath' when calling CopyFolder");
}
// create path and map variables
var resourcePath = this.configuration.GetServerUrl() + "/viewer/storage/folder/copy/{srcPath}";
resourcePath = Regex
.Replace(resourcePath, "\\*", string.Empty)
.Replace("&", "&")
.Replace("/?", "?");
resourcePath = UrlHelper.AddPathParameter(resourcePath, "srcPath", request.srcPath);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "destPath", request.destPath);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "srcStorageName", request.srcStorageName);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "destStorageName", request.destStorageName);
this.apiInvoker.InvokeApi(
resourcePath,
"PUT",
null,
null,
null);
}
/// <summary>
/// Create the folder
/// </summary>
/// <param name="request">Request. <see cref="CreateFolderRequest" /></param>
public void CreateFolder(CreateFolderRequest request)
{
// verify the required parameter 'path' is set
if (request.path == null)
{
throw new ApiException(400, "Missing required parameter 'path' when calling CreateFolder");
}
// create path and map variables
var resourcePath = this.configuration.GetServerUrl() + "/viewer/storage/folder/{path}";
resourcePath = Regex
.Replace(resourcePath, "\\*", string.Empty)
.Replace("&", "&")
.Replace("/?", "?");
resourcePath = UrlHelper.AddPathParameter(resourcePath, "path", request.path);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "storageName", request.storageName);
this.apiInvoker.InvokeApi(
resourcePath,
"PUT",
null,
null,
null);
}
/// <summary>
/// Delete folder
/// </summary>
/// <param name="request">Request. <see cref="DeleteFolderRequest" /></param>
public void DeleteFolder(DeleteFolderRequest request)
{
// verify the required parameter 'path' is set
if (request.path == null)
{
throw new ApiException(400, "Missing required parameter 'path' when calling DeleteFolder");
}
// create path and map variables
var resourcePath = this.configuration.GetServerUrl() + "/viewer/storage/folder/{path}";
resourcePath = Regex
.Replace(resourcePath, "\\*", string.Empty)
.Replace("&", "&")
.Replace("/?", "?");
resourcePath = UrlHelper.AddPathParameter(resourcePath, "path", request.path);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "storageName", request.storageName);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "recursive", request.recursive);
this.apiInvoker.InvokeApi(
resourcePath,
"DELETE",
null,
null,
null);
}
/// <summary>
/// Get all files and folders within a folder
/// </summary>
/// <param name="request">Request. <see cref="GetFilesListRequest" /></param>
/// <returns><see cref="FilesList"/></returns>
public FilesList GetFilesList(GetFilesListRequest request)
{
// verify the required parameter 'path' is set
if (request.path == null)
{
throw new ApiException(400, "Missing required parameter 'path' when calling GetFilesList");
}
// create path and map variables
var resourcePath = this.configuration.GetServerUrl() + "/viewer/storage/folder/{path}";
resourcePath = Regex
.Replace(resourcePath, "\\*", string.Empty)
.Replace("&", "&")
.Replace("/?", "?");
resourcePath = UrlHelper.AddPathParameter(resourcePath, "path", request.path);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "storageName", request.storageName);
var response = this.apiInvoker.InvokeApi(
resourcePath,
"GET",
null,
null,
null);
if (response != null)
{
return (FilesList)SerializationHelper.Deserialize(response, typeof(FilesList));
}
return null;
}
/// <summary>
/// Move folder
/// </summary>
/// <param name="request">Request. <see cref="MoveFolderRequest" /></param>
public void MoveFolder(MoveFolderRequest request)
{
// verify the required parameter 'srcPath' is set
if (request.srcPath == null)
{
throw new ApiException(400, "Missing required parameter 'srcPath' when calling MoveFolder");
}
// verify the required parameter 'destPath' is set
if (request.destPath == null)
{
throw new ApiException(400, "Missing required parameter 'destPath' when calling MoveFolder");
}
// create path and map variables
var resourcePath = this.configuration.GetServerUrl() + "/viewer/storage/folder/move/{srcPath}";
resourcePath = Regex
.Replace(resourcePath, "\\*", string.Empty)
.Replace("&", "&")
.Replace("/?", "?");
resourcePath = UrlHelper.AddPathParameter(resourcePath, "srcPath", request.srcPath);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "destPath", request.destPath);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "srcStorageName", request.srcStorageName);
resourcePath = UrlHelper.AddQueryParameterToUrl(resourcePath, "destStorageName", request.destStorageName);
this.apiInvoker.InvokeApi(
resourcePath,
"PUT",
null,
null,
null);
}
}
}
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="CopyFolderRequest.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Viewer.Cloud.Sdk.Model.Requests
{
using GroupDocs.Viewer.Cloud.Sdk.Model;
/// <summary>
/// Request model for <see cref="GroupDocs.Viewer.Cloud.Sdk.Api.FolderApi.CopyFolder" /> operation.
/// </summary>
public class CopyFolderRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="CopyFolderRequest"/> class.
/// </summary>
public CopyFolderRequest()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CopyFolderRequest"/> class.
/// </summary>
/// <param name="srcPath">Source folder path e.g. '/src'</param>
/// <param name="destPath">Destination folder path e.g. '/dst'</param>
/// <param name="srcStorageName">Source storage name</param>
/// <param name="destStorageName">Destination storage name</param>
public CopyFolderRequest(string srcPath, string destPath, string srcStorageName = null, string destStorageName = null)
{
this.srcPath = srcPath;
this.destPath = destPath;
this.srcStorageName = srcStorageName;
this.destStorageName = destStorageName;
}
/// <summary>
/// Source folder path e.g. '/src'
/// </summary>
public string srcPath { get; set; }
/// <summary>
/// Destination folder path e.g. '/dst'
/// </summary>
public string destPath { get; set; }
/// <summary>
/// Source storage name
/// </summary>
public string srcStorageName { get; set; }
/// <summary>
/// Destination storage name
/// </summary>
public string destStorageName { get; set; }
}
}
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="CreateFolderRequest.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Viewer.Cloud.Sdk.Model.Requests
{
using GroupDocs.Viewer.Cloud.Sdk.Model;
/// <summary>
/// Request model for <see cref="GroupDocs.Viewer.Cloud.Sdk.Api.FolderApi.CreateFolder" /> operation.
/// </summary>
public class CreateFolderRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="CreateFolderRequest"/> class.
/// </summary>
public CreateFolderRequest()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="CreateFolderRequest"/> class.
/// </summary>
/// <param name="path">Folder path to create e.g. 'folder_1/folder_2/'</param>
/// <param name="storageName">Storage name</param>
public CreateFolderRequest(string path, string storageName = null)
{
this.path = path;
this.storageName = storageName;
}
/// <summary>
/// Folder path to create e.g. 'folder_1/folder_2/'
/// </summary>
public string path { get; set; }
/// <summary>
/// Storage name
/// </summary>
public string storageName { get; set; }
}
}
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="DeleteFolderRequest.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Viewer.Cloud.Sdk.Model.Requests
{
using GroupDocs.Viewer.Cloud.Sdk.Model;
/// <summary>
/// Request model for <see cref="GroupDocs.Viewer.Cloud.Sdk.Api.FolderApi.DeleteFolder" /> operation.
/// </summary>
public class DeleteFolderRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="DeleteFolderRequest"/> class.
/// </summary>
public DeleteFolderRequest()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="DeleteFolderRequest"/> class.
/// </summary>
/// <param name="path">Folder path e.g. '/folder'</param>
/// <param name="storageName">Storage name</param>
/// <param name="recursive">Enable to delete folders, subfolders and files</param>
public DeleteFolderRequest(string path, string storageName = null, bool? recursive = null)
{
this.path = path;
this.storageName = storageName;
this.recursive = recursive;
}
/// <summary>
/// Folder path e.g. '/folder'
/// </summary>
public string path { get; set; }
/// <summary>
/// Storage name
/// </summary>
public string storageName { get; set; }
/// <summary>
/// Enable to delete folders, subfolders and files
/// </summary>
public bool? recursive { get; set; }
}
}
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="GetFilesListRequest.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Viewer.Cloud.Sdk.Model.Requests
{
using GroupDocs.Viewer.Cloud.Sdk.Model;
/// <summary>
/// Request model for <see cref="GroupDocs.Viewer.Cloud.Sdk.Api.FolderApi.GetFilesList" /> operation.
/// </summary>
public class GetFilesListRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesListRequest"/> class.
/// </summary>
public GetFilesListRequest()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="GetFilesListRequest"/> class.
/// </summary>
/// <param name="path">Folder path e.g. '/folder'</param>
/// <param name="storageName">Storage name</param>
public GetFilesListRequest(string path, string storageName = null)
{
this.path = path;
this.storageName = storageName;
}
/// <summary>
/// Folder path e.g. '/folder'
/// </summary>
public string path { get; set; }
/// <summary>
/// Storage name
/// </summary>
public string storageName { get; set; }
}
}
// --------------------------------------------------------------------------------------------------------------------
// <copyright company="Aspose Pty Ltd" file="MoveFolderRequest.cs">
// Copyright (c) 2003-2021 Aspose Pty Ltd
// </copyright>
// <summary>
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace GroupDocs.Viewer.Cloud.Sdk.Model.Requests
{
using GroupDocs.Viewer.Cloud.Sdk.Model;
/// <summary>
/// Request model for <see cref="GroupDocs.Viewer.Cloud.Sdk.Api.FolderApi.MoveFolder" /> operation.
/// </summary>
public class MoveFolderRequest
{
/// <summary>
/// Initializes a new instance of the <see cref="MoveFolderRequest"/> class.
/// </summary>
public MoveFolderRequest()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="MoveFolderRequest"/> class.
/// </summary>
/// <param name="srcPath">Folder path to move e.g. '/folder'</param>
/// <param name="destPath">Destination folder path to move to e.g '/dst'</param>
/// <param name="srcStorageName">Source storage name</param>
/// <param name="destStorageName">Destination storage name</param>
public MoveFolderRequest(string srcPath, string destPath, string srcStorageName = null, string destStorageName = null)
{
this.srcPath = srcPath;
this.destPath = destPath;
this.srcStorageName = srcStorageName;
this.destStorageName = destStorageName;
}
/// <summary>
/// Folder path to move e.g. '/folder'
/// </summary>
public string srcPath { get; set; }
/// <summary>
/// Destination folder path to move to e.g '/dst'
/// </summary>
public string destPath { get; set; }
/// <summary>
/// Source storage name
/// </summary>
public string srcStorageName { get; set; }
/// <summary>
/// Destination storage name
/// </summary>
public string destStorageName { get; set; }
}
}
| 44.089983 | 141 | 0.569679 | [
"MIT"
] | groupdocs-viewer-cloud/groupdocs-viewer-cloud-dotnet | src/GroupDocs.Viewer.Cloud.Sdk/Api/FolderApi.cs | 25,969 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CodeStyle;
using Microsoft.CodeAnalysis.CSharp.CodeFixes.GenerateMethod;
using Microsoft.CodeAnalysis.CSharp.CodeStyle;
using Microsoft.CodeAnalysis.Diagnostics;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics.GenerateMethod
{
public class GenerateConversionTest : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest
{
internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace)
=> (null, new GenerateConversionCodeFixProvider());
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateImplicitConversionGenericClass()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Test(int[] a)
{
C<int> x1 = [|1|];
}
}
class C<T>
{
}",
@"using System;
class Program
{
void Test(int[] a)
{
C<int> x1 = 1;
}
}
class C<T>
{
public static implicit operator C<T>(int v)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateImplicitConversionClass()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Test(int[] a)
{
C x1 = [|1|];
}
}
class C
{
}",
@"using System;
class Program
{
void Test(int[] a)
{
C x1 = 1;
}
}
class C
{
public static implicit operator C(int v)
{
throw new NotImplementedException();
}
}");
}
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateImplicitConversionClass_CodeStyle()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Test(int[] a)
{
C x1 = [|1|];
}
}
class C
{
}",
@"using System;
class Program
{
void Test(int[] a)
{
C x1 = 1;
}
}
class C
{
public static implicit operator C(int v) => throw new NotImplementedException();
}",
options: Option(CSharpCodeStyleOptions.PreferExpressionBodiedOperators, CSharpCodeStyleOptions.WhenPossibleWithNoneEnforcement));
}
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateImplicitConversionAwaitExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
var a = Task.FromResult(1);
Program x1 = [|await a|];
}
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
var a = Task.FromResult(1);
Program x1 = await a;
}
public static implicit operator Program(int v)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateImplicitConversionTargetTypeNotInSource()
{
await TestInRegularAndScriptAsync(
@"class Digit
{
public Digit(double d)
{
val = d;
}
public double val;
}
class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
double num = [|dig|];
}
}",
@"using System;
class Digit
{
public Digit(double d)
{
val = d;
}
public double val;
public static implicit operator double(Digit v)
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
double num = dig;
}
}");
}
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateExplicitConversionGenericClass()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Test(int[] a)
{
C<int> x1 = [|(C<int>)1|];
}
}
class C<T>
{
}",
@"using System;
class Program
{
void Test(int[] a)
{
C<int> x1 = (C<int>)1;
}
}
class C<T>
{
public static explicit operator C<T>(int v)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateExplicitConversionClass()
{
await TestInRegularAndScriptAsync(
@"class Program
{
void Test(int[] a)
{
C x1 = [|(C)1|];
}
}
class C
{
}",
@"using System;
class Program
{
void Test(int[] a)
{
C x1 = (C)1;
}
}
class C
{
public static explicit operator C(int v)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateExplicitConversionAwaitExpression()
{
await TestInRegularAndScriptAsync(
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
var a = Task.FromResult(1);
Program x1 = [|(Program)await a|];
}
}",
@"using System;
using System.Threading.Tasks;
class Program
{
async void Test()
{
var a = Task.FromResult(1);
Program x1 = (Program)await a;
}
public static explicit operator Program(int v)
{
throw new NotImplementedException();
}
}");
}
[WorkItem(774321, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/774321")]
[Fact, Trait(Traits.Feature, Traits.Features.CodeActionsGenerateMethod)]
public async Task TestGenerateExplicitConversionTargetTypeNotInSource()
{
await TestInRegularAndScriptAsync(
@"class Digit
{
public Digit(double d)
{
val = d;
}
public double val;
}
class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
double num = [|(double)dig|];
}
}",
@"using System;
class Digit
{
public Digit(double d)
{
val = d;
}
public double val;
public static explicit operator double(Digit v)
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
Digit dig = new Digit(7);
double num = (double)dig;
}
}");
}
}
} | 20.406685 | 160 | 0.626809 | [
"Apache-2.0"
] | Trieste-040/https-github.com-dotnet-roslyn | src/EditorFeatures/CSharpTest/Diagnostics/GenerateMethod/GenerateConversionTests.cs | 7,326 | C# |
using Shared.Enums;
using BUS.Interfaces.Services;
using Core.Helper;
using Core.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Shared.ViewModels;
using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Authorization;
using Core.Models;
using System.IO;
namespace Core.Controllers
{
[ApiController]
[Route("[controller]")]
[Authorize("Bearer")]
public class ProductController : ControllerBase
{
private readonly IProductService _productSer;
private readonly string _imageFolder = "product-images/";
public ProductController(IProductService productSer)
{
_productSer = productSer;
}
[HttpGet("{id}")]
[AllowAnonymous]
public ActionResult<ProductDetailVM> Get(int id)
{
var result = _productSer.Get(id);
if (result == null) return NotFound();
return result;
}
[HttpGet]
[AllowAnonymous]
public IEnumerable<ProductVM> GetList(string query, int typeId, int cateId, int limited, int offset, ProductSort? sort)
{
var result = _productSer.GetList(query, typeId, cateId, limited, offset, sort);
RespHelper.AddTotalPage(HttpContext, result.Total);
return result.Products;
}
[HttpPost]
[Authorize(Roles = "admin")]
public ActionResult<ProductDetailVM> Create(ProductDetailVM productDetailVM)
{
if (!ModelState.IsValid) return BadRequest();
var result = _productSer.Add(productDetailVM);
if (result == null) return Problem("Can't add new product");
return CreatedAtAction(nameof(Get), new { id = result.Id }, result);
}
[HttpPut("{id}")]
[Authorize(Roles = "admin")]
public IActionResult Update(int id, ProductDetailVM productDetailVM)
{
if (id != productDetailVM.Id) return BadRequest();
var result = _productSer.Update(id, productDetailVM);
if (!result) return NotFound();
return NoContent();
}
[HttpDelete("{id}")]
[Authorize(Roles = "admin")]
public IActionResult Delete(int id)
{
if (id <= 0) return BadRequest();
var result = _productSer.Delete(id);
if (!result) return NotFound();
return NoContent();
}
// Image
[HttpGet("{productId}/images")]
[AllowAnonymous]
public ActionResult<IEnumerable<string>> GetListImage([FromServices] IFileService fileSer, int productId)
{
if (productId <= 0) return BadRequest();
return Ok(fileSer.GetFilesInFolder(_imageFolder + productId));
}
[HttpPost("{productId}/images")]
[Authorize(Roles = "admin")]
public ActionResult<List<string>> UploadImage([FromServices] IFileService fileSer, IFormFileCollection images, int productId)
{
if (images == null || images.Count <= 0 || productId <= 0) return BadRequest();
var files = new List<string>();
foreach (var item in images)
{
var fileName = _uploadImage(fileSer, item, productId);
files.Add(fileName);
}
return files;
}
[HttpPut("{productId}/images")]
[Authorize(Roles = "admin")]
public ActionResult<string> ChangeDefaultImage([FromServices] IFileService fileSer, int productId, ProductImageModel imageModel)
{
if (!ModelState.IsValid || productId <= 0) return BadRequest();
// var fileExsist = fileSer.CheckFileExsist(_imageFolder, imageModel.Image);
// if (!fileExsist) return NotFound();
var result = _productSer.Update(imageModel.Id, new ProductDetailVM() { Id = imageModel.Id, Image = imageModel.Image });
if (!result) return NotFound();
return NoContent();
}
[HttpDelete("{productId}/images")]
[Authorize(Roles = "admin")]
public IActionResult DeleteImage([FromServices] IFileService fileSer, string imageName, int productId)
{
if (imageName == null || productId <= 0) return BadRequest();
fileSer.RemoveFile(_imageFolder, imageName);
return NoContent();
}
private string _uploadImage(IFileService fileSer, IFormFile image, int id)
{
var fileName = id + "_" + DateTime.Now.Millisecond + "_" + image.FileName;
fileSer.UploadFileAsync(_imageFolder + id, image, fileName);
return Path.Combine(id + "", fileName);
}
}
} | 36.620155 | 136 | 0.604149 | [
"Unlicense"
] | vtoan/fashion-ecom-ns | src/Core/Apis/ProductController.cs | 4,724 | C# |
//-----------------------------------------------------------------------
// <copyright file="PNCounter.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using Akka.Cluster;
using System;
using System.Collections.Immutable;
using System.Numerics;
namespace Akka.DistributedData
{
/// <summary>
/// Implements a 'Increment/Decrement Counter' CRDT, also called a 'PN-Counter'.
///
/// It is described in the paper
/// <a href="http://hal.upmc.fr/file/index/docid/555588/filename/techreport.pdf">A comprehensive study of Convergent and Commutative Replicated Data Types</a>.
///
/// PN-Counters allow the counter to be incremented by tracking the
/// increments (P) separate from the decrements (N). Both P and N are represented
/// as two internal [[GCounter]]s. Merge is handled by merging the internal P and N
/// counters. The value of the counter is the value of the P _counter minus
/// the value of the N counter.
///
/// This class is immutable, i.e. "modifying" methods return a new instance.
/// </summary>
[Serializable]
public sealed class PNCounter :
IDeltaReplicatedData<PNCounter, PNCounter>,
IRemovedNodePruning<PNCounter>,
IReplicatedDataSerialization,
IEquatable<PNCounter>,
IReplicatedDelta
{
public static readonly PNCounter Empty = new PNCounter();
public BigInteger Value => new BigInteger(Increments.Value) - new BigInteger(Decrements.Value);
public GCounter Increments { get; }
public GCounter Decrements { get; }
public PNCounter() : this(GCounter.Empty, GCounter.Empty) { }
public PNCounter(GCounter increments, GCounter decrements)
{
Increments = increments;
Decrements = decrements;
}
/// <summary>
/// Increment the counter with the delta specified.
/// If the delta is negative then it will decrement instead of increment.
/// </summary>
public PNCounter Increment(Cluster.Cluster node, long delta = 1) => Increment(node.SelfUniqueAddress, delta);
/// <summary>
/// Increment the counter with the delta specified.
/// If the delta is negative then it will decrement instead of increment.
/// </summary>
public PNCounter Increment(UniqueAddress address, long delta = 1) => Change(address, delta);
/// <summary>
/// Decrement the counter with the delta specified.
/// If the delta is negative then it will increment instead of decrement.
/// </summary>
public PNCounter Decrement(Cluster.Cluster node, long delta = 1) => Decrement(node.SelfUniqueAddress, delta);
/// <summary>
/// Decrement the counter with the delta specified.
/// If the delta is negative then it will increment instead of decrement.
/// </summary>
public PNCounter Decrement(UniqueAddress address, long delta = 1) => Change(address, -delta);
private PNCounter Change(UniqueAddress key, long delta)
{
if (delta > 0) return new PNCounter(Increments.Increment(key, (ulong)delta), Decrements);
if (delta < 0) return new PNCounter(Increments, Decrements.Increment(key, (ulong)(-delta)));
return this;
}
public PNCounter Merge(PNCounter other) =>
new PNCounter(Increments.Merge(other.Increments), Decrements.Merge(other.Decrements));
public ImmutableHashSet<UniqueAddress> ModifiedByNodes => Increments.ModifiedByNodes.Union(Decrements.ModifiedByNodes);
public bool NeedPruningFrom(Cluster.UniqueAddress removedNode) =>
Increments.NeedPruningFrom(removedNode) || Decrements.NeedPruningFrom(removedNode);
IReplicatedData IRemovedNodePruning.PruningCleanup(UniqueAddress removedNode) => PruningCleanup(removedNode);
IReplicatedData IRemovedNodePruning.Prune(UniqueAddress removedNode, UniqueAddress collapseInto) => Prune(removedNode, collapseInto);
public PNCounter Prune(Cluster.UniqueAddress removedNode, Cluster.UniqueAddress collapseInto) =>
new PNCounter(Increments.Prune(removedNode, collapseInto), Decrements.Prune(removedNode, collapseInto));
public PNCounter PruningCleanup(Cluster.UniqueAddress removedNode) =>
new PNCounter(Increments.PruningCleanup(removedNode), Decrements.PruningCleanup(removedNode));
public bool Equals(PNCounter other)
{
if (ReferenceEquals(other, null)) return false;
if (ReferenceEquals(this, other)) return true;
return other.Increments.Equals(Increments) && other.Decrements.Equals(Decrements);
}
public override string ToString() => $"PNCounter({Value})";
public override bool Equals(object obj) => obj is PNCounter && Equals((PNCounter)obj);
public override int GetHashCode() => Increments.GetHashCode() ^ Decrements.GetHashCode();
public IReplicatedData Merge(IReplicatedData other) => Merge((PNCounter)other);
IReplicatedDelta IDeltaReplicatedData.Delta => Delta;
IReplicatedData IDeltaReplicatedData.MergeDelta(IReplicatedDelta delta) => Merge((PNCounter)delta);
IReplicatedData IDeltaReplicatedData.ResetDelta() => ResetDelta();
#region delta
public PNCounter Delta => new PNCounter(Increments.Delta ?? GCounter.Empty, Decrements.Delta ?? GCounter.Empty);
public PNCounter MergeDelta(PNCounter delta) => Merge(delta);
public PNCounter ResetDelta()
{
if (Increments.Delta == null && Decrements.Delta == null)
return this;
return new PNCounter(Increments.ResetDelta(), Decrements.ResetDelta());
}
#endregion
IDeltaReplicatedData IReplicatedDelta.Zero => PNCounter.Empty;
}
public sealed class PNCounterKey : Key<PNCounter>
{
public PNCounterKey(string id)
: base(id)
{ }
}
}
| 41.150327 | 163 | 0.65359 | [
"Apache-2.0"
] | BearerPipelineTest/akka.net | src/contrib/cluster/Akka.DistributedData/PNCounter.cs | 6,298 | C# |
using System.Linq;
using System.Web;
using System.Web.WebPages;
using EPiServer.Framework;
using EPiServer.Framework.Initialization;
using EPiServer.ServiceLocation;
using AlloyReact.Business.Channels;
using EPiServer.Web;
namespace AlloyReact.Business.Initialization
{
/// <summary>
/// Adds a new display mode for mobile which is active if the mobile channel is active in addition to if the request is from a mobile device (like the default one)
/// </summary>
/// <remarks>
/// It's also possible to map a display mode as a channel through the DisplayChannelService.RegisterDisplayMode() method.
/// Adding channels that way does not however enable specifying ResolutionId which we want to do for the mobile channel.
/// </remarks>
[ModuleDependency(typeof(EPiServer.Web.InitializationModule))]
public class DisplayModesInitialization : IInitializableModule
{
public void Initialize(InitializationEngine context)
{
var mobileChannelDisplayMode = new DefaultDisplayMode("mobile")
{
ContextCondition = IsMobileDisplayModeActive
};
DisplayModeProvider.Instance.Modes.Insert(0, mobileChannelDisplayMode);
}
private static bool IsMobileDisplayModeActive(HttpContextBase httpContext)
{
if (httpContext.GetOverriddenBrowser().IsMobileDevice)
{
return true;
}
var displayChannelService = ServiceLocator.Current.GetInstance<IDisplayChannelService>();
return displayChannelService.GetActiveChannels(httpContext).Any(x => x.ChannelName == MobileChannel.Name);
}
public void Uninitialize(InitializationEngine context)
{
}
public void Preload(string[] parameters)
{
}
}
}
| 36.92 | 167 | 0.686891 | [
"Apache-2.0"
] | episerver/AlloyReact | AlloyReact/Business/Initialization/DisplayModesInitialization.cs | 1,846 | C# |
/********************************************************************************
* Module : Lapis.Math.Algebra
* Class : Trigonometric
* Description : Provides methods related to trigonometric functions.
* Created : 2015/5/17
* Note :
*********************************************************************************/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Lapis.Math.Algebra.Expressions;
using Lapis.Math.Numbers;
namespace Lapis.Math.Algebra.Arithmetics
{
/// <summary>
/// Provides methods related to trigonometric functions.
/// </summary>
public static class Trigonometric
{
/// <summary>
/// Expands the specified trigonometric expression.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <returns>The expanded expression of <paramref name="expression"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static Expression Expand(this Expression expression)
{
if (expression == null)
throw new ArgumentNullException();
if (expression is Number ||
expression is Symbol ||
expression is Undefined ||
expression is PositiveInfinity ||
expression is NegativeInfinity ||
expression is ComplexInfinity)
{
return expression;
}
var m = Structure.Map(expression, Expand);
if (m is Function)
{
var fun = (Function)m;
if (fun.Identifier == FunctionIdentifiers.Sin)
{
Expression s, c;
ApplySinCos(Elementary.Expand(fun.Argument), out s, out c);
return s;
}
else if (fun.Identifier == FunctionIdentifiers.Cos)
{
Expression s, c;
ApplySinCos(Elementary.Expand(fun.Argument), out s, out c);
return c;
}
else
return fun;
}
else
return m;
}
#region Private
private static void ApplySinCos(Expression expression, out Expression sin,out Expression cos)
{
if (expression is Sum)
{
var sum = (Sum)expression;
Expression s;
Expression c;
Expression s1, c1, s2, c2;
ApplySinCos(sum[0], out s, out c);
for (int i = 1; i < sum.NumberOfAddends;i++ )
{
s1 = s;
c1 = c;
ApplySinCos(sum[i], out s2, out c2);
s = s1 * c2 + c1 * s2;
c = c1 * c2 - s1 * s2;
}
sin = s;
cos = c;
return;
}
else if (expression is Product)
{
var prod = (Product)expression;
Expression head;
List<Expression> list;
Integer num;
prod.Decompose(out head, out list);
if (head.IsInteger(out num) && num.Sign > 0)
{
int n = num.ToInt32();
Expression tail;
if (list.Count == 1)
tail = list[0];
else
tail = new Product(list);
var sint = Expression.Sin(tail);
var cost = Expression.Cos(tail);
Expression s = Number.Zero;
Expression c = Number.Zero;
Expression s1, c1, s2, c2;
for (int i = 1, j = 0; i <= n || j <= n; i += 2, j += 2)
{
if (i <= n)
{
s1 = i;
c1 = (Integer.FromInt32((i - 1) / 2).IsEven ? Number.One : Number.MinusOne) * Integer.Binomial(n, i);
s += c1 * Expression.Pow(cost, n - s1) * Expression.Pow(sint, s1);
}
if (j <= n)
{
s2 = j;
c2 = (Integer.FromInt32(j / 2).IsEven ? Number.One : Number.MinusOne) * Integer.Binomial(n, j);
c += c2 * Expression.Pow(cost, n - s2) * Expression.Pow(sint, s2);
}
}
sin = s;
cos = c;
return;
}
else
{
sin = Expression.Sin(expression);
cos = Expression.Cos(expression);
return;
}
}
else
{
sin = Expression.Sin(expression);
cos = Expression.Cos(expression);
return;
}
}
#endregion
/// <summary>
/// Contracts the specified trigonometric expression.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <returns>The contracted expression of <paramref name="expression"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static Expression Contract(this Expression expression)
{
if (expression == null)
throw new ArgumentNullException();
var m = Structure.Map(expression, Contract);
if (m is Product || m is Power)
return ContractInner(m);
else
return m;
}
#region Private
private static Expression ContractInner(Expression expression)
{
var r = Elementary.Expand(expression);
if (r is Product)
{
Expression sc, rest;
Separate(r, out sc, out rest);
if (sc == Number.One)
return r;
else if (sc is Function)
{
var fun = (Function)sc;
if (fun.Identifier == FunctionIdentifiers.Sin ||
fun.Identifier == FunctionIdentifiers.Cos)
return r;
}
if (sc is Power)
{
var pow = (Power)sc;
return Elementary.Expand(rest * ApplyPow(pow.Base, pow.Exponent));
}
if (sc is Product)
{
var prod = (Product)sc;
return Elementary.Expand(rest * ApplyProduct(prod));
}
return rest * sc;
}
else if (r is Sum)
{
Expression s = Number.Zero;
foreach (Expression t in (Sum)r)
{
if (t is Product || t is Power)
{
s += ContractInner(t);
}
else
{
s += t;
}
}
return s;
}
Expression bas;
Integer exp;
if (r.IsPositiveIntegerPower(out bas, out exp) && bas is Function)
{
var fun = (Function)bas;
if (fun.Identifier == FunctionIdentifiers.Sin ||
fun.Identifier == FunctionIdentifiers.Cos)
{
return ApplyPow(bas, (Number)exp);
}
}
return r;
}
private static void Separate(Expression expression, out Expression sinCosPart, out Expression rest)
{
if (expression is Product)
{
var prod = (Product)expression;
List<Expression> s, r;
prod.Separate((Expression t) => IsSinCosPart(t), out s, out r);
if (s.Count == 0)
sinCosPart = Number.One;
else if (s.Count == 1)
sinCosPart = s[0];
else
sinCosPart = new Product(s);
if (r.Count == 0)
rest = Number.One;
else if (r.Count == 1)
rest = r[0];
else
rest = new Product(r);
return;
}
else if (IsSinCosPart(expression))
{
sinCosPart = expression;
rest = Number.One;
return;
}
else
{
sinCosPart = Number.One;
rest = expression;
return;
}
}
private static bool IsSinCosPart(Expression expression)
{
if (expression is Function)
{
var fun = (Function)expression;
return fun.Identifier == FunctionIdentifiers.Sin ||
fun.Identifier == FunctionIdentifiers.Cos;
}
Expression bas;
Integer exp;
if (expression.IsPositiveIntegerPower(out bas, out exp))
{
return IsSinCosPart(bas);
}
return false;
}
private static Expression ApplyPow(Expression bas, Expression exp)
{
Integer num;
if (exp.IsInteger(out num) && num.Sign >0)
{
if (bas is Function)
{
var fun = (Function)bas;
if (fun.Identifier == FunctionIdentifiers.Sin)
{
var n = num.ToInt32();
if (num.IsEven)
{
var u = ((num / 2).IsEven ? Number.One : Number.MinusOne) * Expression.Pow(2, 1 - n);
Expression s = Number.Zero;
for (int i = 0; i <= n / 2 - 1; i++)
{
s += (Integer.FromInt32(i).IsEven ? Number.One : Number.MinusOne) * u *
(Number)Integer.Binomial(num, i) * Expression.Cos((Number)(num - 2 * i) * fun.Argument);
}
return (num.IsEven ? Number.One : Number.MinusOne) * (Number)Integer.Binomial(n, n / 2) / Expression.Pow(2, n) + s;
}
else
{
var u = ((num -1 / 2).IsEven ? Number.One : Number.MinusOne) * Expression.Pow(2, 1 - n);
Expression s = Number.Zero;
for (int i = 0; i <= n / 2; i++)
{
s += (Integer.FromInt32(i).IsEven ? Number.One : Number.MinusOne) * u *
(Number)Integer.Binomial(num, i) * Expression.Sin((Number)(num - 2 * i) * fun.Argument);
}
return s;
}
}
else if (fun.Identifier == FunctionIdentifiers.Cos)
{
var n = num.ToInt32();
if (num.IsEven)
{
var u = Expression.Pow(2, 1 - n);
Expression s = Number.Zero;
for (int i = 0; i <= n / 2 - 1; i++)
{
s += u * (Number)Integer.Binomial(num, i) * Expression.Cos((Number)(num - 2 * i) * fun.Argument);
}
return (Number)Integer.Binomial(n, n / 2) / Expression.Pow(2, n) + s;
}
else
{
var u = Expression.Pow(2, 1 - n);
Expression s = Number.Zero;
for (int i = 0; i <= n / 2; i++)
{
s += u * (Number)Integer.Binomial(num, i) * Expression.Cos((Number)(num - 2 * i) * fun.Argument);
}
return s;
}
}
}
}
return Expression.Pow(bas, exp);
}
private static Expression ApplyProduct(Product product)
{
if (product.NumberOfFactors == 2)
{
var u = product[0];
var v = product[1];
if (u is Power)
{
var pow = (Power)u;
return ContractInner(v * ApplyPow(pow.Base, pow.Exponent));
}
else if (v is Power)
{
var pow = (Power)v;
return ContractInner(u * ApplyPow(pow.Base, pow.Exponent));
}
else if (u is Function && v is Function)
{
var fun1 = (Function)u;
var fun2 = (Function)v;
if (fun1.Identifier == FunctionIdentifiers.Sin &&
fun2.Identifier == FunctionIdentifiers.Sin)
{
return Expression.Cos(fun1.Argument - fun2.Argument) / 2 -
Expression.Cos(fun1.Argument + fun2.Argument) / 2;
}
else if (fun1.Identifier == FunctionIdentifiers.Cos &&
fun2.Identifier == FunctionIdentifiers.Cos)
{
return Expression.Cos(fun1.Argument + fun2.Argument) / 2 +
Expression.Cos(fun1.Argument - fun2.Argument) / 2;
}
else if (fun1.Identifier == FunctionIdentifiers.Sin &&
fun2.Identifier == FunctionIdentifiers.Cos)
{
return Expression.Sin(fun1.Argument + fun2.Argument) / 2 +
Expression.Sin(fun1.Argument - fun2.Argument) / 2;
}
else if (fun1.Identifier == FunctionIdentifiers.Cos &&
fun2.Identifier == FunctionIdentifiers.Sin)
{
return Expression.Sin(fun1.Argument + fun2.Argument) / 2 -
Expression.Sin(fun1.Argument - fun2.Argument) / 2;
}
}
throw new Exception();
}
else
{
Expression head;
List<Expression> list;
product.Decompose(out head, out list);
if (list.Count == 1)
return ContractInner(head * list[0]);
else
return ContractInner(head * ApplyProduct(new Product(list)));
}
}
#endregion
/// <summary>
/// Simplifies the specified trigonometric expression.
/// </summary>
/// <param name="expression">The algebraic expression.</param>
/// <returns>The simplified expression of <paramref name="expression"/>.</returns>
/// <exception cref="ArgumentNullException">The parameter is <see langword="null"/>.</exception>
public static Expression Simplify(this Expression expression)
{
if (expression == null)
throw new ArgumentNullException();
var r = Fraction.Rationalize(SubstituteToSinCos(expression));
Expression num, den;
Fraction.NumeratorDenominator(r, out num, out den);
return Contract(Expand(num)) / Contract(Expand(den));
}
#region Private
private static Expression SubstituteToSinCos(Expression expression)
{
if (expression is Function)
{
var fun = (Function)expression;
var arg = SubstituteToSinCos(fun.Argument);
if (fun.Identifier == FunctionIdentifiers.Tan)
{
return Expression.Sin(arg) / Expression.Cos(arg);
}
else
return Function.Create(fun.Identifier, arg);
}
else if (expression is Sum)
{
var sum = (Sum)expression;
Expression s = Number.Zero;
foreach (Expression t in sum)
{
s += SubstituteToSinCos(t);
}
return s;
}
else if (expression is Product)
{
var prod = (Product)expression;
Expression p = Number.One;
foreach (Expression t in prod)
{
p *= SubstituteToSinCos(t);
}
return p;
}
else if (expression is Power)
{
var pow = (Power)expression;
return Expression.Pow(SubstituteToSinCos(pow.Base), SubstituteToSinCos(pow.Exponent));
}
else if (expression is MultiArgumentFunction)
{
var mulfun = (MultiArgumentFunction)expression;
return MultiArgumentFunction.Create(mulfun.Identifier, mulfun.Map((Expression t) => SubstituteToSinCos(t)));
}
else
return expression;
}
#endregion
}
}
| 38.563169 | 143 | 0.415959 | [
"MIT"
] | LapisDev/LapisMath | src/Lapis.Math.Algebra/Arithmetics/Trigonometric.cs | 18,015 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Blacker.MangaScraper.Common;
namespace Blacker.Scraper
{
public class FoOlSlideFactory : IScraperFactory
{
// todo: make this configurable
private readonly IEnumerable<FoOlSlide.FoOlSlideConfig> _configurations = new List<FoOlSlide.FoOlSlideConfig>()
{
new FoOlSlide.FoOlSlideConfig()
{
BaseUrl = "http://reader.vortex-scans.com/",
DirectoryUrl = "http://reader.vortex-scans.com/reader/list",
Name = "Vortex-Scans",
ScraperGuid = Guid.Parse("05345360-6ee0-4b74-8378-a69d38700ede")
},
new FoOlSlide.FoOlSlideConfig()
{
BaseUrl = "http://manga.redhawkscans.com",
DirectoryUrl = "http://manga.redhawkscans.com/reader/list",
Name = "Red Hawk Scans",
ScraperGuid = Guid.Parse("e4d2f38b-9e81-4b9a-beb1-bcd09b6388d9")
}
};
private IEnumerable<IScraper> _scrapers;
public IEnumerable<IScraper> GetScrapers()
{
return _scrapers ?? (_scrapers = _configurations.Select(conf => new FoOlSlide(conf)).ToList());
}
}
}
| 53.684211 | 128 | 0.377451 | [
"BSD-2-Clause"
] | blacker-cz/MangaScraper | Blacker.Scraper/FoOlSlideFactory.cs | 2,042 | C# |
using GenericRepositoryHelloWorld.Core;
using GenericRepositoryHelloWorld.Core.Repositories;
using GenericRepositoryHelloWorld.Data.Repositories;
using System.Threading.Tasks;
namespace GenericRepositoryHelloWorld.Data
{
public class UnitOfWork : IUnitOfWork
{
private readonly MusicMarketDbContext _context;
private MusicRepository _musicRepository;
private ArtistRepository _artistRepository;
public UnitOfWork(MusicMarketDbContext context)
{
_context = context;
}
public IMusicRepository Musics => _musicRepository = _musicRepository ?? new MusicRepository(_context);
public IArtistRepository Artists => _artistRepository = _artistRepository ?? new ArtistRepository(_context);
public async Task<int> CommitAsync()
{
return await _context.SaveChangesAsync();
}
public void Dispose()
{
_context.Dispose();
}
}
}
| 30.5625 | 116 | 0.696319 | [
"MIT"
] | Meeyzt/GenericRepositoryHelloWorld | GenericRepositoryHelloWorld.Data/UnitOfWork.cs | 980 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class LineDraw : MonoBehaviour, IPointerDownHandler, IPointerUpHandler
{
[Header("Draw Attributes")] private GameObject _line;
private bool _isDrawing;
private Vector3 _mousePosition;
private Camera _mainCamera;
[SerializeField] private GameObject _drawObjPrefab;
private GameObject _drawInstantiated;
[SerializeField] private Material _lineMaterial;
[Header("Line Attributes")] private LineRenderer _lr;
private int _currentIndex;
private void Awake()
{
CreateLine();
}
void Update()
{
if (_isDrawing)
{
var distance = _mousePosition - Input.mousePosition;
var distanceSqrMagnitude = distance.sqrMagnitude;
if (distance.sqrMagnitude > 1000f)
{
_lr.SetPosition(_currentIndex,
_mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,
Input.mousePosition.z + 10f)));
if (_drawInstantiated)
{
var currentLinePosition = _lr.GetPosition(_currentIndex);
_drawInstantiated.SetActive(true);
_drawInstantiated.transform.LookAt(currentLinePosition);
if (_drawInstantiated.transform.rotation.y == 0)
{
_drawInstantiated.transform.eulerAngles =
new Vector3(_drawInstantiated.transform.rotation.eulerAngles.x, 90,
_drawInstantiated.transform.rotation.eulerAngles.z);
}
_drawInstantiated.transform.localScale = new Vector3(_drawInstantiated.transform.localScale.x,
Vector3.Distance(_drawInstantiated.transform.position, currentLinePosition) * 0.5f,
35f);
}
_drawInstantiated = Instantiate(_drawObjPrefab, _lr.GetPosition(_currentIndex), Quaternion.identity, _line.transform);
_drawInstantiated.SetActive(false);
_mousePosition = Input.mousePosition;
_currentIndex++;
_lr.positionCount = _currentIndex + 1;
_lr.SetPosition(_currentIndex,
_mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y,
Input.mousePosition.z + 10f)));
}
}
}
public void OnPointerDown(PointerEventData eventData)
{
_isDrawing = true;
_mousePosition = Input.mousePosition;
}
public void OnPointerUp(PointerEventData eventData)
{
_isDrawing = false;
_line.AddComponent<Rigidbody>();
_lr.useWorldSpace = false;
_currentIndex = 0;
Destroy(_drawInstantiated);
CreateLine();
}
public void CreateLine()
{
_line = new GameObject();
_line.transform.name = "Line";
_lr = _line.AddComponent<LineRenderer>();
_lr.startWidth = 0.2f;
_lr.material = _lineMaterial;
_lr.enabled = false;
if (Camera.main) _mainCamera = Camera.main;
}
} | 36 | 134 | 0.606884 | [
"MIT"
] | canerozdemirr/MeshDrawingRuntime | Assets/Scripts/LineDraw.cs | 3,314 | C# |
namespace C_sharp_LOGIN
{
partial class uC_IN_OUT
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.sw_out0 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label10 = new System.Windows.Forms.Label();
this.sw_out1 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label11 = new System.Windows.Forms.Label();
this.label28 = new System.Windows.Forms.Label();
this.sw_out7 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label12 = new System.Windows.Forms.Label();
this.label29 = new System.Windows.Forms.Label();
this.sw_out2 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label13 = new System.Windows.Forms.Label();
this.label30 = new System.Windows.Forms.Label();
this.sw_out6 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label14 = new System.Windows.Forms.Label();
this.label31 = new System.Windows.Forms.Label();
this.sw_out3 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label15 = new System.Windows.Forms.Label();
this.label32 = new System.Windows.Forms.Label();
this.sw_out5 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label16 = new System.Windows.Forms.Label();
this.label33 = new System.Windows.Forms.Label();
this.sw_out4 = new Guna.UI2.WinForms.Guna2ToggleSwitch();
this.label17 = new System.Windows.Forms.Label();
this.label34 = new System.Windows.Forms.Label();
this.ptb_IN0 = new System.Windows.Forms.PictureBox();
this.ptb_IN1 = new System.Windows.Forms.PictureBox();
this.ptb_IN7 = new System.Windows.Forms.PictureBox();
this.ptb_IN2 = new System.Windows.Forms.PictureBox();
this.ptb_IN6 = new System.Windows.Forms.PictureBox();
this.ptb_IN3 = new System.Windows.Forms.PictureBox();
this.ptb_IN5 = new System.Windows.Forms.PictureBox();
this.ptb_IN4 = new System.Windows.Forms.PictureBox();
this.label27 = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN0)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN1)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN7)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN2)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN6)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN3)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN5)).BeginInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN4)).BeginInit();
this.SuspendLayout();
//
// sw_out0
//
this.sw_out0.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out0.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out0.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out0.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out0.CheckedState.Parent = this.sw_out0;
this.sw_out0.Location = new System.Drawing.Point(108, 48);
this.sw_out0.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out0.Name = "sw_out0";
this.sw_out0.ShadowDecoration.Parent = this.sw_out0;
this.sw_out0.Size = new System.Drawing.Size(35, 20);
this.sw_out0.TabIndex = 36;
this.sw_out0.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out0.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out0.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out0.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out0.UncheckedState.Parent = this.sw_out0;
this.sw_out0.Click += new System.EventHandler(this.CheckedChanged);
//
// label10
//
this.label10.AutoSize = true;
this.label10.Location = new System.Drawing.Point(507, 273);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(29, 17);
this.label10.TabIndex = 97;
this.label10.Text = "IN7";
//
// sw_out1
//
this.sw_out1.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out1.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out1.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out1.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out1.CheckedState.Parent = this.sw_out1;
this.sw_out1.Location = new System.Drawing.Point(108, 122);
this.sw_out1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out1.Name = "sw_out1";
this.sw_out1.ShadowDecoration.Parent = this.sw_out1;
this.sw_out1.Size = new System.Drawing.Size(35, 20);
this.sw_out1.TabIndex = 44;
this.sw_out1.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out1.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out1.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out1.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out1.UncheckedState.Parent = this.sw_out1;
this.sw_out1.Click += new System.EventHandler(this.CheckedChanged);
//
// label11
//
this.label11.AutoSize = true;
this.label11.Location = new System.Drawing.Point(179, 273);
this.label11.Name = "label11";
this.label11.Size = new System.Drawing.Size(46, 17);
this.label11.TabIndex = 95;
this.label11.Text = "OUT7";
//
// label28
//
this.label28.AutoSize = true;
this.label28.Location = new System.Drawing.Point(395, 49);
this.label28.Name = "label28";
this.label28.Size = new System.Drawing.Size(29, 17);
this.label28.TabIndex = 42;
this.label28.Text = "IN0";
//
// sw_out7
//
this.sw_out7.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out7.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out7.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out7.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out7.CheckedState.Parent = this.sw_out7;
this.sw_out7.Location = new System.Drawing.Point(248, 271);
this.sw_out7.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out7.Name = "sw_out7";
this.sw_out7.ShadowDecoration.Parent = this.sw_out7;
this.sw_out7.Size = new System.Drawing.Size(35, 20);
this.sw_out7.TabIndex = 92;
this.sw_out7.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out7.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out7.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out7.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out7.UncheckedState.Parent = this.sw_out7;
this.sw_out7.Click += new System.EventHandler(this.CheckedChanged);
//
// label12
//
this.label12.AutoSize = true;
this.label12.Location = new System.Drawing.Point(507, 194);
this.label12.Name = "label12";
this.label12.Size = new System.Drawing.Size(29, 17);
this.label12.TabIndex = 90;
this.label12.Text = "IN6";
//
// label29
//
this.label29.AutoSize = true;
this.label29.Location = new System.Drawing.Point(37, 124);
this.label29.Name = "label29";
this.label29.Size = new System.Drawing.Size(46, 17);
this.label29.TabIndex = 47;
this.label29.Text = "OUT1";
//
// sw_out2
//
this.sw_out2.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out2.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out2.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out2.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out2.CheckedState.Parent = this.sw_out2;
this.sw_out2.Location = new System.Drawing.Point(108, 198);
this.sw_out2.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out2.Name = "sw_out2";
this.sw_out2.ShadowDecoration.Parent = this.sw_out2;
this.sw_out2.Size = new System.Drawing.Size(35, 20);
this.sw_out2.TabIndex = 52;
this.sw_out2.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out2.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out2.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out2.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out2.UncheckedState.Parent = this.sw_out2;
this.sw_out2.Click += new System.EventHandler(this.CheckedChanged);
//
// label13
//
this.label13.AutoSize = true;
this.label13.Location = new System.Drawing.Point(179, 197);
this.label13.Name = "label13";
this.label13.Size = new System.Drawing.Size(46, 17);
this.label13.TabIndex = 88;
this.label13.Text = "OUT6";
//
// label30
//
this.label30.AutoSize = true;
this.label30.Location = new System.Drawing.Point(395, 119);
this.label30.Name = "label30";
this.label30.Size = new System.Drawing.Size(29, 17);
this.label30.TabIndex = 49;
this.label30.Text = "IN1";
//
// sw_out6
//
this.sw_out6.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out6.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out6.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out6.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out6.CheckedState.Parent = this.sw_out6;
this.sw_out6.Location = new System.Drawing.Point(248, 197);
this.sw_out6.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out6.Name = "sw_out6";
this.sw_out6.ShadowDecoration.Parent = this.sw_out6;
this.sw_out6.Size = new System.Drawing.Size(35, 20);
this.sw_out6.TabIndex = 84;
this.sw_out6.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out6.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out6.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out6.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out6.UncheckedState.Parent = this.sw_out6;
this.sw_out6.Click += new System.EventHandler(this.CheckedChanged);
//
// label14
//
this.label14.AutoSize = true;
this.label14.Location = new System.Drawing.Point(507, 119);
this.label14.Name = "label14";
this.label14.Size = new System.Drawing.Size(29, 17);
this.label14.TabIndex = 81;
this.label14.Text = "IN5";
//
// label31
//
this.label31.AutoSize = true;
this.label31.Location = new System.Drawing.Point(37, 199);
this.label31.Name = "label31";
this.label31.Size = new System.Drawing.Size(46, 17);
this.label31.TabIndex = 55;
this.label31.Text = "OUT2";
//
// sw_out3
//
this.sw_out3.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out3.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out3.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out3.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out3.CheckedState.Parent = this.sw_out3;
this.sw_out3.Location = new System.Drawing.Point(108, 272);
this.sw_out3.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out3.Name = "sw_out3";
this.sw_out3.ShadowDecoration.Parent = this.sw_out3;
this.sw_out3.Size = new System.Drawing.Size(35, 20);
this.sw_out3.TabIndex = 60;
this.sw_out3.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out3.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out3.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out3.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out3.UncheckedState.Parent = this.sw_out3;
this.sw_out3.Click += new System.EventHandler(this.CheckedChanged);
//
// label15
//
this.label15.AutoSize = true;
this.label15.Location = new System.Drawing.Point(179, 122);
this.label15.Name = "label15";
this.label15.Size = new System.Drawing.Size(46, 17);
this.label15.TabIndex = 79;
this.label15.Text = "OUT5";
//
// label32
//
this.label32.AutoSize = true;
this.label32.Location = new System.Drawing.Point(395, 192);
this.label32.Name = "label32";
this.label32.Size = new System.Drawing.Size(29, 17);
this.label32.TabIndex = 57;
this.label32.Text = "IN2";
//
// sw_out5
//
this.sw_out5.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out5.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out5.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out5.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out5.CheckedState.Parent = this.sw_out5;
this.sw_out5.Location = new System.Drawing.Point(248, 122);
this.sw_out5.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out5.Name = "sw_out5";
this.sw_out5.ShadowDecoration.Parent = this.sw_out5;
this.sw_out5.Size = new System.Drawing.Size(35, 20);
this.sw_out5.TabIndex = 75;
this.sw_out5.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out5.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out5.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out5.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out5.UncheckedState.Parent = this.sw_out5;
this.sw_out5.Click += new System.EventHandler(this.CheckedChanged);
//
// label16
//
this.label16.AutoSize = true;
this.label16.Location = new System.Drawing.Point(505, 50);
this.label16.Name = "label16";
this.label16.Size = new System.Drawing.Size(29, 17);
this.label16.TabIndex = 74;
this.label16.Text = "IN4";
//
// label33
//
this.label33.AutoSize = true;
this.label33.Location = new System.Drawing.Point(37, 276);
this.label33.Name = "label33";
this.label33.Size = new System.Drawing.Size(46, 17);
this.label33.TabIndex = 63;
this.label33.Text = "OUT3";
//
// sw_out4
//
this.sw_out4.CheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out4.CheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(94)))), ((int)(((byte)(148)))), ((int)(((byte)(255)))));
this.sw_out4.CheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out4.CheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out4.CheckedState.Parent = this.sw_out4;
this.sw_out4.Location = new System.Drawing.Point(248, 48);
this.sw_out4.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.sw_out4.Name = "sw_out4";
this.sw_out4.ShadowDecoration.Parent = this.sw_out4;
this.sw_out4.Size = new System.Drawing.Size(35, 20);
this.sw_out4.TabIndex = 67;
this.sw_out4.UncheckedState.BorderColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out4.UncheckedState.FillColor = System.Drawing.Color.FromArgb(((int)(((byte)(125)))), ((int)(((byte)(137)))), ((int)(((byte)(149)))));
this.sw_out4.UncheckedState.InnerBorderColor = System.Drawing.Color.White;
this.sw_out4.UncheckedState.InnerColor = System.Drawing.Color.White;
this.sw_out4.UncheckedState.Parent = this.sw_out4;
this.sw_out4.Click += new System.EventHandler(this.CheckedChanged);
//
// label17
//
this.label17.AutoSize = true;
this.label17.Location = new System.Drawing.Point(179, 49);
this.label17.Name = "label17";
this.label17.Size = new System.Drawing.Size(46, 17);
this.label17.TabIndex = 71;
this.label17.Text = "OUT4";
//
// label34
//
this.label34.AutoSize = true;
this.label34.Location = new System.Drawing.Point(395, 272);
this.label34.Name = "label34";
this.label34.Size = new System.Drawing.Size(29, 17);
this.label34.TabIndex = 65;
this.label34.Text = "IN3";
//
// ptb_IN0
//
this.ptb_IN0.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN0.Location = new System.Drawing.Point(436, 33);
this.ptb_IN0.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN0.Name = "ptb_IN0";
this.ptb_IN0.Size = new System.Drawing.Size(57, 47);
this.ptb_IN0.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN0.TabIndex = 37;
this.ptb_IN0.TabStop = false;
//
// ptb_IN1
//
this.ptb_IN1.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN1.Location = new System.Drawing.Point(436, 105);
this.ptb_IN1.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN1.Name = "ptb_IN1";
this.ptb_IN1.Size = new System.Drawing.Size(57, 50);
this.ptb_IN1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN1.TabIndex = 45;
this.ptb_IN1.TabStop = false;
//
// ptb_IN7
//
this.ptb_IN7.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN7.Location = new System.Drawing.Point(543, 256);
this.ptb_IN7.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN7.Name = "ptb_IN7";
this.ptb_IN7.Size = new System.Drawing.Size(53, 47);
this.ptb_IN7.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN7.TabIndex = 93;
this.ptb_IN7.TabStop = false;
//
// ptb_IN2
//
this.ptb_IN2.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN2.Location = new System.Drawing.Point(436, 177);
this.ptb_IN2.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN2.Name = "ptb_IN2";
this.ptb_IN2.Size = new System.Drawing.Size(57, 48);
this.ptb_IN2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN2.TabIndex = 54;
this.ptb_IN2.TabStop = false;
//
// ptb_IN6
//
this.ptb_IN6.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN6.Location = new System.Drawing.Point(543, 177);
this.ptb_IN6.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN6.Name = "ptb_IN6";
this.ptb_IN6.Size = new System.Drawing.Size(53, 48);
this.ptb_IN6.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN6.TabIndex = 85;
this.ptb_IN6.TabStop = false;
//
// ptb_IN3
//
this.ptb_IN3.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN3.Location = new System.Drawing.Point(435, 254);
this.ptb_IN3.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN3.Name = "ptb_IN3";
this.ptb_IN3.Size = new System.Drawing.Size(59, 48);
this.ptb_IN3.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN3.TabIndex = 62;
this.ptb_IN3.TabStop = false;
//
// ptb_IN5
//
this.ptb_IN5.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN5.Location = new System.Drawing.Point(543, 105);
this.ptb_IN5.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN5.Name = "ptb_IN5";
this.ptb_IN5.Size = new System.Drawing.Size(53, 50);
this.ptb_IN5.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN5.TabIndex = 77;
this.ptb_IN5.TabStop = false;
//
// ptb_IN4
//
this.ptb_IN4.Image = global::C_sharp_LOGIN.Properties.Resources.lamp_off;
this.ptb_IN4.Location = new System.Drawing.Point(543, 33);
this.ptb_IN4.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.ptb_IN4.Name = "ptb_IN4";
this.ptb_IN4.Size = new System.Drawing.Size(53, 47);
this.ptb_IN4.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.ptb_IN4.TabIndex = 70;
this.ptb_IN4.TabStop = false;
//
// label27
//
this.label27.AutoSize = true;
this.label27.Location = new System.Drawing.Point(37, 50);
this.label27.Name = "label27";
this.label27.Size = new System.Drawing.Size(46, 17);
this.label27.TabIndex = 39;
this.label27.Text = "OUT0";
//
// uC_IN_OUT
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.Controls.Add(this.sw_out0);
this.Controls.Add(this.ptb_IN0);
this.Controls.Add(this.label10);
this.Controls.Add(this.label27);
this.Controls.Add(this.sw_out1);
this.Controls.Add(this.label11);
this.Controls.Add(this.label28);
this.Controls.Add(this.ptb_IN1);
this.Controls.Add(this.ptb_IN7);
this.Controls.Add(this.sw_out7);
this.Controls.Add(this.label12);
this.Controls.Add(this.label29);
this.Controls.Add(this.sw_out2);
this.Controls.Add(this.label13);
this.Controls.Add(this.label30);
this.Controls.Add(this.ptb_IN2);
this.Controls.Add(this.ptb_IN6);
this.Controls.Add(this.sw_out6);
this.Controls.Add(this.label14);
this.Controls.Add(this.label31);
this.Controls.Add(this.sw_out3);
this.Controls.Add(this.label15);
this.Controls.Add(this.label32);
this.Controls.Add(this.ptb_IN3);
this.Controls.Add(this.ptb_IN5);
this.Controls.Add(this.sw_out5);
this.Controls.Add(this.label16);
this.Controls.Add(this.label33);
this.Controls.Add(this.sw_out4);
this.Controls.Add(this.label17);
this.Controls.Add(this.label34);
this.Controls.Add(this.ptb_IN4);
this.Margin = new System.Windows.Forms.Padding(3, 2, 3, 2);
this.Name = "uC_IN_OUT";
this.Size = new System.Drawing.Size(672, 347);
this.Load += new System.EventHandler(this.uC_IN_OUT_Load);
((System.ComponentModel.ISupportInitialize)(this.ptb_IN0)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN1)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN7)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN2)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN6)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN3)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN5)).EndInit();
((System.ComponentModel.ISupportInitialize)(this.ptb_IN4)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out0;
private System.Windows.Forms.PictureBox ptb_IN0;
private System.Windows.Forms.Label label10;
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out1;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.Label label28;
private System.Windows.Forms.PictureBox ptb_IN1;
private System.Windows.Forms.PictureBox ptb_IN7;
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out7;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.Label label29;
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out2;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label30;
private System.Windows.Forms.PictureBox ptb_IN2;
private System.Windows.Forms.PictureBox ptb_IN6;
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out6;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label31;
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out3;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label32;
private System.Windows.Forms.PictureBox ptb_IN3;
private System.Windows.Forms.PictureBox ptb_IN5;
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out5;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Label label33;
private Guna.UI2.WinForms.Guna2ToggleSwitch sw_out4;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label label34;
private System.Windows.Forms.PictureBox ptb_IN4;
private System.Windows.Forms.Label label27;
}
}
| 56.041591 | 156 | 0.59272 | [
"MIT"
] | daotuyen9244/Indruino-Iot-Project | SW/PC_App/Hau/C#_LOGIN/C_sharp_LOGIN/C_sharp_LOGIN/uC_IN_OUT.Designer.cs | 30,993 | C# |
//------------------------------------------------------------------------------
// <auto-generated />
//
// This file was automatically generated by SWIG (http://www.swig.org).
// Version 3.0.12
//
// Do not make changes to this file unless you know what you are doing--modify
// the SWIG interface file instead.
//------------------------------------------------------------------------------
namespace pxr {
public class SWIGTYPE_p_PcpPrimIndex {
private global::System.Runtime.InteropServices.HandleRef swigCPtr;
internal SWIGTYPE_p_PcpPrimIndex(global::System.IntPtr cPtr, bool futureUse) {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(this, cPtr);
}
protected SWIGTYPE_p_PcpPrimIndex() {
swigCPtr = new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero);
}
internal static global::System.Runtime.InteropServices.HandleRef getCPtr(SWIGTYPE_p_PcpPrimIndex obj) {
return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr;
}
}
}
| 36.066667 | 129 | 0.641405 | [
"Apache-2.0"
] | Vochsel/usd-unity-sdk | src/USD.NET/generated/SWIG/SWIGTYPE_p_PcpPrimIndex.cs | 1,082 | C# |
namespace Dissertation.Algorithms.Algorithms.Newton
{
public interface IFunction
{
double CalculateFunctionValue(double x);
}
}
| 18.625 | 52 | 0.711409 | [
"MIT"
] | Fairday/Dissertation | src/Dissertation.Algorithms/Algorithms/Newton/IFunction.cs | 151 | C# |
namespace MonkeyButler.Abstractions.Data.Storage.Models.Guild;
/// <summary>
/// Query for getting options for a guild.
/// </summary>
public record GetOptionsQuery
{
/// <summary>
/// The Id of the guild.
/// </summary>
public ulong GuildId { get; set; }
}
| 21.230769 | 63 | 0.652174 | [
"MIT"
] | Foshkey/MonkeyButler | src/MonkeyButler.Abstractions/Data/Storage/Models/Guild/GetOptionsQuery.cs | 278 | C# |
#region Header
// Vorspire _,-'/-'/ ObjectExt.cs
// . __,-; ,'( '/
// \. `-.__`-._`:_,-._ _ , . ``
// `:-._,------' ` _,`--` -: `_ , ` ,' :
// `---..__,,--' (C) 2018 ` -'. -'
// # Vita-Nex [http://core.vita-nex.com] #
// {o)xxx|===============- # -===============|xxx(o}
// # The MIT License (MIT) #
#endregion
#region References
using System.Linq;
using System.Reflection;
using VitaNex;
using VitaNex.Reflection;
#endregion
namespace System
{
public static class ObjectExtUtility
{
private static readonly Delegate[] _EmptyDelegates = new Delegate[0];
public static Delegate[] GetEventDelegates(this object obj, string eventName)
{
var type = obj as Type ?? obj.GetType();
var bind = BindingFlags.Public;
if (type.IsSealed && type.IsAbstract)
{
bind |= BindingFlags.Static;
}
else
{
bind |= BindingFlags.Instance;
}
var ei = type.GetEvent(eventName, bind);
if (ei == null)
{
return _EmptyDelegates;
}
bind &= ~BindingFlags.Public;
bind |= BindingFlags.GetField;
var efi = type.GetField(ei.Name, bind);
if (efi == null)
{
return _EmptyDelegates;
}
var efv = (Delegate)efi.GetValue(obj is Type ? null : obj);
return efv.GetInvocationList();
}
public static MethodInfo[] GetEventMethods(this object obj, string eventName)
{
return GetEventDelegates(obj, eventName).Select(e => e.Method).ToArray();
}
public static bool GetFieldValue(this object obj, string name, out object value)
{
return GetFieldValue<object>(obj, name, out value);
}
public static bool GetFieldValue<T>(this object obj, string name, out T value)
{
value = default(T);
if (obj == null || String.IsNullOrWhiteSpace(name))
{
return false;
}
var t = obj as Type ?? obj.GetType();
var f = BindingFlags.NonPublic;
if (t.IsSealed && t.IsAbstract)
{
f |= BindingFlags.Static;
}
else
{
f |= BindingFlags.Instance;
}
var p = t.GetFields(f);
foreach (var o in p.Where(o => o.Name == name))
{
try
{
value = (T)o.GetValue(obj);
return true;
}
catch
{ }
}
return false;
}
public static bool SetFieldValue(this object obj, string name, object value)
{
return SetFieldValue<object>(obj, name, value);
}
public static bool SetFieldValue<T>(this object obj, string name, T value)
{
if (obj == null || String.IsNullOrWhiteSpace(name))
{
return false;
}
var t = obj as Type ?? obj.GetType();
var f = BindingFlags.NonPublic;
if (t.IsSealed && t.IsAbstract)
{
f |= BindingFlags.Static;
}
else
{
f |= BindingFlags.Instance;
}
var p = t.GetFields(f);
foreach (var o in p.Where(o => o.Name == name))
{
try
{
o.SetValue(obj, value);
return true;
}
catch
{ }
}
return false;
}
public static bool GetPropertyValue(this object obj, string name, out object value)
{
return GetPropertyValue<object>(obj, name, out value);
}
public static bool GetPropertyValue<T>(this object obj, string name, out T value)
{
value = default(T);
if (obj == null || String.IsNullOrWhiteSpace(name))
{
return false;
}
var t = obj as Type ?? obj.GetType();
var f = BindingFlags.Public;
if (t.IsSealed && t.IsAbstract)
{
f |= BindingFlags.Static;
}
else
{
f |= BindingFlags.Instance;
}
var p = t.GetProperties(f);
foreach (var o in p.Where(o => o.Name == name).OrderBy(o => o.CanRead))
{
try
{
value = (T)o.GetValue(obj, null);
return true;
}
catch
{ }
}
return false;
}
public static bool SetPropertyValue(this object obj, string name, object value)
{
return SetPropertyValue<object>(obj, name, value);
}
public static bool SetPropertyValue<T>(this object obj, string name, T value)
{
if (obj == null || String.IsNullOrWhiteSpace(name))
{
return false;
}
var t = obj as Type ?? obj.GetType();
var f = BindingFlags.Public;
if (t.IsSealed && t.IsAbstract)
{
f |= BindingFlags.Static;
}
else
{
f |= BindingFlags.Instance;
}
var p = t.GetProperties(f);
foreach (var o in p.Where(o => o.Name == name).OrderBy(o => o.CanWrite))
{
try
{
o.SetValue(obj, value, null);
return true;
}
catch
{ }
}
return false;
}
public static object CallMethod(this object obj, string name, params object[] args)
{
if (obj == null || String.IsNullOrWhiteSpace(name))
{
return null;
}
var t = obj as Type ?? obj.GetType();
var f = BindingFlags.Public | BindingFlags.NonPublic;
if (t.IsSealed && t.IsAbstract)
{
f |= BindingFlags.Static;
}
else
{
f |= BindingFlags.Instance;
}
var m = t.GetMethods(f);
foreach (var o in m.Where(o => o.Name == name).OrderBy(o => o.IsPublic))
{
try
{
return o.Invoke(obj, args);
}
catch
{ }
}
return null;
}
public static T CallMethod<T>(this object obj, string name, params object[] args)
{
return (T)CallMethod(obj, name, args);
}
public static int GetTypeHashCode(this object obj)
{
if (obj == null)
{
return 0;
}
return obj.GetType().GetValueHashCode();
}
public static string GetTypeName(this object obj, bool raw)
{
Type t;
if (obj is Type)
{
t = (Type)obj;
}
else if (obj is ITypeSelectProperty)
{
t = ((ITypeSelectProperty)obj).ExpectedType;
}
else
{
t = obj.GetType();
}
return raw ? t.Name : t.ResolveName();
}
public static bool Is<T>(this object obj)
{
return TypeEquals<T>(obj);
}
public static bool TypeEquals<T>(this object obj)
{
return TypeEquals<T>(obj, true);
}
public static bool TypeEquals<T>(this object obj, bool child)
{
return TypeEquals(obj, typeof(T), child);
}
public static bool TypeEquals(this object obj, object other)
{
return TypeEquals(obj, other, true);
}
public static bool TypeEquals(this object obj, object other, bool child)
{
if (obj == null || other == null)
{
return false;
}
if (ReferenceEquals(obj, other))
{
return true;
}
Type l, r;
if (obj is ITypeSelectProperty)
{
l = ((ITypeSelectProperty)obj).InternalType;
}
else
{
l = obj as Type ?? obj.GetType();
}
if (other is ITypeSelectProperty)
{
r = ((ITypeSelectProperty)other).InternalType;
}
else
{
r = other as Type ?? other.GetType();
}
return child ? l.IsEqualOrChildOf(r) : l.IsEqual(r);
}
public static bool IsNull<T>(this T obj)
where T : class
{
return ReferenceEquals(obj, null);
}
public static T IfNull<T>(this T obj, Func<T> resolve)
where T : class
{
if (IsNull(obj) && !IsNull(resolve))
{
return resolve();
}
return obj;
}
public static void IfNull<T>(this T obj, Action action)
where T : class
{
if (IsNull(obj) && !IsNull(action))
{
action();
}
}
public static D IfNull<T, D>(this T obj, Func<D> resolve, D def)
where T : class
{
if (IsNull(obj) && !IsNull(resolve))
{
return resolve();
}
return def;
}
public static T IfNotNull<T>(this T obj, Func<T, T> resolve)
where T : class
{
if (!IsNull(obj) && !IsNull(resolve))
{
return resolve(obj);
}
return obj;
}
public static void IfNotNull<T>(this T obj, Action<T> action)
where T : class
{
if (!IsNull(obj) && !IsNull(action))
{
action(obj);
}
}
public static D IfNotNull<T, D>(this T obj, Func<T, D> resolve, D def)
where T : class
{
if (!IsNull(obj) && !IsNull(resolve))
{
return resolve(obj);
}
return def;
}
public static int CompareNull<T>(this T obj, T other)
{
var result = 0;
CompareNull(obj, other, ref result);
return result;
}
public static bool CompareNull<T>(this T obj, T other, ref int result)
{
if (obj == null && other == null)
{
return true;
}
if (obj == null)
{
++result;
return true;
}
if (other == null)
{
--result;
return true;
}
return false;
}
public static FieldList<T> GetFields<T>(
this T obj,
BindingFlags flags = BindingFlags.Default,
Func<FieldInfo, bool> filter = null)
{
return new FieldList<T>(obj, flags, filter);
}
public static PropertyList<T> GetProperties<T>(
this T obj,
BindingFlags flags = BindingFlags.Default,
Func<PropertyInfo, bool> filter = null)
{
return new PropertyList<T>(obj, flags, filter);
}
}
} | 19.233193 | 86 | 0.557619 | [
"MIT"
] | Vita-Nex/Core | Extensions/System/ObjectExt.cs | 9,157 | C# |
//----------------------------------------------------------------------------------------------
// <copyright file="ComposeExtensionValue.cs" company="Microsoft">
// Copyright (c) Microsoft. All rights reserved.
// </copyright>
//----------------------------------------------------------------------------------------------
namespace Clippy.WebModels
{
using Newtonsoft.Json;
/// <summary>
/// Class used to serialize and deserialize a Compose Extension value.
/// </summary>
public class ComposeExtensionValue
{
/// <summary>
/// Gets or sets the command Id of the value.
/// </summary>
[JsonProperty("commandId")]
public string CommandId { get; set; }
/// <summary>
/// Gets or sets the parameters of the value.
/// </summary>
[JsonProperty("parameters")]
public ComposeExtensionParameter[] Parameters { get; set; }
/// <summary>
/// Gets or sets the query options of the value.
/// </summary>
[JsonProperty("queryOptions")]
public ComposeExtensionQueryOptions QueryOptions { get; set; }
}
}
| 32.828571 | 97 | 0.502176 | [
"MIT"
] | asdkant/microsoft-teams-clippy-app | Clippy/WebModels/ComposeExtensionValue.cs | 1,151 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.FlowAnalysis;
using Microsoft.CodeAnalysis.Operations;
using Microsoft.CodeAnalysis.Test.Extensions;
using Roslyn.Test.Utilities;
using Roslyn.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.Test.Utilities
{
public class OperationTreeVerifier : OperationWalker
{
protected readonly Compilation _compilation;
protected readonly IOperation _root;
protected readonly StringBuilder _builder;
private readonly Dictionary<SyntaxNode, IOperation> _explicitNodeMap;
private readonly Dictionary<ILabelSymbol, uint> _labelIdMap;
private const string indent = " ";
protected string _currentIndent;
private bool _pendingIndent;
private uint _currentLabelId = 0;
public OperationTreeVerifier(Compilation compilation, IOperation root, int initialIndent)
{
_compilation = compilation;
_root = root;
_builder = new StringBuilder();
_currentIndent = new string(' ', initialIndent);
_pendingIndent = true;
_explicitNodeMap = new Dictionary<SyntaxNode, IOperation>();
_labelIdMap = new Dictionary<ILabelSymbol, uint>();
}
public static string GetOperationTree(Compilation compilation, IOperation operation, int initialIndent = 0)
{
var walker = new OperationTreeVerifier(compilation, operation, initialIndent);
walker.Visit(operation);
return walker._builder.ToString();
}
public static void Verify(string expectedOperationTree, string actualOperationTree)
{
char[] newLineChars = Environment.NewLine.ToCharArray();
string actual = actualOperationTree.Trim(newLineChars);
actual = actual.Replace("\"", "\"\"");
expectedOperationTree = expectedOperationTree.Trim(newLineChars);
expectedOperationTree = expectedOperationTree.Replace("\r\n", "\n").Replace("\n", Environment.NewLine);
expectedOperationTree = expectedOperationTree.Replace("\"", "\"\"");
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedOperationTree, actual);
}
#region Logging helpers
private void LogPatternPropertiesAndNewLine(IPatternOperation operation)
{
LogPatternProperties(operation);
LogString(")");
LogNewLine();
}
private void LogPatternProperties(IPatternOperation operation)
{
LogCommonProperties(operation);
LogString(" (");
LogType(operation.InputType, $"{nameof(operation.InputType)}");
}
private void LogCommonPropertiesAndNewLine(IOperation operation)
{
LogCommonProperties(operation);
LogNewLine();
}
private void LogCommonProperties(IOperation operation)
{
LogString(" (");
// Kind
LogString($"{nameof(OperationKind)}.{GetKindText(operation.Kind)}");
// Type
LogString(", ");
LogType(operation.Type);
// ConstantValue
if (operation.ConstantValue.HasValue)
{
LogString(", ");
LogConstant(operation.ConstantValue);
}
// IsInvalid
if (operation.HasErrors(_compilation))
{
LogString(", IsInvalid");
}
// IsImplicit
if (operation.IsImplicit)
{
LogString(", IsImplicit");
}
LogString(")");
// Syntax
Assert.NotNull(operation.Syntax);
LogString($" (Syntax: {GetSnippetFromSyntax(operation.Syntax)})");
// Some of these kinds were inconsistent in the first release, and in standardizing them the
// string output isn't guaranteed to be one or the other. So standardize manually.
string GetKindText(OperationKind kind)
{
switch (kind)
{
case OperationKind.Unary:
return "Unary";
case OperationKind.Binary:
return "Binary";
case OperationKind.TupleBinary:
return "TupleBinary";
case OperationKind.MethodBody:
return "MethodBody";
case OperationKind.ConstructorBody:
return "ConstructorBody";
default:
return kind.ToString();
}
}
}
private static string GetSnippetFromSyntax(SyntaxNode syntax)
{
if (syntax == null)
{
return "null";
}
var text = syntax.ToString().Trim(Environment.NewLine.ToCharArray());
var lines = text.Split(new[] { Environment.NewLine, "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(l => l.Trim()).ToArray();
if (lines.Length <= 1 && text.Length < 25)
{
return $"'{text}'";
}
const int maxTokenLength = 11;
var firstLine = lines[0];
var lastLine = lines[lines.Length - 1];
var prefix = firstLine.Length <= maxTokenLength ? firstLine : firstLine.Substring(0, maxTokenLength);
var suffix = lastLine.Length <= maxTokenLength ? lastLine : lastLine.Substring(lastLine.Length - maxTokenLength, maxTokenLength);
return $"'{prefix} ... {suffix}'";
}
private static bool ShouldLogType(IOperation operation)
{
var operationKind = (int)operation.Kind;
// Expressions
if (operationKind >= 0x100 && operationKind < 0x400)
{
return true;
}
return false;
}
protected void LogString(string str)
{
if (_pendingIndent)
{
str = _currentIndent + str;
_pendingIndent = false;
}
_builder.Append(str);
}
protected void LogNewLine()
{
LogString(Environment.NewLine);
_pendingIndent = true;
}
private void Indent()
{
_currentIndent += indent;
}
private void Unindent()
{
_currentIndent = _currentIndent.Substring(indent.Length);
}
private void LogConstant(Optional<object> constant, string header = "Constant")
{
if (constant.HasValue)
{
LogConstant(constant.Value, header);
}
}
private static string ConstantToString(object constant, bool quoteString = true)
{
switch (constant)
{
case null:
return "null";
case string s:
if (quoteString)
{
return @"""" + s + @"""";
}
return s;
case IFormattable formattable:
return formattable.ToString(null, CultureInfo.InvariantCulture);
default:
return constant.ToString();
}
}
private void LogConstant(object constant, string header = "Constant")
{
string valueStr = ConstantToString(constant);
LogString($"{header}: {valueStr}");
}
private void LogConversion(CommonConversion conversion, string header = "Conversion")
{
var exists = FormatBoolProperty(nameof(conversion.Exists), conversion.Exists);
var isIdentity = FormatBoolProperty(nameof(conversion.IsIdentity), conversion.IsIdentity);
var isNumeric = FormatBoolProperty(nameof(conversion.IsNumeric), conversion.IsNumeric);
var isReference = FormatBoolProperty(nameof(conversion.IsReference), conversion.IsReference);
var isUserDefined = FormatBoolProperty(nameof(conversion.IsUserDefined), conversion.IsUserDefined);
LogString($"{header}: {nameof(CommonConversion)} ({exists}, {isIdentity}, {isNumeric}, {isReference}, {isUserDefined}) (");
LogSymbol(conversion.MethodSymbol, nameof(conversion.MethodSymbol));
LogString(")");
}
private void LogSymbol(ISymbol symbol, string header, bool logDisplayString = true)
{
if (!string.IsNullOrEmpty(header))
{
LogString($"{header}: ");
}
var symbolStr = symbol != null ? (logDisplayString ? symbol.ToTestDisplayString() : symbol.Name) : "null";
LogString($"{symbolStr}");
}
private void LogType(ITypeSymbol type, string header = "Type")
{
var typeStr = type != null ? type.ToTestDisplayString() : "null";
LogString($"{header}: {typeStr}");
}
private uint GetLabelId(ILabelSymbol symbol)
{
if (_labelIdMap.ContainsKey(symbol))
{
return _labelIdMap[symbol];
}
var id = _currentLabelId++;
_labelIdMap[symbol] = id;
return id;
}
private static string FormatBoolProperty(string propertyName, bool value) => $"{propertyName}: {(value ? "True" : "False")}";
#endregion
#region Visit methods
public override void Visit(IOperation operation)
{
if (operation == null)
{
Indent();
LogString("null");
LogNewLine();
Unindent();
return;
}
if (!operation.IsImplicit)
{
try
{
_explicitNodeMap.Add(operation.Syntax, operation);
}
catch (ArgumentException)
{
Assert.False(true, $"Duplicate explicit node for syntax ({operation.Syntax.RawKind}): {operation.Syntax.ToString()}");
}
}
Assert.True(operation.Type == null || !operation.MustHaveNullType(), $"Unexpected non-null type: {operation.Type}");
if (operation != _root)
{
Indent();
}
base.Visit(operation);
if (operation != _root)
{
Unindent();
}
Assert.True(operation.Syntax.Language == operation.Language);
}
private void Visit(IOperation operation, string header)
{
Debug.Assert(!string.IsNullOrEmpty(header));
Indent();
LogString($"{header}: ");
LogNewLine();
Visit(operation);
Unindent();
}
private void VisitArrayCommon<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault, Action<T> arrayElementVisitor)
{
Debug.Assert(!string.IsNullOrEmpty(header));
Indent();
if (!list.IsDefaultOrEmpty)
{
var elementCount = logElementCount ? $"({list.Count()})" : string.Empty;
LogString($"{header}{elementCount}:");
LogNewLine();
Indent();
foreach (var element in list)
{
arrayElementVisitor(element);
}
Unindent();
}
else
{
var suffix = logNullForDefault && list.IsDefault ? ": null" : "(0)";
LogString($"{header}{suffix}");
LogNewLine();
}
Unindent();
}
internal void VisitSymbolArrayElement(ISymbol element)
{
LogSymbol(element, header: "Symbol");
LogNewLine();
}
internal void VisitStringArrayElement(string element)
{
var valueStr = element != null ? element.ToString() : "null";
valueStr = @"""" + valueStr + @"""";
LogString(valueStr);
LogNewLine();
}
internal void VisitRefKindArrayElement(RefKind element)
{
LogString(element.ToString());
LogNewLine();
}
private void VisitChildren(IOperation operation)
{
Debug.Assert(operation.Children.All(o => o != null));
var children = operation.Children.ToImmutableArray();
if (!children.IsEmpty || operation.Kind != OperationKind.None)
{
VisitArray(children, "Children", logElementCount: true);
}
}
private void VisitArray<T>(ImmutableArray<T> list, string header, bool logElementCount, bool logNullForDefault = false)
where T : IOperation
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitOperationArrayElement);
}
private void VisitArray(ImmutableArray<ISymbol> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitSymbolArrayElement);
}
private void VisitArray(ImmutableArray<string> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitStringArrayElement);
}
private void VisitArray(ImmutableArray<RefKind> list, string header, bool logElementCount, bool logNullForDefault = false)
{
VisitArrayCommon(list, header, logElementCount, logNullForDefault, VisitRefKindArrayElement);
}
private void VisitInstance(IOperation instance)
{
Visit(instance, header: "Instance Receiver");
}
internal override void VisitNoneOperation(IOperation operation)
{
LogString("IOperation: ");
LogCommonPropertiesAndNewLine(operation);
VisitChildren(operation);
}
public override void VisitBlock(IBlockOperation operation)
{
LogString(nameof(IBlockOperation));
var statementsStr = $"{operation.Operations.Length} statements";
var localStr = !operation.Locals.IsEmpty ? $", {operation.Locals.Length} locals" : string.Empty;
LogString($" ({statementsStr}{localStr})");
LogCommonPropertiesAndNewLine(operation);
if (operation.Operations.IsEmpty)
{
return;
}
LogLocals(operation.Locals);
base.VisitBlock(operation);
}
public override void VisitVariableDeclarationGroup(IVariableDeclarationGroupOperation operation)
{
var variablesCountStr = $"{operation.Declarations.Length} declarations";
LogString($"{nameof(IVariableDeclarationGroupOperation)} ({variablesCountStr})");
LogCommonPropertiesAndNewLine(operation);
base.VisitVariableDeclarationGroup(operation);
}
public override void VisitUsingDeclaration(IUsingDeclarationOperation operation)
{
LogString($"{nameof(IUsingDeclarationOperation)}");
LogString($"(IsAsynchronous: {operation.IsAsynchronous})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.DeclarationGroup, "DeclarationGroup");
}
public override void VisitVariableDeclarator(IVariableDeclaratorOperation operation)
{
LogString($"{nameof(IVariableDeclaratorOperation)} (");
LogSymbol(operation.Symbol, "Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
if (!operation.IgnoredArguments.IsEmpty)
{
VisitArray(operation.IgnoredArguments, "IgnoredArguments", logElementCount: true);
}
}
public override void VisitVariableDeclaration(IVariableDeclarationOperation operation)
{
var variableCount = operation.Declarators.Length;
LogString($"{nameof(IVariableDeclarationOperation)} ({variableCount} declarators)");
LogCommonPropertiesAndNewLine(operation);
if (!operation.IgnoredDimensions.IsEmpty)
{
VisitArray(operation.IgnoredDimensions, "Ignored Dimensions", true);
}
VisitArray(operation.Declarators, "Declarators", false);
Visit(operation.Initializer, "Initializer");
}
public override void VisitSwitch(ISwitchOperation operation)
{
var caseCountStr = $"{operation.Cases.Length} cases";
var exitLabelStr = $", Exit Label Id: {GetLabelId(operation.ExitLabel)}";
LogString($"{nameof(ISwitchOperation)} ({caseCountStr}{exitLabelStr})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, header: "Switch expression");
LogLocals(operation.Locals);
foreach (ISwitchCaseOperation section in operation.Cases)
{
foreach (ICaseClauseOperation c in section.Clauses)
{
if (c.Label != null)
{
GetLabelId(c.Label);
}
}
}
VisitArray(operation.Cases, "Sections", logElementCount: false);
}
public override void VisitSwitchCase(ISwitchCaseOperation operation)
{
var caseClauseCountStr = $"{operation.Clauses.Length} case clauses";
var statementCountStr = $"{operation.Body.Length} statements";
LogString($"{nameof(ISwitchCaseOperation)} ({caseClauseCountStr}, {statementCountStr})");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Indent();
VisitArray(operation.Clauses, "Clauses", logElementCount: false);
VisitArray(operation.Body, "Body", logElementCount: false);
Unindent();
_ = ((BaseSwitchCaseOperation)operation).Condition;
}
public override void VisitWhileLoop(IWhileLoopOperation operation)
{
LogString(nameof(IWhileLoopOperation));
LogString($" (ConditionIsTop: {operation.ConditionIsTop}, ConditionIsUntil: {operation.ConditionIsUntil})");
LogLoopStatementHeader(operation);
Visit(operation.Condition, "Condition");
Visit(operation.Body, "Body");
Visit(operation.IgnoredCondition, "IgnoredCondition");
}
public override void VisitForLoop(IForLoopOperation operation)
{
LogString(nameof(IForLoopOperation));
LogLoopStatementHeader(operation);
LogLocals(operation.ConditionLocals, header: nameof(operation.ConditionLocals));
Visit(operation.Condition, "Condition");
VisitArray(operation.Before, "Before", logElementCount: false);
VisitArray(operation.AtLoopBottom, "AtLoopBottom", logElementCount: false);
Visit(operation.Body, "Body");
}
public override void VisitForToLoop(IForToLoopOperation operation)
{
LogString(nameof(IForToLoopOperation));
LogLoopStatementHeader(operation, operation.IsChecked);
Visit(operation.LoopControlVariable, "LoopControlVariable");
Visit(operation.InitialValue, "InitialValue");
Visit(operation.LimitValue, "LimitValue");
Visit(operation.StepValue, "StepValue");
Visit(operation.Body, "Body");
VisitArray(operation.NextVariables, "NextVariables", logElementCount: true);
(ILocalSymbol loopObject, ForToLoopOperationUserDefinedInfo userDefinedInfo) = ((BaseForToLoopOperation)operation).Info;
if (userDefinedInfo != null)
{
_ = userDefinedInfo.Addition.Value;
_ = userDefinedInfo.Subtraction.Value;
_ = userDefinedInfo.LessThanOrEqual.Value;
_ = userDefinedInfo.GreaterThanOrEqual.Value;
}
}
private void LogLocals(IEnumerable<ILocalSymbol> locals, string header = "Locals")
{
if (!locals.Any())
{
return;
}
Indent();
LogString($"{header}: ");
Indent();
int localIndex = 1;
foreach (var local in locals)
{
LogSymbol(local, header: $"Local_{localIndex++}");
LogNewLine();
}
Unindent();
Unindent();
}
private void LogLoopStatementHeader(ILoopOperation operation, bool? isChecked = null)
{
Assert.Equal(OperationKind.Loop, operation.Kind);
var propertyStringBuilder = new StringBuilder();
propertyStringBuilder.Append(" (");
propertyStringBuilder.Append($"{nameof(LoopKind)}.{operation.LoopKind}");
if (operation is IForEachLoopOperation { IsAsynchronous: true })
{
propertyStringBuilder.Append($", IsAsynchronous");
}
propertyStringBuilder.Append($", Continue Label Id: {GetLabelId(operation.ContinueLabel)}");
propertyStringBuilder.Append($", Exit Label Id: {GetLabelId(operation.ExitLabel)}");
if (isChecked.GetValueOrDefault())
{
propertyStringBuilder.Append($", Checked");
}
propertyStringBuilder.Append(")");
LogString(propertyStringBuilder.ToString());
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
}
public override void VisitForEachLoop(IForEachLoopOperation operation)
{
LogString(nameof(IForEachLoopOperation));
LogLoopStatementHeader(operation);
Assert.NotNull(operation.LoopControlVariable);
Visit(operation.LoopControlVariable, "LoopControlVariable");
Visit(operation.Collection, "Collection");
Visit(operation.Body, "Body");
VisitArray(operation.NextVariables, "NextVariables", logElementCount: true);
ForEachLoopOperationInfo info = ((BaseForEachLoopOperation)operation).Info;
}
public override void VisitLabeled(ILabeledOperation operation)
{
LogString(nameof(ILabeledOperation));
if (!operation.Label.IsImplicitlyDeclared)
{
LogString($" (Label: {operation.Label.Name})");
}
else
{
LogString($" (Label Id: {GetLabelId(operation.Label)})");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Statement");
}
public override void VisitBranch(IBranchOperation operation)
{
LogString(nameof(IBranchOperation));
var kindStr = $"{nameof(BranchKind)}.{operation.BranchKind}";
// If the label is implicit, or if it has been assigned an id (such as VB Exit Do/While/Switch labels) then print the id, instead of the name.
var labelStr = !(operation.Target.IsImplicitlyDeclared || _labelIdMap.ContainsKey(operation.Target)) ? $", Label: {operation.Target.Name}" : $", Label Id: {GetLabelId(operation.Target)}";
LogString($" ({kindStr}{labelStr})");
LogCommonPropertiesAndNewLine(operation);
base.VisitBranch(operation);
}
public override void VisitEmpty(IEmptyOperation operation)
{
LogString(nameof(IEmptyOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitReturn(IReturnOperation operation)
{
LogString(nameof(IReturnOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ReturnedValue, "ReturnedValue");
}
public override void VisitLock(ILockOperation operation)
{
LogString(nameof(ILockOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LockedValue, "Expression");
Visit(operation.Body, "Body");
}
public override void VisitTry(ITryOperation operation)
{
LogString(nameof(ITryOperation));
if (operation.ExitLabel != null)
{
LogString($" (Exit Label Id: {GetLabelId(operation.ExitLabel)})");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Body, "Body");
VisitArray(operation.Catches, "Catch clauses", logElementCount: true);
Visit(operation.Finally, "Finally");
}
public override void VisitCatchClause(ICatchClauseOperation operation)
{
LogString(nameof(ICatchClauseOperation));
var exceptionTypeStr = operation.ExceptionType != null ? operation.ExceptionType.ToTestDisplayString() : "null";
LogString($" (Exception type: {exceptionTypeStr})");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.ExceptionDeclarationOrExpression, "ExceptionDeclarationOrExpression");
Visit(operation.Filter, "Filter");
Visit(operation.Handler, "Handler");
}
public override void VisitUsing(IUsingOperation operation)
{
LogString(nameof(IUsingOperation));
if (operation.IsAsynchronous)
{
LogString($" (IsAsynchronous)");
}
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Resources, "Resources");
Visit(operation.Body, "Body");
Assert.NotEqual(OperationKind.VariableDeclaration, operation.Resources.Kind);
Assert.NotEqual(OperationKind.VariableDeclarator, operation.Resources.Kind);
}
// https://github.com/dotnet/roslyn/issues/21281
internal override void VisitFixed(IFixedOperation operation)
{
LogString(nameof(IFixedOperation));
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Variables, "Declaration");
Visit(operation.Body, "Body");
}
internal override void VisitAggregateQuery(IAggregateQueryOperation operation)
{
LogString(nameof(IAggregateQueryOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Group, "Group");
Visit(operation.Aggregation, "Aggregation");
}
public override void VisitExpressionStatement(IExpressionStatementOperation operation)
{
LogString(nameof(IExpressionStatementOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
internal override void VisitWithStatement(IWithStatementOperation operation)
{
LogString(nameof(IWithStatementOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
Visit(operation.Body, "Body");
}
public override void VisitStop(IStopOperation operation)
{
LogString(nameof(IStopOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitEnd(IEndOperation operation)
{
LogString(nameof(IEndOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitInvocation(IInvocationOperation operation)
{
LogString(nameof(IInvocationOperation));
var isVirtualStr = operation.IsVirtual ? "virtual " : string.Empty;
var spacing = !operation.IsVirtual && operation.Instance != null ? " " : string.Empty;
LogString($" ({isVirtualStr}{spacing}");
LogSymbol(operation.TargetMethod, header: string.Empty);
LogString(")");
LogCommonPropertiesAndNewLine(operation);
VisitInstance(operation.Instance);
VisitArguments(operation.Arguments);
}
private void VisitArguments(ImmutableArray<IArgumentOperation> arguments)
{
VisitArray(arguments, "Arguments", logElementCount: true);
}
private void VisitDynamicArguments(HasDynamicArgumentsExpression operation)
{
VisitArray(operation.Arguments, "Arguments", logElementCount: true);
VisitArray(operation.ArgumentNames, "ArgumentNames", logElementCount: true);
VisitArray(operation.ArgumentRefKinds, "ArgumentRefKinds", logElementCount: true, logNullForDefault: true);
VerifyGetArgumentNamePublicApi(operation, operation.ArgumentNames);
VerifyGetArgumentRefKindPublicApi(operation, operation.ArgumentRefKinds);
}
private static void VerifyGetArgumentNamePublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<string> argumentNames)
{
var length = operation.Arguments.Length;
if (argumentNames.IsDefaultOrEmpty)
{
for (int i = 0; i < length; i++)
{
Assert.Null(operation.GetArgumentName(i));
}
}
else
{
Assert.Equal(length, argumentNames.Length);
for (var i = 0; i < length; i++)
{
Assert.Equal(argumentNames[i], operation.GetArgumentName(i));
}
}
}
private static void VerifyGetArgumentRefKindPublicApi(HasDynamicArgumentsExpression operation, ImmutableArray<RefKind> argumentRefKinds)
{
var length = operation.Arguments.Length;
if (argumentRefKinds.IsDefault)
{
for (int i = 0; i < length; i++)
{
Assert.Null(operation.GetArgumentRefKind(i));
}
}
else if (argumentRefKinds.IsEmpty)
{
for (int i = 0; i < length; i++)
{
Assert.Equal(RefKind.None, operation.GetArgumentRefKind(i));
}
}
else
{
Assert.Equal(length, argumentRefKinds.Length);
for (var i = 0; i < length; i++)
{
Assert.Equal(argumentRefKinds[i], operation.GetArgumentRefKind(i));
}
}
}
public override void VisitArgument(IArgumentOperation operation)
{
LogString($"{nameof(IArgumentOperation)} (");
LogString($"{nameof(ArgumentKind)}.{operation.ArgumentKind}, ");
LogSymbol(operation.Parameter, header: "Matching Parameter", logDisplayString: false);
LogString(")");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value);
Indent();
LogConversion(operation.InConversion, "InConversion");
LogNewLine();
LogConversion(operation.OutConversion, "OutConversion");
LogNewLine();
Unindent();
}
public override void VisitOmittedArgument(IOmittedArgumentOperation operation)
{
LogString(nameof(IOmittedArgumentOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitArrayElementReference(IArrayElementReferenceOperation operation)
{
LogString(nameof(IArrayElementReferenceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ArrayReference, "Array reference");
VisitArray(operation.Indices, "Indices", logElementCount: true);
}
internal override void VisitPointerIndirectionReference(IPointerIndirectionReferenceOperation operation)
{
LogString(nameof(IPointerIndirectionReferenceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Pointer, "Pointer");
}
public override void VisitLocalReference(ILocalReferenceOperation operation)
{
LogString(nameof(ILocalReferenceOperation));
LogString($": {operation.Local.Name}");
if (operation.IsDeclaration)
{
LogString($" (IsDeclaration: {operation.IsDeclaration})");
}
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitFlowCapture(IFlowCaptureOperation operation)
{
LogString(nameof(IFlowCaptureOperation));
LogString($": {operation.Id.Value}");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
TestOperationVisitor.Singleton.VisitFlowCapture(operation);
}
public override void VisitFlowCaptureReference(IFlowCaptureReferenceOperation operation)
{
LogString(nameof(IFlowCaptureReferenceOperation));
LogString($": {operation.Id.Value}");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitIsNull(IIsNullOperation operation)
{
LogString(nameof(IIsNullOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitCaughtException(ICaughtExceptionOperation operation)
{
LogString(nameof(ICaughtExceptionOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitParameterReference(IParameterReferenceOperation operation)
{
LogString(nameof(IParameterReferenceOperation));
LogString($": {operation.Parameter.Name}");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitInstanceReference(IInstanceReferenceOperation operation)
{
LogString(nameof(IInstanceReferenceOperation));
LogString($" (ReferenceKind: {operation.ReferenceKind})");
LogCommonPropertiesAndNewLine(operation);
if (operation.IsImplicit)
{
if (operation.Parent is IMemberReferenceOperation memberReference && memberReference.Instance == operation)
{
Assert.False(memberReference.Member.IsStatic && !operation.HasErrors(this._compilation));
}
else if (operation.Parent is IInvocationOperation invocation && invocation.Instance == operation)
{
Assert.False(invocation.TargetMethod.IsStatic);
}
}
}
private void VisitMemberReferenceExpressionCommon(IMemberReferenceOperation operation)
{
if (operation.Member.IsStatic)
{
LogString(" (Static)");
}
LogCommonPropertiesAndNewLine(operation);
VisitInstance(operation.Instance);
}
public override void VisitFieldReference(IFieldReferenceOperation operation)
{
LogString(nameof(IFieldReferenceOperation));
LogString($": {operation.Field.ToTestDisplayString()}");
if (operation.IsDeclaration)
{
LogString($" (IsDeclaration: {operation.IsDeclaration})");
}
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitMethodReference(IMethodReferenceOperation operation)
{
LogString(nameof(IMethodReferenceOperation));
LogString($": {operation.Method.ToTestDisplayString()}");
if (operation.IsVirtual)
{
LogString(" (IsVirtual)");
}
Assert.Null(operation.Type);
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitPropertyReference(IPropertyReferenceOperation operation)
{
LogString(nameof(IPropertyReferenceOperation));
LogString($": {operation.Property.ToTestDisplayString()}");
VisitMemberReferenceExpressionCommon(operation);
if (operation.Arguments.Length > 0)
{
VisitArguments(operation.Arguments);
}
}
public override void VisitEventReference(IEventReferenceOperation operation)
{
LogString(nameof(IEventReferenceOperation));
LogString($": {operation.Event.ToTestDisplayString()}");
VisitMemberReferenceExpressionCommon(operation);
}
public override void VisitEventAssignment(IEventAssignmentOperation operation)
{
var kindStr = operation.Adds ? "EventAdd" : "EventRemove";
LogString($"{nameof(IEventAssignmentOperation)} ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
Assert.NotNull(operation.EventReference);
Visit(operation.EventReference, header: "Event Reference");
Visit(operation.HandlerValue, header: "Handler");
}
public override void VisitConditionalAccess(IConditionalAccessOperation operation)
{
LogString(nameof(IConditionalAccessOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, header: nameof(operation.Operation));
Visit(operation.WhenNotNull, header: nameof(operation.WhenNotNull));
Assert.NotNull(operation.Type);
}
public override void VisitConditionalAccessInstance(IConditionalAccessInstanceOperation operation)
{
LogString(nameof(IConditionalAccessInstanceOperation));
LogCommonPropertiesAndNewLine(operation);
}
internal override void VisitPlaceholder(IPlaceholderOperation operation)
{
LogString(nameof(IPlaceholderOperation));
LogCommonPropertiesAndNewLine(operation);
Assert.Equal(PlaceholderKind.AggregationGroup, operation.PlaceholderKind);
}
public override void VisitUnaryOperator(IUnaryOperation operation)
{
LogString(nameof(IUnaryOperation));
var kindStr = $"{nameof(UnaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitBinaryOperator(IBinaryOperation operation)
{
LogString(nameof(IBinaryOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
if (operation.IsCompareText)
{
kindStr += ", CompareText";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
var unaryOperatorMethod = ((BaseBinaryOperation)operation).UnaryOperatorMethod;
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, "Left");
Visit(operation.RightOperand, "Right");
}
public override void VisitTupleBinaryOperator(ITupleBinaryOperation operation)
{
LogString(nameof(ITupleBinaryOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
LogString($" ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, "Left");
Visit(operation.RightOperand, "Right");
}
private void LogHasOperatorMethodExpressionCommon(IMethodSymbol operatorMethodOpt)
{
if (operatorMethodOpt != null)
{
LogSymbol(operatorMethodOpt, header: " (OperatorMethod");
LogString(")");
}
}
public override void VisitConversion(IConversionOperation operation)
{
LogString(nameof(IConversionOperation));
var isTryCast = $"TryCast: {(operation.IsTryCast ? "True" : "False")}";
var isChecked = operation.IsChecked ? "Checked" : "Unchecked";
LogString($" ({isTryCast}, {isChecked})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Indent();
LogConversion(operation.Conversion);
if (((Operation)operation).OwningSemanticModel == null)
{
LogNewLine();
Indent();
LogString($"({((BaseConversionOperation)operation).ConversionConvertible})");
Unindent();
}
Unindent();
LogNewLine();
Visit(operation.Operand, "Operand");
}
public override void VisitConditional(IConditionalOperation operation)
{
LogString(nameof(IConditionalOperation));
if (operation.IsRef)
{
LogString(" (IsRef)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Condition, "Condition");
Visit(operation.WhenTrue, "WhenTrue");
Visit(operation.WhenFalse, "WhenFalse");
}
public override void VisitCoalesce(ICoalesceOperation operation)
{
LogString(nameof(ICoalesceOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, "Expression");
Indent();
LogConversion(operation.ValueConversion, "ValueConversion");
LogNewLine();
Indent();
LogString($"({((BaseCoalesceOperation)operation).ValueConversionConvertible})");
Unindent();
LogNewLine();
Unindent();
Visit(operation.WhenNull, "WhenNull");
}
public override void VisitCoalesceAssignment(ICoalesceAssignmentOperation operation)
{
LogString(nameof(ICoalesceAssignmentOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, nameof(operation.Target));
Visit(operation.Value, nameof(operation.Value));
}
public override void VisitIsType(IIsTypeOperation operation)
{
LogString(nameof(IIsTypeOperation));
if (operation.IsNegated)
{
LogString(" (IsNotExpression)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.ValueOperand, "Operand");
Indent();
LogType(operation.TypeOperand, "IsType");
LogNewLine();
Unindent();
}
public override void VisitSizeOf(ISizeOfOperation operation)
{
LogString(nameof(ISizeOfOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.TypeOperand, "TypeOperand");
LogNewLine();
Unindent();
}
public override void VisitTypeOf(ITypeOfOperation operation)
{
LogString(nameof(ITypeOfOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.TypeOperand, "TypeOperand");
LogNewLine();
Unindent();
}
public override void VisitAnonymousFunction(IAnonymousFunctionOperation operation)
{
LogString(nameof(IAnonymousFunctionOperation));
// For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart.
// That is how symbol display is implemented for C#.
// https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output.
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
base.VisitAnonymousFunction(operation);
}
public override void VisitFlowAnonymousFunction(IFlowAnonymousFunctionOperation operation)
{
LogString(nameof(IFlowAnonymousFunctionOperation));
// For C# this prints "lambda expression", which is not very helpful if we want to tell lambdas apart.
// That is how symbol display is implemented for C#.
// https://github.com/dotnet/roslyn/issues/22559#issuecomment-393667316 tracks improving the output.
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
base.VisitFlowAnonymousFunction(operation);
}
public override void VisitDelegateCreation(IDelegateCreationOperation operation)
{
LogString(nameof(IDelegateCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, nameof(operation.Target));
}
public override void VisitLiteral(ILiteralOperation operation)
{
LogString(nameof(ILiteralOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitAwait(IAwaitOperation operation)
{
LogString(nameof(IAwaitOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
public override void VisitNameOf(INameOfOperation operation)
{
LogString(nameof(INameOfOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Argument);
}
public override void VisitThrow(IThrowOperation operation)
{
LogString(nameof(IThrowOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Exception);
}
public override void VisitAddressOf(IAddressOfOperation operation)
{
LogString(nameof(IAddressOfOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Reference, "Reference");
}
public override void VisitObjectCreation(IObjectCreationOperation operation)
{
LogString(nameof(IObjectCreationOperation));
LogString($" (Constructor: {operation.Constructor?.ToTestDisplayString() ?? "<null>"})");
LogCommonPropertiesAndNewLine(operation);
VisitArguments(operation.Arguments);
Visit(operation.Initializer, "Initializer");
}
public override void VisitAnonymousObjectCreation(IAnonymousObjectCreationOperation operation)
{
LogString(nameof(IAnonymousObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
foreach (var initializer in operation.Initializers)
{
var simpleAssignment = (ISimpleAssignmentOperation)initializer;
var propertyReference = (IPropertyReferenceOperation)simpleAssignment.Target;
Assert.Empty(propertyReference.Arguments);
Assert.Equal(OperationKind.InstanceReference, propertyReference.Instance.Kind);
Assert.Equal(InstanceReferenceKind.ImplicitReceiver, ((IInstanceReferenceOperation)propertyReference.Instance).ReferenceKind);
}
VisitArray(operation.Initializers, "Initializers", logElementCount: true);
}
public override void VisitDynamicObjectCreation(IDynamicObjectCreationOperation operation)
{
LogString(nameof(IDynamicObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
Visit(operation.Initializer, "Initializer");
}
public override void VisitDynamicInvocation(IDynamicInvocationOperation operation)
{
LogString(nameof(IDynamicInvocationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
}
public override void VisitDynamicIndexerAccess(IDynamicIndexerAccessOperation operation)
{
LogString(nameof(IDynamicIndexerAccessOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
VisitDynamicArguments((HasDynamicArgumentsExpression)operation);
}
public override void VisitObjectOrCollectionInitializer(IObjectOrCollectionInitializerOperation operation)
{
LogString(nameof(IObjectOrCollectionInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Initializers, "Initializers", logElementCount: true);
}
public override void VisitMemberInitializer(IMemberInitializerOperation operation)
{
LogString(nameof(IMemberInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.InitializedMember, "InitializedMember");
Visit(operation.Initializer, "Initializer");
}
[Obsolete("ICollectionElementInitializerOperation has been replaced with IInvocationOperation and IDynamicInvocationOperation", error: true)]
public override void VisitCollectionElementInitializer(ICollectionElementInitializerOperation operation)
{
// Kept to ensure that it's never called, as we can't override DefaultVisit in this visitor
throw ExceptionUtilities.Unreachable;
}
public override void VisitFieldInitializer(IFieldInitializerOperation operation)
{
LogString(nameof(IFieldInitializerOperation));
if (operation.InitializedFields.Length <= 1)
{
if (operation.InitializedFields.Length == 1)
{
LogSymbol(operation.InitializedFields[0], header: " (Field");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
}
else
{
LogString($" ({operation.InitializedFields.Length} initialized fields)");
LogCommonPropertiesAndNewLine(operation);
Indent();
int index = 1;
foreach (var local in operation.InitializedFields)
{
LogSymbol(local, header: $"Field_{index++}");
LogNewLine();
}
Unindent();
}
LogLocals(operation.Locals);
base.VisitFieldInitializer(operation);
}
public override void VisitVariableInitializer(IVariableInitializerOperation operation)
{
LogString(nameof(IVariableInitializerOperation));
LogCommonPropertiesAndNewLine(operation);
Assert.Empty(operation.Locals);
base.VisitVariableInitializer(operation);
}
public override void VisitPropertyInitializer(IPropertyInitializerOperation operation)
{
LogString(nameof(IPropertyInitializerOperation));
if (operation.InitializedProperties.Length <= 1)
{
if (operation.InitializedProperties.Length == 1)
{
LogSymbol(operation.InitializedProperties[0], header: " (Property");
LogString(")");
}
LogCommonPropertiesAndNewLine(operation);
}
else
{
LogString($" ({operation.InitializedProperties.Length} initialized properties)");
LogCommonPropertiesAndNewLine(operation);
Indent();
int index = 1;
foreach (var property in operation.InitializedProperties)
{
LogSymbol(property, header: $"Property_{index++}");
LogNewLine();
}
Unindent();
}
LogLocals(operation.Locals);
base.VisitPropertyInitializer(operation);
}
public override void VisitParameterInitializer(IParameterInitializerOperation operation)
{
LogString(nameof(IParameterInitializerOperation));
LogSymbol(operation.Parameter, header: " (Parameter");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
base.VisitParameterInitializer(operation);
}
public override void VisitArrayCreation(IArrayCreationOperation operation)
{
LogString(nameof(IArrayCreationOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.DimensionSizes, "Dimension Sizes", logElementCount: true);
Visit(operation.Initializer, "Initializer");
}
public override void VisitArrayInitializer(IArrayInitializerOperation operation)
{
LogString(nameof(IArrayInitializerOperation));
LogString($" ({operation.ElementValues.Length} elements)");
LogCommonPropertiesAndNewLine(operation);
Assert.Null(operation.Type);
VisitArray(operation.ElementValues, "Element Values", logElementCount: true);
}
public override void VisitSimpleAssignment(ISimpleAssignmentOperation operation)
{
LogString(nameof(ISimpleAssignmentOperation));
if (operation.IsRef)
{
LogString(" (IsRef)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitDeconstructionAssignment(IDeconstructionAssignmentOperation operation)
{
LogString(nameof(IDeconstructionAssignmentOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitDeclarationExpression(IDeclarationExpressionOperation operation)
{
LogString(nameof(IDeclarationExpressionOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Expression);
}
public override void VisitCompoundAssignment(ICompoundAssignmentOperation operation)
{
LogString(nameof(ICompoundAssignmentOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.OperatorKind}";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Indent();
LogConversion(operation.InConversion, "InConversion");
LogNewLine();
LogConversion(operation.OutConversion, "OutConversion");
LogNewLine();
Unindent();
Visit(operation.Target, "Left");
Visit(operation.Value, "Right");
}
public override void VisitIncrementOrDecrement(IIncrementOrDecrementOperation operation)
{
LogString(nameof(IIncrementOrDecrementOperation));
var kindStr = operation.IsPostfix ? "Postfix" : "Prefix";
if (operation.IsLifted)
{
kindStr += ", IsLifted";
}
if (operation.IsChecked)
{
kindStr += ", Checked";
}
LogString($" ({kindStr})");
LogHasOperatorMethodExpressionCommon(operation.OperatorMethod);
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Target, "Target");
}
public override void VisitParenthesized(IParenthesizedOperation operation)
{
LogString(nameof(IParenthesizedOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
}
public override void VisitDynamicMemberReference(IDynamicMemberReferenceOperation operation)
{
LogString(nameof(IDynamicMemberReferenceOperation));
// (Member Name: "quoted name", Containing Type: type)
LogString(" (");
LogConstant((object)operation.MemberName, "Member Name");
LogString(", ");
LogType(operation.ContainingType, "Containing Type");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
VisitArrayCommon(operation.TypeArguments, "Type Arguments", logElementCount: true, logNullForDefault: false, arrayElementVisitor: VisitSymbolArrayElement);
VisitInstance(operation.Instance);
}
public override void VisitDefaultValue(IDefaultValueOperation operation)
{
LogString(nameof(IDefaultValueOperation));
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitTypeParameterObjectCreation(ITypeParameterObjectCreationOperation operation)
{
LogString(nameof(ITypeParameterObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
}
internal override void VisitNoPiaObjectCreation(INoPiaObjectCreationOperation operation)
{
LogString(nameof(INoPiaObjectCreationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Initializer, "Initializer");
}
public override void VisitInvalid(IInvalidOperation operation)
{
LogString(nameof(IInvalidOperation));
LogCommonPropertiesAndNewLine(operation);
VisitChildren(operation);
}
public override void VisitLocalFunction(ILocalFunctionOperation operation)
{
LogString(nameof(ILocalFunctionOperation));
LogSymbol(operation.Symbol, header: " (Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
if (operation.Body != null)
{
if (operation.IgnoredBody != null)
{
Visit(operation.Body, "Body");
Visit(operation.IgnoredBody, "IgnoredBody");
}
else
{
Visit(operation.Body);
}
}
else
{
Assert.Null(operation.IgnoredBody);
}
}
private void LogCaseClauseCommon(ICaseClauseOperation operation)
{
Assert.Equal(OperationKind.CaseClause, operation.Kind);
if (operation.Label != null)
{
LogString($" (Label Id: {GetLabelId(operation.Label)})");
}
var kindStr = $"{nameof(CaseKind)}.{operation.CaseKind}";
LogString($" ({kindStr})");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitSingleValueCaseClause(ISingleValueCaseClauseOperation operation)
{
LogString(nameof(ISingleValueCaseClauseOperation));
LogCaseClauseCommon(operation);
Visit(operation.Value, "Value");
}
public override void VisitRelationalCaseClause(IRelationalCaseClauseOperation operation)
{
LogString(nameof(IRelationalCaseClauseOperation));
var kindStr = $"{nameof(BinaryOperatorKind)}.{operation.Relation}";
LogString($" (Relational operator kind: {kindStr})");
LogCaseClauseCommon(operation);
Visit(operation.Value, "Value");
}
public override void VisitRangeCaseClause(IRangeCaseClauseOperation operation)
{
LogString(nameof(IRangeCaseClauseOperation));
LogCaseClauseCommon(operation);
Visit(operation.MinimumValue, "Min");
Visit(operation.MaximumValue, "Max");
}
public override void VisitDefaultCaseClause(IDefaultCaseClauseOperation operation)
{
LogString(nameof(IDefaultCaseClauseOperation));
LogCaseClauseCommon(operation);
}
public override void VisitTuple(ITupleOperation operation)
{
LogString(nameof(ITupleOperation));
LogCommonPropertiesAndNewLine(operation);
Indent();
LogType(operation.NaturalType, nameof(operation.NaturalType));
LogNewLine();
Unindent();
VisitArray(operation.Elements, "Elements", logElementCount: true);
}
public override void VisitInterpolatedString(IInterpolatedStringOperation operation)
{
LogString(nameof(IInterpolatedStringOperation));
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Parts, "Parts", logElementCount: true);
}
public override void VisitInterpolatedStringText(IInterpolatedStringTextOperation operation)
{
LogString(nameof(IInterpolatedStringTextOperation));
LogCommonPropertiesAndNewLine(operation);
Assert.Equal(OperationKind.Literal, operation.Text.Kind);
Visit(operation.Text, "Text");
}
public override void VisitInterpolation(IInterpolationOperation operation)
{
LogString(nameof(IInterpolationOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Expression, "Expression");
Visit(operation.Alignment, "Alignment");
Visit(operation.FormatString, "FormatString");
if (operation.FormatString != null)
{
Assert.Equal(OperationKind.Literal, operation.FormatString.Kind);
}
}
public override void VisitConstantPattern(IConstantPatternOperation operation)
{
LogString(nameof(IConstantPatternOperation));
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
}
public override void VisitRelationalPattern(IRelationalPatternOperation operation)
{
LogString(nameof(IRelationalPatternOperation));
LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})");
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Value, "Value");
}
public override void VisitNegatedPattern(INegatedPatternOperation operation)
{
LogString(nameof(INegatedPatternOperation));
LogPatternPropertiesAndNewLine(operation);
Visit(operation.Pattern, "Pattern");
}
public override void VisitBinaryPattern(IBinaryPatternOperation operation)
{
LogString(nameof(IBinaryPatternOperation));
LogString($" ({nameof(BinaryOperatorKind)}.{operation.OperatorKind})");
LogPatternPropertiesAndNewLine(operation);
Visit(operation.LeftPattern, "LeftPattern");
Visit(operation.RightPattern, "RightPattern");
}
public override void VisitTypePattern(ITypePatternOperation operation)
{
LogString(nameof(ITypePatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.MatchedType, $", {nameof(operation.MatchedType)}");
LogString(")");
LogNewLine();
}
public override void VisitDeclarationPattern(IDeclarationPatternOperation operation)
{
LogString(nameof(IDeclarationPatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}");
LogConstant((object)operation.MatchesNull, $", {nameof(operation.MatchesNull)}");
LogString(")");
LogNewLine();
}
public override void VisitRecursivePattern(IRecursivePatternOperation operation)
{
LogString(nameof(IRecursivePatternOperation));
LogPatternProperties(operation);
LogSymbol(operation.DeclaredSymbol, $", {nameof(operation.DeclaredSymbol)}");
LogType(operation.MatchedType, $", {nameof(operation.MatchedType)}");
LogSymbol(operation.DeconstructSymbol, $", {nameof(operation.DeconstructSymbol)}");
LogString(")");
LogNewLine();
VisitArray(operation.DeconstructionSubpatterns, $"{nameof(operation.DeconstructionSubpatterns)} ", true, true);
VisitArray(operation.PropertySubpatterns, $"{nameof(operation.PropertySubpatterns)} ", true, true);
}
public override void VisitPropertySubpattern(IPropertySubpatternOperation operation)
{
LogString(nameof(IPropertySubpatternOperation));
LogCommonProperties(operation);
LogNewLine();
Visit(operation.Member, $"{nameof(operation.Member)}");
Visit(operation.Pattern, $"{nameof(operation.Pattern)}");
}
public override void VisitIsPattern(IIsPatternOperation operation)
{
LogString(nameof(IIsPatternOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, $"{nameof(operation.Value)}");
Visit(operation.Pattern, "Pattern");
}
public override void VisitPatternCaseClause(IPatternCaseClauseOperation operation)
{
LogString(nameof(IPatternCaseClauseOperation));
LogCaseClauseCommon(operation);
Assert.Same(((ICaseClauseOperation)operation).Label, operation.Label);
Visit(operation.Pattern, "Pattern");
if (operation.Guard != null)
Visit(operation.Guard, nameof(operation.Guard));
}
public override void VisitTranslatedQuery(ITranslatedQueryOperation operation)
{
LogString(nameof(ITranslatedQueryOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operation, "Expression");
}
public override void VisitRaiseEvent(IRaiseEventOperation operation)
{
LogString(nameof(IRaiseEventOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.EventReference, header: "Event Reference");
VisitArguments(operation.Arguments);
}
public override void VisitConstructorBodyOperation(IConstructorBodyOperation operation)
{
LogString(nameof(IConstructorBodyOperation));
LogCommonPropertiesAndNewLine(operation);
LogLocals(operation.Locals);
Visit(operation.Initializer, "Initializer");
Visit(operation.BlockBody, "BlockBody");
Visit(operation.ExpressionBody, "ExpressionBody");
}
public override void VisitMethodBodyOperation(IMethodBodyOperation operation)
{
LogString(nameof(IMethodBodyOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.BlockBody, "BlockBody");
Visit(operation.ExpressionBody, "ExpressionBody");
}
public override void VisitDiscardOperation(IDiscardOperation operation)
{
LogString(nameof(IDiscardOperation));
LogString(" (");
LogSymbol(operation.DiscardSymbol, "Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitDiscardPattern(IDiscardPatternOperation operation)
{
LogString(nameof(IDiscardPatternOperation));
LogPatternPropertiesAndNewLine(operation);
}
public override void VisitSwitchExpression(ISwitchExpressionOperation operation)
{
LogString($"{nameof(ISwitchExpressionOperation)} ({operation.Arms.Length} arms)");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Value, nameof(operation.Value));
VisitArray(operation.Arms, nameof(operation.Arms), logElementCount: true);
}
public override void VisitSwitchExpressionArm(ISwitchExpressionArmOperation operation)
{
LogString($"{nameof(ISwitchExpressionArmOperation)} ({operation.Locals.Length} locals)");
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Pattern, nameof(operation.Pattern));
if (operation.Guard != null)
Visit(operation.Guard, nameof(operation.Guard));
Visit(operation.Value, nameof(operation.Value));
LogLocals(operation.Locals);
}
public override void VisitStaticLocalInitializationSemaphore(IStaticLocalInitializationSemaphoreOperation operation)
{
LogString(nameof(IStaticLocalInitializationSemaphoreOperation));
LogSymbol(operation.Local, " (Local Symbol");
LogString(")");
LogCommonPropertiesAndNewLine(operation);
}
public override void VisitRangeOperation(IRangeOperation operation)
{
LogString(nameof(IRangeOperation));
if (operation.IsLifted)
{
LogString(" (IsLifted)");
}
LogCommonPropertiesAndNewLine(operation);
Visit(operation.LeftOperand, nameof(operation.LeftOperand));
Visit(operation.RightOperand, nameof(operation.RightOperand));
}
public override void VisitReDim(IReDimOperation operation)
{
LogString(nameof(IReDimOperation));
if (operation.Preserve)
{
LogString(" (Preserve)");
}
LogCommonPropertiesAndNewLine(operation);
VisitArray(operation.Clauses, "Clauses", logElementCount: true);
}
public override void VisitReDimClause(IReDimClauseOperation operation)
{
LogString(nameof(IReDimClauseOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
VisitArray(operation.DimensionSizes, "DimensionSizes", logElementCount: true);
}
public override void VisitWith(IWithOperation operation)
{
LogString(nameof(IWithOperation));
LogCommonPropertiesAndNewLine(operation);
Visit(operation.Operand, "Operand");
Indent();
LogSymbol(operation.CloneMethod, nameof(operation.CloneMethod));
LogNewLine();
Unindent();
Visit(operation.Initializer, "Initializer");
}
#endregion
}
}
| 36.694124 | 199 | 0.604397 | [
"MIT"
] | myblindy/roslyn | src/Test/Utilities/Portable/Compilation/OperationTreeVerifier.cs | 73,060 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities;
#if WINDOWS_UWP && !ENABLE_IL2CPP
using Microsoft.MixedReality.Toolkit.Core.Extensions;
#endif // WINDOWS_UWP && !ENABLE_IL2CPP
using System;
namespace Microsoft.MixedReality.Toolkit.Core.Attributes
{
/// <summary>
/// Constraint that allows selection of classes that implement a specific interface
/// when selecting a <see cref="Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities.SystemType"/> with the Unity inspector.
/// </summary>
public sealed class ImplementsAttribute : SystemTypeAttribute
{
/// <summary>
/// Gets the type of interface that selectable classes must implement.
/// </summary>
public Type InterfaceType { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="ImplementsAttribute"/> class.
/// </summary>
/// <param name="interfaceType">Type of interface that selectable classes must implement.</param>
/// <param name="grouping">Gets or sets grouping of selectable classes. Defaults to <see cref="Microsoft.MixedReality.Toolkit.Core.Definitions.Utilities.TypeGrouping.ByNamespaceFlat"/> unless explicitly specified.</param>
public ImplementsAttribute(Type interfaceType, TypeGrouping grouping) : base(interfaceType, grouping)
{
InterfaceType = interfaceType;
}
/// <inheritdoc />
public override bool IsConstraintSatisfied(Type type)
{
if (base.IsConstraintSatisfied(type))
{
var interfaces = type.GetInterfaces();
for (var i = 0; i < interfaces.Length; i++)
{
if (interfaces[i] == InterfaceType)
{
return true;
}
}
}
return false;
}
}
} | 40.882353 | 229 | 0.634053 | [
"MIT"
] | jdehotin/holotoolkit | Assets/MixedRealityToolkit/Attributes/ImplementsAttribute.cs | 2,087 | C# |
using System.IO;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Serilog;
using Serilog.Events;
namespace CompanyName.ProjectName.DbMigrator
{
class Program
{
static async Task Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
.MinimumLevel.Override("Volo.Abp", LogEventLevel.Warning)
#if DEBUG
.MinimumLevel.Override("CompanyName.ProjectName", LogEventLevel.Debug)
#else
.MinimumLevel.Override("CompanyName.ProjectName", LogEventLevel.Information)
#endif
.Enrich.FromLogContext()
.WriteTo.Async(c => c.File("Logs/logs.txt"))
.WriteTo.Async(c => c.Console())
.CreateLogger();
await CreateHostBuilder(args).RunConsoleAsync();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureLogging((context, logging) => logging.ClearProviders())
.ConfigureServices((hostContext, services) =>
{
services.AddHostedService<DbMigratorHostedService>();
});
}
}
| 34.512195 | 92 | 0.624028 | [
"MIT"
] | shuangbaojun/abp-vnext-pro | aspnet-core/services/src/CompanyName.ProjectName.DbMigrator/Program.cs | 1,415 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BDFramework.Mgr;
namespace BDFramework.UI
{
[Obsolete("please use new uiframe: uflux.")]
public class UIAttribute : ManagerAtrribute
{
public string ResourcePath { get; private set; }
public UIAttribute(int intTag, string resPath):base(intTag)
{
this.ResourcePath = resPath;
}
}
}
| 22.15 | 67 | 0.654628 | [
"Apache-2.0"
] | ZetLiu/BDFramework.Core | Assets/Code/BDFramework/Core/UI(Deprecated)/@hotfix/UIAttribute.cs | 445 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNative.MachineLearning.Inputs
{
/// <summary>
/// Defines an edge within the web service's graph.
/// </summary>
public sealed class GraphEdgeArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The source graph node's identifier.
/// </summary>
[Input("sourceNodeId")]
public Input<string>? SourceNodeId { get; set; }
/// <summary>
/// The identifier of the source node's port that the edge connects from.
/// </summary>
[Input("sourcePortId")]
public Input<string>? SourcePortId { get; set; }
/// <summary>
/// The destination graph node's identifier.
/// </summary>
[Input("targetNodeId")]
public Input<string>? TargetNodeId { get; set; }
/// <summary>
/// The identifier of the destination node's port that the edge connects into.
/// </summary>
[Input("targetPortId")]
public Input<string>? TargetPortId { get; set; }
public GraphEdgeArgs()
{
}
}
}
| 29.404255 | 86 | 0.604197 | [
"Apache-2.0"
] | polivbr/pulumi-azure-native | sdk/dotnet/MachineLearning/Inputs/GraphEdgeArgs.cs | 1,382 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using TheLiquidFire.Notifications;
public class Clickable : MonoBehaviour, IPointerClickHandler {
public const string ClickedNotification = "Clickable.ClickedNotification";
public void OnPointerClick(PointerEventData eventData) {
this.PostNotification (ClickedNotification, eventData);
}
} | 31.384615 | 75 | 0.833333 | [
"MIT"
] | DapperDino/CCG-Single-Player-Learning | Assets/Scripts/Components/Clickable.cs | 410 | C# |
////////////////////////////////////////////////////////////////////////////////
// //
// MIT X11 license, Copyright (c) 2005-2006 by: //
// //
// Authors: //
// Michael Dominic K. <michaldominik@gmail.com> //
// //
// Permission is hereby granted, free of charge, to any person obtaining a //
// copy of this software and associated documentation files (the "Software"), //
// to deal in the Software without restriction, including without limitation //
// the rights to use, copy, modify, merge, publish, distribute, sublicense, //
// and/or sell copies of the Software, and to permit persons to whom the //
// Software is furnished to do so, subject to the following conditions: //
// //
// The above copyright notice and this permission notice shall be included //
// in all copies or substantial portions of the Software. //
// //
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS //
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF //
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN //
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, //
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR //
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE //
// USE OR OTHER DEALINGS IN THE SOFTWARE. //
// //
////////////////////////////////////////////////////////////////////////////////
namespace Diva.Editor.Timeline {
using System;
using Gtk;
using Gdk;
using Diva;
using Gdv;
using Cairo;
public class TrackLinesElement : ViewElement {
// Properties //////////////////////////////////////////////////
public override Rectangle DrawingRect {
get {
Gdk.Rectangle full = modelRoot.Timeline.ViewportRectangle;
return new Gdk.Rectangle (full.Left, full.Top + 16,
full.Width, full.Height - 16);
}
}
// Public methods /////////////////////////////////////////////
/* CONSTRUCTOR */
public TrackLinesElement (Model.Root modelRoot) :
base (modelRoot, ElementLayer.Background)
{
}
public override void Draw (Graphics gr, Rectangle rect)
{
// Draw using a nice ready made
ReadyMade.TimelineRect (gr, rect, DrawingRect);
// Draw the lines
// FIXME: TRACKS!
double y = DrawingRect.Top;
for (int i = 0; i < modelRoot.Tracks.Count; i++) {
if (y >= rect.Y && y <= rect.Y + rect.Height)
// FIXME: I think the cairo-pixel correction causes a 1 px shift here
// henece the rect.X -1 thing that solves #66
Cairo.Draw.Line (gr, rect.X - 1, y, rect.X + rect.Width, y,
Gdv.Color.FromConst (ColorConst.Black), 1.0, true);
y += 31;
}
base.Draw (gr, rect);
}
}
}
| 53.0625 | 110 | 0.390813 | [
"MIT"
] | mdk/diva | src/Diva.Editor.Timeline/Diva.Editor.Timeline.TrackLinesElement.cs | 4,245 | C# |
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;
using NBTExplorer.Model;
using NBTExplorer.Windows;
namespace NBTExplorer.Controllers
{
class ExplorerBarController
{
private ToolStrip _explorerStrip;
private DataNode _rootNode;
private IconRegistry _registry;
private ImageList _iconList;
public ExplorerBarController (ToolStrip toolStrip, IconRegistry registry, ImageList iconList, DataNode rootNode)
{
_explorerStrip = toolStrip;
_registry = registry;
_iconList = iconList;
_rootNode = rootNode;
Initialize();
}
private void Initialize ()
{
_explorerStrip.Items.Clear();
List<DataNode> ancestry = new List<DataNode>();
DataNode node = _rootNode;
while (node != null) {
ancestry.Add(node);
node = node.Parent;
}
ancestry.Reverse();
foreach (DataNode item in ancestry) {
ToolStripSplitButton itemButton = new ToolStripSplitButton(item.NodePathName) {
Tag = item,
};
itemButton.ButtonClick += (s, e) => {
ToolStripSplitButton button = s as ToolStripSplitButton;
if (button != null)
SearchRoot = button.Tag as DataNode;
};
itemButton.DropDown.ImageList = _iconList;
if (_explorerStrip.Items.Count == 0)
itemButton.ImageIndex = _registry.Lookup(item.GetType());
if (!item.IsExpanded)
item.Expand();
foreach (DataNode subItem in item.Nodes) {
if (!subItem.IsContainerType)
continue;
ToolStripMenuItem menuItem = new ToolStripMenuItem(subItem.NodePathName) {
ImageIndex = _registry.Lookup(subItem.GetType()),
Tag = subItem,
};
menuItem.Click += (s, e) => {
ToolStripMenuItem mItem = s as ToolStripMenuItem;
if (mItem != null)
SearchRoot = mItem.Tag as DataNode;
};
if (ancestry.Contains(subItem))
menuItem.Font = new Font(menuItem.Font, FontStyle.Bold);
itemButton.DropDownItems.Add(menuItem);
}
_explorerStrip.Items.Add(itemButton);
}
}
public DataNode SearchRoot
{
get { return _rootNode; }
set
{
if (_rootNode == value)
return;
_rootNode = value;
Initialize();
OnSearchRootChanged();
}
}
public event EventHandler SearchRootChanged;
protected virtual void OnSearchRootChanged ()
{
var ev = SearchRootChanged;
if (ev != null)
ev(this, EventArgs.Empty);
}
}
}
| 30.196262 | 120 | 0.504488 | [
"MIT"
] | 3prm3/NBTExplorer-Reloaded | NBTExplorer/Controllers/ExplorerBarController.cs | 3,233 | C# |
using System;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
using Npgsql;
namespace Marten.Services
{
public class TransactionState : IDisposable
{
private readonly CommandRunnerMode _mode;
private readonly IsolationLevel _isolationLevel;
private readonly int _commandTimeout;
private readonly bool _ownsConnection;
public TransactionState(CommandRunnerMode mode, IsolationLevel isolationLevel, int? commandTimeout, NpgsqlConnection connection, bool ownsConnection, NpgsqlTransaction transaction = null)
{
_mode = mode;
_isolationLevel = isolationLevel;
_ownsConnection = ownsConnection;
Transaction = transaction;
Connection = connection;
_commandTimeout = commandTimeout ?? Connection.CommandTimeout;
}
public TransactionState(IConnectionFactory factory, CommandRunnerMode mode, IsolationLevel isolationLevel, int? commandTimeout, bool ownsConnection)
{
_mode = mode;
_isolationLevel = isolationLevel;
_ownsConnection = ownsConnection;
Connection = factory.Create();
_commandTimeout = commandTimeout ?? Connection.CommandTimeout;
}
public bool IsOpen => Connection.State != ConnectionState.Closed;
public void Open()
{
if (IsOpen)
{
return;
}
Connection.Open();
}
public Task OpenAsync(CancellationToken token)
{
if (IsOpen)
{
return Task.CompletedTask;
}
return Connection.OpenAsync(token);
}
public IMartenSessionLogger Logger { get; set; } = NulloMartenLogger.Flyweight;
public void BeginTransaction()
{
if (Transaction != null || _mode == CommandRunnerMode.External) return;
if (_mode == CommandRunnerMode.Transactional || _mode == CommandRunnerMode.ReadOnly)
{
Transaction = Connection.BeginTransaction(_isolationLevel);
}
if (_mode == CommandRunnerMode.ReadOnly)
{
using (var cmd = new NpgsqlCommand("SET TRANSACTION READ ONLY;"))
{
Apply(cmd);
cmd.ExecuteNonQuery();
}
}
}
public void Apply(NpgsqlCommand cmd)
{
cmd.Connection = Connection;
if (Transaction != null) cmd.Transaction = Transaction;
cmd.CommandTimeout = _commandTimeout;
}
public NpgsqlTransaction Transaction { get; private set; }
public NpgsqlConnection Connection { get; }
public void Commit()
{
if (_mode != CommandRunnerMode.External)
{
Transaction?.Commit();
Transaction?.Dispose();
Transaction = null;
}
if (_ownsConnection)
{
Connection.Close();
}
}
public async Task CommitAsync(CancellationToken token)
{
if (Transaction != null && _mode != CommandRunnerMode.External)
{
await Transaction.CommitAsync(token).ConfigureAwait(false);
Transaction.Dispose();
Transaction = null;
}
if (_ownsConnection)
{
Connection.Close();
}
}
public void Rollback()
{
if (Transaction != null && !Transaction.IsCompleted && _mode != CommandRunnerMode.External)
{
try
{
Transaction?.Rollback();
Transaction?.Dispose();
Transaction = null;
}
catch (Exception e)
{
throw new RollbackException(e);
}
finally
{
Connection.Close();
}
}
}
public async Task RollbackAsync(CancellationToken token)
{
if (Transaction != null && !Transaction.IsCompleted && _mode != CommandRunnerMode.External)
{
try
{
await Transaction.RollbackAsync(token).ConfigureAwait(false);
Transaction.Dispose();
Transaction = null;
}
catch (Exception e)
{
throw new RollbackException(e);
}
finally
{
Connection.Close();
}
}
}
public void Dispose()
{
if (_mode != CommandRunnerMode.External)
{
Transaction?.Dispose();
Transaction = null;
}
if (_ownsConnection)
{
Connection.Close();
Connection.Dispose();
}
}
public NpgsqlCommand CreateCommand()
{
var cmd = Connection.CreateCommand();
if (Transaction != null) cmd.Transaction = Transaction;
return cmd;
}
}
public class RollbackException : Exception
{
public RollbackException(Exception innerException) : base("Failed while trying to rollback an exception", innerException)
{
}
}
} | 29.434555 | 195 | 0.509605 | [
"MIT"
] | jacobpovar/marten | src/Marten/Services/TransactionState.cs | 5,622 | C# |
using System;
using System.Collections.Generic;
using System.IdentityModel.Services;
using System.Linq;
using System.Security.Claims;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace FormsAndBasicAuth
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
protected void Application_PostAuthenticateRequest()
{
if (ClaimsPrincipal.Current.Identity.IsAuthenticated)
{
var transformer = FederatedAuthentication.FederationConfiguration.IdentityConfiguration.ClaimsAuthenticationManager;
var newPrincipal = transformer.Authenticate(string.Empty, ClaimsPrincipal.Current);
Thread.CurrentPrincipal = newPrincipal;
HttpContext.Current.User = newPrincipal;
}
}
}
} | 33.5 | 132 | 0.69936 | [
"BSD-3-Clause"
] | YouthLab/Thinktecture.IdentityModel.45 | Samples/FormsAndBasicAuth/FormsAndBasicAuth/Global.asax.cs | 1,409 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Stencil.Native
{
public enum I18NToken
{
ConnectionTimeOut, //"Connection timed out."
Notification, //"Notification"
VersionNotSupported, //"This version of the app is no longer supported."
AppExpired, //"App Expired"
LatestVersionAndroid, //"Please download the latest version from the Play Store."
LatestVersionIOS, //"Please download the latest version from the App Store.
Login_LoggingIn, //"Logging In.."
Login_MissingUser, //"You must provide your email"
Login_MissingPassword, //"You must provide a password"
Login_SignIn, //"Sign In"
General_NoResultsFor, //"No results found for: {0}"
General_ErrorSearching, //"Error Searching, please try again."
General_Edit, //"Edit"
General_OK, //"OK"
General_Updating, //"Updating.."
General_Remove, //"Remove"
General_Select, //"Select"
General_NoThanks, //"No Thanks"
General_Leave, //"Leave"
General_UnableToLoad, //"Unable to load requested item. Please try again in a few moments."
General_Loading, //"Loading.."
General_Sending, //"Sending.."
General_Cancel, //"Cancel"
General_Update, //"Update"
General_Deleting, //"Deleting.."
General_Upload, //"Upload"
General_Post, //"Post"
General_EmailWatermark, //"email@domain.com"
General_PasswordWatermark, //"Password"
General_WriteCaption, //"Write a caption.."
General_WritePost, //"Write a post.."
General_Send, //"Send"
General_MustProvideText, //"You must provide text"
General_LoadingVideo, //"Loading Video.."
General_LoadingPhoto, //"Loading Photo.."
General_Processing, //"Processing.."
General_UnableToSubmit, //"Unable to process request. Please try again in a few moments."
General_Delete, //"Delete"
ALERT_SAMPLE, //"{0} said: {1}"
}
}
| 38.074074 | 99 | 0.63716 | [
"MIT"
] | DanMasterson1/stencil | Source/Stencil.Native/Stencil.Native/I18NToken.cs | 2,058 | C# |
#pragma warning disable 612, 618
using FoxDb.Interfaces;
using System.Linq;
using System;
using System.Threading.Tasks;
namespace FoxDb
{
public partial class EntityPersister : IEntityPersister
{
public EntityPersister(IDatabase database, ITableConfig table, ITransactionSource transaction = null)
{
this.Database = database;
this.Table = table;
this.Transaction = transaction;
}
public IDatabase Database { get; private set; }
public ITableConfig Table { get; private set; }
public ITransactionSource Transaction { get; private set; }
public EntityAction Add(object item, DatabaseParameterHandler parameters = null)
{
this.OnAdding(item);
var add = this.Database.QueryCache.Add(this.Table);
if (parameters == null)
{
parameters = new ParameterHandlerStrategy(this.Table, item).Handler;
}
var key = this.Database.ExecuteScalar<object>(add, parameters, this.Transaction);
this.OnAdded(key, item);
return EntityAction.Added;
}
public EntityAction Update(object persisted, object updated, DatabaseParameterHandler parameters = null)
{
this.OnUpdating(updated);
var update = default(IDatabaseQuery);
if (!this.GetUpdateQuery(persisted, updated, out update))
{
return EntityAction.None;
}
if (parameters == null)
{
parameters = new ParameterHandlerStrategy(this.Table, updated).Handler;
}
var count = this.Database.Execute(update, parameters, this.Transaction);
if (count != 1)
{
this.OnConcurrencyViolation(updated);
}
else
{
this.OnUpdated(updated);
}
return EntityAction.Updated;
}
public EntityAction Delete(object item, DatabaseParameterHandler parameters = null)
{
var delete = this.Database.QueryCache.Delete(this.Table);
if (parameters == null)
{
parameters = new ParameterHandlerStrategy(this.Table, item).Handler;
}
var count = this.Database.Execute(delete, parameters, this.Transaction);
if (count != 1)
{
this.OnConcurrencyViolation(item);
}
else
{
this.OnDeleted(item);
}
return EntityAction.Deleted;
}
protected virtual void OnAdding(object item)
{
foreach (var column in this.Table.LocalGeneratedColumns)
{
column.Setter(item, ValueGeneratorStrategy.Instance.CreateValue(this.Table, column, item));
}
}
protected virtual void OnAdded(object key, object item)
{
if (key != null && !DBNull.Value.Equals(key))
{
EntityKey.SetKey(this.Table, item, key);
}
}
protected virtual void OnUpdating(object item)
{
//Nothing to do.
}
protected virtual void OnUpdated(object item)
{
foreach (var column in this.Table.ConcurrencyColumns)
{
if (column.Incrementor != null)
{
column.Incrementor(item);
}
}
}
protected virtual void OnDeleted(object item)
{
//Nothing to do.
}
protected virtual void OnConcurrencyViolation(object item)
{
throw new InvalidOperationException(string.Format(
"Failed to update or delete data of type {0} with id {1}.",
this.Table.TableType.Name,
this.Table.PrimaryKey.Getter(item)
));
}
protected virtual bool GetUpdateQuery(object persisted, object updated, out IDatabaseQuery query)
{
var columns = EntityDiffer.Instance.GetColumns(this.Table, persisted, updated);
if (!columns.Any())
{
query = null;
return false;
}
query = this.Database.QueryCache.GetOrAdd(new DatabaseQueryColumnsCacheKey(this.Table, columns, DatabaseQueryCache.UPDATE), () =>
{
var builder = this.Database.QueryFactory.Build();
builder.Update.SetTable(this.Table);
builder.Update.AddColumns(columns.Concat(this.Table.ConcurrencyColumns));
builder.Filter.AddColumns(this.Table.PrimaryKeys);
builder.Filter.AddColumns(this.Table.ConcurrencyColumns);
return builder.Build();
});
return true;
}
}
public partial class EntityPersister
{
public async Task<EntityAction> AddAsync(object item, DatabaseParameterHandler parameters = null)
{
this.OnAdding(item);
var add = this.Database.QueryCache.Add(this.Table);
if (parameters == null)
{
parameters = new ParameterHandlerStrategy(this.Table, item).Handler;
}
var key = await this.Database.ExecuteScalarAsync<object>(add, parameters, this.Transaction).ConfigureAwait(false);
this.OnAdded(key, item);
return EntityAction.Added;
}
public async Task<EntityAction> UpdateAsync(object persisted, object updated, DatabaseParameterHandler parameters = null)
{
this.OnUpdating(updated);
var update = default(IDatabaseQuery);
if (!this.GetUpdateQuery(persisted, updated, out update))
{
return EntityAction.None;
}
if (parameters == null)
{
parameters = new ParameterHandlerStrategy(this.Table, updated).Handler;
}
var count = await this.Database.ExecuteAsync(update, parameters, this.Transaction).ConfigureAwait(false);
if (count != 1)
{
this.OnConcurrencyViolation(updated);
}
else
{
this.OnUpdated(updated);
}
return EntityAction.Updated;
}
public async Task<EntityAction> DeleteAsync(object item, DatabaseParameterHandler parameters = null)
{
var delete = this.Database.QueryCache.Delete(this.Table);
if (parameters == null)
{
parameters = new ParameterHandlerStrategy(this.Table, item).Handler;
}
var count = await this.Database.ExecuteAsync(delete, parameters, this.Transaction).ConfigureAwait(false);
if (count != 1)
{
this.OnConcurrencyViolation(item);
}
else
{
this.OnDeleted(item);
}
return EntityAction.Deleted;
}
}
}
| 35.665049 | 142 | 0.538043 | [
"MIT"
] | Raimusoft/FoxDb | FoxDb.Core/Entity/EntityPersister.cs | 7,349 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
namespace NuGet.Packaging
{
/// <summary>
/// Represents an empty framework folder in NuGet 2.0+ packages.
/// An empty framework folder is represented by a file named "_._".
/// </summary>
internal sealed class EmptyFrameworkFolderFile : PhysicalPackageFile
{
public EmptyFrameworkFolderFile(string directoryPathInPackage) :
base(() => Stream.Null)
{
if (directoryPathInPackage == null)
{
throw new ArgumentNullException(nameof(directoryPathInPackage));
}
TargetPath = System.IO.Path.Combine(directoryPathInPackage, PackagingConstants.PackageEmptyFileName);
}
}
} | 34.423077 | 113 | 0.664804 | [
"Apache-2.0"
] | BdDsl/NuGet.Client | src/NuGet.Core/NuGet.Packaging/PackageCreation/Authoring/EmptyFrameworkFolderFile.cs | 897 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
// Information about this assembly is defined by the following attributes.
// Change them to the values specific to your project.
[assembly: AssemblyTitle("CrudDatastore.Topper Data Access Framework")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("CrudDatastore.Topper")]
[assembly: AssemblyCopyright("Copyright © 2019 Tyrone Roson")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// The assembly version has the format "{Major}.{Minor}.{Build}.{Revision}".
// The form "{Major}.{Minor}.*" will automatically update the build and revision,
// and "{Major}.{Minor}.{Build}.*" will update just the revision.
[assembly: AssemblyVersion("1.0.3.0")]
// The following attributes are used to specify the signing key for the assembly,
// if desired. See the Mono documentation for more information about signing.
//[assembly: AssemblyDelaySign(false)]
//[assembly: AssemblyKeyFile("")]
| 39.222222 | 82 | 0.752597 | [
"MIT"
] | tyronevergil/CrudDatastore.Topper | CrudDatastore.Topper/Properties/AssemblyInfo.cs | 1,062 | C# |
using InDepthSearch.Core.Types;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace InDepthSearch.Core.Services.Interfaces
{
public interface IAppService
{
public string GetVersion();
public string GetCurrentLanguage();
public string GetSearchStatus(SearchStatus ss = SearchStatus.Unknown);
public string GetSearchInfo(SearchInfo si = SearchInfo.Unknown);
public string GetSecondsString();
public void ChangeLanguage();
}
}
| 28 | 78 | 0.732143 | [
"Apache-2.0"
] | radoslawik/InDepthSearch | InDepthSearch.Core/Services/Interfaces/IAppService.cs | 562 | C# |
using System.Collections;
using System.Collections.Generic;
namespace Tests.Rrs.ObjectCompare.Classes
{
class ValueEnumerableClass
{
public IEnumerable<int> EnumerableProperty { get; set; }
}
}
| 19.636364 | 64 | 0.726852 | [
"MIT"
] | rrs/ObjectCompare | src/Tests.Rrs.ObjectCompare/Classes/ValueEnumerableClass.cs | 218 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class ReevaluatePresetEvent : redEvent
{
public ReevaluatePresetEvent(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 21.133333 | 108 | 0.728707 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/ReevaluatePresetEvent.cs | 303 | C# |
using UnityEngine;
public class Hoge149 : MonoBehaviour{
void Start(){
Debug.Log(Hoge149.GetIndex());
}
void Update(){
}
public static int GetIndex(){ return 149; }
public int GetIndex0(){ return 0; }
public int GetIndex1(){ return 1; }
public int GetIndex2(){ return 2; }
public int GetIndex3(){ return 3; }
public int GetIndex4(){ return 4; }
public int GetIndex5(){ return 5; }
public int GetIndex6(){ return 6; }
public int GetIndex7(){ return 7; }
public int GetIndex8(){ return 8; }
public int GetIndex9(){ return 9; }
public int GetIndex10(){ return 10; }
public int GetIndex11(){ return 11; }
public int GetIndex12(){ return 12; }
public int GetIndex13(){ return 13; }
public int GetIndex14(){ return 14; }
public int GetIndex15(){ return 15; }
public int GetIndex16(){ return 16; }
public int GetIndex17(){ return 17; }
public int GetIndex18(){ return 18; }
public int GetIndex19(){ return 19; }
public int GetIndex20(){ return 20; }
public int GetIndex21(){ return 21; }
public int GetIndex22(){ return 22; }
public int GetIndex23(){ return 23; }
public int GetIndex24(){ return 24; }
public int GetIndex25(){ return 25; }
public int GetIndex26(){ return 26; }
public int GetIndex27(){ return 27; }
public int GetIndex28(){ return 28; }
public int GetIndex29(){ return 29; }
public int GetIndex30(){ return 30; }
public int GetIndex31(){ return 31; }
public int GetIndex32(){ return 32; }
public int GetIndex33(){ return 33; }
public int GetIndex34(){ return 34; }
public int GetIndex35(){ return 35; }
public int GetIndex36(){ return 36; }
public int GetIndex37(){ return 37; }
public int GetIndex38(){ return 38; }
public int GetIndex39(){ return 39; }
public int GetIndex40(){ return 40; }
public int GetIndex41(){ return 41; }
public int GetIndex42(){ return 42; }
public int GetIndex43(){ return 43; }
public int GetIndex44(){ return 44; }
public int GetIndex45(){ return 45; }
public int GetIndex46(){ return 46; }
public int GetIndex47(){ return 47; }
public int GetIndex48(){ return 48; }
public int GetIndex49(){ return 49; }
public int GetIndex50(){ return 50; }
public int GetIndex51(){ return 51; }
public int GetIndex52(){ return 52; }
public int GetIndex53(){ return 53; }
public int GetIndex54(){ return 54; }
public int GetIndex55(){ return 55; }
public int GetIndex56(){ return 56; }
public int GetIndex57(){ return 57; }
public int GetIndex58(){ return 58; }
public int GetIndex59(){ return 59; }
public int GetIndex60(){ return 60; }
public int GetIndex61(){ return 61; }
public int GetIndex62(){ return 62; }
public int GetIndex63(){ return 63; }
public int GetIndex64(){ return 64; }
public int GetIndex65(){ return 65; }
public int GetIndex66(){ return 66; }
public int GetIndex67(){ return 67; }
public int GetIndex68(){ return 68; }
public int GetIndex69(){ return 69; }
public int GetIndex70(){ return 70; }
public int GetIndex71(){ return 71; }
public int GetIndex72(){ return 72; }
public int GetIndex73(){ return 73; }
public int GetIndex74(){ return 74; }
public int GetIndex75(){ return 75; }
public int GetIndex76(){ return 76; }
public int GetIndex77(){ return 77; }
public int GetIndex78(){ return 78; }
public int GetIndex79(){ return 79; }
public int GetIndex80(){ return 80; }
public int GetIndex81(){ return 81; }
public int GetIndex82(){ return 82; }
public int GetIndex83(){ return 83; }
public int GetIndex84(){ return 84; }
public int GetIndex85(){ return 85; }
public int GetIndex86(){ return 86; }
public int GetIndex87(){ return 87; }
public int GetIndex88(){ return 88; }
public int GetIndex89(){ return 89; }
public int GetIndex90(){ return 90; }
public int GetIndex91(){ return 91; }
public int GetIndex92(){ return 92; }
public int GetIndex93(){ return 93; }
public int GetIndex94(){ return 94; }
public int GetIndex95(){ return 95; }
public int GetIndex96(){ return 96; }
public int GetIndex97(){ return 97; }
public int GetIndex98(){ return 98; }
public int GetIndex99(){ return 99; }
public int GetIndex100(){ return 100; }
public int GetIndex101(){ return 101; }
public int GetIndex102(){ return 102; }
public int GetIndex103(){ return 103; }
public int GetIndex104(){ return 104; }
public int GetIndex105(){ return 105; }
public int GetIndex106(){ return 106; }
public int GetIndex107(){ return 107; }
public int GetIndex108(){ return 108; }
public int GetIndex109(){ return 109; }
public int GetIndex110(){ return 110; }
public int GetIndex111(){ return 111; }
public int GetIndex112(){ return 112; }
public int GetIndex113(){ return 113; }
public int GetIndex114(){ return 114; }
public int GetIndex115(){ return 115; }
public int GetIndex116(){ return 116; }
public int GetIndex117(){ return 117; }
public int GetIndex118(){ return 118; }
public int GetIndex119(){ return 119; }
public int GetIndex120(){ return 120; }
public int GetIndex121(){ return 121; }
public int GetIndex122(){ return 122; }
public int GetIndex123(){ return 123; }
public int GetIndex124(){ return 124; }
public int GetIndex125(){ return 125; }
public int GetIndex126(){ return 126; }
public int GetIndex127(){ return 127; }
public int GetIndex128(){ return 128; }
public int GetIndex129(){ return 129; }
public int GetIndex130(){ return 130; }
public int GetIndex131(){ return 131; }
public int GetIndex132(){ return 132; }
public int GetIndex133(){ return 133; }
public int GetIndex134(){ return 134; }
public int GetIndex135(){ return 135; }
public int GetIndex136(){ return 136; }
public int GetIndex137(){ return 137; }
public int GetIndex138(){ return 138; }
public int GetIndex139(){ return 139; }
public int GetIndex140(){ return 140; }
public int GetIndex141(){ return 141; }
public int GetIndex142(){ return 142; }
public int GetIndex143(){ return 143; }
public int GetIndex144(){ return 144; }
public int GetIndex145(){ return 145; }
public int GetIndex146(){ return 146; }
public int GetIndex147(){ return 147; }
public int GetIndex148(){ return 148; }
public int GetIndex149(){ return 149; }
public int GetIndex150(){ return 150; }
public int GetIndex151(){ return 151; }
public int GetIndex152(){ return 152; }
public int GetIndex153(){ return 153; }
public int GetIndex154(){ return 154; }
public int GetIndex155(){ return 155; }
public int GetIndex156(){ return 156; }
public int GetIndex157(){ return 157; }
public int GetIndex158(){ return 158; }
public int GetIndex159(){ return 159; }
public int GetIndex160(){ return 160; }
public int GetIndex161(){ return 161; }
public int GetIndex162(){ return 162; }
public int GetIndex163(){ return 163; }
public int GetIndex164(){ return 164; }
public int GetIndex165(){ return 165; }
public int GetIndex166(){ return 166; }
public int GetIndex167(){ return 167; }
public int GetIndex168(){ return 168; }
public int GetIndex169(){ return 169; }
public int GetIndex170(){ return 170; }
public int GetIndex171(){ return 171; }
public int GetIndex172(){ return 172; }
public int GetIndex173(){ return 173; }
public int GetIndex174(){ return 174; }
public int GetIndex175(){ return 175; }
public int GetIndex176(){ return 176; }
public int GetIndex177(){ return 177; }
public int GetIndex178(){ return 178; }
public int GetIndex179(){ return 179; }
public int GetIndex180(){ return 180; }
public int GetIndex181(){ return 181; }
public int GetIndex182(){ return 182; }
public int GetIndex183(){ return 183; }
public int GetIndex184(){ return 184; }
public int GetIndex185(){ return 185; }
public int GetIndex186(){ return 186; }
public int GetIndex187(){ return 187; }
public int GetIndex188(){ return 188; }
public int GetIndex189(){ return 189; }
public int GetIndex190(){ return 190; }
public int GetIndex191(){ return 191; }
public int GetIndex192(){ return 192; }
public int GetIndex193(){ return 193; }
public int GetIndex194(){ return 194; }
public int GetIndex195(){ return 195; }
public int GetIndex196(){ return 196; }
public int GetIndex197(){ return 197; }
public int GetIndex198(){ return 198; }
public int GetIndex199(){ return 199; }
public int GetIndex200(){ return 200; }
public int GetIndex201(){ return 201; }
public int GetIndex202(){ return 202; }
public int GetIndex203(){ return 203; }
public int GetIndex204(){ return 204; }
public int GetIndex205(){ return 205; }
public int GetIndex206(){ return 206; }
public int GetIndex207(){ return 207; }
public int GetIndex208(){ return 208; }
public int GetIndex209(){ return 209; }
public int GetIndex210(){ return 210; }
public int GetIndex211(){ return 211; }
public int GetIndex212(){ return 212; }
public int GetIndex213(){ return 213; }
public int GetIndex214(){ return 214; }
public int GetIndex215(){ return 215; }
public int GetIndex216(){ return 216; }
public int GetIndex217(){ return 217; }
public int GetIndex218(){ return 218; }
public int GetIndex219(){ return 219; }
public int GetIndex220(){ return 220; }
public int GetIndex221(){ return 221; }
public int GetIndex222(){ return 222; }
public int GetIndex223(){ return 223; }
public int GetIndex224(){ return 224; }
public int GetIndex225(){ return 225; }
public int GetIndex226(){ return 226; }
public int GetIndex227(){ return 227; }
public int GetIndex228(){ return 228; }
public int GetIndex229(){ return 229; }
public int GetIndex230(){ return 230; }
public int GetIndex231(){ return 231; }
public int GetIndex232(){ return 232; }
public int GetIndex233(){ return 233; }
public int GetIndex234(){ return 234; }
public int GetIndex235(){ return 235; }
public int GetIndex236(){ return 236; }
public int GetIndex237(){ return 237; }
public int GetIndex238(){ return 238; }
public int GetIndex239(){ return 239; }
public int GetIndex240(){ return 240; }
public int GetIndex241(){ return 241; }
public int GetIndex242(){ return 242; }
public int GetIndex243(){ return 243; }
public int GetIndex244(){ return 244; }
public int GetIndex245(){ return 245; }
public int GetIndex246(){ return 246; }
public int GetIndex247(){ return 247; }
public int GetIndex248(){ return 248; }
public int GetIndex249(){ return 249; }
public int GetIndex250(){ return 250; }
public int GetIndex251(){ return 251; }
public int GetIndex252(){ return 252; }
public int GetIndex253(){ return 253; }
public int GetIndex254(){ return 254; }
public int GetIndex255(){ return 255; }
public int GetIndex256(){ return 256; }
public int GetIndex257(){ return 257; }
public int GetIndex258(){ return 258; }
public int GetIndex259(){ return 259; }
public int GetIndex260(){ return 260; }
public int GetIndex261(){ return 261; }
public int GetIndex262(){ return 262; }
public int GetIndex263(){ return 263; }
public int GetIndex264(){ return 264; }
public int GetIndex265(){ return 265; }
public int GetIndex266(){ return 266; }
public int GetIndex267(){ return 267; }
public int GetIndex268(){ return 268; }
public int GetIndex269(){ return 269; }
public int GetIndex270(){ return 270; }
public int GetIndex271(){ return 271; }
public int GetIndex272(){ return 272; }
public int GetIndex273(){ return 273; }
public int GetIndex274(){ return 274; }
public int GetIndex275(){ return 275; }
public int GetIndex276(){ return 276; }
public int GetIndex277(){ return 277; }
public int GetIndex278(){ return 278; }
public int GetIndex279(){ return 279; }
public int GetIndex280(){ return 280; }
public int GetIndex281(){ return 281; }
public int GetIndex282(){ return 282; }
public int GetIndex283(){ return 283; }
public int GetIndex284(){ return 284; }
public int GetIndex285(){ return 285; }
public int GetIndex286(){ return 286; }
public int GetIndex287(){ return 287; }
public int GetIndex288(){ return 288; }
public int GetIndex289(){ return 289; }
public int GetIndex290(){ return 290; }
public int GetIndex291(){ return 291; }
public int GetIndex292(){ return 292; }
public int GetIndex293(){ return 293; }
public int GetIndex294(){ return 294; }
public int GetIndex295(){ return 295; }
public int GetIndex296(){ return 296; }
public int GetIndex297(){ return 297; }
public int GetIndex298(){ return 298; }
public int GetIndex299(){ return 299; }
public int GetIndex300(){ return 300; }
public int GetIndex301(){ return 301; }
public int GetIndex302(){ return 302; }
public int GetIndex303(){ return 303; }
public int GetIndex304(){ return 304; }
public int GetIndex305(){ return 305; }
public int GetIndex306(){ return 306; }
public int GetIndex307(){ return 307; }
public int GetIndex308(){ return 308; }
public int GetIndex309(){ return 309; }
public int GetIndex310(){ return 310; }
public int GetIndex311(){ return 311; }
public int GetIndex312(){ return 312; }
public int GetIndex313(){ return 313; }
public int GetIndex314(){ return 314; }
public int GetIndex315(){ return 315; }
public int GetIndex316(){ return 316; }
public int GetIndex317(){ return 317; }
public int GetIndex318(){ return 318; }
public int GetIndex319(){ return 319; }
public int GetIndex320(){ return 320; }
public int GetIndex321(){ return 321; }
public int GetIndex322(){ return 322; }
public int GetIndex323(){ return 323; }
public int GetIndex324(){ return 324; }
public int GetIndex325(){ return 325; }
public int GetIndex326(){ return 326; }
public int GetIndex327(){ return 327; }
public int GetIndex328(){ return 328; }
public int GetIndex329(){ return 329; }
public int GetIndex330(){ return 330; }
public int GetIndex331(){ return 331; }
public int GetIndex332(){ return 332; }
public int GetIndex333(){ return 333; }
public int GetIndex334(){ return 334; }
public int GetIndex335(){ return 335; }
public int GetIndex336(){ return 336; }
public int GetIndex337(){ return 337; }
public int GetIndex338(){ return 338; }
public int GetIndex339(){ return 339; }
public int GetIndex340(){ return 340; }
public int GetIndex341(){ return 341; }
public int GetIndex342(){ return 342; }
public int GetIndex343(){ return 343; }
public int GetIndex344(){ return 344; }
public int GetIndex345(){ return 345; }
public int GetIndex346(){ return 346; }
public int GetIndex347(){ return 347; }
public int GetIndex348(){ return 348; }
public int GetIndex349(){ return 349; }
public int GetIndex350(){ return 350; }
public int GetIndex351(){ return 351; }
public int GetIndex352(){ return 352; }
public int GetIndex353(){ return 353; }
public int GetIndex354(){ return 354; }
public int GetIndex355(){ return 355; }
public int GetIndex356(){ return 356; }
public int GetIndex357(){ return 357; }
public int GetIndex358(){ return 358; }
public int GetIndex359(){ return 359; }
public int GetIndex360(){ return 360; }
public int GetIndex361(){ return 361; }
public int GetIndex362(){ return 362; }
public int GetIndex363(){ return 363; }
public int GetIndex364(){ return 364; }
public int GetIndex365(){ return 365; }
public int GetIndex366(){ return 366; }
public int GetIndex367(){ return 367; }
public int GetIndex368(){ return 368; }
public int GetIndex369(){ return 369; }
public int GetIndex370(){ return 370; }
public int GetIndex371(){ return 371; }
public int GetIndex372(){ return 372; }
public int GetIndex373(){ return 373; }
public int GetIndex374(){ return 374; }
public int GetIndex375(){ return 375; }
public int GetIndex376(){ return 376; }
public int GetIndex377(){ return 377; }
public int GetIndex378(){ return 378; }
public int GetIndex379(){ return 379; }
public int GetIndex380(){ return 380; }
public int GetIndex381(){ return 381; }
public int GetIndex382(){ return 382; }
public int GetIndex383(){ return 383; }
public int GetIndex384(){ return 384; }
public int GetIndex385(){ return 385; }
public int GetIndex386(){ return 386; }
public int GetIndex387(){ return 387; }
public int GetIndex388(){ return 388; }
public int GetIndex389(){ return 389; }
public int GetIndex390(){ return 390; }
public int GetIndex391(){ return 391; }
public int GetIndex392(){ return 392; }
public int GetIndex393(){ return 393; }
public int GetIndex394(){ return 394; }
public int GetIndex395(){ return 395; }
public int GetIndex396(){ return 396; }
public int GetIndex397(){ return 397; }
public int GetIndex398(){ return 398; }
public int GetIndex399(){ return 399; }
public int GetIndex400(){ return 400; }
public int GetIndex401(){ return 401; }
public int GetIndex402(){ return 402; }
public int GetIndex403(){ return 403; }
public int GetIndex404(){ return 404; }
public int GetIndex405(){ return 405; }
public int GetIndex406(){ return 406; }
public int GetIndex407(){ return 407; }
public int GetIndex408(){ return 408; }
public int GetIndex409(){ return 409; }
public int GetIndex410(){ return 410; }
public int GetIndex411(){ return 411; }
public int GetIndex412(){ return 412; }
public int GetIndex413(){ return 413; }
public int GetIndex414(){ return 414; }
public int GetIndex415(){ return 415; }
public int GetIndex416(){ return 416; }
public int GetIndex417(){ return 417; }
public int GetIndex418(){ return 418; }
public int GetIndex419(){ return 419; }
public int GetIndex420(){ return 420; }
public int GetIndex421(){ return 421; }
public int GetIndex422(){ return 422; }
public int GetIndex423(){ return 423; }
public int GetIndex424(){ return 424; }
public int GetIndex425(){ return 425; }
public int GetIndex426(){ return 426; }
public int GetIndex427(){ return 427; }
public int GetIndex428(){ return 428; }
public int GetIndex429(){ return 429; }
public int GetIndex430(){ return 430; }
public int GetIndex431(){ return 431; }
public int GetIndex432(){ return 432; }
public int GetIndex433(){ return 433; }
public int GetIndex434(){ return 434; }
public int GetIndex435(){ return 435; }
public int GetIndex436(){ return 436; }
public int GetIndex437(){ return 437; }
public int GetIndex438(){ return 438; }
public int GetIndex439(){ return 439; }
public int GetIndex440(){ return 440; }
public int GetIndex441(){ return 441; }
public int GetIndex442(){ return 442; }
public int GetIndex443(){ return 443; }
public int GetIndex444(){ return 444; }
public int GetIndex445(){ return 445; }
public int GetIndex446(){ return 446; }
public int GetIndex447(){ return 447; }
public int GetIndex448(){ return 448; }
public int GetIndex449(){ return 449; }
public int GetIndex450(){ return 450; }
public int GetIndex451(){ return 451; }
public int GetIndex452(){ return 452; }
public int GetIndex453(){ return 453; }
public int GetIndex454(){ return 454; }
public int GetIndex455(){ return 455; }
public int GetIndex456(){ return 456; }
public int GetIndex457(){ return 457; }
public int GetIndex458(){ return 458; }
public int GetIndex459(){ return 459; }
public int GetIndex460(){ return 460; }
public int GetIndex461(){ return 461; }
public int GetIndex462(){ return 462; }
public int GetIndex463(){ return 463; }
public int GetIndex464(){ return 464; }
public int GetIndex465(){ return 465; }
public int GetIndex466(){ return 466; }
public int GetIndex467(){ return 467; }
public int GetIndex468(){ return 468; }
public int GetIndex469(){ return 469; }
public int GetIndex470(){ return 470; }
public int GetIndex471(){ return 471; }
public int GetIndex472(){ return 472; }
public int GetIndex473(){ return 473; }
public int GetIndex474(){ return 474; }
public int GetIndex475(){ return 475; }
public int GetIndex476(){ return 476; }
public int GetIndex477(){ return 477; }
public int GetIndex478(){ return 478; }
public int GetIndex479(){ return 479; }
public int GetIndex480(){ return 480; }
public int GetIndex481(){ return 481; }
public int GetIndex482(){ return 482; }
public int GetIndex483(){ return 483; }
public int GetIndex484(){ return 484; }
public int GetIndex485(){ return 485; }
public int GetIndex486(){ return 486; }
public int GetIndex487(){ return 487; }
public int GetIndex488(){ return 488; }
public int GetIndex489(){ return 489; }
public int GetIndex490(){ return 490; }
public int GetIndex491(){ return 491; }
public int GetIndex492(){ return 492; }
public int GetIndex493(){ return 493; }
public int GetIndex494(){ return 494; }
public int GetIndex495(){ return 495; }
public int GetIndex496(){ return 496; }
public int GetIndex497(){ return 497; }
public int GetIndex498(){ return 498; }
public int GetIndex499(){ return 499; }
public int GetIndex500(){ return 500; }
public int GetIndex501(){ return 501; }
public int GetIndex502(){ return 502; }
public int GetIndex503(){ return 503; }
public int GetIndex504(){ return 504; }
public int GetIndex505(){ return 505; }
public int GetIndex506(){ return 506; }
public int GetIndex507(){ return 507; }
public int GetIndex508(){ return 508; }
public int GetIndex509(){ return 509; }
public int GetIndex510(){ return 510; }
public int GetIndex511(){ return 511; }
public int GetIndex512(){ return 512; }
public int GetIndex513(){ return 513; }
public int GetIndex514(){ return 514; }
public int GetIndex515(){ return 515; }
public int GetIndex516(){ return 516; }
public int GetIndex517(){ return 517; }
public int GetIndex518(){ return 518; }
public int GetIndex519(){ return 519; }
public int GetIndex520(){ return 520; }
public int GetIndex521(){ return 521; }
public int GetIndex522(){ return 522; }
public int GetIndex523(){ return 523; }
public int GetIndex524(){ return 524; }
public int GetIndex525(){ return 525; }
public int GetIndex526(){ return 526; }
public int GetIndex527(){ return 527; }
public int GetIndex528(){ return 528; }
public int GetIndex529(){ return 529; }
public int GetIndex530(){ return 530; }
public int GetIndex531(){ return 531; }
public int GetIndex532(){ return 532; }
public int GetIndex533(){ return 533; }
public int GetIndex534(){ return 534; }
public int GetIndex535(){ return 535; }
public int GetIndex536(){ return 536; }
public int GetIndex537(){ return 537; }
public int GetIndex538(){ return 538; }
public int GetIndex539(){ return 539; }
public int GetIndex540(){ return 540; }
public int GetIndex541(){ return 541; }
public int GetIndex542(){ return 542; }
public int GetIndex543(){ return 543; }
public int GetIndex544(){ return 544; }
public int GetIndex545(){ return 545; }
public int GetIndex546(){ return 546; }
public int GetIndex547(){ return 547; }
public int GetIndex548(){ return 548; }
public int GetIndex549(){ return 549; }
public int GetIndex550(){ return 550; }
public int GetIndex551(){ return 551; }
public int GetIndex552(){ return 552; }
public int GetIndex553(){ return 553; }
public int GetIndex554(){ return 554; }
public int GetIndex555(){ return 555; }
public int GetIndex556(){ return 556; }
public int GetIndex557(){ return 557; }
public int GetIndex558(){ return 558; }
public int GetIndex559(){ return 559; }
public int GetIndex560(){ return 560; }
public int GetIndex561(){ return 561; }
public int GetIndex562(){ return 562; }
public int GetIndex563(){ return 563; }
public int GetIndex564(){ return 564; }
public int GetIndex565(){ return 565; }
public int GetIndex566(){ return 566; }
public int GetIndex567(){ return 567; }
public int GetIndex568(){ return 568; }
public int GetIndex569(){ return 569; }
public int GetIndex570(){ return 570; }
public int GetIndex571(){ return 571; }
public int GetIndex572(){ return 572; }
public int GetIndex573(){ return 573; }
public int GetIndex574(){ return 574; }
public int GetIndex575(){ return 575; }
public int GetIndex576(){ return 576; }
public int GetIndex577(){ return 577; }
public int GetIndex578(){ return 578; }
public int GetIndex579(){ return 579; }
public int GetIndex580(){ return 580; }
public int GetIndex581(){ return 581; }
public int GetIndex582(){ return 582; }
public int GetIndex583(){ return 583; }
public int GetIndex584(){ return 584; }
public int GetIndex585(){ return 585; }
public int GetIndex586(){ return 586; }
public int GetIndex587(){ return 587; }
public int GetIndex588(){ return 588; }
public int GetIndex589(){ return 589; }
public int GetIndex590(){ return 590; }
public int GetIndex591(){ return 591; }
public int GetIndex592(){ return 592; }
public int GetIndex593(){ return 593; }
public int GetIndex594(){ return 594; }
public int GetIndex595(){ return 595; }
public int GetIndex596(){ return 596; }
public int GetIndex597(){ return 597; }
public int GetIndex598(){ return 598; }
public int GetIndex599(){ return 599; }
public int GetIndex600(){ return 600; }
public int GetIndex601(){ return 601; }
public int GetIndex602(){ return 602; }
public int GetIndex603(){ return 603; }
public int GetIndex604(){ return 604; }
public int GetIndex605(){ return 605; }
public int GetIndex606(){ return 606; }
public int GetIndex607(){ return 607; }
public int GetIndex608(){ return 608; }
public int GetIndex609(){ return 609; }
public int GetIndex610(){ return 610; }
public int GetIndex611(){ return 611; }
public int GetIndex612(){ return 612; }
public int GetIndex613(){ return 613; }
public int GetIndex614(){ return 614; }
public int GetIndex615(){ return 615; }
public int GetIndex616(){ return 616; }
public int GetIndex617(){ return 617; }
public int GetIndex618(){ return 618; }
public int GetIndex619(){ return 619; }
public int GetIndex620(){ return 620; }
public int GetIndex621(){ return 621; }
public int GetIndex622(){ return 622; }
public int GetIndex623(){ return 623; }
public int GetIndex624(){ return 624; }
public int GetIndex625(){ return 625; }
public int GetIndex626(){ return 626; }
public int GetIndex627(){ return 627; }
public int GetIndex628(){ return 628; }
public int GetIndex629(){ return 629; }
public int GetIndex630(){ return 630; }
public int GetIndex631(){ return 631; }
public int GetIndex632(){ return 632; }
public int GetIndex633(){ return 633; }
public int GetIndex634(){ return 634; }
public int GetIndex635(){ return 635; }
public int GetIndex636(){ return 636; }
public int GetIndex637(){ return 637; }
public int GetIndex638(){ return 638; }
public int GetIndex639(){ return 639; }
public int GetIndex640(){ return 640; }
public int GetIndex641(){ return 641; }
public int GetIndex642(){ return 642; }
public int GetIndex643(){ return 643; }
public int GetIndex644(){ return 644; }
public int GetIndex645(){ return 645; }
public int GetIndex646(){ return 646; }
public int GetIndex647(){ return 647; }
public int GetIndex648(){ return 648; }
public int GetIndex649(){ return 649; }
public int GetIndex650(){ return 650; }
public int GetIndex651(){ return 651; }
public int GetIndex652(){ return 652; }
public int GetIndex653(){ return 653; }
public int GetIndex654(){ return 654; }
public int GetIndex655(){ return 655; }
public int GetIndex656(){ return 656; }
public int GetIndex657(){ return 657; }
public int GetIndex658(){ return 658; }
public int GetIndex659(){ return 659; }
public int GetIndex660(){ return 660; }
public int GetIndex661(){ return 661; }
public int GetIndex662(){ return 662; }
public int GetIndex663(){ return 663; }
public int GetIndex664(){ return 664; }
public int GetIndex665(){ return 665; }
public int GetIndex666(){ return 666; }
public int GetIndex667(){ return 667; }
public int GetIndex668(){ return 668; }
public int GetIndex669(){ return 669; }
public int GetIndex670(){ return 670; }
public int GetIndex671(){ return 671; }
public int GetIndex672(){ return 672; }
public int GetIndex673(){ return 673; }
public int GetIndex674(){ return 674; }
public int GetIndex675(){ return 675; }
public int GetIndex676(){ return 676; }
public int GetIndex677(){ return 677; }
public int GetIndex678(){ return 678; }
public int GetIndex679(){ return 679; }
public int GetIndex680(){ return 680; }
public int GetIndex681(){ return 681; }
public int GetIndex682(){ return 682; }
public int GetIndex683(){ return 683; }
public int GetIndex684(){ return 684; }
public int GetIndex685(){ return 685; }
public int GetIndex686(){ return 686; }
public int GetIndex687(){ return 687; }
public int GetIndex688(){ return 688; }
public int GetIndex689(){ return 689; }
public int GetIndex690(){ return 690; }
public int GetIndex691(){ return 691; }
public int GetIndex692(){ return 692; }
public int GetIndex693(){ return 693; }
public int GetIndex694(){ return 694; }
public int GetIndex695(){ return 695; }
public int GetIndex696(){ return 696; }
public int GetIndex697(){ return 697; }
public int GetIndex698(){ return 698; }
public int GetIndex699(){ return 699; }
public int GetIndex700(){ return 700; }
public int GetIndex701(){ return 701; }
public int GetIndex702(){ return 702; }
public int GetIndex703(){ return 703; }
public int GetIndex704(){ return 704; }
public int GetIndex705(){ return 705; }
public int GetIndex706(){ return 706; }
public int GetIndex707(){ return 707; }
public int GetIndex708(){ return 708; }
public int GetIndex709(){ return 709; }
public int GetIndex710(){ return 710; }
public int GetIndex711(){ return 711; }
public int GetIndex712(){ return 712; }
public int GetIndex713(){ return 713; }
public int GetIndex714(){ return 714; }
public int GetIndex715(){ return 715; }
public int GetIndex716(){ return 716; }
public int GetIndex717(){ return 717; }
public int GetIndex718(){ return 718; }
public int GetIndex719(){ return 719; }
public int GetIndex720(){ return 720; }
public int GetIndex721(){ return 721; }
public int GetIndex722(){ return 722; }
public int GetIndex723(){ return 723; }
public int GetIndex724(){ return 724; }
public int GetIndex725(){ return 725; }
public int GetIndex726(){ return 726; }
public int GetIndex727(){ return 727; }
public int GetIndex728(){ return 728; }
public int GetIndex729(){ return 729; }
public int GetIndex730(){ return 730; }
public int GetIndex731(){ return 731; }
public int GetIndex732(){ return 732; }
public int GetIndex733(){ return 733; }
public int GetIndex734(){ return 734; }
public int GetIndex735(){ return 735; }
public int GetIndex736(){ return 736; }
public int GetIndex737(){ return 737; }
public int GetIndex738(){ return 738; }
public int GetIndex739(){ return 739; }
public int GetIndex740(){ return 740; }
public int GetIndex741(){ return 741; }
public int GetIndex742(){ return 742; }
public int GetIndex743(){ return 743; }
public int GetIndex744(){ return 744; }
public int GetIndex745(){ return 745; }
public int GetIndex746(){ return 746; }
public int GetIndex747(){ return 747; }
public int GetIndex748(){ return 748; }
public int GetIndex749(){ return 749; }
public int GetIndex750(){ return 750; }
public int GetIndex751(){ return 751; }
public int GetIndex752(){ return 752; }
public int GetIndex753(){ return 753; }
public int GetIndex754(){ return 754; }
public int GetIndex755(){ return 755; }
public int GetIndex756(){ return 756; }
public int GetIndex757(){ return 757; }
public int GetIndex758(){ return 758; }
public int GetIndex759(){ return 759; }
public int GetIndex760(){ return 760; }
public int GetIndex761(){ return 761; }
public int GetIndex762(){ return 762; }
public int GetIndex763(){ return 763; }
public int GetIndex764(){ return 764; }
public int GetIndex765(){ return 765; }
public int GetIndex766(){ return 766; }
public int GetIndex767(){ return 767; }
public int GetIndex768(){ return 768; }
public int GetIndex769(){ return 769; }
public int GetIndex770(){ return 770; }
public int GetIndex771(){ return 771; }
public int GetIndex772(){ return 772; }
public int GetIndex773(){ return 773; }
public int GetIndex774(){ return 774; }
public int GetIndex775(){ return 775; }
public int GetIndex776(){ return 776; }
public int GetIndex777(){ return 777; }
public int GetIndex778(){ return 778; }
public int GetIndex779(){ return 779; }
public int GetIndex780(){ return 780; }
public int GetIndex781(){ return 781; }
public int GetIndex782(){ return 782; }
public int GetIndex783(){ return 783; }
public int GetIndex784(){ return 784; }
public int GetIndex785(){ return 785; }
public int GetIndex786(){ return 786; }
public int GetIndex787(){ return 787; }
public int GetIndex788(){ return 788; }
public int GetIndex789(){ return 789; }
public int GetIndex790(){ return 790; }
public int GetIndex791(){ return 791; }
public int GetIndex792(){ return 792; }
public int GetIndex793(){ return 793; }
public int GetIndex794(){ return 794; }
public int GetIndex795(){ return 795; }
public int GetIndex796(){ return 796; }
public int GetIndex797(){ return 797; }
public int GetIndex798(){ return 798; }
public int GetIndex799(){ return 799; }
public int GetIndex800(){ return 800; }
public int GetIndex801(){ return 801; }
public int GetIndex802(){ return 802; }
public int GetIndex803(){ return 803; }
public int GetIndex804(){ return 804; }
public int GetIndex805(){ return 805; }
public int GetIndex806(){ return 806; }
public int GetIndex807(){ return 807; }
public int GetIndex808(){ return 808; }
public int GetIndex809(){ return 809; }
public int GetIndex810(){ return 810; }
public int GetIndex811(){ return 811; }
public int GetIndex812(){ return 812; }
public int GetIndex813(){ return 813; }
public int GetIndex814(){ return 814; }
public int GetIndex815(){ return 815; }
public int GetIndex816(){ return 816; }
public int GetIndex817(){ return 817; }
public int GetIndex818(){ return 818; }
public int GetIndex819(){ return 819; }
public int GetIndex820(){ return 820; }
public int GetIndex821(){ return 821; }
public int GetIndex822(){ return 822; }
public int GetIndex823(){ return 823; }
public int GetIndex824(){ return 824; }
public int GetIndex825(){ return 825; }
public int GetIndex826(){ return 826; }
public int GetIndex827(){ return 827; }
public int GetIndex828(){ return 828; }
public int GetIndex829(){ return 829; }
public int GetIndex830(){ return 830; }
public int GetIndex831(){ return 831; }
public int GetIndex832(){ return 832; }
public int GetIndex833(){ return 833; }
public int GetIndex834(){ return 834; }
public int GetIndex835(){ return 835; }
public int GetIndex836(){ return 836; }
public int GetIndex837(){ return 837; }
public int GetIndex838(){ return 838; }
public int GetIndex839(){ return 839; }
public int GetIndex840(){ return 840; }
public int GetIndex841(){ return 841; }
public int GetIndex842(){ return 842; }
public int GetIndex843(){ return 843; }
public int GetIndex844(){ return 844; }
public int GetIndex845(){ return 845; }
public int GetIndex846(){ return 846; }
public int GetIndex847(){ return 847; }
public int GetIndex848(){ return 848; }
public int GetIndex849(){ return 849; }
public int GetIndex850(){ return 850; }
public int GetIndex851(){ return 851; }
public int GetIndex852(){ return 852; }
public int GetIndex853(){ return 853; }
public int GetIndex854(){ return 854; }
public int GetIndex855(){ return 855; }
public int GetIndex856(){ return 856; }
public int GetIndex857(){ return 857; }
public int GetIndex858(){ return 858; }
public int GetIndex859(){ return 859; }
public int GetIndex860(){ return 860; }
public int GetIndex861(){ return 861; }
public int GetIndex862(){ return 862; }
public int GetIndex863(){ return 863; }
public int GetIndex864(){ return 864; }
public int GetIndex865(){ return 865; }
public int GetIndex866(){ return 866; }
public int GetIndex867(){ return 867; }
public int GetIndex868(){ return 868; }
public int GetIndex869(){ return 869; }
public int GetIndex870(){ return 870; }
public int GetIndex871(){ return 871; }
public int GetIndex872(){ return 872; }
public int GetIndex873(){ return 873; }
public int GetIndex874(){ return 874; }
public int GetIndex875(){ return 875; }
public int GetIndex876(){ return 876; }
public int GetIndex877(){ return 877; }
public int GetIndex878(){ return 878; }
public int GetIndex879(){ return 879; }
public int GetIndex880(){ return 880; }
public int GetIndex881(){ return 881; }
public int GetIndex882(){ return 882; }
public int GetIndex883(){ return 883; }
public int GetIndex884(){ return 884; }
public int GetIndex885(){ return 885; }
public int GetIndex886(){ return 886; }
public int GetIndex887(){ return 887; }
public int GetIndex888(){ return 888; }
public int GetIndex889(){ return 889; }
public int GetIndex890(){ return 890; }
public int GetIndex891(){ return 891; }
public int GetIndex892(){ return 892; }
public int GetIndex893(){ return 893; }
public int GetIndex894(){ return 894; }
public int GetIndex895(){ return 895; }
public int GetIndex896(){ return 896; }
public int GetIndex897(){ return 897; }
public int GetIndex898(){ return 898; }
public int GetIndex899(){ return 899; }
public int GetIndex900(){ return 900; }
public int GetIndex901(){ return 901; }
public int GetIndex902(){ return 902; }
public int GetIndex903(){ return 903; }
public int GetIndex904(){ return 904; }
public int GetIndex905(){ return 905; }
public int GetIndex906(){ return 906; }
public int GetIndex907(){ return 907; }
public int GetIndex908(){ return 908; }
public int GetIndex909(){ return 909; }
public int GetIndex910(){ return 910; }
public int GetIndex911(){ return 911; }
public int GetIndex912(){ return 912; }
public int GetIndex913(){ return 913; }
public int GetIndex914(){ return 914; }
public int GetIndex915(){ return 915; }
public int GetIndex916(){ return 916; }
public int GetIndex917(){ return 917; }
public int GetIndex918(){ return 918; }
public int GetIndex919(){ return 919; }
public int GetIndex920(){ return 920; }
public int GetIndex921(){ return 921; }
public int GetIndex922(){ return 922; }
public int GetIndex923(){ return 923; }
public int GetIndex924(){ return 924; }
public int GetIndex925(){ return 925; }
public int GetIndex926(){ return 926; }
public int GetIndex927(){ return 927; }
public int GetIndex928(){ return 928; }
public int GetIndex929(){ return 929; }
public int GetIndex930(){ return 930; }
public int GetIndex931(){ return 931; }
public int GetIndex932(){ return 932; }
public int GetIndex933(){ return 933; }
public int GetIndex934(){ return 934; }
public int GetIndex935(){ return 935; }
public int GetIndex936(){ return 936; }
public int GetIndex937(){ return 937; }
public int GetIndex938(){ return 938; }
public int GetIndex939(){ return 939; }
public int GetIndex940(){ return 940; }
public int GetIndex941(){ return 941; }
public int GetIndex942(){ return 942; }
public int GetIndex943(){ return 943; }
public int GetIndex944(){ return 944; }
public int GetIndex945(){ return 945; }
public int GetIndex946(){ return 946; }
public int GetIndex947(){ return 947; }
public int GetIndex948(){ return 948; }
public int GetIndex949(){ return 949; }
public int GetIndex950(){ return 950; }
public int GetIndex951(){ return 951; }
public int GetIndex952(){ return 952; }
public int GetIndex953(){ return 953; }
public int GetIndex954(){ return 954; }
public int GetIndex955(){ return 955; }
public int GetIndex956(){ return 956; }
public int GetIndex957(){ return 957; }
public int GetIndex958(){ return 958; }
public int GetIndex959(){ return 959; }
public int GetIndex960(){ return 960; }
public int GetIndex961(){ return 961; }
public int GetIndex962(){ return 962; }
public int GetIndex963(){ return 963; }
public int GetIndex964(){ return 964; }
public int GetIndex965(){ return 965; }
public int GetIndex966(){ return 966; }
public int GetIndex967(){ return 967; }
public int GetIndex968(){ return 968; }
public int GetIndex969(){ return 969; }
public int GetIndex970(){ return 970; }
public int GetIndex971(){ return 971; }
public int GetIndex972(){ return 972; }
public int GetIndex973(){ return 973; }
public int GetIndex974(){ return 974; }
public int GetIndex975(){ return 975; }
public int GetIndex976(){ return 976; }
public int GetIndex977(){ return 977; }
public int GetIndex978(){ return 978; }
public int GetIndex979(){ return 979; }
public int GetIndex980(){ return 980; }
public int GetIndex981(){ return 981; }
public int GetIndex982(){ return 982; }
public int GetIndex983(){ return 983; }
public int GetIndex984(){ return 984; }
public int GetIndex985(){ return 985; }
public int GetIndex986(){ return 986; }
public int GetIndex987(){ return 987; }
public int GetIndex988(){ return 988; }
public int GetIndex989(){ return 989; }
public int GetIndex990(){ return 990; }
public int GetIndex991(){ return 991; }
public int GetIndex992(){ return 992; }
public int GetIndex993(){ return 993; }
public int GetIndex994(){ return 994; }
public int GetIndex995(){ return 995; }
public int GetIndex996(){ return 996; }
public int GetIndex997(){ return 997; }
public int GetIndex998(){ return 998; }
public int GetIndex999(){ return 999; }
}
| 40.548515 | 44 | 0.705694 | [
"MIT"
] | mao-test-h/SamplePackage | Runtime/Generated/Hoge149.generated.cs | 40,954 | C# |
using System;
namespace HeptaSoft.SmartEntity.Mapping.Conversion
{
public interface IConverter
{
/// <summary>
/// Converts the specified value to required type.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="requiredType">Type of the required.</param>
/// <returns>
/// The converted value.
/// </returns>
object ConvertTo(object value, Type requiredType);
/// <summary>
/// Determines whether this instance can convert from <paramref name="from"/> type to <paramref name="to"/> type.
/// </summary>
/// <param name="from">Source type</param>
/// <param name="to">Required output type.</param>
/// <returns>
/// <c>true</c> if this instance can perform the conversion between specified types; otherwise, <c>false</c>.
/// </returns>
bool CanConvert(Type from, Type to);
}
}
| 35.392857 | 122 | 0.564077 | [
"MIT"
] | HeptaSoft/SmartEntity | HeptaSoft.SmartEntity/Mapping/Conversion/IConverter.cs | 993 | C# |
using component.logger.data.log.Interface;
using System;
using System.Collections.Generic;
using System.Linq;
using iot.solution.common;
namespace component.services.logger.viewer.Application.AppSetting
{
public class ServiceAppSetting
{
readonly IAppSettingRepository _appSettingRepository;
private static List<component.logger.data.log.Model.AppSetting> _appSettings { get; set; }
private static ServiceAppSetting instance = null;
private static readonly object _lock = new object();
private ServiceAppSetting()
{
}
public static ServiceAppSetting Instance
{
get
{
if (instance == null)
{
lock (_lock)
{
Object _object;
// create the instance only if the instance is null
if (instance == null)
{
instance = new ServiceAppSetting();
}
}
}
// Otherwise return the already existing instance
return instance;
}
}
public ServiceAppSetting(IAppSettingRepository appSettingRepository)
{
_appSettingRepository = appSettingRepository ?? throw new ArgumentNullException(nameof(appSettingRepository));
}
public void GetDefaultServiceAppSettings()
{
try
{
List<component.logger.data.log.Model.AppSetting> appSettingList = new List<component.logger.data.log.Model.AppSetting>();
System.Threading.Tasks.Task<List<component.logger.data.log.Model.AppSetting>> getTask = _appSettingRepository.GetAll();
appSettingList = getTask.Result;
if (appSettingList != null && appSettingList.Count > 0)
{
_appSettings = new List<component.logger.data.log.Model.AppSetting>();
_appSettings.AddRange(appSettingList);
}
}
catch
{
}
}
public string GetAppSettingByKey(string appSettingKey)
{
if (_appSettings != null && _appSettings.Count > 0)
return _appSettings.Where(x => x.Key.ToLower() == appSettingKey.ToLower()).Select(x => x.Value).FirstOrDefault();
else
return string.Empty;
}
public string GetRequiredAppSettingByKey(string appSettingKey)
{
if (_appSettings?.Any() == true)
return _appSettings.Where(x => string.Equals(x.Key, appSettingKey, StringComparison.OrdinalIgnoreCase)).Select(x => x.Value).FirstOrDefault() ?? General.RaiseConfigurationMissingException(appSettingKey);
else
return General.RaiseConfigurationMissingException(appSettingKey);
}
}
}
| 37.325 | 219 | 0.569324 | [
"MIT"
] | iotconnect-apps/AppConnect-AirQualityMonitoring | iot.solution.logviewer/Application/AppSetting/ServiceAppSetting.cs | 2,988 | C# |
// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Generated code. DO NOT EDIT!
using gagvr = Google.Ads.GoogleAds.V9.Resources;
namespace Google.Ads.GoogleAds.V9.Services
{
public partial class GetKeywordPlanAdGroupKeywordRequest
{
/// <summary>
/// <see cref="gagvr::KeywordPlanAdGroupKeywordName"/>-typed view over the <see cref="ResourceName"/> resource
/// name property.
/// </summary>
public gagvr::KeywordPlanAdGroupKeywordName ResourceNameAsKeywordPlanAdGroupKeywordName
{
get => string.IsNullOrEmpty(ResourceName) ? null : gagvr::KeywordPlanAdGroupKeywordName.Parse(ResourceName, allowUnparsed: true);
set => ResourceName = value?.ToString() ?? "";
}
}
public partial class KeywordPlanAdGroupKeywordOperation
{
/// <summary>
/// <see cref="gagvr::KeywordPlanAdGroupKeywordName"/>-typed view over the <see cref="Remove"/> resource name
/// property.
/// </summary>
public gagvr::KeywordPlanAdGroupKeywordName RemoveAsKeywordPlanAdGroupKeywordName
{
get => string.IsNullOrEmpty(Remove) ? null : gagvr::KeywordPlanAdGroupKeywordName.Parse(Remove, allowUnparsed: true);
set => Remove = value?.ToString() ?? "";
}
}
}
| 39.382979 | 141 | 0.683955 | [
"Apache-2.0"
] | friedenberg/google-ads-dotnet | src/V9/Services/KeywordPlanAdGroupKeywordServiceResourceNames.g.cs | 1,851 | C# |
using HarmonyLib;
namespace BabboSettings.Patches
{
[HarmonyPatch(typeof(PlayerController), "get_IsSwitch")]
static class PlayerController_IsSwitch_Patch
{
static bool Postfix(bool __result) {
var cameraMode = PatchData.Instance.cameraMode;
// isSwitch needs to be calculated all the time, otherwise it loses track of the stance
var isSwitch = PatchData.Instance.isSwitch();
if (cameraMode == CameraMode.POV || cameraMode == CameraMode.Skate) {
return isSwitch;
}
return __result;
}
}
[HarmonyPatch(typeof(PlayerController), "get_IsAnimSwitch")]
static class PlayerController_IsAnimSwitch_Patch
{
static bool Postfix(bool __result) {
var cameraMode = PatchData.Instance.cameraMode;
// isSwitch needs to be calculated all the time, otherwise it loses track of the stance
var isSwitch = PatchData.Instance.isSwitch();
if (cameraMode == CameraMode.POV || cameraMode == CameraMode.Skate) {
return isSwitch;
}
return __result;
}
}
}
| 30.147059 | 91 | 0.714146 | [
"MIT"
] | Amatobahn/Skater-XL-mods | BabboSettings/Patches/PlayerControllerPatches.cs | 994 | C# |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
using System.Collections.Generic;
using Aliyun.Acs.Core;
namespace Aliyun.Acs.CCC.Model.V20200701
{
public class ListDevicesResponse : AcsResponse
{
private string code;
private int? httpStatusCode;
private string message;
private string requestId;
private List<ListDevices_Device> data;
private List<string> _params;
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public int? HttpStatusCode
{
get
{
return httpStatusCode;
}
set
{
httpStatusCode = value;
}
}
public string Message
{
get
{
return message;
}
set
{
message = value;
}
}
public string RequestId
{
get
{
return requestId;
}
set
{
requestId = value;
}
}
public List<ListDevices_Device> Data
{
get
{
return data;
}
set
{
data = value;
}
}
public List<string> _Params
{
get
{
return _params;
}
set
{
_params = value;
}
}
public class ListDevices_Device
{
private string extension;
private long? expires;
private string contact;
private string deviceId;
private string userId;
private string callId;
private string instanceId;
public string Extension
{
get
{
return extension;
}
set
{
extension = value;
}
}
public long? Expires
{
get
{
return expires;
}
set
{
expires = value;
}
}
public string Contact
{
get
{
return contact;
}
set
{
contact = value;
}
}
public string DeviceId
{
get
{
return deviceId;
}
set
{
deviceId = value;
}
}
public string UserId
{
get
{
return userId;
}
set
{
userId = value;
}
}
public string CallId
{
get
{
return callId;
}
set
{
callId = value;
}
}
public string InstanceId
{
get
{
return instanceId;
}
set
{
instanceId = value;
}
}
}
}
}
| 14.516279 | 63 | 0.553348 | [
"Apache-2.0"
] | pengweiqhca/aliyun-openapi-net-sdk | aliyun-net-sdk-ccc/CCC/Model/V20200701/ListDevicesResponse.cs | 3,121 | C# |
/*----------------------------------------------------------------
Copyright (C) 2019 Senparc
文件名:EncryptResponseMessage.cs
文件功能描述:返回给服务器的加密消息
创建标识:Senparc - 20150313
修改标识:Senparc - 20150313
修改描述:整理接口
----------------------------------------------------------------*/
namespace Senparc.Weixin.Work.Entities.Response
{
/// <summary>
/// 返回给服务器的加密消息
/// </summary>
public class EncryptResponseMessage
{
public string Encrypt { get; set; }
public string MsgSignature { get; set; }
public string TimeStamp { get; set; }
public string Nonce { get; set; }
}
}
| 24.296296 | 67 | 0.481707 | [
"Apache-2.0"
] | 370041597/WeiXinMPSDK | src/Senparc.Weixin.Work/Senparc.Weixin.Work/Entities/Response/EncryptResponseMessage.cs | 762 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.ComponentModel;
namespace HKLite
{
/* 作者:何宏卿
* 日期:2014-12-23
* 描述:IDALayer接口
*/
public interface IDALayer : IDALayerBase
{
/// <summary>
/// 通过SqlCeResultSet 高效复制
/// </summary>
/// <param name="SqlCommand"></param>
/// <param name="bulkCopy"></param>
void BulkCopy(string SqlCommand, BulkCopyHandler bulkCopy);
}
}
| 20.75 | 67 | 0.608434 | [
"Apache-2.0"
] | hhqing999/HKLite | HKLite.Sqlce.Wince/Provider/IDALayer.cs | 540 | C# |
// <copyright file="EllipticalPlanetaryDetails.cs" company="Traced-Ideas, Czech republic">
// Copyright (c) 1990-2021 All Right Reserved
// </copyright>
// <author></author>
// <email></email>
// <date>2021-09-01</date>
// <summary>Part of Astro Observatory</summary>
namespace AstroSharedClasses.OrbitalElements {
using JetBrains.Annotations;
/// <summary>
/// Elliptical Planetary Details.
/// </summary>
public sealed class EllipticalPlanetaryDetails
{
/// <summary>
/// Gets or sets the apparent geocentric longitude.
/// </summary>
/// <value>The apparent geocentric longitude.</value>
public double ApparentGeocentricLongitude { get; set; }
/// <summary>
/// Gets or sets the apparent geocentric latitude.
/// </summary>
/// <value>The apparent geocentric latitude.</value>
public double ApparentGeocentricLatitude { get; set; }
/// <summary>
/// Gets or sets the apparent geocentric distance.
/// </summary>
/// <value>The apparent geocentric distance.</value>
public double ApparentGeocentricDistance { get; set; }
/// <summary>
/// Gets or sets the apparent light time.
/// </summary>
/// <value>The apparent light time.</value>
public double ApparentLightTime { [UsedImplicitly] get; set; }
/// <summary>
/// Gets or sets the apparent geocentric RA.
/// </summary>
/// <value>The apparent geocentric RA.</value>
public double ApparentGeocentricRA { [UsedImplicitly] get; set; }
/// <summary>
/// Gets or sets the apparent geocentric declination.
/// </summary>
/// <value>The apparent geocentric declination.</value>
public double ApparentGeocentricDeclination { [UsedImplicitly] get; set; }
}
}
| 34.851852 | 91 | 0.618491 | [
"MIT"
] | Vladimir1965/AstroObservatory | AstroSharedClasses/OrbitalElements/EllipticalPlanetaryDetails.cs | 1,884 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Net.Surviveplus.LightCutter.Core;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Net.Surviveplus.LightCutter.Core.Tests
{
[TestClass()]
public class FrozenScreenTests
{
[TestMethod()]
public void CropTest()
{
var bound = new Rectangle(0,0, 10,10);
using (var frozen = new FrozenScreen(bound))
{
}
}
}
} | 21.576923 | 56 | 0.643494 | [
"MIT"
] | surviveplus/Light-Cutter | LightCutter/LightCutter.Core.Tests/FrozenScreenTests.cs | 563 | C# |
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections;
using System.Diagnostics.CodeAnalysis;
namespace Shift.Common.ExpressionUtil
{
// based on System.Web.Util.HashCodeCombiner
[ExcludeFromCodeCoverage]
internal class HashCodeCombiner
{
private long _combinedHash64 = 0x1505L;
public int CombinedHash
{
get { return _combinedHash64.GetHashCode(); }
}
public void AddFingerprint(ExpressionFingerprint fingerprint)
{
if (fingerprint != null)
{
fingerprint.AddToHashCodeCombiner(this);
}
else
{
AddInt32(0);
}
}
public void AddEnumerable(IEnumerable e)
{
if (e == null)
{
AddInt32(0);
}
else
{
int count = 0;
foreach (object o in e)
{
AddObject(o);
count++;
}
AddInt32(count);
}
}
public void AddInt32(int i)
{
_combinedHash64 = ((_combinedHash64 << 5) + _combinedHash64) ^ i;
}
public void AddObject(object o)
{
int hashCode = (o != null) ? o.GetHashCode() : 0;
AddInt32(hashCode);
}
}
}
| 24.721311 | 133 | 0.492706 | [
"MIT"
] | hhalim/Shift | Shift.DataLayer/Common/ExpressionUtil/HashCodeCombiner.cs | 1,510 | C# |
using RoboRemote.Interfaces;
using System;
using Xamarin.Forms;
namespace RoboRemote.Converters
{
public class IsWriteableBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((IItem)value).Type == "bool" && (((IItem)value).Access == "W" || ((IItem)value).Access == "RW");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}
public class IsNotWriteableBoolConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return ((IItem)value).Type != "bool" && (((IItem)value).Access == "W" || ((IItem)value).Access == "RW");
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
return value;
}
}
}
| 33.636364 | 124 | 0.645946 | [
"MIT"
] | ZeroxCorbin/RoboRemote | RoboRemote/RoboRemote/Converters/AccessCheckConverter.cs | 1,112 | C# |
using System;
using System.Collections.Generic;
using YTSubConverter.Shared.Animations;
namespace YTSubConverter.Shared.Formats.Ass.Tags
{
internal class AssSimpleFadeTagHandler : AssTagHandlerBase
{
public override string Tag => "fad";
public override bool AffectsWholeLine => true;
public override void Handle(AssTagContext context, string arg)
{
List<float> times = ParseFloatList(arg);
if (times == null || times.Count != 2)
return;
AssLine line = context.Line;
DateTime fadeInStartTime = line.Start;
DateTime fadeInEndTime = line.Start.AddMilliseconds(times[0]);
DateTime fadeOutStartTime = line.End.AddMilliseconds(-times[1]);
DateTime fadeOutEndTime = line.End;
if (fadeInEndTime > fadeInStartTime)
line.Animations.Add(new FadeAnimation(fadeInStartTime, 0, fadeInEndTime, 255));
if (fadeOutEndTime > fadeOutStartTime)
line.Animations.Add(new FadeAnimation(fadeOutStartTime, 255, fadeOutEndTime, 0));
}
}
}
| 35.151515 | 98 | 0.626724 | [
"MIT"
] | Meigyoku-Thmn/YTSubConverter | YTSubConverter.Shared/Formats/Ass/Tags/AssSimpleFadeTagHandler.cs | 1,162 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Geotab.Checkmate;
using Geotab.Checkmate.ObjectModel;
using Geotab.Checkmate.ObjectModel.Fuel;
namespace Geotab.SDK.GetFuelTaxDetails
{
static class Program
{
/// <summary>
/// The amount of ticks in an hour.
/// </summary>
const long HourTicks = TimeSpan.TicksPerHour;
static async Task Main(string[] args)
{
try
{
// Validate the command line.
if (args.Length != 3)
{
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine("dotnet run <database> <username> <password>");
Console.WriteLine();
Console.WriteLine(" database - Database name (e.g. g560)");
Console.WriteLine(" username - Geotab user name");
Console.WriteLine(" password - Geotab password");
return;
}
// Retrieve the database name and credentials from the command line.
string database = args[0];
string username = args[1];
string password = args[2];
// Fuel tax details support the following attributes: jurisdiction, toll road, and authority. To forego toll road identification, authority identification, or fuel usage calculation, set the corresponding option(s) to <c>false</c>.
dynamic options = new
{
DriverIdentification = true,
TollRoadIdentification = true,
AuthorityIdentification = true,
FuelUsage = true
};
// Set the beginning of the time interval. It will be extended to the nearest hour. For example, 4:20:00 will become 4:00:00.
DateTime fromDate = new DateTime(2018, 1, 1, 5, 0, 0, DateTimeKind.Utc);
// Set the end of the time interval. It will be extended to the nearest hour. For example, 3:45:00 will become 4:00:00.
DateTime toDate = new DateTime(2018, 2, 1, 5, 0, 0, DateTimeKind.Utc);
// Create the Geotab API object.
// It is important to create this object with the base "Federation" server (my.geotab.com) NOT the specific server (e.g. my3.geotab.com).
// A database can be moved to another server without notice.
Console.WriteLine();
Console.WriteLine("Creating API...");
const string server = "my.geotab.com";
API api = new API(username, password, null, database, server);
// The example code will retrieve fuel tax details for one device at a time. For smaller fleets, it is feasible to retrieve the details for all devices by removing the device search from the search object below.
Console.WriteLine("Retrieving devices...");
IList<Device> devices = await api.CallAsync<IList<Device>>("Get", typeof(Device));
// Get the fuel tax details restricted to the time interval, grouped by device, and sorted by enter time.
Console.WriteLine("Retrieving fuel tax details...");
List<FuelTaxDetail> details = new List<FuelTaxDetail>();
var fuelUsageByDevice = new Dictionary<Device, Dictionary<string, Dictionary<FuelType, FuelUsage>>>();
foreach (var device in devices)
{
Search fuelTaxDetailSearch = new FuelTaxDetailSearch
{
DeviceSearch = new DeviceSearch(device.Id),
FromDate = fromDate,
ToDate = toDate,
IncludeHourlyData = false,
IncludeBoundaries = false
};
List<FuelTaxDetail> deviceDetails = (await api.CallAsync<IList<FuelTaxDetail>>("Get", typeof(FuelTaxDetail), new { search = fuelTaxDetailSearch })).ToList();
if (deviceDetails.Count > 0)
{
// Group successive details depending on the options.
List<List<FuelTaxDetail>> groups = Group(deviceDetails, options);
List<FuelTaxDetail> mergedDetails = Merge(groups);
details.AddRange(deviceDetails);
if (options.FuelUsage)
{
if (device is GoDevice)
{
var deviceFuelUsage = await GetFuelUsageByJurisdictionAsync(api, device as GoDevice, deviceDetails);
fuelUsageByDevice[device] = deviceFuelUsage;
}
}
}
}
Console.WriteLine($"{details.Count} fuel tax details ready.");
if (options.FuelUsage)
{
Console.WriteLine($"Fuel usage for {fuelUsageByDevice.Count} devices ready.");
}
}
catch (InvalidUserException)
{
// Invalid credentials.
Console.WriteLine("Incorrect database name, user name or password");
}
catch (Exception exception)
{
Console.WriteLine($"Exception: {exception.Message}\n\n{exception.StackTrace}");
}
finally
{
Console.WriteLine();
Console.Write("Press any key to exit...");
Console.ReadKey(true);
}
}
/// <summary>
/// Groups successive <see cref="FuelTaxDetail"/> elements by their attributes, depending on the <see cref="options"/>.
/// </summary>
/// <param name="details">The details.</param>
/// <param name="options">The options.</param>
/// <returns>A list of detail groups.</returns>
static List<List<FuelTaxDetail>> Group(IList<FuelTaxDetail> details, dynamic options)
{
List<List<FuelTaxDetail>> groups = new List<List<FuelTaxDetail>> { new List<FuelTaxDetail>() };
List<FuelTaxDetail> group = groups[0];
FuelTaxDetail previousDetail = null;
foreach (var detail in details)
{
if (previousDetail == null || AreAttributesEqual(detail, previousDetail, options))
{
group.Add(detail);
}
else
{
group = new List<FuelTaxDetail> { detail };
groups.Add(group);
}
previousDetail = detail;
}
return groups;
}
/// <summary>
/// Compares two <see cref="FuelTaxDetail"/> elements based on their attributes.
/// </summary>
/// <param name="detail1">The first detail.</param>
/// <param name="detail2">The second detail.</param>
/// <param name="options">The grouping options.</param>
/// <returns><c>true</c> iff both details share the same attributes, depending on the <see cref="options"/>.</returns>
static bool AreAttributesEqual(FuelTaxDetail detail1, FuelTaxDetail detail2, dynamic options)
{
return detail1.Jurisdiction == detail2.Jurisdiction
&& (!options.DriverIdentification || detail1.Driver.Equals(detail2.TollRoad))
&& (!options.TollRoadIdentification || detail1.TollRoad == detail2.TollRoad)
&& (!options.AuthorityIdentification || detail1.Authority == detail2.Authority);
}
/// <summary>
/// Merges successive <see cref="FuelTaxDetail"/> elements that share the same attributes into one detail.
/// </summary>
/// <param name="groups">Groups of details that share the same attributes.</param>
/// <returns>The resulting merged details.</returns>
static List<FuelTaxDetail> Merge(List<List<FuelTaxDetail>> groups)
{
var groupedDetails = new List<FuelTaxDetail>();
foreach (var group in groups)
{
var detail = group[0];
var detailCount = group.Count;
if (detailCount > 1)
{
var lastDetail = group[detailCount - 1];
detail.ExitTime = lastDetail.ExitTime;
detail.ExitOdometer = lastDetail.ExitOdometer;
detail.ExitGpsOdometer = lastDetail.ExitGpsOdometer;
detail.ExitLatitude = lastDetail.ExitLatitude;
detail.ExitLongitude = lastDetail.ExitLongitude;
for (var detailIndex = 1; detailIndex < detailCount; detailIndex++)
{
var nextDetail = group[detailIndex];
if (nextDetail.EnterTime.Ticks % TimeSpan.TicksPerHour == 0)
{
detail.HourlyOdometer.Add(nextDetail.EnterOdometer);
detail.HourlyGpsOdometer.Add(nextDetail.EnterGpsOdometer);
detail.HourlyLatitude.Add(nextDetail.EnterLatitude);
detail.HourlyLongitude.Add(nextDetail.EnterLongitude);
}
for (int hourIndex = 0; hourIndex < nextDetail.HourlyOdometer.Count; hourIndex++)
{
detail.HourlyOdometer.Add(nextDetail.HourlyOdometer[hourIndex]);
detail.HourlyGpsOdometer.Add(nextDetail.HourlyGpsOdometer[hourIndex]);
detail.HourlyLatitude.Add(nextDetail.HourlyLatitude[hourIndex]);
detail.HourlyLongitude.Add(nextDetail.HourlyLongitude[hourIndex]);
}
}
}
groupedDetails.Add(detail);
}
return groupedDetails;
}
/// <summary>
/// Calculates fuel usage for a collection of fuel tax details, classified by jurisdiction and fuel type.
/// </summary>
/// <param name="api">The Geotab API.</param>
/// <param name="device">The device.</param>
/// <param name="details">The fuel tax details.</param>
/// <returns>A list of fuel tax data objects.</returns>
static async Task<Dictionary<string, Dictionary<FuelType, FuelUsage>>> GetFuelUsageByJurisdictionAsync(API api, GoDevice device, IList<FuelTaxDetail> details)
{
var fuelUsageByJurisdiction = new Dictionary<string, Dictionary<FuelType, FuelUsage>>();
// Get the details' time interval.
DateTime fromDate = details[0].EnterTime;
DateTime toDate = details[details.Count - 1].ExitTime;
// Get the fuel transactions within the details' time interval.
Search fuelTransactionSearch = new FuelTransactionSearch
{
VehicleIdentificationNumber = device.VehicleIdentificationNumber,
FromDate = fromDate,
ToDate = toDate
};
List<FuelTransaction> fuelTransactions = (await api.CallAsync<IList<FuelTransaction>>("Get", typeof(FuelTransaction), new { search = fuelTransactionSearch })).ToList();
fuelTransactions.Sort((transaction1, transaction2) => DateTime.Compare(transaction1.DateTime.Value, transaction2.DateTime.Value));
// Calculate total purchased fuel by fuel type and jurisdiction.
Dictionary<FuelType, double> fuelPurchasedByType = new Dictionary<FuelType, double>();
double totalDistance = 0;
foreach (var fuelTransaction in fuelTransactions)
{
// Locate the fuel transaction within a detail.
FuelTaxDetail detail = details.Last(x => x.EnterTime <= fuelTransaction.DateTime);
// Update jurisdiction fuel usage.
string jurisdiction = detail.Jurisdiction;
if (jurisdiction != null)
{
if (!fuelUsageByJurisdiction.TryGetValue(jurisdiction, out Dictionary<FuelType, FuelUsage> fuelUsageByType))
{
fuelUsageByType = new Dictionary<FuelType, FuelUsage>();
fuelUsageByJurisdiction.Add(jurisdiction, fuelUsageByType);
}
FuelTransactionProductType? productType = fuelTransaction.ProductType;
FuelType fuelType = productType == null ? FuelType.None : GetFuelType(productType.Value);
if (!fuelUsageByType.TryGetValue(fuelType, out FuelUsage fuelUsage))
{
fuelUsage = new FuelUsage();
fuelUsageByType.Add(fuelType, fuelUsage);
}
double volume = fuelTransaction.Volume.Value;
fuelUsage.FuelPurchased += volume;
if (!fuelPurchasedByType.ContainsKey(fuelType))
{
fuelPurchasedByType.Add(fuelType, 0);
}
fuelPurchasedByType[fuelType] += volume;
}
}
// Resolve fuel type None into the fuel type with the largest purchased volume.
if (fuelPurchasedByType.TryGetValue(FuelType.None, out double _))
{
FuelType topFuelType = FuelType.None;
double topVolume = 0;
foreach (var fuelTypePurchased in fuelPurchasedByType)
{
FuelType fuelType = fuelTypePurchased.Key;
if (fuelType != FuelType.None)
{
double volume = fuelTypePurchased.Value;
if (volume > topVolume)
{
topVolume = volume;
topFuelType = fuelType;
}
}
}
if (topFuelType != FuelType.None)
{
fuelPurchasedByType[topFuelType] += fuelPurchasedByType[FuelType.None];
fuelPurchasedByType.Remove(FuelType.None);
}
foreach (var fuelUsageByType in fuelUsageByJurisdiction.Values)
{
if (fuelUsageByType.TryGetValue(FuelType.None, out FuelUsage typeNoneFuelUsage))
{
fuelUsageByType[topFuelType].FuelPurchased += typeNoneFuelUsage.FuelPurchased;
fuelUsageByType.Remove(FuelType.None);
}
}
}
// Create fuel usage stumps for jurisdictions where no fuel transactions occurred.
foreach (var detail in details)
{
string jurisdiction = detail.Jurisdiction;
if (jurisdiction != null)
{
if (!fuelUsageByJurisdiction.TryGetValue(jurisdiction, out Dictionary<FuelType, FuelUsage> fuelUsageByType))
{
fuelUsageByType = new Dictionary<FuelType, FuelUsage>();
fuelUsageByJurisdiction.Add(jurisdiction, fuelUsageByType);
}
double detailDistance = detail.ExitOdometer - detail.EnterOdometer;
foreach (var fuelType in fuelPurchasedByType.Keys)
{
if (!fuelUsageByType.TryGetValue(fuelType, out FuelUsage fuelUsage))
{
fuelUsage = new FuelUsage();
fuelUsageByType.Add(fuelType, fuelUsage);
}
fuelUsage.Distance += detailDistance;
}
totalDistance += detailDistance;
}
}
// Calculate fuel economy for each fuel type. Fill in fuel usage per jurisdiction and fuel type.
foreach (var typeVolume in fuelPurchasedByType)
{
FuelType fuelType = typeVolume.Key;
double totalVolume = typeVolume.Value;
double volumePerKm = totalVolume / totalDistance;
foreach (var fuelUsageByType in fuelUsageByJurisdiction.Values)
{
FuelUsage fuelUsage = fuelUsageByType[fuelType];
fuelUsage.FuelUsed = volumePerKm * fuelUsage.Distance;
fuelUsage.FuelEconomy = volumePerKm * 100;
}
}
return fuelUsageByJurisdiction;
}
/// <summary>
/// Converts fuel product type to fuel tax fuel type.
/// </summary>
/// <param name="productType">The product type.</param>
/// <returns>The fuel tax fuel type.</returns>
static FuelType GetFuelType(FuelTransactionProductType productType)
{
switch (productType)
{
case FuelTransactionProductType.NonFuel:
return FuelType.NonFuel;
case FuelTransactionProductType.Regular:
case FuelTransactionProductType.Midgrade:
case FuelTransactionProductType.Premium:
case FuelTransactionProductType.Super:
return FuelType.Gasoline;
case FuelTransactionProductType.Diesel:
return FuelType.Diesel;
case FuelTransactionProductType.E85:
return FuelType.Ethanol;
case FuelTransactionProductType.CNG:
return FuelType.CNG;
case FuelTransactionProductType.LPG:
return FuelType.LPG;
default:
return FuelType.None;
}
}
enum FuelType
{
None,
NonFuel,
Gasoline,
Diesel,
Ethanol,
CNG,
LPG
}
class FuelUsage
{
public double FuelPurchased { get; set; }
public double FuelUsed { get; set; }
public double NetTaxableFuel => FuelUsed - FuelPurchased;
public double FuelEconomy { get; set; }
public double Distance { get; set; }
}
}
}
| 47.897698 | 247 | 0.538499 | [
"MIT"
] | Geotab/sdk-dotnet-samples | GetFuelTaxDetails/Program.cs | 18,728 | C# |
/*******************************************************************************
* Copyright 2012-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use
* this file except in compliance with the License. A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file.
* This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* *****************************************************************************
*
* AWS Tools for Windows (TM) PowerShell (TM)
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Text;
using Amazon.PowerShell.Common;
using Amazon.Runtime;
using Amazon.AppConfig;
using Amazon.AppConfig.Model;
namespace Amazon.PowerShell.Cmdlets.APPC
{
/// <summary>
/// A deployment strategy defines important criteria for rolling out your configuration
/// to the designated targets. A deployment strategy includes: the overall duration required,
/// a percentage of targets to receive the deployment during each interval, an algorithm
/// that defines how percentage grows, and bake time.
/// </summary>
[Cmdlet("New", "APPCDeploymentStrategy", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Medium)]
[OutputType("Amazon.AppConfig.Model.CreateDeploymentStrategyResponse")]
[AWSCmdlet("Calls the AWS AppConfig CreateDeploymentStrategy API operation.", Operation = new[] {"CreateDeploymentStrategy"}, SelectReturnType = typeof(Amazon.AppConfig.Model.CreateDeploymentStrategyResponse))]
[AWSCmdletOutput("Amazon.AppConfig.Model.CreateDeploymentStrategyResponse",
"This cmdlet returns an Amazon.AppConfig.Model.CreateDeploymentStrategyResponse object containing multiple properties. The object can also be referenced from properties attached to the cmdlet entry in the $AWSHistory stack."
)]
public partial class NewAPPCDeploymentStrategyCmdlet : AmazonAppConfigClientCmdlet, IExecutor
{
#region Parameter DeploymentDurationInMinute
/// <summary>
/// <para>
/// <para>Total amount of time for a deployment to last.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[Alias("DeploymentDurationInMinutes")]
public System.Int32? DeploymentDurationInMinute { get; set; }
#endregion
#region Parameter Description
/// <summary>
/// <para>
/// <para>A description of the deployment strategy.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public System.String Description { get; set; }
#endregion
#region Parameter FinalBakeTimeInMinute
/// <summary>
/// <para>
/// <para>The amount of time AppConfig monitors for alarms before considering the deployment
/// to be complete and no longer eligible for automatic roll back.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("FinalBakeTimeInMinutes")]
public System.Int32? FinalBakeTimeInMinute { get; set; }
#endregion
#region Parameter GrowthFactor
/// <summary>
/// <para>
/// <para>The percentage of targets to receive a deployed configuration during each interval.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.Single? GrowthFactor { get; set; }
#endregion
#region Parameter GrowthType
/// <summary>
/// <para>
/// <para>The algorithm used to define how percentage grows over time.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[AWSConstantClassSource("Amazon.AppConfig.GrowthType")]
public Amazon.AppConfig.GrowthType GrowthType { get; set; }
#endregion
#region Parameter Name
/// <summary>
/// <para>
/// <para>A name for the deployment strategy.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true)]
#else
[System.Management.Automation.Parameter(Position = 0, ValueFromPipelineByPropertyName = true, ValueFromPipeline = true, Mandatory = true)]
[System.Management.Automation.AllowEmptyString]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
public System.String Name { get; set; }
#endregion
#region Parameter ReplicateTo
/// <summary>
/// <para>
/// <para>Save the deployment strategy to a Systems Manager (SSM) document.</para>
/// </para>
/// </summary>
#if !MODULAR
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
#else
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true, Mandatory = true)]
[System.Management.Automation.AllowNull]
#endif
[Amazon.PowerShell.Common.AWSRequiredParameter]
[AWSConstantClassSource("Amazon.AppConfig.ReplicateTo")]
public Amazon.AppConfig.ReplicateTo ReplicateTo { get; set; }
#endregion
#region Parameter Tag
/// <summary>
/// <para>
/// <para>Metadata to assign to the deployment strategy. Tags help organize and categorize your
/// AppConfig resources. Each tag consists of a key and an optional value, both of which
/// you define.</para>
/// </para>
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
[Alias("Tags")]
public System.Collections.Hashtable Tag { get; set; }
#endregion
#region Parameter Select
/// <summary>
/// Use the -Select parameter to control the cmdlet output. The default value is '*'.
/// Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.AppConfig.Model.CreateDeploymentStrategyResponse).
/// Specifying the name of a property of type Amazon.AppConfig.Model.CreateDeploymentStrategyResponse will result in that property being returned.
/// Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public string Select { get; set; } = "*";
#endregion
#region Parameter PassThru
/// <summary>
/// Changes the cmdlet behavior to return the value passed to the Name parameter.
/// The -PassThru parameter is deprecated, use -Select '^Name' instead. This parameter will be removed in a future version.
/// </summary>
[System.Obsolete("The -PassThru parameter is deprecated, use -Select '^Name' instead. This parameter will be removed in a future version.")]
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter PassThru { get; set; }
#endregion
#region Parameter Force
/// <summary>
/// This parameter overrides confirmation prompts to force
/// the cmdlet to continue its operation. This parameter should always
/// be used with caution.
/// </summary>
[System.Management.Automation.Parameter(ValueFromPipelineByPropertyName = true)]
public SwitchParameter Force { get; set; }
#endregion
protected override void ProcessRecord()
{
base.ProcessRecord();
var resourceIdentifiersText = FormatParameterValuesForConfirmationMsg(nameof(this.Name), MyInvocation.BoundParameters);
if (!ConfirmShouldProceed(this.Force.IsPresent, resourceIdentifiersText, "New-APPCDeploymentStrategy (CreateDeploymentStrategy)"))
{
return;
}
var context = new CmdletContext();
// allow for manipulation of parameters prior to loading into context
PreExecutionContextLoad(context);
#pragma warning disable CS0618, CS0612 //A class member was marked with the Obsolete attribute
if (ParameterWasBound(nameof(this.Select)))
{
context.Select = CreateSelectDelegate<Amazon.AppConfig.Model.CreateDeploymentStrategyResponse, NewAPPCDeploymentStrategyCmdlet>(Select) ??
throw new System.ArgumentException("Invalid value for -Select parameter.", nameof(this.Select));
if (this.PassThru.IsPresent)
{
throw new System.ArgumentException("-PassThru cannot be used when -Select is specified.", nameof(this.Select));
}
}
else if (this.PassThru.IsPresent)
{
context.Select = (response, cmdlet) => this.Name;
}
#pragma warning restore CS0618, CS0612 //A class member was marked with the Obsolete attribute
context.DeploymentDurationInMinute = this.DeploymentDurationInMinute;
#if MODULAR
if (this.DeploymentDurationInMinute == null && ParameterWasBound(nameof(this.DeploymentDurationInMinute)))
{
WriteWarning("You are passing $null as a value for parameter DeploymentDurationInMinute which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.Description = this.Description;
context.FinalBakeTimeInMinute = this.FinalBakeTimeInMinute;
context.GrowthFactor = this.GrowthFactor;
#if MODULAR
if (this.GrowthFactor == null && ParameterWasBound(nameof(this.GrowthFactor)))
{
WriteWarning("You are passing $null as a value for parameter GrowthFactor which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.GrowthType = this.GrowthType;
context.Name = this.Name;
#if MODULAR
if (this.Name == null && ParameterWasBound(nameof(this.Name)))
{
WriteWarning("You are passing $null as a value for parameter Name which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
context.ReplicateTo = this.ReplicateTo;
#if MODULAR
if (this.ReplicateTo == null && ParameterWasBound(nameof(this.ReplicateTo)))
{
WriteWarning("You are passing $null as a value for parameter ReplicateTo which is marked as required. In case you believe this parameter was incorrectly marked as required, report this by opening an issue at https://github.com/aws/aws-tools-for-powershell/issues.");
}
#endif
if (this.Tag != null)
{
context.Tag = new Dictionary<System.String, System.String>(StringComparer.Ordinal);
foreach (var hashKey in this.Tag.Keys)
{
context.Tag.Add((String)hashKey, (String)(this.Tag[hashKey]));
}
}
// allow further manipulation of loaded context prior to processing
PostExecutionContextLoad(context);
var output = Execute(context) as CmdletOutput;
ProcessOutput(output);
}
#region IExecutor Members
public object Execute(ExecutorContext context)
{
var cmdletContext = context as CmdletContext;
// create request
var request = new Amazon.AppConfig.Model.CreateDeploymentStrategyRequest();
if (cmdletContext.DeploymentDurationInMinute != null)
{
request.DeploymentDurationInMinutes = cmdletContext.DeploymentDurationInMinute.Value;
}
if (cmdletContext.Description != null)
{
request.Description = cmdletContext.Description;
}
if (cmdletContext.FinalBakeTimeInMinute != null)
{
request.FinalBakeTimeInMinutes = cmdletContext.FinalBakeTimeInMinute.Value;
}
if (cmdletContext.GrowthFactor != null)
{
request.GrowthFactor = cmdletContext.GrowthFactor.Value;
}
if (cmdletContext.GrowthType != null)
{
request.GrowthType = cmdletContext.GrowthType;
}
if (cmdletContext.Name != null)
{
request.Name = cmdletContext.Name;
}
if (cmdletContext.ReplicateTo != null)
{
request.ReplicateTo = cmdletContext.ReplicateTo;
}
if (cmdletContext.Tag != null)
{
request.Tags = cmdletContext.Tag;
}
CmdletOutput output;
// issue call
var client = Client ?? CreateClient(_CurrentCredentials, _RegionEndpoint);
try
{
var response = CallAWSServiceOperation(client, request);
object pipelineOutput = null;
pipelineOutput = cmdletContext.Select(response, this);
output = new CmdletOutput
{
PipelineOutput = pipelineOutput,
ServiceResponse = response
};
}
catch (Exception e)
{
output = new CmdletOutput { ErrorResponse = e };
}
return output;
}
public ExecutorContext CreateContext()
{
return new CmdletContext();
}
#endregion
#region AWS Service Operation Call
private Amazon.AppConfig.Model.CreateDeploymentStrategyResponse CallAWSServiceOperation(IAmazonAppConfig client, Amazon.AppConfig.Model.CreateDeploymentStrategyRequest request)
{
Utils.Common.WriteVerboseEndpointMessage(this, client.Config, "AWS AppConfig", "CreateDeploymentStrategy");
try
{
#if DESKTOP
return client.CreateDeploymentStrategy(request);
#elif CORECLR
return client.CreateDeploymentStrategyAsync(request).GetAwaiter().GetResult();
#else
#error "Unknown build edition"
#endif
}
catch (AmazonServiceException exc)
{
var webException = exc.InnerException as System.Net.WebException;
if (webException != null)
{
throw new Exception(Utils.Common.FormatNameResolutionFailureMessage(client.Config, webException.Message), webException);
}
throw;
}
}
#endregion
internal partial class CmdletContext : ExecutorContext
{
public System.Int32? DeploymentDurationInMinute { get; set; }
public System.String Description { get; set; }
public System.Int32? FinalBakeTimeInMinute { get; set; }
public System.Single? GrowthFactor { get; set; }
public Amazon.AppConfig.GrowthType GrowthType { get; set; }
public System.String Name { get; set; }
public Amazon.AppConfig.ReplicateTo ReplicateTo { get; set; }
public Dictionary<System.String, System.String> Tag { get; set; }
public System.Func<Amazon.AppConfig.Model.CreateDeploymentStrategyResponse, NewAPPCDeploymentStrategyCmdlet, object> Select { get; set; } =
(response, cmdlet) => response;
}
}
}
| 46.325459 | 297 | 0.616431 | [
"Apache-2.0"
] | SpandanaS9/aws-tools-for-powershell | modules/AWSPowerShell/Cmdlets/AppConfig/Basic/New-APPCDeploymentStrategy-Cmdlet.cs | 17,650 | C# |
using System.IO;
using CP77.CR2W.Reflection;
using FastMember;
using static CP77.CR2W.Types.Enums;
namespace CP77.CR2W.Types
{
[REDMeta]
public class UIGameDataDef : gamebbScriptDefinition
{
[Ordinal(0)] [RED("ActivityLog")] public gamebbScriptID_Variant ActivityLog { get; set; }
[Ordinal(1)] [RED("Controller_Disconnected")] public gamebbScriptID_Bool Controller_Disconnected { get; set; }
[Ordinal(2)] [RED("HideDialogLine")] public gamebbScriptID_Variant HideDialogLine { get; set; }
[Ordinal(3)] [RED("HideDialogLineByData")] public gamebbScriptID_Variant HideDialogLineByData { get; set; }
[Ordinal(4)] [RED("HideSceneComment")] public gamebbScriptID_Bool HideSceneComment { get; set; }
[Ordinal(5)] [RED("InteractionData")] public gamebbScriptID_Variant InteractionData { get; set; }
[Ordinal(6)] [RED("LeftWeaponRecordID")] public gamebbScriptID_Variant LeftWeaponRecordID { get; set; }
[Ordinal(7)] [RED("NotificationJournalHash")] public gamebbScriptID_Int32 NotificationJournalHash { get; set; }
[Ordinal(8)] [RED("Popup_Data")] public gamebbScriptID_Variant Popup_Data { get; set; }
[Ordinal(9)] [RED("Popup_IsModal")] public gamebbScriptID_Bool Popup_IsModal { get; set; }
[Ordinal(10)] [RED("Popup_IsShown")] public gamebbScriptID_Bool Popup_IsShown { get; set; }
[Ordinal(11)] [RED("Popup_Settings")] public gamebbScriptID_Variant Popup_Settings { get; set; }
[Ordinal(12)] [RED("QuestTimerCurrentDuration")] public gamebbScriptID_Float QuestTimerCurrentDuration { get; set; }
[Ordinal(13)] [RED("QuestTimerInitialDuration")] public gamebbScriptID_Float QuestTimerInitialDuration { get; set; }
[Ordinal(14)] [RED("RightWeaponRecordID")] public gamebbScriptID_Variant RightWeaponRecordID { get; set; }
[Ordinal(15)] [RED("ShowDialogLine")] public gamebbScriptID_Variant ShowDialogLine { get; set; }
[Ordinal(16)] [RED("ShowSceneComment")] public gamebbScriptID_String ShowSceneComment { get; set; }
[Ordinal(17)] [RED("ShowSubtitlesBackground")] public gamebbScriptID_Bool ShowSubtitlesBackground { get; set; }
[Ordinal(18)] [RED("Tutorial_EnableHighlight")] public gamebbScriptID_Bool Tutorial_EnableHighlight { get; set; }
[Ordinal(19)] [RED("Tutorial_EntityRefToHighlight")] public gamebbScriptID_Variant Tutorial_EntityRefToHighlight { get; set; }
[Ordinal(20)] [RED("UIVendorContextRequest")] public gamebbScriptID_Bool UIVendorContextRequest { get; set; }
[Ordinal(21)] [RED("UIjailbreakData")] public gamebbScriptID_Variant UIjailbreakData { get; set; }
[Ordinal(22)] [RED("WeaponSway")] public gamebbScriptID_Vector2 WeaponSway { get; set; }
public UIGameDataDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { }
}
}
| 73.157895 | 130 | 0.745683 | [
"MIT"
] | Eingin/CP77Tools | CP77.CR2W/Types/cp77/UIGameDataDef.cs | 2,743 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
namespace UnityEditor.VFX.Operator
{
abstract class NoiseBase : VFXOperator
{
public class InputProperties1D
{
[Tooltip("Sets the coordinate in the noise field to take the sample from.")]
public float coordinate = 0.0f;
}
public class InputProperties2D
{
[Tooltip("Sets the coordinate in the noise field to take the sample from.")]
public Vector2 coordinate = Vector2.zero;
}
public class InputProperties3D
{
[Tooltip("Sets the coordinate in the noise field to take the sample from.")]
public Vector3 coordinate = Vector3.zero;
}
public class InputPropertiesCommon
{
[Tooltip("Sets the period in which the noise is sampled. Higher frequencies result in more frequent noise change.")]
public float frequency = 1.0f;
[Range(1, 8), Tooltip("Sets the number of layers of noise. More octaves create a more varied look, but are also more expensive to calculate.")]
public int octaves = 1;
[Range(0, 1), Tooltip("Sets the scaling factor applied to each octave (also known as persistence.) ")]
public float roughness = 0.5f;
[Min(0), Tooltip("Sets the rate of change of the frequency for each successive octave. A lacunarity value of 1 results in each octave having the same frequency. Higher values result in more details, and values below 1 produce less details.")]
public float lacunarity = 2.0f;
}
public enum NoiseType
{
Value,
Perlin,
Cellular
}
[VFXSetting, Tooltip("Specifies the algorithm used to generate the noise field.")]
public NoiseType type = NoiseType.Perlin;
}
}
| 38.568627 | 255 | 0.613625 | [
"MIT"
] | JesusGarciaValadez/RenderStreamingHDRP | RenderStreamingHDRP/Library/PackageCache/com.unity.visualeffectgraph@8.2.0/Editor/Models/Operators/Implementations/NoiseBase.cs | 1,967 | C# |
using Houzkin;
using Calamelia.StockPrice.Serialize;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Serialization;
using CsvHelper.Configuration;
using CsvHelper.TypeConversion;
using System.Net;
using CsvHelper;
using Caramelia;
namespace Calamelia.StockPrice.DataClient {
enum KdbData { stocks,indices,}
internal static class KdbClient {
static string localPath = Local.CurrentPath + "K-db" + Path.DirectorySeparatorChar;// + "stocks" + Path.DirectorySeparatorChar;
static DateTime sinceMin = new DateTime(2016,5,25);// new DateTime(2007, 1, 4);
internal static void Delete() {
if (Directory.Exists(localPath)) Directory.Delete(localPath);
}
internal static void Update() {
foreach (KdbData en in Enum.GetValues(typeof(KdbData))) {
IEnumerable<Tuple<DateTime, IEnumerable<SerializablePrices>>> srcs
= Enumerable.Empty<Tuple<DateTime, IEnumerable<SerializablePrices>>>();
var today = DateTime.Today.AddDays(-1);
try {
var sdate = getExistingDataDate(en);
if (getExistingDataDate(en).Any()) {
var localMin = getExistingDataDate(en).Min();
var localMax = getExistingDataDate(en).Max();
if (sinceMin < localMin) srcs = srcs.Union(download(localMin.AddDays(-1), sinceMin, en));
if (localMax < today) srcs = srcs.Union(download(localMax.AddDays(1), today, en));
} else {
srcs = download(sinceMin, today, en);
}
foreach (var kvp in srcs) {
add(kvp.Item1, kvp.Item2.ToArray(), en);
}
} catch (WebException we) {
StockPriceManager.SetMessage(
new ManagementMessage() {
Sender = DataSource.Kdb,
Signal = MessageSignal.Error,
Message = en.ToString() + " 接続エラー発生",
Detail = we.Message,
});
} catch (CsvHelperException ce) {
StockPriceManager.SetMessage(
new ManagementMessage() {
Sender = DataSource.Kdb,
Signal = MessageSignal.Error,
Message = en.ToString() +" 解析中にエラー発生",
Detail = ce.Message,
});
}
}
}
internal static IEnumerable<SerializablePrices> Acquire(KdbData kdb, DateTime since,DateTime until,Func<SerializablePrices,bool> pred) {
var span = getExistingDataDate(kdb).SkipWhile(a => a < since).TakeWhile(a => a <= until);
foreach(var dt in span) {
var d = tryGet(dt, kdb).OfType<SerializablePrices>()
.Where(a => pred(a));
foreach (var c in d) yield return c;
}
}
internal static IEnumerable<DateTime> GetTimeLineScale() { return getExistingDataDate(KdbData.stocks); }
#region download
static IEnumerable<Tuple<DateTime,IEnumerable<SerializablePrices>>> download(DateTime start, DateTime end,KdbData type) {
Func<DateTime, DateTime, DateTime> nxt = (c, e) => {
return (c < e) ? c.AddDays(1) : (c > e) ? c.AddDays(-1) : c;
};
DateTime current = start;
do {
if (current.DayOfWeek != DayOfWeek.Saturday && current.DayOfWeek != DayOfWeek.Sunday) {
Thread.Sleep(2000);
var s = _download(current, type);
StockPriceManager.SetMessage(
DataSource.Kdb,
type.ToString() + ", " + current.ToString("yyyy-MM-dd") + ", ダウンロード完了"
);
if (!string.IsNullOrEmpty(s)) {
using (var str = new StreamReader(new MemoryStream(Encoding.UTF8.GetBytes(s))))
using (var csv = new CsvReader(str)) {
switch (type) {
case KdbData.stocks:
csv.Configuration.RegisterClassMap<StockCsvMap>();
break;
case KdbData.indices:
csv.Configuration.RegisterClassMap<IndexCsvMap>();
break;
}
var rec = csv.GetRecords<SerializablePrices>().ToArray();
foreach (var r in rec) r.Date = current;
yield return new Tuple<DateTime, IEnumerable<SerializablePrices>>(current, rec);
}
}
Thread.Sleep(3000);
}
current = nxt(current, end);
} while (current != end);
}
//WebClientを作成
static WebClient wc = new WebClient() { Encoding = Encoding.Default };
static string _download(DateTime dt,KdbData type) {
//try {
//ダウンロード元のURL
//string url = "http://k-db.com/stocks/" + dt.ToString("yyyy-MM-dd") + "?download=csv";
string url = "http://k-db.com/" + type.ToString() + "/" + dt.ToString("yyyy-MM-dd") + "?download=csv";
//データを文字列としてダウンロードする
return wc.DownloadString(url);
//} catch {
// return "";
//}
}
#endregion
#region IO
static IEnumerable<DateTime> getExistingDataDate(KdbData type) {
try {
return Directory.GetFiles(localPath + type.ToString() + Path.DirectorySeparatorChar, "*", SearchOption.AllDirectories)
.Select(a=>Path.GetFileNameWithoutExtension(a))
.Select(a => ResultWithValue.Of<string, DateTime>(DateTime.TryParse, a))
.Where(a => a.Result)
.Select(a => a.Value)
.OrderBy(a => a);
} catch (DirectoryNotFoundException) {
return new DateTime[0];
}
}
static string createFileName(DateTime date,KdbData type) {
return localPath + type.ToString() + Path.DirectorySeparatorChar + date.Year.ToString() + Path.DirectorySeparatorChar + date.ToString("yyyy-MM-dd") + ".xml";
}
static void createDirectoryIfNotFound(DateTime date, KdbData type) {
string s = localPath + type.ToString() + Path.DirectorySeparatorChar + date.Year.ToString();
if (!Directory.Exists(s)) Directory.CreateDirectory(s);
}
static void add(DateTime date, IEnumerable<SerializablePrices> table,KdbData type) {
if (!table.Any()) return;
createDirectoryIfNotFound(date, type);
string targetPath = createFileName(date, type);
try {
var seri = new XmlSerializer(typeof(SerializablePrices[]));
using (FileStream fs = new FileStream(targetPath, FileMode.Create)) {
seri.Serialize(fs, table.ToArray());
}
StockPriceManager.SetMessage(
DataSource.Kdb,
type.ToString() + ", " + date.ToString("yyyy-MM-dd") + ", 書き込み完了"
);
} catch (Exception e) {
StockPriceManager.SetMessage(new ManagementMessage() {
Sender = DataSource.Kdb,
Signal = MessageSignal.Error,
Message = type.ToString() + " " + date.ToString("yyyy-MM-dd") + " のデータの書き込みに失敗しました。",
Detail = e.Message,
});
}
}
static SerializablePrices[] tryGet(DateTime date, KdbData type) {
if (!getExistingDataDate(type).Any(a => a == date)) return new SerializablePrices[0];
try {
var deseri = new XmlSerializer(typeof(SerializablePrices[]));
using (FileStream fs = new FileStream(createFileName(date, type), FileMode.Open)) {
return deseri.Deserialize(fs) as SerializablePrices[];
}
}catch(Exception e){
StockPriceManager.SetMessage(new ManagementMessage() {
Sender = DataSource.Kdb,
Signal = MessageSignal.Error,
Message = type.ToString() + " " + date.ToString("yyyy-MM-dd") + " のデータの読み込みに失敗しました。",
Detail = e.Message
});
return new SerializablePrices[0];
}
}
#endregion IO
}
public class StockCsvMap : CsvClassMap<SerializablePrices> {
public StockCsvMap() {
Map(m => m.TickerSymbol).Index(0).TypeConverter<TickerCodeConv>();
Map(m => m.SymbolName).Index(1);
Map(m => m.Market).Index(2).Default("Unknown");
Map(m => m.OpeningPrice).Index(3).Default(0);
Map(m => m.High).Index(4).Default(0);
Map(m => m.Low).Index(5).Default(0);
Map(m => m.ClosingPrice).Index(6).Default(0);
Map(m => m.Turnover).Index(7).Default(0);
}
}
public class TickerCodeConv : DefaultTypeConverter {
public override bool CanConvertFrom(Type type) {
return type == typeof(string);
}
public override object ConvertFromString(TypeConverterOptions options, string text) {
var s = text.Split('-').FirstOrDefault();
var numberStyle = options.NumberStyle ?? System.Globalization.NumberStyles.Integer;
int i;
if (int.TryParse(s, numberStyle, options.CultureInfo, out i)) {
return i;
}
return 0;
}
}
public class IndexCsvMap : CsvClassMap<SerializablePrices> {
public IndexCsvMap() {
Map(m => m.SymbolName).Index(0);
Map(m => m.OpeningPrice).Index(1);
Map(m => m.High).Index(2);
Map(m => m.Low).Index(3);
Map(m => m.ClosingPrice).Index(4);
}
}
}
| 36.702703 | 160 | 0.667158 | [
"Apache-2.0"
] | Houzkin/Caramelia | src/Caramelia/Caramelia.Source/StockPrice/Clients/KdbClient.cs | 8,336 | C# |
// Copyright (C) 2018 Fievus
//
// This software may be modified and distributed under the terms
// of the MIT license. See the LICENSE file for details.
using Carna;
namespace Charites.Windows.Forms
{
[Specification("ListBoxItemsSource Spec")]
class ListBoxItemsSourceSpec
{
[Context]
ListBoxItemsSourceSpec_ValueNotSpecified ValueNotSpecified { get; }
[Context]
ListBoxItemsSourceSpec_ValueSpecified ValueSpecified { get; }
}
}
| 25.368421 | 75 | 0.711618 | [
"MIT"
] | averrunci/WindowsFormsMvc | Spec/WindowsFormsMvc.Spec/Forms/ListBoxItemsSourceSpec.cs | 484 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// Class for managing the Equipment of the characters.
/// </summary>
public class EquipmentManager : MonoBehaviour
{
/// Singleton instance of the EquipmentManager.
public static EquipmentManager instance;
/// UI of the Inventory.
public InventoryUI inventoryUI;
/// Delegate void for changing equipment.
public delegate void OnEquipmentChanged (Equipment newItem, Equipment oldItem);
/// Instance of delegate OnEquipmentChanged.
public OnEquipmentChanged onEquipmentChanged;
/// Array of Equipment currently equipped by the Player.
public Equipment[] currentEquipment;
void Awake ()
{
if (instance != null)
{
{
Destroy (this);
return;
}
}
instance = this;
GameObject.DontDestroyOnLoad (this);
}
void Start ()
{
int numSlots = System.Enum.GetNames (typeof (EquipmentSlot)).Length;
currentEquipment = new Equipment[numSlots];
}
/// <summary>
/// Equip the <paramref name="newItem"/> and remove any current Equipment.
/// </summary>
/// <param name="newItem">The new item to be equipped.</param>
public void Equip (Equipment newItem)
{
int slotIndex = (int) newItem.equipmentSlot;
Equipment oldItem = null;
if (currentEquipment[slotIndex] != null)
{
oldItem = currentEquipment[slotIndex];
Inventory.instance.Add (oldItem);
}
if (onEquipmentChanged != null)
{
onEquipmentChanged.Invoke (newItem, oldItem);
}
currentEquipment[slotIndex] = newItem;
inventoryUI.UpdateStats ();
}
/// <summary>
/// Unequip the Equipment located at the <paramref name="slotIndex"/>.
/// </summary>
/// </param name="slotIndex">The index pointing to the equipment slot.</param>
public void Unequip (int slotIndex)
{
if (currentEquipment[slotIndex] != null)
{
Equipment oldItem = currentEquipment[slotIndex];
Inventory.instance.Add (oldItem);
currentEquipment[slotIndex] = null;
if (onEquipmentChanged != null)
{
onEquipmentChanged.Invoke (null, oldItem);
}
}
inventoryUI.UpdateStats ();
}
/// <summary>
/// Unequip All Equipment currently equipped.
/// </summary>
public void UnequipAll ()
{
for (int i = 0; i < currentEquipment.Length; i++)
{
Unequip (i);
}
inventoryUI.UpdateStats ();
}
void Update ()
{
if (Input.GetKeyDown (KeyCode.U))
{
UnequipAll ();
}
inventoryUI.UpdateStats ();
}
} | 27.037736 | 83 | 0.586532 | [
"MIT"
] | Mahmood34/Withering | Withering/Assets/Scripts/Manager/EquipmentManager.cs | 2,868 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections;
using System.Collections.Generic;
using Microsoft.Extensions.Primitives;
namespace Microsoft.AspNetCore.Http
{
/// <summary>
/// Contains the parsed HTTP form values.
/// </summary>
public class FormCollection : IFormCollection
{
/// <summary>
/// An empty <see cref="FormCollection"/>.
/// </summary>
public static readonly FormCollection Empty = new FormCollection();
private static readonly string[] EmptyKeys = Array.Empty<string>();
private static readonly Enumerator EmptyEnumerator = new Enumerator();
// Pre-box
private static readonly IEnumerator<
KeyValuePair<string, StringValues>
> EmptyIEnumeratorType = EmptyEnumerator;
private static readonly IEnumerator EmptyIEnumerator = EmptyEnumerator;
private static IFormFileCollection EmptyFiles = new FormFileCollection();
private IFormFileCollection? _files;
private FormCollection()
{
// For static Empty
}
/// <summary>
/// Initializes a new instance of <see cref="FormCollection"/>.
/// </summary>
/// <param name="fields">The backing fields.</param>
/// <param name="files">The files associated with the form.</param>
public FormCollection(
Dictionary<string, StringValues>? fields,
IFormFileCollection? files = null
)
{
// can be null
Store = fields;
_files = files;
}
/// <summary>
/// Gets the files associated with the HTTP form.
/// </summary>
public IFormFileCollection Files
{
get => _files ?? EmptyFiles;
private set => _files = value;
}
private Dictionary<string, StringValues>? Store { get; set; }
/// <summary>
/// Get or sets the associated value from the collection as a single string.
/// </summary>
/// <param name="key">The header name.</param>
/// <returns>the associated value from the collection as a <see cref="StringValues"/>
/// or <see cref="StringValues.Empty"/> if the key is not present.</returns>
public StringValues this[string key]
{
get
{
if (Store == null)
{
return StringValues.Empty;
}
if (TryGetValue(key, out StringValues value))
{
return value;
}
return StringValues.Empty;
}
}
/// <inheritdoc />
public int Count
{
get { return Store?.Count ?? 0; }
}
/// <inheritdoc />
public ICollection<string> Keys
{
get
{
if (Store == null)
{
return EmptyKeys;
}
return Store.Keys;
}
}
/// <inheritdoc />
public bool ContainsKey(string key)
{
if (Store == null)
{
return false;
}
return Store.ContainsKey(key);
}
/// <inheritdoc />
public bool TryGetValue(string key, out StringValues value)
{
if (Store == null)
{
value = default(StringValues);
return false;
}
return Store.TryGetValue(key, out value);
}
/// <summary>
/// Returns an struct enumerator that iterates through a collection without boxing and
/// is also used via the <see cref="IFormCollection" /> interface.
/// </summary>
/// <returns>An <see cref="Enumerator" /> object that can be used to iterate through the collection.</returns>
public Enumerator GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
// Non-boxed Enumerator
return EmptyEnumerator;
}
// Non-boxed Enumerator
return new Enumerator(Store.GetEnumerator());
}
/// <summary>
/// Returns an enumerator that iterates through a collection, boxes in non-empty path.
/// </summary>
/// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator<KeyValuePair<string, StringValues>> IEnumerable<
KeyValuePair<string, StringValues>
>.GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
// Non-boxed Enumerator
return EmptyIEnumeratorType;
}
// Boxed Enumerator
return Store.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through a collection, boxes in non-empty path.
/// </summary>
/// <returns>An <see cref="IEnumerator" /> object that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
if (Store == null || Store.Count == 0)
{
// Non-boxed Enumerator
return EmptyIEnumerator;
}
// Boxed Enumerator
return Store.GetEnumerator();
}
/// <summary>
/// Enumerates a <see cref="FormCollection"/>.
/// </summary>
public struct Enumerator : IEnumerator<KeyValuePair<string, StringValues>>
{
// Do NOT make this readonly, or MoveNext will not work
private Dictionary<string, StringValues>.Enumerator _dictionaryEnumerator;
private bool _notEmpty;
internal Enumerator(Dictionary<string, StringValues>.Enumerator dictionaryEnumerator)
{
_dictionaryEnumerator = dictionaryEnumerator;
_notEmpty = true;
}
/// <summary>
/// Advances the enumerator to the next element of the <see cref="FormCollection"/>.
/// </summary>
/// <returns><see langword="true"/> if the enumerator was successfully advanced to the next element;
/// <see langword="false"/> if the enumerator has passed the end of the collection.</returns>
public bool MoveNext()
{
if (_notEmpty)
{
return _dictionaryEnumerator.MoveNext();
}
return false;
}
/// <summary>
/// Gets the element at the current position of the enumerator.
/// </summary>
public KeyValuePair<string, StringValues> Current
{
get
{
if (_notEmpty)
{
return _dictionaryEnumerator.Current;
}
return default;
}
}
/// <inheritdoc />
public void Dispose() { }
object IEnumerator.Current
{
get { return Current; }
}
void IEnumerator.Reset()
{
if (_notEmpty)
{
((IEnumerator)_dictionaryEnumerator).Reset();
}
}
}
}
}
| 32.388186 | 119 | 0.516675 | [
"Apache-2.0"
] | belav/aspnetcore | src/Http/Http/src/FormCollection.cs | 7,676 | C# |
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.Sakuracloud.Inputs
{
public sealed class PacketFilterExpressionArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The flag to allow the packet through the filter.
/// </summary>
[Input("allow")]
public Input<bool>? Allow { get; set; }
/// <summary>
/// The description of the packetFilter. The length of this value must be in the range [`1`-`512`].
/// </summary>
[Input("description")]
public Input<string>? Description { get; set; }
/// <summary>
/// A destination port number or port range used for filtering (e.g. `1024`, `1024-2048`).
/// </summary>
[Input("destinationPort")]
public Input<string>? DestinationPort { get; set; }
/// <summary>
/// The protocol used for filtering. This must be one of [`http`/`https`/`tcp`/`udp`/`icmp`/`fragment`/`ip`].
/// </summary>
[Input("protocol", required: true)]
public Input<string> Protocol { get; set; } = null!;
/// <summary>
/// A source IP address or CIDR block used for filtering (e.g. `192.0.2.1`, `192.0.2.0/24`).
/// </summary>
[Input("sourceNetwork")]
public Input<string>? SourceNetwork { get; set; }
/// <summary>
/// A source port number or port range used for filtering (e.g. `1024`, `1024-2048`).
/// </summary>
[Input("sourcePort")]
public Input<string>? SourcePort { get; set; }
public PacketFilterExpressionArgs()
{
}
}
}
| 33.892857 | 117 | 0.586407 | [
"ECL-2.0",
"Apache-2.0"
] | sacloud/pulumi-sakuracloud | sdk/dotnet/Inputs/PacketFilterExpressionArgs.cs | 1,898 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.