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 |
|---|---|---|---|---|---|---|---|---|
namespace DfuSe.Core
{
public enum DfuCommands : byte
{
DFU_DETACH = 0x00,
DFU_DNLOAD = 0x01,
DFU_UPLOAD = 0x02,
DFU_GETSTATUS = 0x03,
DFU_CLRSTATUS = 0x04,
DFU_GETSTATE = 0x05,
DFU_ABORT = 0x06,
}
}
| 19.214286 | 34 | 0.550186 | [
"MIT"
] | josesimoes/DfuSe.Net | DfuSe.Core/DfuCommands.cs | 271 | C# |
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
[assembly: InternalsVisibleTo("IntelliTect.TestTools.Console.Tests")]
| 25.428571 | 69 | 0.825843 | [
"MIT"
] | COsborn2/TestTools | IntelliTect.TestTools.Console/Properties/AssemblyInfo.cs | 180 | C# |
//=====================================================================================
// Developed by Kallebe Lins (https://github.com/kallebelins)
//=====================================================================================
// Reproduction or sharing is free! Contribute to a better world!
//=====================================================================================
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Mvp24Hours.Core.Contract.Data;
using Mvp24Hours.Infrastructure.Data.EFCore;
using Mvp24Hours.Infrastructure.Data.EFCore.Configuration;
using System;
namespace Mvp24Hours.Extensions
{
public static class EFCoreServiceExtensions
{
/// <summary>
/// Add database context
/// </summary>
public static IServiceCollection AddMvp24HoursDbContext<TDbContext>(this IServiceCollection services,
Func<IServiceProvider, TDbContext> dbFactory = null,
ServiceLifetime lifetime = ServiceLifetime.Scoped) where TDbContext : DbContext
{
if (dbFactory != null)
{
services.Add(new ServiceDescriptor(typeof(DbContext), dbFactory, lifetime));
}
else
{
services.Add(new ServiceDescriptor(typeof(DbContext), typeof(TDbContext), lifetime));
}
return services;
}
/// <summary>
/// Add repository
/// </summary>
public static IServiceCollection AddMvp24HoursRepository(this IServiceCollection services,
Action<EFCoreRepositoryOptions> options = null,
Type repository = null,
Type unitOfWork = null,
ServiceLifetime lifetime = ServiceLifetime.Scoped)
{
if (options != null)
{
services.Configure(options);
}
else
{
services.Configure<EFCoreRepositoryOptions>(options => { });
}
if (unitOfWork != null)
{
services.Add(new ServiceDescriptor(typeof(IUnitOfWork), unitOfWork, lifetime));
}
else
{
services.Add(new ServiceDescriptor(typeof(IUnitOfWork), typeof(UnitOfWork), lifetime));
}
if (repository != null)
{
services.Add(new ServiceDescriptor(typeof(IRepository<>), repository, lifetime));
}
else
{
services.Add(new ServiceDescriptor(typeof(IRepository<>), typeof(Repository<>), lifetime));
}
return services;
}
/// <summary>
/// Add repository
/// </summary>
public static IServiceCollection AddMvp24HoursRepositoryAsync(this IServiceCollection services,
Action<EFCoreRepositoryOptions> options = null,
Type repositoryAsync = null,
Type unitOfWorkAsync = null,
ServiceLifetime lifetime = ServiceLifetime.Scoped)
{
if (options != null)
{
services.Configure(options);
}
else
{
services.Configure<EFCoreRepositoryOptions>(options => { });
}
if (unitOfWorkAsync != null)
{
services.Add(new ServiceDescriptor(typeof(IUnitOfWorkAsync), unitOfWorkAsync, lifetime));
}
else
{
services.Add(new ServiceDescriptor(typeof(IUnitOfWorkAsync), typeof(UnitOfWorkAsync), lifetime));
}
if (repositoryAsync != null)
{
services.Add(new ServiceDescriptor(typeof(IRepositoryAsync<>), repositoryAsync, lifetime));
}
else
{
services.Add(new ServiceDescriptor(typeof(IRepositoryAsync<>), typeof(RepositoryAsync<>), lifetime));
}
return services;
}
}
}
| 35.078261 | 117 | 0.529995 | [
"MIT"
] | kallebelins/mvp24hours-netcore | src/Mvp24Hours.Infrastructure.Data.EFCore/Extensions/EFCoreServiceExtensions.cs | 4,034 | C# |
using Microsoft.Extensions.Hosting;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Volo.Abp;
namespace EShopOnAbp.CatalogService.HttpApi.Client.ConsoleTestApp
{
public class ConsoleTestAppHostedService : IHostedService
{
private readonly IConfiguration _configuration;
public ConsoleTestAppHostedService(IConfiguration configuration)
{
_configuration = configuration;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
using (var application = AbpApplicationFactory.Create<CatalogServiceConsoleApiClientModule>(options =>
{
options.Services.ReplaceConfiguration(_configuration);
}))
{
application.Initialize();
//var demo = application.ServiceProvider.GetRequiredService<ClientDemoService>();
//await demo.RunAsync();
application.Shutdown();
}
}
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
}
}
| 31.263158 | 114 | 0.675084 | [
"MIT"
] | 271943794/eShopOnAbp | services/catalog/test/EShopOnAbp.CatalogService.HttpApi.Client.ConsoleTestApp/ConsoleTestAppHostedService.cs | 1,188 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Coevery.Logging;
namespace Coevery.Environment {
public interface IAssemblyLoader {
Assembly Load(string assemblyName);
}
public class DefaultAssemblyLoader : IAssemblyLoader {
private readonly IEnumerable<IAssemblyNameResolver> _assemblyNameResolvers;
private readonly ConcurrentDictionary<string, Assembly> _loadedAssemblies = new ConcurrentDictionary<string, Assembly>(StringComparer.OrdinalIgnoreCase);
public DefaultAssemblyLoader(IEnumerable<IAssemblyNameResolver> assemblyNameResolvers) {
_assemblyNameResolvers = assemblyNameResolvers.OrderBy(l => l.Order);
Logger = NullLogger.Instance;
}
public ILogger Logger { get; set; }
public Assembly Load(string assemblyName) {
try {
return _loadedAssemblies.GetOrAdd(this.ExtractAssemblyShortName(assemblyName), shortName => LoadWorker(shortName, assemblyName));
}
catch (Exception e) {
Logger.Error(e, "Error loading assembly '{0}'", assemblyName);
return null;
}
}
private Assembly LoadWorker(string shortName, string fullName) {
Assembly result;
// Try loading with full name first (if there is a full name)
if (fullName != shortName) {
result = TryAssemblyLoad(fullName);
if (result != null)
return result;
}
// Try loading with short name
result = TryAssemblyLoad(shortName);
if (result != null)
return result;
// Try resolving the short name to a full name
var resolvedName = _assemblyNameResolvers.Select(r => r.Resolve(shortName)).FirstOrDefault(f => f != null);
if (resolvedName != null) {
return Assembly.Load(resolvedName);
}
// Try again so that we get the exception this time
return Assembly.Load(fullName);
}
private static Assembly TryAssemblyLoad(string name) {
try {
return Assembly.Load(name);
}
catch {
return null;
}
}
}
public static class AssemblyLoaderExtensions {
public static string ExtractAssemblyShortName(this IAssemblyLoader assemblyLoader, string fullName) {
return ExtractAssemblyShortName(fullName);
}
public static string ExtractAssemblyShortName(string fullName) {
int index = fullName.IndexOf(',');
if (index < 0)
return fullName;
return fullName.Substring(0, index);
}
}
}
| 34.95122 | 161 | 0.608863 | [
"BSD-3-Clause"
] | Coevery/Coevery-Framework | src/Coevery/Environment/IAssemblyLoader.cs | 2,868 | C# |
using System.Threading.Tasks;
namespace UnitTests.Grains
{
public class CodeGenTestPoco
{
public int SomeProperty { get; set; }
}
// This class forms a code generation test case.
// If the code generator does generate any code for the async state machine in the Product
// method, it must generate valid C# syntax. See: https://github.com/dotnet/orleans/pull/3639
public class FeaturePopulatorCodeGenTestClass : CodeGenTestPoco, FeaturePopulatorCodeGenTestClass.IFactory<int, double>
{
public interface IFactory<TInput, TOutput>
{
Task<TOutput> Product(TInput input);
}
async Task<double> IFactory<int, double>.Product(int input)
{
await Task.Delay(100);
return input;
}
}
}
| 29.888889 | 123 | 0.654275 | [
"MIT"
] | AmedeoV/orleans | test/Grains/TestGrains/MultipleGenericParameterInterfaceImpl.cs | 809 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text;
namespace ESS.Amanse.DAL
{
[Table("tblpractice")]
public class practice
{
[Key]
public long id { get; set; }
[MaxLength(150)]
public string Name { get; set; }
[MaxLength(500)]
public string Adress1 { get; set; }
[MaxLength(500)]
public string Adress2 { get; set; }
[MaxLength(50)]
public string PostCode { get; set; }
[MaxLength(150)]
public string City { get; set; }
[MaxLength(50)]
public string Phone { get; set; }
[MaxLength(150)]
public string Website { get; set; }
[MaxLength(150)]
public string Email { get; set; }
[MaxLength(500)]
public string Logo { get; set; }
public bool BlockingPassword { get; set; }
public bool BugReports { get; set; }
public DateTime BugReportTime { get; set; }
public bool sendanalyticsdata { get; set; }
public bool AllowPriviousEntry { get; set; }
public string NavigateTo { get; set; }
public string DangerZonePassword { get; set; }
}
}
| 29.651163 | 54 | 0.595294 | [
"MIT"
] | EssDevUi/AnamneseHomeDashboardApi | Anamnese/ESS.Amanse/DAL/practice.cs | 1,277 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace _2.Book_Library
{
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
}
}
| 26.090909 | 70 | 0.707317 | [
"MIT"
] | MihailDobrev/SoftUni | Tech Module/Software Technologies/11. C# ASP.NET MVC Overview- Exercises/2. Book Library/2. Book Library/Global.asax.cs | 576 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Codeless.SharePoint {
/// <summary>
/// Providers a base class that visits a CAML expression.
/// </summary>
public abstract class CamlExpressionVisitor {
/// <summary>
/// Instantiate an instance of the <see cref="CamlExpressionVisitor"/> class.
/// </summary>
public CamlExpressionVisitor() {
this.Bindings = CamlExpression.EmptyBindings;
}
/// <summary>
/// Gets the values binded to the CAML expression that is visiting.
/// </summary>
protected Hashtable Bindings { get; private set; }
/// <summary>
/// Called when visiting a sub-expression.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlExpression"/> class representing the visiting expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression Visit(CamlExpression expression) {
CommonHelper.ConfirmNotNull(expression, "expression");
switch (expression.Type) {
case CamlExpressionType.Binded:
return VisitBindedExpression((CamlBindedExpression)expression);
case CamlExpressionType.GroupBy:
return VisitGroupByExpression((CamlGroupByExpression)expression);
case CamlExpressionType.GroupByFieldRef:
return VisitGroupByFieldRefExpression((CamlGroupByFieldRefExpression)expression);
case CamlExpressionType.OrderBy:
return VisitOrderByExpression((CamlOrderByExpression)expression);
case CamlExpressionType.OrderByFieldRef:
return VisitOrderByFieldRefExpression((CamlOrderByFieldRefExpression)expression);
case CamlExpressionType.Query:
return VisitQueryExpression((CamlQueryExpression)expression);
case CamlExpressionType.ViewFields:
return VisitViewFieldsExpression((CamlViewFieldsExpression)expression);
case CamlExpressionType.ViewFieldsFieldRef:
return VisitViewFieldsFieldRefExpression((CamlViewFieldsFieldRefExpression)expression);
case CamlExpressionType.Where:
return VisitWhereExpression((CamlWhereExpression)expression);
case CamlExpressionType.WhereBinaryComparison:
return VisitWhereBinaryComparisonExpression((CamlWhereBinaryComparisonExpression)expression);
case CamlExpressionType.WhereLogical:
return VisitWhereLogicalExpression((CamlWhereLogicalExpression)expression);
case CamlExpressionType.WhereUnaryComparison:
return VisitWhereUnaryComparisonExpression((CamlWhereUnaryComparisonExpression)expression);
}
return expression;
}
/// <summary>
/// Called when visiting a CAML expression with binded values.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlBindedExpression"/> class representing the value-binded expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitBindedExpression(CamlBindedExpression expression) {
Hashtable previous = this.Bindings;
try {
this.Bindings = expression.Bindings;
CamlExpression result = Visit(expression.Expression);
if (result != expression.Expression) {
return new CamlBindedExpression(result, this.Bindings);
}
return expression;
} finally {
this.Bindings = previous;
}
}
/// <summary>
/// Called when visiting a <ViewFields/> element.
/// </summary>=
/// <param name="expression">An instance of the <see cref="CamlViewFieldsExpression"/> class representing the <ViewFields/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitViewFieldsExpression(CamlViewFieldsExpression expression) {
CommonHelper.ConfirmNotNull(expression, "expression");
return VisitExpressionList(expression);
}
/// <summary>
/// Called when visiting a <OrderBy/> element.
/// </summary>=
/// <param name="expression">An instance of the <see cref="CamlOrderByExpression"/> class representing the <OrderBy/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitOrderByExpression(CamlOrderByExpression expression) {
CommonHelper.ConfirmNotNull(expression, "expression");
return VisitExpressionList(expression);
}
/// <summary>
/// Called when visiting a <GroupBy/> element.
/// </summary>=
/// <param name="expression">An instance of the <see cref="CamlGroupByExpression"/> class representing the <GroupBy/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitGroupByExpression(CamlGroupByExpression expression) {
CommonHelper.ConfirmNotNull(expression, "expression");
return VisitExpressionList(expression);
}
/// <summary>
/// Called when visiting a <FieldRef/> expression inside a <ViewFields/> element.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlViewFieldsFieldRefExpression"/> class representing the <FieldRef/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitViewFieldsFieldRefExpression(CamlViewFieldsFieldRefExpression expression) {
return expression;
}
/// <summary>
/// Called when visiting a <FieldRef/> expression inside an <OrderBy/> element.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlOrderByFieldRefExpression"/> class representing the <FieldRef/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitOrderByFieldRefExpression(CamlOrderByFieldRefExpression expression) {
return expression;
}
/// <summary>
/// Called when visiting a <FieldRef/> expression inside a <GroupBy/> element.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlGroupByFieldRefExpression"/> class representing the <FieldRef/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitGroupByFieldRefExpression(CamlGroupByFieldRefExpression expression) {
return expression;
}
/// <summary>
/// Called when visiting a unary comparison expression inside a <Where/> element.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlWhereUnaryComparisonExpression"/> class representing the unary comparison expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitWhereUnaryComparisonExpression(CamlWhereUnaryComparisonExpression expression) {
return expression;
}
/// <summary>
/// Called when visiting a binary comparison expression inside a <Where/> element.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlWhereBinaryComparisonExpression"/> class representing the binary comparison expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitWhereBinaryComparisonExpression(CamlWhereBinaryComparisonExpression expression) {
return expression;
}
/// <summary>
/// Called when visiting a logical comparison expression inside a <Where/> element.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlWhereLogicalExpression"/> class representing the logical comparison expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitWhereLogicalExpression(CamlWhereLogicalExpression expression) {
CommonHelper.ConfirmNotNull(expression, "expression");
CamlExpression l = VisitChecked(expression.Left, CamlExpressionType.Where);
CamlExpression r = VisitChecked(expression.Right, CamlExpressionType.Where);
if (l != expression.Left || r != expression.Right) {
switch (expression.Operator) {
case CamlLogicalOperator.And:
return Caml.And(l, r);
case CamlLogicalOperator.Or:
return Caml.Or(l, r);
case CamlLogicalOperator.Not:
return Caml.Not(l);
}
throw new InvalidOperationException();
}
return expression;
}
/// <summary>
/// Called when visiting a <Where/> expression.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlWhereExpression"/> class representing the <Where/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitWhereExpression(CamlWhereExpression expression) {
CommonHelper.ConfirmNotNull(expression, "expression");
CamlExpression bodyExpression = VisitChecked(expression.Body, CamlExpressionType.Where);
if (bodyExpression != expression.Body) {
switch (bodyExpression.Type) {
case CamlExpressionType.WhereUnaryComparison:
case CamlExpressionType.WhereBinaryComparison:
case CamlExpressionType.WhereLogical:
return new CamlWhereExpression((CamlWhereComparisonExpression)bodyExpression);
case CamlExpressionType.Where:
case CamlExpressionType.Empty:
return bodyExpression;
}
throw new InvalidOperationException();
}
return expression;
}
/// <summary>
/// Called when visiting a <Query/> expression.
/// </summary>
/// <param name="expression">An instance of the <see cref="CamlQueryExpression"/> class representing the <Query/> expression.</param>
/// <returns>When overriden, returns an expression to replace the expression given in arguments.</returns>
protected virtual CamlExpression VisitQueryExpression(CamlQueryExpression expression) {
CommonHelper.ConfirmNotNull(expression, "expression");
CamlExpression x = VisitChecked(expression.Where, CamlExpressionType.Where);
CamlExpression y = VisitChecked(expression.OrderBy, CamlExpressionType.OrderBy);
CamlExpression z = VisitChecked(expression.GroupBy, CamlExpressionType.GroupBy);
if (x == Caml.False) {
return x;
}
if (x != expression.Where || y != expression.OrderBy || z != expression.GroupBy) {
return new CamlQueryExpression(x as ICamlQueryComponent<CamlWhereExpression>, y as ICamlQueryComponent<CamlOrderByExpression>, z as ICamlQueryComponent<CamlGroupByExpression>);
}
return expression;
}
private CamlExpression VisitExpressionList<T>(CamlExpressionList<T> expression) where T : CamlExpression {
CamlExpression[] src = expression.Expressions;
CamlExpression[] dst = new CamlExpression[src.Length];
Type expectedType = null;
switch (expression.Type) {
case CamlExpressionType.GroupBy:
expectedType = typeof(CamlGroupByExpression);
break;
case CamlExpressionType.OrderBy:
expectedType = typeof(CamlOrderByExpression);
break;
case CamlExpressionType.ViewFields:
expectedType = typeof(CamlViewFieldsExpression);
break;
}
for (int i = 0; i < src.Length; i++) {
dst[i] = VisitChecked(src[i], expression.Type);
}
if (!src.SequenceEqual(dst)) {
IEnumerable<CamlFieldRefExpression> fields = dst.OfType<ICamlFieldRefComponent>().SelectMany(v => v.EnumerateFieldRefExpression());
switch (expression.Type) {
case CamlExpressionType.GroupBy:
return new CamlGroupByExpression(fields.OfType<CamlGroupByFieldRefExpression>(), ((CamlGroupByExpression)(object)expression).Collapse);
case CamlExpressionType.OrderBy:
return new CamlOrderByExpression(fields.OfType<CamlOrderByFieldRefExpression>());
case CamlExpressionType.ViewFields:
return new CamlViewFieldsExpression(fields.OfType<CamlViewFieldsFieldRefExpression>());
}
}
return expression;
}
private CamlExpression VisitChecked(CamlExpression expression, CamlExpressionType expressionType) {
if (expression != null) {
CamlExpression result = Visit(expression);
if (result != expression) {
if (result == null) {
throw new InvalidOperationException(String.Format("Expected an expression of compatiable type to {0} but NULL returned.", expressionType));
}
if (result.Type != CamlExpressionType.Empty && result.Type != expression.Type) {
Type expectedType = null;
switch (expressionType) {
case CamlExpressionType.Where:
expectedType = typeof(ICamlQueryComponent<CamlWhereExpression>);
break;
case CamlExpressionType.GroupBy:
expectedType = typeof(ICamlQueryComponent<CamlWhereExpression>);
break;
case CamlExpressionType.OrderBy:
expectedType = typeof(ICamlQueryComponent<CamlWhereExpression>);
break;
case CamlExpressionType.ViewFields:
expectedType = typeof(CamlViewFieldsExpression);
break;
}
if (!result.GetType().IsOf(expectedType)) {
throw new InvalidOperationException(String.Format("Expected an expression of compatiable type to {0} but expression of type {1} returned.", expressionType, result.Type));
}
}
}
return result;
}
return null;
}
}
}
| 50.929825 | 184 | 0.70403 | [
"MIT"
] | misonou/codeless | src/Codeless.SharePoint/SharePoint/CamlExpressionVisitor.cs | 14,517 | 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 Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.Rds.Transform;
using Aliyun.Acs.Rds.Transform.V20140815;
using System.Collections.Generic;
namespace Aliyun.Acs.Rds.Model.V20140815
{
public class DescribeLogBackupFilesRequest : RpcAcsRequest<DescribeLogBackupFilesResponse>
{
public DescribeLogBackupFilesRequest()
: base("Rds", "2014-08-15", "DescribeLogBackupFiles", "rds", "openAPI")
{
}
private long? resourceOwnerId;
private string resourceOwnerAccount;
private string ownerAccount;
private int? pageSize;
private string action;
private string endTime;
private string dBInstanceId;
private string startTime;
private long? ownerId;
private int? pageNumber;
private string accessKeyId;
public long? ResourceOwnerId
{
get
{
return resourceOwnerId;
}
set
{
resourceOwnerId = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerId", value.ToString());
}
}
public string ResourceOwnerAccount
{
get
{
return resourceOwnerAccount;
}
set
{
resourceOwnerAccount = value;
DictionaryUtil.Add(QueryParameters, "ResourceOwnerAccount", value);
}
}
public string OwnerAccount
{
get
{
return ownerAccount;
}
set
{
ownerAccount = value;
DictionaryUtil.Add(QueryParameters, "OwnerAccount", value);
}
}
public int? PageSize
{
get
{
return pageSize;
}
set
{
pageSize = value;
DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString());
}
}
public string Action
{
get
{
return action;
}
set
{
action = value;
DictionaryUtil.Add(QueryParameters, "Action", value);
}
}
public string EndTime
{
get
{
return endTime;
}
set
{
endTime = value;
DictionaryUtil.Add(QueryParameters, "EndTime", value);
}
}
public string DBInstanceId
{
get
{
return dBInstanceId;
}
set
{
dBInstanceId = value;
DictionaryUtil.Add(QueryParameters, "DBInstanceId", value);
}
}
public string StartTime
{
get
{
return startTime;
}
set
{
startTime = value;
DictionaryUtil.Add(QueryParameters, "StartTime", value);
}
}
public long? OwnerId
{
get
{
return ownerId;
}
set
{
ownerId = value;
DictionaryUtil.Add(QueryParameters, "OwnerId", value.ToString());
}
}
public int? PageNumber
{
get
{
return pageNumber;
}
set
{
pageNumber = value;
DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString());
}
}
public string AccessKeyId
{
get
{
return accessKeyId;
}
set
{
accessKeyId = value;
DictionaryUtil.Add(QueryParameters, "AccessKeyId", value);
}
}
public override DescribeLogBackupFilesResponse GetResponse(Core.Transform.UnmarshallerContext unmarshallerContext)
{
return DescribeLogBackupFilesResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
} | 19.975728 | 122 | 0.640583 | [
"Apache-2.0"
] | brightness007/unofficial-aliyun-openapi-net-sdk | aliyun-net-sdk-rds/Rds/Model/V20140815/DescribeLogBackupFilesRequest.cs | 4,115 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace viewTitle
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private Form2 f2;
private void Form1_Load(object sender, EventArgs e)
{
//this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;
//this.Visible = false;
this.notifyIcon1.Visible = true;
notifyIcon1.ContextMenuStrip = contextMenuStrip1;
}
private void notifyIcon1_MouseClick(object sender, MouseEventArgs e)
{
}
private void toolStripMenuItem2_Click(object sender, EventArgs e)
{
}
private void 종료XToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Close();
}
private void 타이틀바꾸기ToolStripMenuItem_Click(object sender, EventArgs e)
{
String strTitle = "";
foreach(Form openForm in Application.OpenForms)
{
if (openForm.Name == "Form2")
{
openForm.Activate();
return;
}
}
f2 = new Form2();
f2.TextSendEvent += new Form2.Form2_EventHandler(form2_getEventhandler);
f2.Show();
}
private void form2_getEventhandler(String t)
{
this.Text = Text;
}
}
}
| 23.971014 | 84 | 0.560459 | [
"MIT"
] | Blueluby/VSStudy | viewTitle/viewTitle/Form1.cs | 1,672 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Text;
using Xfrogcn.BinaryFormatter.Serialization;
namespace Xfrogcn.BinaryFormatter
{
[DebuggerDisplay("Path:{BinaryPath()} Current: ClassType.{Current.BinaryClassInfo.ClassType}, {Current.BinaryClassInfo.Type.Name}")]
internal struct ReadStack
{
internal static readonly char[] SpecialCharacters = { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' };
private int _continuationCount;
internal byte Version { get; set; }
internal TypeMap TypeMap { get; set; }
internal Dictionary<uint, ulong> RefMap { get; set; }
internal ushort PrimaryTypeSeq { get; set; }
internal Type PrimaryType { get; set; }
internal TypeResolver TypeResolver { get; set; }
internal BinarySerializerOptions Options { get; set; }
public ReadStackFrame Current;
public bool IsContinuation => _continuationCount != 0;
public bool IsLastContinuation => _continuationCount == _count;
private int _count;
private List<ReadStackFrame> _previous;
private List<ArgumentState> _ctorArgStateCache;
/// <summary>
/// Whether we need to read ahead in the inner read loop.
/// </summary>
public bool SupportContinuation;
/// <summary>
/// Whether we can read without the need of saving state for stream and preserve references cases.
/// </summary>
public bool UseFastPath;
public long BytesConsumed;
public ReferenceResolver ReferenceResolver;
internal void ResolveTypes(BinarySerializerOptions options, Type returnType)
{
Options = options;
if( options.TypeHandler!=null)
{
TypeResolver = options.TypeHandler.CreateResolver();
}
else
{
TypeResolver = TypeHandler.DefaultTypeResolver;
}
TypeMap.ResolveTypes(TypeResolver);
PrimaryType = TypeMap.GetType(PrimaryTypeSeq);
if (PrimaryType != null)
{
if (PrimaryType.IsClass && !returnType.IsAssignableFrom(PrimaryType) )
{
PrimaryType = returnType;
}
}
else
{
PrimaryType = returnType;
}
if (PrimaryType.IsInterface || PrimaryType.IsAbstract)
{
ThrowHelper.ThrowNotSupportedException_SerializationNotSupported(PrimaryType);
}
}
public void Initialize(Type type, BinarySerializerOptions options, bool supportContinuation)
{
BinaryClassInfo binaryClassInfo = options.GetOrAddClass(type);
Current.BinaryClassInfo = binaryClassInfo;
// The initial BinaryPropertyInfo will be used to obtain the converter.
Current.BinaryPropertyInfo = binaryClassInfo.PropertyInfoForClassInfo;
Current.BinaryTypeInfo = TypeMap.GetTypeInfo(type);
Current.TypeMap = TypeMap;
if (options.ReferenceHandler != null)
{
ReferenceResolver = options.ReferenceHandler!.CreateResolver(writing: false);
}
else
{
ReferenceResolver = new ObjectReferenceResolver();
}
SupportContinuation = supportContinuation;
UseFastPath = !supportContinuation;
}
internal BinaryPropertyInfo LookupProperty(string propertyName)
{
var binaryClassInfo = Current.BinaryClassInfo;
if (binaryClassInfo.PropertyCache.ContainsKey(propertyName))
{
return binaryClassInfo.PropertyCache[propertyName];
}
return null;
}
internal BinaryMemberInfo GetMemberInfo(ushort seq)
{
if(Current.BinaryTypeInfo != null && Current.BinaryTypeInfo.MemberInfos!=null &&
Current.BinaryTypeInfo.MemberInfos.ContainsKey(seq))
{
return Current.BinaryTypeInfo.MemberInfos[seq];
}
return null;
}
private void AddCurrent()
{
if (_previous == null)
{
_previous = new List<ReadStackFrame>();
}
if (_count > _previous.Count)
{
// Need to allocate a new array element.
_previous.Add(Current);
}
else
{
// Use a previously allocated slot.
_previous[_count - 1] = Current;
}
_count++;
}
public void Push(BinaryTypeInfo typeInfo)
{
if (_continuationCount == 0)
{
if (_count == 0)
{
// The first stack frame is held in Current.
Current.BinaryTypeInfo = typeInfo;
Current.TypeMap = TypeMap;
_count = 1;
}
else
{
BinaryClassInfo binaryClassInfo;
if (Current.BinaryClassInfo.ClassType == ClassType.Object)
{
if (Current.BinaryPropertyInfo != null)
{
binaryClassInfo = Current.PolymorphicBinaryClassInfo?? Current.BinaryPropertyInfo.RuntimeClassInfo;
}
else
{
binaryClassInfo = Current.PolymorphicBinaryClassInfo ?? Current.CtorArgumentState!.BinaryParameterInfo!.RuntimeClassInfo;
}
}
else if (((ClassType.Value | ClassType.NewValue) & Current.BinaryClassInfo.ClassType) != 0)
{
// Although ClassType.Value doesn't push, a custom custom converter may re-enter serialization.
binaryClassInfo = Current.BinaryPropertyInfo!.RuntimeClassInfo;
}
else
{
Debug.Assert(((ClassType.Enumerable | ClassType.Dictionary) & Current.BinaryClassInfo.ClassType) != 0);
binaryClassInfo = Current.PolymorphicBinaryClassInfo ?? Current.BinaryClassInfo.ElementClassInfo!;
}
AddCurrent();
Current.Reset();
Current.BinaryClassInfo = binaryClassInfo;
Current.BinaryPropertyInfo = binaryClassInfo.PropertyInfoForClassInfo;
Current.BinaryTypeInfo = typeInfo;
Current.TypeMap = TypeMap;
}
}
else if (_continuationCount == 1)
{
// No need for a push since there is only one stack frame.
Debug.Assert(_count == 1);
_continuationCount = 0;
}
else
{
// A continuation; adjust the index.
Current = _previous[_count - 1];
// Check if we are done.
if (_count == _continuationCount)
{
_continuationCount = 0;
}
else
{
_count++;
}
}
SetConstructorArgumentState();
}
public void Pop(bool success)
{
Debug.Assert(_count > 0);
if (!success)
{
// Check if we need to initialize the continuation.
if (_continuationCount == 0)
{
if (_count == 1)
{
// No need for a continuation since there is only one stack frame.
_continuationCount = 1;
}
else
{
AddCurrent();
_count--;
_continuationCount = _count;
_count--;
Current = _previous[_count - 1];
}
return;
}
if (_continuationCount == 1)
{
// No need for a pop since there is only one stack frame.
Debug.Assert(_count == 1);
return;
}
// Update the list entry to the current value.
_previous[_count - 1] = Current;
Debug.Assert(_count > 0);
}
else
{
Debug.Assert(_continuationCount == 0);
}
if (_count > 1)
{
Current = _previous[--_count - 1];
}
SetConstructorArgumentState();
}
// Return a BinaryPath using simple dot-notation when possible. When special characters are present, bracket-notation is used:
// $.x.y[0].z
// $['PropertyName.With.Special.Chars']
public string BinaryPath()
{
StringBuilder sb = new StringBuilder("$");
// If a continuation, always report back full stack.
int count = Math.Max(_count, _continuationCount);
for (int i = 0; i < count - 1; i++)
{
AppendStackFrame(sb, _previous[i]);
}
if (_continuationCount == 0)
{
AppendStackFrame(sb, Current);
}
return sb.ToString();
static void AppendStackFrame(StringBuilder sb, in ReadStackFrame frame)
{
// Append the property name.
string propertyName = GetPropertyName(frame);
AppendPropertyName(sb, propertyName);
if (frame.BinaryClassInfo != null && frame.IsProcessingEnumerable())
{
IEnumerable enumerable = (IEnumerable)frame.ReturnValue;
if (enumerable == null)
{
return;
}
// For continuation scenarios only, before or after all elements are read, the exception is not within the array.
//if (frame.ObjectState == StackFrameObjectState.None ||
// frame.ObjectState == StackFrameObjectState.CreatedObject ||
// frame.ObjectState == StackFrameObjectState.ReadElements)
//{
// sb.Append('[');
// sb.Append(GetCount(enumerable));
// sb.Append(']');
//}
}
}
//static int GetCount(IEnumerable enumerable)
//{
// if (enumerable is ICollection collection)
// {
// return collection.Count;
// }
// int count = 0;
// IEnumerator enumerator = enumerable.GetEnumerator();
// while (enumerator.MoveNext())
// {
// count++;
// }
// return count;
//}
static void AppendPropertyName(StringBuilder sb, string propertyName)
{
if (propertyName != null)
{
if (propertyName.IndexOfAny(SpecialCharacters) != -1)
{
sb.Append(@"['");
sb.Append(propertyName);
sb.Append(@"']");
}
else
{
sb.Append('.');
sb.Append(propertyName);
}
}
}
static string GetPropertyName(in ReadStackFrame frame)
{
string propertyName = null;
// Attempt to get the Binary property name from the frame.
byte[] utf8PropertyName = frame.BinaryPropertyName;
if (utf8PropertyName == null)
{
if (frame.BinaryPropertyNameAsString != null)
{
// Attempt to get the Binary property name set manually for dictionary
// keys and KeyValuePair property names.
propertyName = frame.BinaryPropertyNameAsString;
}
else
{
utf8PropertyName = frame.BinaryPropertyInfo.NameAsUtf8Bytes ??
frame.CtorArgumentState?.BinaryParameterInfo?.NameAsUtf8Bytes;
}
}
if (utf8PropertyName != null)
{
propertyName = BinaryReaderHelper.TranscodeHelper(utf8PropertyName);
}
return propertyName;
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void SetConstructorArgumentState()
{
if (Current.BinaryClassInfo.ParameterCount > 0)
{
// A zero index indicates a new stack frame.
if (Current.CtorArgumentStateIndex == 0)
{
if (_ctorArgStateCache == null)
{
_ctorArgStateCache = new List<ArgumentState>();
}
var newState = new ArgumentState();
_ctorArgStateCache.Add(newState);
(Current.CtorArgumentStateIndex, Current.CtorArgumentState) = (_ctorArgStateCache.Count, newState);
}
else
{
Current.CtorArgumentState = _ctorArgStateCache![Current.CtorArgumentStateIndex - 1];
}
}
}
}
}
| 33.740566 | 175 | 0.485391 | [
"MIT"
] | xfrogcn/Xfrogcn.BinaryFormatter | src/BinaryFormatter/Serialization/ReadStack.cs | 14,308 | C# |
/***
*
* Copyright (c) 1996-2001, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* This source code contains proprietary and confidential information of
* Valve LLC and its suppliers. Access to this code is restricted to
* persons who have executed a written SDK license with Valve. Any access,
* use or distribution of this code by or to any unlicensed person is illegal.
*
****/
using System.Xml.Serialization;
namespace GoldSource.Shared.Engine.Config
{
public sealed class ModAssemblyInfo
{
[XmlAttribute]
public string AssemblyName { get; set; }
}
}
| 28.846154 | 79 | 0.713333 | [
"Unlicense"
] | UAVXP/SharpLife-Wrapper | src/GoldSource.Shared/Engine/Config/ModAssemblyInfo.cs | 752 | C# |
using System.IO;
namespace TeleSharp.TL
{
[TLObject(512535275)]
public class TLPostAddress : TLObject
{
public override int Constructor
{
get
{
return 512535275;
}
}
public string StreetLine1 { get; set; }
public string StreetLine2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string CountryIso2 { get; set; }
public string PostCode { get; set; }
public void ComputeFlags()
{
}
public override void DeserializeBody(BinaryReader br)
{
StreetLine1 = StringUtil.Deserialize(br);
StreetLine2 = StringUtil.Deserialize(br);
City = StringUtil.Deserialize(br);
State = StringUtil.Deserialize(br);
CountryIso2 = StringUtil.Deserialize(br);
PostCode = StringUtil.Deserialize(br);
}
public override void SerializeBody(BinaryWriter bw)
{
bw.Write(Constructor);
StringUtil.Serialize(StreetLine1, bw);
StringUtil.Serialize(StreetLine2, bw);
StringUtil.Serialize(City, bw);
StringUtil.Serialize(State, bw);
StringUtil.Serialize(CountryIso2, bw);
StringUtil.Serialize(PostCode, bw);
}
}
}
| 26.769231 | 61 | 0.561782 | [
"MIT"
] | cobra91/TelegramCSharpForward | TeleSharp.TL/TL/TLPostAddress.cs | 1,392 | C# |
using MinecraftMappings.Internal.Models.Block;
namespace MinecraftMappings.Minecraft.Java.Models.Block
{
public class BirchSapling : JavaBlockModel
{
public BirchSapling() : base("Birch Sapling")
{
AddVersion("birch_sapling", "1.0.0")
.WithPath("models/block")
.WithParent("block/cross")
.AddTexture("cross", "block/birch_sapling");
}
}
}
| 27.3125 | 60 | 0.594966 | [
"MIT"
] | null511/MinecraftMappings.NET | MinecraftMappings.NET/Minecraft/Java/Models/Block/BirchSapling.cs | 439 | C# |
using System;
using System.Collections.Generic;
using System.Net.Http.Headers;
using KeyPayV2.Nz.Models.Common;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json;
using KeyPayV2.Nz.Enums;
namespace KeyPayV2.Nz.Models.Ess
{
public class NzFeaturesModel
{
public bool AllowEmployeeKiwiSaverSelfService { get; set; }
public bool AllowEmployeeLeaveSelfService { get; set; }
public bool AllowEmployeeSelfEditing { get; set; }
public bool AllowEmployeeTimesheetsSelfService { get; set; }
public bool AllowEmployeeToSetUnavailability { get; set; }
public bool AllowEmployeeToDeclineShifts { get; set; }
public bool AllowEmployeeBankAccountSelfService { get; set; }
public bool AllowEmployeeSatisfactionSurvey { get; set; }
public bool AllowEmployeesToViewAllApprovedLeave { get; set; }
public int UnavailabilityCutOff { get; set; }
public bool AllowEmployeesToUploadProfilePicture { get; set; }
public bool AllowEmployeeRosteringSelfService { get; set; }
public bool AllowEmployeeExpensesSelfService { get; set; }
public bool AllowEmployeeOverrideTaxCodes { get; set; }
public bool AllowEmployeesToEditKioskTimesheets { get; set; }
[JsonConverter(typeof(StringEnumConverter))]
public ESSTimesheetSetting EssTimesheetSetting { get; set; }
public bool EmployeeMustAcceptShifts { get; set; }
public bool AllowEmployeeTimesheetsWithoutStartStopTimes { get; set; }
public bool AllowEmployeeToSwapShifts { get; set; }
public bool ClockOnRequirePhoto { get; set; }
public bool ClockOnAllowEmployeeShiftSelection { get; set; }
public int? ClockOnWindowMinutes { get; set; }
public int? ClockOffWindowMinutes { get; set; }
public bool TimesheetsRequireLocation { get; set; }
public bool TimesheetsRequireWorkType { get; set; }
public bool EnableWorkZoneClockOn { get; set; }
public bool ShiftBidding { get; set; }
public bool AllowToSelectHigherClassification { get; set; }
}
}
| 49 | 79 | 0.696197 | [
"MIT"
] | KeyPay/keypay-dotnet-v2 | src/keypay-dotnet/Nz/Models/Ess/NzFeaturesModel.cs | 2,156 | C# |
using System;
namespace CommunityPlugin.Objects.Interface
{
public interface ILoanClosing
{
void LoanClosing(object sender, EventArgs e);
}
}
| 16.4 | 53 | 0.70122 | [
"MIT"
] | BPenPen/CommunityPlugin-1 | CommunityPlugin/Objects/Interface/ILoanClosing.cs | 166 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
namespace Microsoft.Telepathy.ServiceBroker.BrokerQueue
{
using System;
/// <summary>
/// the async token class.
/// </summary>
internal class BrokerQueueAsyncToken
{
#region private fields
/// <summary>
/// the broker queue.
/// </summary>
private BrokerQueue queueField;
/// <summary>
/// the async state related to the request.
/// </summary>
private object asyncStateField;
/// <summary>
/// the async token related with the persisted request.
/// </summary>
private object asyncTokenField;
/// <summary>the disapathed number of the related request.</summary>
private int dispatchNumberField;
/// <summary>
/// Stores the total try count
/// </summary>
private int tryCount;
/// <summary>
/// the persist id.
/// </summary>
private Guid persistIdField;
#endregion
/// <summary>
/// Initializes a new instance of the BrokerQueueAsyncToken class,
/// </summary>
/// <param name="persistId">the persist id.</param>
/// <param name="asyncState">the async state.</param>
/// <param name="asyncToken">the async toekn.</param>
/// <param name="dispatchNumber">the dispatch number of the request.</param>
public BrokerQueueAsyncToken(Guid persistId, object asyncState, object asyncToken, int dispatchNumber)
{
this.persistIdField = persistId;
this.asyncStateField = asyncState;
this.asyncTokenField = asyncToken;
this.dispatchNumberField = dispatchNumber;
}
/// <summary>
/// Gets the persist id.
/// </summary>
public Guid PersistId
{
get
{
return this.persistIdField;
}
}
/// <summary>
/// Gets or sets the broker queue.
/// </summary>
public BrokerQueue Queue
{
get
{
return this.queueField;
}
set
{
this.queueField = value;
}
}
/// <summary>
/// Gets or sets the async token object
/// </summary>
public object AsyncToken
{
get
{
return this.asyncTokenField;
}
set
{
this.asyncTokenField = value;
}
}
/// <summary>
/// Gets the async state object.
/// </summary>
public object AsyncState
{
get
{
return this.asyncStateField;
}
}
/// <summary>
/// Gets or sets the dispatched number of the related request message.
/// </summary>
internal int DispatchNumber
{
get
{
return this.dispatchNumberField;
}
set
{
this.dispatchNumberField = value;
}
}
/// <summary>
/// Gets or sets the total try count of this broker queue item
/// </summary>
internal int TryCount
{
get { return this.tryCount; }
set { this.tryCount = value; }
}
}
}
| 25.34058 | 110 | 0.492994 | [
"MIT"
] | dubrie/Telepathy | src/soa/CcpWSLB/BrokerQueue/BrokerQueueAsyncToken.cs | 3,499 | C# |
using ESRI.ArcGIS.Client;
using ESRI.ArcGIS.Client.Geometry;
using ESRI.ArcGIS.Client.Tasks;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Resources;
namespace ESRIStandardMapApplication7
{
public partial class MainPage : UserControl
{
//the path to the image
string pathToFile = "http://csc-nhaney7d.esri.com/images/Cooper.jpg";
//extension used by the world file
string worldFileExtention = ".jgw";
double imageHeight;
double imageWidth;
ElementLayer myElementLayer;
Image image;
public MainPage()
{
InitializeComponent();
}
private void WorldFileLoaded(object sender, DownloadStringCompletedEventArgs e)
{
//Checks to see if there was an error
if (e.Error == null)
{
//grab the data from the world file
string myData = e.Result;
//split string into an array based on new line characters
string[] lines = myData.Split(new string[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries);
//convert the strings into doubles
double[] coordValues = new double[6];
for(int i = 0; i < 6; i++) {
coordValues[i] = Convert.ToDouble(lines[i]);
}
//calculate the pixel height and width in real world coordinates
double pixelWidth = Math.Sqrt(Math.Pow(coordValues[0], 2) + Math.Pow(coordValues[1], 2));
double pixelHeight = Math.Sqrt(Math.Pow(coordValues[2], 2) + Math.Pow(coordValues[3], 2));
//Create a map point for the top left and bottom right
MapPoint topLeft = new MapPoint(coordValues[4], coordValues[5]);
MapPoint bottomRight = new MapPoint(coordValues[4] + (pixelWidth * imageWidth), coordValues[5] + (pixelHeight * imageHeight));
//create an envelope for the elmently layer
Envelope extent = new Envelope(topLeft.X, topLeft.Y, bottomRight.X, bottomRight.Y);
ElementLayer.SetEnvelope(image, extent);
//Zoom to the extent of the image
MyMap.Extent = extent;
}
}
//Wait for the element layer to initialize
private void ElementLayer_Initialized(object sender, EventArgs e)
{
//Grab the element layer
myElementLayer = MyMap.Layers["ElementLayer"] as ElementLayer;
//Create a new bitmap image from the image file
BitmapImage bitImage = new BitmapImage(new Uri(pathToFile));
//When the image has successfully been opened
bitImage.ImageOpened += (sender1, e1) =>
{
//grab the image height and width
imageHeight = bitImage.PixelHeight;
imageWidth = bitImage.PixelWidth;
//Create a new web client to send the request for the world file
WebClient myClient = new WebClient();
//The event handler for when the world file has been loaded
myClient.DownloadStringCompleted += new DownloadStringCompletedEventHandler(WorldFileLoaded);
//Replaces the .jpg extension with the .jgw extension
String pathToWorldFile = (pathToFile.Remove(pathToFile.Length - 4, 4)) + worldFileExtention;
//Download the world file
myClient.DownloadStringAsync(new Uri(pathToWorldFile));
};
//Create a new image element
image = new Image();
image.Source = bitImage;
//Set the envelope for the image. Note the extent is merely a placeholder, we will replace it in a momment.
ElementLayer.SetEnvelope(image, new Envelope(100, 100, 100, 100));
//Add the image to element layer
myElementLayer.Children.Add(image);
}
}
}
| 44.542553 | 142 | 0.607356 | [
"Apache-2.0"
] | Esri/developer-support | web-sl/display-image-with-world-file/MainPage.xaml.cs | 4,189 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GISModel.Enums
{
public enum ESeveridadeSeg
{
// Diária, com necessidade frequente de horas extras
[Display(Name = "Muito Alta")]
Muito_Alta = 1,
//Diária
[Display(Name = "Alta")]
Alta = 2,
//Semanal
[Display(Name = "Média")]
Media = 3,
// Mensal
[Display(Name = "Baixa")]
Baixa = 4,
// Semestral
[Display(Name = "Muito Baixa")]
Muito_Baixa = 5
}
}
| 17.447368 | 60 | 0.571644 | [
"Apache-2.0"
] | tonihenriques/SesmtTecnologico02 | SESTEC/GISModel/Enums/ESeveridadeSeg.cs | 668 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Repository.Entities
{
public class PartyMaster
{
public int Sr { get; }
[Key]
public string Id { get; set; }
public string CompanyId { get; set; }
public string BrokerageId { get; set; }
public int Type { get; set; }
public int SubType { get; set; }
public string Name { get; set; }
public string ShortName { get; set; }
public string EmailId { get; set; }
public string Address { get; set; }
public string Address2 { get; set; }
public string MobileNo { get; set; }
public string OfficeNo { get; set; }
public string GSTNo { get; set; }
public string AadharCardNo { get; set; }
public string PancardNo { get; set; }
[Column(TypeName = "decimal(18, 4)")]
public decimal OpeningBalance { get; set; }
public bool IsDelete { get; set; }
public bool Status { get; set; }
public DateTime CreatedDate { get; set; }
public DateTime? UpdatedDate { get; set; }
public string CreatedBy { get; set; }
public string UpdatedBy { get; set; }
[ForeignKey("CompanyId")]
public virtual CompanyMaster CompanyMaster { get; set; }
}
}
| 35.076923 | 64 | 0.599415 | [
"Apache-2.0"
] | infologs/DTSolutions | src/BuildingBlocks/EFCore.Support/Repository.Entities/PartyMaster.cs | 1,370 | C# |
using Abp.MultiTenancy;
using Abp.Zero.Configuration;
namespace HappyKids.Parties.Authorization.Roles
{
public static class AppRoleConfig
{
public static void Configure(IRoleManagementConfig roleManagementConfig)
{
// Static host roles
roleManagementConfig.StaticRoles.Add(
new StaticRoleDefinition(
StaticRoleNames.Host.Admin,
MultiTenancySides.Host
)
);
// Static tenant roles
roleManagementConfig.StaticRoles.Add(
new StaticRoleDefinition(
StaticRoleNames.Tenants.Admin,
MultiTenancySides.Tenant
)
);
}
}
}
| 25.566667 | 80 | 0.554107 | [
"MIT"
] | marcosmoski/HappyKidsSite | src/HappyKids.Parties.Core/Authorization/Roles/AppRoleConfig.cs | 769 | C# |
using UnityEngine;
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
[AddComponentMenu( "Daikon Forge/Examples/Game Menu/Achievements Grid" )]
[Serializable]
public class DemoAchievementsGrid : MonoBehaviour
{
#region Public events
public delegate void SelectionChangedHandler( DemoAchievementInfo item );
public event SelectionChangedHandler SelectionChanged;
#endregion
#region Public serialized fields
public List<DemoAchievementInfo> Items = new List<DemoAchievementInfo>();
public dfDataObjectProxy SelectedItemProxy;
#endregion
#region Private variables
private bool isGridPopulated = false;
private List<dfControl> rows = new List<dfControl>();
private bool showAll = true;
private bool showAsGrid = false;
#endregion
#region Public properties
public DemoAchievementInfo SelectedItem { get; private set; }
#endregion
#region Unity events
void Awake() { }
void OnEnable() { }
void Start()
{
var container = GetComponent<dfControl>();
if( container == null )
return;
container = container.GetRootContainer();
container.EnterFocus += ( sender, args ) =>
{
StartCoroutine( PopulateGrid() );
};
container.LeaveFocus += ( sender, args ) =>
{
StopAllCoroutines();
isGridPopulated = false;
for( int i = 0; i < rows.Count; i++ )
{
rows[ i ].RemoveAllEventHandlers();
dfPoolManager.Pool[ "Achievement" ].Despawn( rows[ i ].gameObject );
}
rows.Clear();
};
ExpandAll();
}
#endregion
#region Public methods
public void ToggleShowAll()
{
this.showAll = !this.showAll;
for( int i = 0; i < rows.Count; i++ )
{
var item = Items[ i ];
var row = rows[ i ];
row.IsVisible = item.Unlocked || showAll;
}
rows.First( r => r.IsVisible ).Focus();
var grid = GetComponent<dfScrollPanel>();
grid.Reset();
}
public void ExpandAll()
{
showAsGrid = false;
for( int i = 0; i < rows.Count; i++ )
{
var item = rows[ i ].GetComponent<DemoAchievementListItem>();
item.Expand();
}
var grid = GetComponent<dfScrollPanel>();
grid.Parent.Find<dfSprite>( "grid-style" ).Opacity = 0.5f;
grid.Parent.Find<dfSprite>( "list-style" ).Opacity = 1f;
if( rows.Count > 0 )
{
rows.First( r => r.IsVisible ).Focus();
grid.Reset();
}
}
public void CollapseAll()
{
showAsGrid = true;
for( int i = 0; i < rows.Count; i++ )
{
var item = rows[ i ].GetComponent<DemoAchievementListItem>();
item.Collapse();
}
var grid = GetComponent<dfScrollPanel>();
grid.Parent.Find<dfSprite>( "grid-style" ).Opacity = 1f;
grid.Parent.Find<dfSprite>( "list-style" ).Opacity = 0.5f;
rows.First( r => r.IsVisible ).Focus();
grid.Reset();
}
#endregion
#region Private utility methods
private IEnumerator PopulateGrid()
{
if( isGridPopulated )
yield break;
isGridPopulated = true;
if( Items.Count == 0 )
yield break;
var container = GetComponent<dfControl>();
if( container == null )
yield break;
for( int i = 0; i < Items.Count; i++ )
{
yield return null;
var item = Items[ i ];
var rowGO = dfPoolManager.Pool[ "Achievement" ].Spawn( false );
rowGO.hideFlags = HideFlags.DontSave;
rowGO.transform.parent = container.transform;
rowGO.gameObject.SetActive( true );
var row = rowGO.GetComponent<dfControl>();
row.ZOrder = rows.Count;
row.Show();
rows.Add( row );
var itemIndex = i;
initializeRowEvents( item, row, itemIndex );
if( !( showAll || item.Unlocked ) )
{
row.Hide();
}
var listItem = row.GetComponent<DemoAchievementListItem>();
listItem.Bind( item );
if( !showAsGrid )
{
listItem.Expand();
}
if( i == 0 )
{
row.Focus();
}
}
}
private void initializeRowEvents( DemoAchievementInfo item, dfControl row, int itemIndex )
{
//row.MouseEnter += ( sender, args ) => { row.Focus(); };
row.EnterFocus += ( sender, args ) =>
{
this.SelectedItem = item;
if( SelectionChanged != null ) SelectionChanged( item );
if( SelectedItemProxy != null ) SelectedItemProxy.Data = item;
};
row.KeyDown += ( sender, args ) =>
{
if( args.Used )
return;
if( args.KeyCode == KeyCode.RightArrow )
{
selectNext( itemIndex );
args.Use();
}
else if( args.KeyCode == KeyCode.LeftArrow )
{
selectPrevious( itemIndex );
args.Use();
}
else if( args.KeyCode == KeyCode.UpArrow )
{
selectUp( itemIndex );
args.Use();
}
else if( args.KeyCode == KeyCode.DownArrow )
{
selectDown( itemIndex );
args.Use();
}
else if( args.KeyCode == KeyCode.Home )
{
selectFirst();
args.Use();
}
else if( args.KeyCode == KeyCode.End )
{
selectLast();
args.Use();
}
};
}
private int getColumnCount()
{
var container = GetComponent<dfScrollPanel>();
var horz = Mathf.CeilToInt( container.Width - container.FlowPadding.horizontal - container.ScrollPadding.horizontal );
var columns = horz / Mathf.CeilToInt( rows[ 0 ].Width );
return columns;
}
private void selectLast()
{
var row = rows.LastOrDefault( control => control.IsEnabled && control.IsVisible );
if( row != null )
{
row.Focus();
}
}
private void selectFirst()
{
var row = rows.FirstOrDefault( control => control.IsEnabled && control.IsVisible );
if( row != null )
{
row.Focus();
}
}
private void selectUp( int index )
{
var columns = getColumnCount();
if( index >= columns )
{
rows[ index - columns ].Focus();
return;
}
}
private void selectDown( int index )
{
var columns = getColumnCount();
if( index <= rows.Count - columns - 1 )
{
rows[ index + columns ].Focus();
return;
}
}
private void selectPrevious( int index )
{
while( --index >= 0 )
{
if( rows[ index ].IsEnabled && rows[ index ].IsVisible )
{
rows[ index ].Focus();
return;
}
}
}
private void selectNext( int index )
{
while( ++index < rows.Count )
{
if( rows[ index ].IsEnabled && rows[ index ].IsVisible )
{
rows[ index ].Focus();
return;
}
}
}
#endregion
}
| 17.551429 | 120 | 0.632102 | [
"Apache-2.0"
] | takemurakimio/missing-part-1 | Assets/Daikon Forge/Examples/Game Menu/Scripts/DemoAchievementsGrid.cs | 6,143 | C# |
using Bookkeeping.Common.Exceptions;
using Bookkeeping.Common.Interfaces;
using System;
using System.IO;
using System.Threading.Tasks;
using System.Web.Mvc;
namespace Bookkeeping.WebUi.Controllers
{
public class BaseController : Controller
{
protected readonly ILogger _logger;
public BaseController(ILogger logger)
{
_logger = logger;
}
protected async Task<JsonResult> RunWithResult(Func<Task<object>> func, string errorMessage)
{
try
{
return new JsonResult
{
Data = new
{
data = await func()
},
MaxJsonLength = Int32.MaxValue
};
}
catch(SessionExpiredException ex)
{
_logger.Error("Время сессии истекло", ex);
return new JsonResult
{
Data = new
{
error = ex.Message,
redirectUrl = Url.Action("logout", "account")
}
};
}
catch (PublicException ex)
{
_logger.Error(errorMessage, ex);
return new JsonResult
{
Data = new
{
error = ex.Message
}
};
}
catch (Exception ex)
{
_logger.Error(errorMessage, ex);
return new JsonResult
{
Data = new
{
error = errorMessage
}
};
}
}
protected async Task<JsonResult> Run(Func<Task> func, string errorMessage)
{
try
{
await func();
return new JsonResult
{
Data = new
{
data = string.Empty
}
};
}
catch (SessionExpiredException ex)
{
_logger.Error("Время сессии истекло", ex);
return new JsonResult
{
Data = new
{
error = ex.Message,
redirectUrl = Url.Action("logout", "account")
}
};
}
catch (PublicException ex)
{
_logger.Error(errorMessage, ex);
return new JsonResult
{
Data = new
{
error = ex.Message
}
};
}
catch (Exception ex)
{
_logger.Error(errorMessage, ex);
return new JsonResult
{
Data = new
{
error = errorMessage
}
};
}
}
protected string RenderViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
}
} | 29.886364 | 100 | 0.387579 | [
"MIT"
] | zhuchenko-w/legal-entities-checker | Bookkeeping.WebUI/Controllers/BaseController.cs | 3,983 | C# |
using System;
using System.Collections.Generic;
public class PriorityQueue<T>
{
// I'm using an unsorted array for this example, but ideally this
// would be a binary heap. There's an open issue for adding a binary
// heap to the standard C# library: https://github.com/dotnet/corefx/issues/574
//
// Until then, find a binary heap class:
// * https://github.com/BlueRaja/High-Speed-Priority-Queue-for-C-Sharp
// * http://visualstudiomagazine.com/articles/2012/11/01/priority-queues-with-c.aspx
// * http://xfleury.github.io/graphsearch.html
// * http://stackoverflow.com/questions/102398/priority-queue-in-net
private List<Tuple<T, double>> elements = new List<Tuple<T, double>>();
public int Count
{
get { return elements.Count; }
}
public void Enqueue(T item, double priority)
{
elements.Add(Tuple.Create(item, priority));
}
public T Dequeue()
{
int bestIndex = 0;
for (int i = 0; i < elements.Count; i++)
{
if (elements[i].Item2 < elements[bestIndex].Item2)
{
bestIndex = i;
}
}
T bestItem = elements[bestIndex].Item1;
elements.RemoveAt(bestIndex);
return bestItem;
}
} | 29.113636 | 88 | 0.612802 | [
"Apache-2.0"
] | adidinchuk/GMTK-2021 | Assets/Scripts/Search/PriorityQueue.cs | 1,283 | 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.Resources.V20191001
{
public static class GetDeploymentAtTenantScope
{
/// <summary>
/// Deployment information.
/// </summary>
public static Task<GetDeploymentAtTenantScopeResult> InvokeAsync(GetDeploymentAtTenantScopeArgs args, InvokeOptions? options = null)
=> Pulumi.Deployment.Instance.InvokeAsync<GetDeploymentAtTenantScopeResult>("azure-nextgen:resources/v20191001:getDeploymentAtTenantScope", args ?? new GetDeploymentAtTenantScopeArgs(), options.WithVersion());
}
public sealed class GetDeploymentAtTenantScopeArgs : Pulumi.InvokeArgs
{
/// <summary>
/// The name of the deployment.
/// </summary>
[Input("deploymentName", required: true)]
public string DeploymentName { get; set; } = null!;
public GetDeploymentAtTenantScopeArgs()
{
}
}
[OutputType]
public sealed class GetDeploymentAtTenantScopeResult
{
/// <summary>
/// The ID of the deployment.
/// </summary>
public readonly string Id;
/// <summary>
/// the location of the deployment.
/// </summary>
public readonly string? Location;
/// <summary>
/// The name of the deployment.
/// </summary>
public readonly string Name;
/// <summary>
/// Deployment properties.
/// </summary>
public readonly Outputs.DeploymentPropertiesExtendedResponse Properties;
/// <summary>
/// Deployment tags
/// </summary>
public readonly ImmutableDictionary<string, string>? Tags;
/// <summary>
/// The type of the deployment.
/// </summary>
public readonly string Type;
[OutputConstructor]
private GetDeploymentAtTenantScopeResult(
string id,
string? location,
string name,
Outputs.DeploymentPropertiesExtendedResponse properties,
ImmutableDictionary<string, string>? tags,
string type)
{
Id = id;
Location = location;
Name = name;
Properties = properties;
Tags = tags;
Type = type;
}
}
}
| 29.793103 | 221 | 0.608025 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/Resources/V20191001/GetDeploymentAtTenantScope.cs | 2,592 | C# |
using System;
using Screna;
using System.Drawing;
namespace Captura.Models
{
public class WindowItem : NotifyPropertyChanged, IVideoItem
{
public IWindow Window { get; }
public WindowItem(IWindow Window)
{
this.Window = Window;
Name = Window.Title;
}
public override string ToString() => Name;
public string Name { get; }
public IImageProvider GetImageProvider(bool IncludeCursor, out Func<Point, Point> Transform)
{
if (!Window.IsAlive)
{
throw new WindowClosedException();
}
return new WindowProvider(Window, IncludeCursor, out Transform);
}
}
} | 23.419355 | 100 | 0.584022 | [
"MIT"
] | ClsTe/CapturaKorean | src/Screna/VideoItems/WindowItem.cs | 728 | C# |
using Android.Support.V7.Widget;
using AView = Android.Views.View;
namespace Xamarin.Forms.Platform.Android
{
internal abstract class EdgeSnapHelper : NongreedySnapHelper
{
protected static OrientationHelper CreateOrientationHelper(RecyclerView.LayoutManager layoutManager)
{
return layoutManager.CanScrollHorizontally()
? OrientationHelper.CreateHorizontalHelper(layoutManager)
: OrientationHelper.CreateVerticalHelper(layoutManager);
}
protected static bool IsLayoutReversed(RecyclerView.LayoutManager layoutManager)
{
if (layoutManager is LinearLayoutManager linearLayoutManager)
{
return linearLayoutManager.ReverseLayout;
}
return false;
}
protected int[] CalculateDistanceToFinalSnap(RecyclerView.LayoutManager layoutManager, AView targetView,
int direction = 1)
{
var orientationHelper = CreateOrientationHelper(layoutManager);
var isHorizontal = layoutManager.CanScrollHorizontally();
var rtl = isHorizontal && IsLayoutReversed(layoutManager);
var size = orientationHelper.GetDecoratedMeasurement(targetView);
var hiddenPortion = size - VisiblePortion(targetView, orientationHelper, rtl);
var distance = (rtl ? hiddenPortion : -hiddenPortion) * direction;
return isHorizontal
? new[] { distance, 1 }
: new[] { 1, distance };
}
protected bool IsAtLeastHalfVisible(AView view, RecyclerView.LayoutManager layoutManager)
{
var orientationHelper = CreateOrientationHelper(layoutManager);
var reversed = IsLayoutReversed(layoutManager);
var isHorizontal = layoutManager.CanScrollHorizontally();
// Find the size of the view (including margins, etc.)
var size = orientationHelper.GetDecoratedMeasurement(view);
var portionInViewPort = VisiblePortion(view, orientationHelper, reversed && isHorizontal);
// Is the first visible view at least halfway on screen?
return portionInViewPort >= size / 2;
}
protected abstract int VisiblePortion(AView view, OrientationHelper orientationHelper, bool rtl);
}
} | 33.883333 | 107 | 0.772258 | [
"MIT"
] | AlfonChitoSalano/Xamarin.Forms | Xamarin.Forms.Platform.Android/CollectionView/EdgeSnapHelper.cs | 2,033 | C# |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* 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
* 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.
*
*/
namespace ASC.Web.Core
{
public class AddonContext : WebItemContext
{
}
}
| 30.125 | 76 | 0.706777 | [
"Apache-2.0"
] | jeanluctritsch/CommunityServer | web/core/ASC.Web.Core/AddonContext.cs | 723 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.ComponentModel;
namespace A_Friend.CustomControls
{
internal class ToggleButton : CheckBox
{
private Color onBackColor = Color.MediumSlateBlue;
private Color onToggleColor = Color.WhiteSmoke;
private Color offBackColor = Color.Gray;
private Color offToggleColor = Color.Gainsboro;
private bool solidStyle = true;
public ToggleButton()
{
this.MinimumSize = new Size(80, 40);
}
public Color OnBackColor
{
get { return onBackColor; }
set
{
onBackColor = value;
this.Invalidate();
}
}
public Color OnToggleColor
{
get { return onToggleColor; }
set
{
onToggleColor = value;
this.Invalidate();
}
}
public Color OffBackColor
{
get { return offBackColor; }
set
{
offBackColor = value;
this.Invalidate();
}
}
public Color OffToggleColor
{
get { return offToggleColor; }
set
{
offToggleColor = value;
this.Invalidate();
}
}
[Browsable(false)]
public override string Text
{
get { return base.Text; }
set { }
}
[DefaultValue(true)]
public bool SolidStyle
{
get { return solidStyle; }
set
{
solidStyle = value;
this.Invalidate();
}
}
private GraphicsPath GetFigurePath()
{
int arcSize = this.Height - 1;
Rectangle leftArc = new Rectangle(1, 1, arcSize, arcSize - 3);
Rectangle rightArc = new Rectangle(this.Width - arcSize - 2, 1, arcSize, arcSize - 3);
GraphicsPath path = new GraphicsPath();
path.StartFigure();
path.AddArc(leftArc, 90, 180);
path.AddArc(rightArc, 270, 180);
path.CloseFigure();
return path;
}
protected override void OnPaint(PaintEventArgs pevent)
{
int toggleSize = this.Height - 10;
pevent.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
pevent.Graphics.Clear(this.Parent.BackColor);
if (this.Checked) //ON
{
if (solidStyle)
pevent.Graphics.FillPath(new SolidBrush(onBackColor), GetFigurePath());
else pevent.Graphics.DrawPath(new Pen(onBackColor, 2), GetFigurePath());
pevent.Graphics.FillEllipse(new SolidBrush(onToggleColor),
new Rectangle(this.Width - this.Height + 5, 4, toggleSize, toggleSize));
}
else //OFF
{
if (solidStyle)
pevent.Graphics.FillPath(new SolidBrush(offBackColor), GetFigurePath());
else pevent.Graphics.DrawPath(new Pen(offBackColor, 2), GetFigurePath());
pevent.Graphics.FillEllipse(new SolidBrush(offToggleColor),
new Rectangle(4, 4, toggleSize, toggleSize));
}
}
}
}
| 29.45 | 98 | 0.522637 | [
"BSD-3-Clause"
] | Mancitiss/AFriendChatApp | A Friend/A Friend/CustomControls/ToggleButton.cs | 3,536 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace PSFramework.Utility
{
/// <summary>
/// A scriptblock container item
/// </summary>
public class ScriptBlockItem
{
/// <summary>
/// Name of the scriptblock
/// </summary>
public string Name;
/// <summary>
/// The scriptblock stored
/// </summary>
public ScriptBlock ScriptBlock
{
get
{
CountRetrieved++;
LastRetrieved = DateTime.Now;
return _ScriptBlock;
}
set { _ScriptBlock = value; }
}
private ScriptBlock _ScriptBlock;
/// <summary>
/// Whether the scriptblock should be invoked as global scriptblock
/// </summary>
public bool Global;
/// <summary>
/// The number of times this scriptblock has been used
/// </summary>
public int CountRetrieved { get; private set; }
/// <summary>
/// When the scriptblock has last been used
/// </summary>
public DateTime LastRetrieved { get; private set; }
/// <summary>
/// Create a new scriptblock item by offering both name and code
/// </summary>
/// <param name="Name">The name of the scriptblock</param>
/// <param name="ScriptBlock">The scriptblock</param>
/// <param name="Global">Whether the scriptblock should be invoked as global scriptblock</param>
public ScriptBlockItem(string Name, ScriptBlock ScriptBlock, bool Global = false)
{
this.Name = Name;
this.ScriptBlock = ScriptBlock;
this.Global = Global;
}
}
}
| 28.661538 | 104 | 0.567901 | [
"MIT"
] | Zhunya/psframework | library/PSFramework/Utility/ScriptBlockItem.cs | 1,865 | C# |
namespace LLibrary
{
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
internal sealed class OpenStreams : IDisposable
{
private readonly string _directory;
private readonly Dictionary<DateTime, StreamWriter> _streams;
private readonly Timer _timer;
private readonly object _lock;
internal OpenStreams(string directory)
{
_directory = directory;
_streams = new Dictionary<DateTime, StreamWriter>();
_lock = new object();
_timer = new Timer(ClosePastStreams, null, 0, (int)TimeSpan.FromHours(2).TotalMilliseconds);
}
public void Dispose()
{
_timer.Dispose();
CloseAllStreams();
}
internal void Append(DateTime date, string content)
{
lock (_lock)
{
GetStream(date.Date).WriteLine(content);
}
}
internal string[] Filepaths() =>
_streams.Values.Select(s => s.BaseStream).Cast<FileStream>().Select(s => s.Name).ToArray();
private void ClosePastStreams(object ignored)
{
lock (_lock)
{
var today = DateTime.Today;
var past = _streams.Where(kvp => kvp.Key < today).ToList();
foreach (var kvp in past)
{
kvp.Value.Dispose();
_streams.Remove(kvp.Key);
}
}
}
private void CloseAllStreams()
{
lock (_lock)
{
foreach (var stream in _streams.Values)
stream.Dispose();
_streams.Clear();
}
}
[SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope",
Justification = "It's disposed on this class Dispose.")]
private StreamWriter GetStream(DateTime date)
{
// Opening the stream if needed
if (!_streams.ContainsKey(date))
{
// Building stream's filepath
var filename = $"{date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture)}.log";
var filepath = Path.Combine(_directory, filename);
// Making sure the directory exists
Directory.CreateDirectory(_directory);
// Opening the stream
var stream = new StreamWriter(
File.Open(filepath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)
);
stream.AutoFlush = true;
// Storing the created stream
_streams[date] = stream;
}
return _streams[date];
}
}
}
| 30.42 | 105 | 0.514793 | [
"Unlicense"
] | tallesl/LogThis | L/OpenStreams.cs | 3,044 | C# |
// FILE AUTOGENERATED. DO NOT MODIFY
namespace Starfield.Core.Item.Items {
[Item("minecraft:lodestone", 958, 64, 742)]
public class ItemLodestone : BlockItem { }
} | 29.5 | 48 | 0.689266 | [
"MIT"
] | StarfieldMC/Starfield | Starfield.Core/Item/Items/ItemLodestone.cs | 177 | C# |
using System;
namespace ListasEnlazadas
{
class Program
{
static void Main(string[] args)
{
int opcion = 0;
String x = "";
Lista l = new Lista();
while (opcion != 4)
{
Console.Clear();
Console.WriteLine("1. Insertar");
Console.WriteLine("2. Eliminar");
Console.WriteLine("3. Mostrar");
Console.WriteLine("4. Ordenar");
Console.WriteLine("5. Salir");
opcion = int.Parse(Console.ReadLine());
switch (opcion)
{
case 1:
Console.WriteLine("introduzca un elemento");
x = Console.ReadLine();
l.Insertar(x);
break;
case 2:
Console.WriteLine("que elemnto quiere eliminar");
x = Console.ReadLine();
l.Eliminar(x);
Console.ReadKey();
break;
case 3:
l.Mostrar();
Console.ReadKey();
break;
}
}
}
}
}
| 28.413043 | 73 | 0.368018 | [
"MIT"
] | cmontellanob/programacionIII | ListasEnlazadas/ListasEnlazadas/Program.cs | 1,309 | C# |
using eProdaja.Model.Requests;
using eProdaja.Model.SearchObjects;
using eProdaja.Services;
namespace eProdaja.Controllers
{
public class VrsteProizvodumController : BaseCRUDController<Model.VrsteProizvodum, VrsteProizvodumSearchObject, VrsteProizvodumUpsertRequest, VrsteProizvodumUpsertRequest>
{
public VrsteProizvodumController(IVrsteProizvodumService service)
: base(service)
{
}
}
}
| 29.266667 | 175 | 0.763098 | [
"MIT"
] | amelmusic/FIT-RS2-2022 | eProdaja/Controllers/VrsteProizvodumController.cs | 441 | C# |
using System.Collections.Generic;
using System.Linq;
using Unity.UIWidgets.foundation;
using Unity.UIWidgets.material;
using Unity.UIWidgets.painting;
using Unity.UIWidgets.ui;
using Unity.UIWidgets.widgets;
namespace UIWidgetsGallery.gallery {
class TabsFabDemoUtils {
public const string _explanatoryText =
"When the Scaffold's floating action button changes, the new button fades and " +
"turns into view. In this demo, changing tabs can cause the app to be rebuilt " +
"with a FloatingActionButton that the Scaffold distinguishes from the others " +
"by its key.";
public static readonly List<_Page> _allPages = new List<_Page> {
new _Page(label: "Blue", colors: Colors.indigo, icon: Icons.add),
new _Page(label: "Eco", colors: Colors.green, icon: Icons.create),
new _Page(label: "No"),
new _Page(label: "Teal", colors: Colors.teal, icon: Icons.add),
new _Page(label: "Red", colors: Colors.red, icon: Icons.create)
};
}
class _Page {
public _Page(
string label,
MaterialColor colors = null,
IconData icon = null
) {
this.label = label;
this.colors = colors;
this.icon = icon;
}
public readonly string label;
public readonly MaterialColor colors;
public readonly IconData icon;
public Color labelColor {
get { return this.colors != null ? this.colors.shade300 : Colors.grey.shade300; }
}
public bool fabDefined {
get { return this.colors != null && this.icon != null; }
}
public Color fabColor {
get { return this.colors.shade400; }
}
public Icon fabIcon {
get { return new Icon(this.icon); }
}
public Key fabKey {
get { return new ValueKey<Color>(this.fabColor); }
}
}
public class TabsFabDemo : StatefulWidget {
public const string routeName = "/material/tabs-fab";
public override State createState() {
return new _TabsFabDemoState();
}
}
class _TabsFabDemoState : SingleTickerProviderStateMixin<TabsFabDemo> {
GlobalKey<ScaffoldState> _scaffoldKey = GlobalKey<ScaffoldState>.key();
TabController _controller;
_Page _selectedPage;
bool _extendedButtons = false;
public override void initState() {
base.initState();
this._controller = new TabController(vsync: this, length: TabsFabDemoUtils._allPages.Count);
this._controller.addListener(this._handleTabSelection);
this._selectedPage = TabsFabDemoUtils._allPages[0];
}
public override void dispose() {
this._controller.dispose();
base.dispose();
}
void _handleTabSelection() {
this.setState(() => { this._selectedPage = TabsFabDemoUtils._allPages[this._controller.index]; });
}
void _showExplanatoryText() {
this._scaffoldKey.currentState.showBottomSheet((BuildContext context) => {
return new Container(
decoration: new BoxDecoration(
border: new Border(top: new BorderSide(color: Theme.of(this.context).dividerColor))
),
child: new Padding(
padding: EdgeInsets.all(32.0f),
child: new Text(TabsFabDemoUtils._explanatoryText,
style: Theme.of(this.context).textTheme.subhead)
)
);
});
}
Widget buildTabView(_Page page) {
return new Builder(
builder: (BuildContext context) => {
return new Container(
key: new ValueKey<string>(page.label),
padding: EdgeInsets.fromLTRB(48.0f, 48.0f, 48.0f, 96.0f),
child: new Card(
child: new Center(
child: new Text(page.label,
style: new TextStyle(
color: page.labelColor,
fontSize: 32.0f
),
textAlign: TextAlign.center
)
)
)
);
}
);
}
Widget buildFloatingActionButton(_Page page) {
if (!page.fabDefined) {
return null;
}
if (this._extendedButtons) {
return FloatingActionButton.extended(
key: new ValueKey<Key>(page.fabKey),
tooltip: "Show explanation",
backgroundColor: page.fabColor,
icon: page.fabIcon,
label: new Text(page.label.ToUpper()),
onPressed: this._showExplanatoryText
);
}
return new FloatingActionButton(
key: page.fabKey,
tooltip: "Show explanation",
backgroundColor: page.fabColor,
child: page.fabIcon,
onPressed: this._showExplanatoryText
);
}
public override Widget build(BuildContext context) {
return new Scaffold(
key: this._scaffoldKey,
appBar: new AppBar(
title: new Text("FAB per tab"),
bottom: new TabBar(
controller: this._controller,
tabs: TabsFabDemoUtils._allPages
.Select<_Page, Widget>((_Page page) => new Tab(text: page.label.ToUpper())).ToList()
),
actions: new List<Widget> {
new MaterialDemoDocumentationButton(TabsFabDemo.routeName),
new IconButton(
icon: new Icon(Icons.sentiment_very_satisfied),
onPressed: () => {
this.setState(() => { this._extendedButtons = !this._extendedButtons; });
}
)
}
),
floatingActionButton: this.buildFloatingActionButton(this._selectedPage),
body: new TabBarView(
controller: this._controller,
children: TabsFabDemoUtils._allPages.Select<_Page, Widget>(this.buildTabView).ToList()
)
);
}
}
} | 38.168478 | 113 | 0.495942 | [
"Apache-2.0"
] | Luciano-0/2048-Demo | Library/PackageCache/com.unity.uiwidgets@1.5.4-preview.12/Samples~/UIWidgetsGallery/demo/material/tabs_fab_demo.cs | 7,023 | C# |
////////////////////////////////////////////////////////////////////////////////
//EF Core Provider for LCPI OLE DB.
// IBProvider and Contributors. 25.04.2021.
using Microsoft.EntityFrameworkCore.Migrations;
namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Migrations{
////////////////////////////////////////////////////////////////////////////////
//class FB_V03_0_0__MigrationsSqlGenerator
partial class FB_V03_0_0__MigrationsSqlGenerator
{
//MigrationsSqlGenerator interface --------------------------------------
protected override void ForeignKeyAction(ReferentialAction referentialAction,
MigrationCommandListBuilder builder)
{
switch(referentialAction)
{
case ReferentialAction.NoAction:
builder.Append("NO ACTION");
break;
case ReferentialAction.Cascade:
builder.Append("CASCADE");
break;
case ReferentialAction.SetNull:
builder.Append("SET NULL");
break;
case ReferentialAction.SetDefault:
builder.Append("SET DEFAULT");
break;
default:
{
ThrowError.MSqlGenErr__UnknownFkReferentialAction
(c_ErrSrcID,
referentialAction);
break;
}//default
}//switch referentialAction
}//ForeignKeyAction
};//class FB_V03_0_0__MigrationsSqlGenerator
////////////////////////////////////////////////////////////////////////////////
}//namespace Lcpi.EntityFrameworkCore.DataProvider.LcpiOleDb.Basement.EF.Dbms.Firebird.V03_0_0.Migrations
| 31.734694 | 105 | 0.592926 | [
"MIT"
] | ibprovider/Lcpi.EFCore.LcpiOleDb | Code/Provider/Source/Basement/EF/Dbms/Firebird/V03_0_0/Migrations/FB_V03_0_0__MigrationsSqlGenerator-ForeignKeyAction.cs | 1,557 | C# |
namespace SGson.Grammar.Number
{
public class NumberCharType
{
public static bool IsDigit(int c)
{
return c >= 0x30 && c <= 0x39;
}
public static bool IsBinaryDigit(int c)
{
return c == '0' || c =='1';
}
public static bool IsOctDigit(int c)
{
return c >= 0x30 && c <= 0x37;
}
public static bool IsHexDigit(int c)
{
return c >= 0x30 && c <= 0x39 ||
c >= 0x41 && c <= 0x46 ||
c >= 0x61 && c <= 0x66;
}
}
} | 16.777778 | 41 | 0.551876 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | zaobao/SGson | src/Grammar/Number/NumberCharType.cs | 453 | C# |
namespace Crm.Admin
{
using System.Web.Mvc;
internal static class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
}
}
} | 18.083333 | 74 | 0.75576 | [
"MIT"
] | VladimirSozinov/ROI-Web-School | CRM/Admin/App_Start/FilterConfig.cs | 219 | C# |
using System.Collections;
using System.Collections.Generic;
using MoreMountains.Tools;
using UnityEngine;
using UnityEngine.SceneManagement;
namespace MoreMountains.Feel
{
/// <summary>
/// A simple class used to spawn snake food in Feel's Snake demo scene
/// </summary>
public class SnakeFoodSpawner : MonoBehaviour
{
/// the food prefab to spawn
public SnakeFood SnakeFoodPrefab;
/// the maximum amount of food in the scene
public int AmountOfFood = 3;
/// the minimum coordinates to spawn at (in viewport units)
public Vector2 MinRandom = new Vector2(0.1f, 0.1f);
/// the maximum coordinates to spawn at (in viewport units)
public Vector2 MaxRandom = new Vector2(0.9f, 0.9f);
protected List<SnakeFood> Foods;
protected Camera _mainCamera;
/// <summary>
/// On start, instantiates food
/// </summary>
protected virtual void Start()
{
_mainCamera = Camera.main;
Foods = new List<SnakeFood>();
for (int i = 0; i < AmountOfFood; i++)
{
SnakeFood food = Instantiate(SnakeFoodPrefab);
food.transform.position = DetermineSpawnPosition();
food.Spawner = this;
Foods.Add(food);
}
}
/// <summary>
/// Determines a valid position at which to spawn food
/// </summary>
/// <returns></returns>
public virtual Vector3 DetermineSpawnPosition()
{
Vector3 newPosition = MMMaths.RandomVector2(MinRandom, MaxRandom);
newPosition.z = 10f;
newPosition = _mainCamera.ViewportToWorldPoint(newPosition);
return newPosition;
}
}
}
| 32.763636 | 78 | 0.59101 | [
"MIT"
] | random-agile/slowmo_mobile | Assets/Amazing Assets/Feel/FeelDemos/Snake/Scripts/SnakeFoodSpawner.cs | 1,802 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Xml;
namespace WinSW.Util
{
public static class XmlHelper
{
/// <summary>
/// Retrieves a single string element
/// </summary>
/// <param name="node">Parent node</param>
/// <param name="tagName">Element name</param>
/// <param name="optional">If optional, don't throw an exception if the element is missing</param>
/// <returns>String value or null</returns>
/// <exception cref="InvalidDataException">The required element is missing</exception>
public static string? SingleElement(XmlNode node, string tagName, bool optional)
{
XmlNode? n = node.SelectSingleNode(tagName);
if (n is null && !optional)
{
throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
}
return n is null ? null : Environment.ExpandEnvironmentVariables(n.InnerText);
}
/// <summary>
/// Retrieves a single node
/// </summary>
/// <param name="node">Parent node</param>
/// <param name="tagName">Element name</param>
/// <param name="optional">If otional, don't throw an exception if the element is missing</param>
/// <returns>String value or null</returns>
/// <exception cref="InvalidDataException">The required element is missing</exception>
public static XmlNode? SingleNode(XmlNode node, string tagName, bool optional)
{
XmlNode? n = node.SelectSingleNode(tagName);
if (n is null && !optional)
{
throw new InvalidDataException("<" + tagName + "> is missing in configuration XML");
}
return n;
}
/// <summary>
/// Retrieves a single mandatory attribute
/// </summary>
/// <param name="node">Parent node</param>
/// <param name="attributeName">Attribute name</param>
/// <returns>Attribute value</returns>
/// <exception cref="InvalidDataException">The required attribute is missing</exception>
public static TAttributeType SingleAttribute<TAttributeType>(XmlElement node, string attributeName)
{
if (!node.HasAttribute(attributeName))
{
throw new InvalidDataException("Attribute <" + attributeName + "> is missing in configuration XML");
}
return SingleAttribute<TAttributeType>(node, attributeName, default)!;
}
/// <summary>
/// Retrieves a single optional attribute
/// </summary>
/// <param name="node">Parent node</param>
/// <param name="attributeName">Attribute name</param>
/// <param name="defaultValue">Default value</param>
/// <returns>Attribute value (or default)</returns>
[return: MaybeNull]
public static TAttributeType SingleAttribute<TAttributeType>(XmlElement node, string attributeName, [AllowNull] TAttributeType defaultValue)
{
if (!node.HasAttribute(attributeName))
{
return defaultValue;
}
string rawValue = node.GetAttribute(attributeName);
string substitutedValue = Environment.ExpandEnvironmentVariables(rawValue);
var value = (TAttributeType)Convert.ChangeType(substitutedValue, typeof(TAttributeType));
return value;
}
/// <summary>
/// Retireves a single enum attribute
/// </summary>
/// <typeparam name="TAttributeType">Type of the enum</typeparam>
/// <param name="node">Parent node</param>
/// <param name="attributeName">Attribute name</param>
/// <param name="defaultValue">Default value</param>
/// <returns>Attribute value (or default)</returns>
/// <exception cref="InvalidDataException">Wrong enum value</exception>
public static TAttributeType EnumAttribute<TAttributeType>(XmlElement node, string attributeName, TAttributeType defaultValue)
where TAttributeType : struct
{
if (!node.HasAttribute(attributeName))
{
return defaultValue;
}
string rawValue = node.GetAttribute(attributeName);
string substitutedValue = Environment.ExpandEnvironmentVariables(rawValue);
try
{
return (TAttributeType)Enum.Parse(typeof(TAttributeType), substitutedValue, true);
}
catch (ArgumentException ex)
{
throw new InvalidDataException(
"Cannot parse <" + attributeName + "> Enum value from string '" + substitutedValue + "'. Enum type: " + typeof(TAttributeType), ex);
}
}
}
}
| 41.74359 | 152 | 0.600328 | [
"MIT"
] | UGreek/winsw | src/WinSW.Core/Util/XmlHelper.cs | 4,886 | C# |
#region License
// Distributed under the MIT License
// ============================================================
// Copyright (c) 2016 Hotcakes Commerce, LLC
//
// 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.
#endregion
using System;
using System.Runtime.Serialization;
namespace Hotcakes.CommerceDTO.v1.Catalog
{
/// <summary>
/// This is the primary object that is used to manage all aspects of product volume discount in the REST API.
/// </summary>
/// <remarks>The main application equivalent is ProductVolumeDiscount.</remarks>
[DataContract]
[Serializable]
public class ProductVolumeDiscountDTO
{
public ProductVolumeDiscountDTO()
{
Bvin = string.Empty;
StoreId = 0;
LastUpdated = DateTime.UtcNow;
ProductId = string.Empty;
Qty = 0;
Amount = 0;
DiscountType = ProductVolumeDiscountTypeDTO.None;
}
/// <summary>
/// The unique ID or primary key of the product volume discount.
/// </summary>
[DataMember]
public string Bvin { get; set; }
/// <summary>
/// This is the ID of the Hotcakes store. Typically, this is 1, except in multi-tenant environments.
/// </summary>
[DataMember]
public long StoreId { get; set; }
/// <summary>
/// The last updated date is used for auditing purposes to know when the product volume discount was last updated.
/// </summary>
[DataMember]
public DateTime LastUpdated { get; set; }
/// <summary>
/// The unique ID or Bvin of the product that this discount applies to.
/// </summary>
[DataMember]
public string ProductId { get; set; }
/// <summary>
/// The minimum number of products that must be in the cart to qualify for this volume discount.
/// </summary>
[DataMember]
public int Qty { get; set; }
/// <summary>
/// This property should hold the new product price or the discount percentage for the product.
/// </summary>
[DataMember]
public decimal Amount { get; set; }
/// <summary>
/// Specifies the type of discount that the amount is, decimal or percentage.
/// </summary>
[DataMember]
public ProductVolumeDiscountTypeDTO DiscountType { get; set; }
}
} | 38.119565 | 126 | 0.630739 | [
"MIT"
] | ketangarala/core | Libraries/Hotcakes.CommerceDTO/v1/Catalog/ProductVolumeDiscountDTO.cs | 3,509 | 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 Compliance.EarlyBound
{
[System.Runtime.Serialization.DataContractAttribute()]
public enum opc_pipedafileopc_PriorityIncident
{
[System.Runtime.Serialization.EnumMemberAttribute()]
High = 1,
[System.Runtime.Serialization.EnumMemberAttribute()]
Low = 3,
[System.Runtime.Serialization.EnumMemberAttribute()]
Medium = 2,
}
} | 26.555556 | 80 | 0.559275 | [
"MIT"
] | opc-cpvp/OPC.PowerApps | src/Compliance.EarlyBound/OptionSets/opc_pipedafileopc_PriorityIncident.cs | 717 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.open.lottery.region.create
/// </summary>
public class AlipayOpenLotteryRegionCreateRequest : IAopRequest<AlipayOpenLotteryRegionCreateResponse>
{
/// <summary>
/// 天天抽奖-商家新增
/// </summary>
public string BizContent { get; set; }
#region IAopRequest 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 AopObject bizModel;
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.open.lottery.region.create";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 23.563636 | 106 | 0.604938 | [
"Apache-2.0"
] | Varorbc/alipay-sdk-net-all | AlipaySDKNet/Request/AlipayOpenLotteryRegionCreateRequest.cs | 2,608 | C# |
using System.Drawing;
namespace mivcs.Rendering
{
public class DisplayCell
{
public Color Background { get; set; }
public Color Foreground { get; set; }
public char Char { get; set; }
public static implicit operator DisplayCell(char value)
{
return new DisplayCell
{
Char = value,
Background = DisplayBuffer.Background,
Foreground = DisplayBuffer.Foreground,
};
}
}
} | 24.809524 | 63 | 0.537428 | [
"MIT"
] | Desimis/mivcs | src/Rendering/DisplayCell.cs | 521 | C# |
using System.Collections.Generic;
using Microsoft.AspNetCore.Components;
using Skclusive.Material.Core;
namespace Skclusive.Material.Card
{
public class CardActionsComponent : MaterialComponent
{
public CardActionsComponent() : base("CardActions")
{
}
/// <summary>
/// html component tag to be used as container.
/// </summary>
[Parameter]
public string Component { set; get; } = "div";
/// <summary>
/// If <c>true</c>, the actions do not have additional margin.
/// </summary>
[Parameter]
public bool DisableSpacing { set; get; } = false;
protected override IEnumerable<string> Classes
{
get
{
foreach (var item in base.Classes)
yield return item;
if (!DisableSpacing)
yield return "Spacing";
}
}
}
}
| 25.210526 | 70 | 0.539666 | [
"MIT"
] | esso23/Skclusive.Material.Component | Card/src/CardActions/CardActions.cs | 960 | C# |
// Copyright 2017 Google Inc. 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.
// 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 GoogleCloudExtension.GCloud;
using GoogleCloudExtension.Services;
using GoogleCloudExtension.Services.FileSystem;
using GoogleCloudExtension.Utils;
using GoogleCloudExtension.VsVersion;
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Diagnostics;
using System.IO;
using System.Threading.Tasks;
namespace GoogleCloudExtension.Deployment
{
/// <summary>
/// This class contains methods used to manipulate ASP.NET Core projects.
/// </summary>
[Export(typeof(INetCoreAppUtils))]
public class NetCoreAppUtils : INetCoreAppUtils
{
private readonly Lazy<IProcessService> _processService;
private readonly Lazy<IFileSystem> _fileSystem;
private readonly Lazy<IGCloudWrapper> _gcloudWrapper;
private readonly Lazy<IEnvironment> _environment;
private readonly IToolsPathProvider _toolsPathProvider;
public const string DockerfileName = "Dockerfile";
private const string RuntimeImageFormat = "gcr.io/google-appengine/aspnetcore:{0}";
private IProcessService ProcessService => _processService.Value;
private IFileSystem FileSystem => _fileSystem.Value;
private IGCloudWrapper GCloudWrapper => _gcloudWrapper.Value;
private IEnvironment Environment => _environment.Value;
/// <summary>
/// This template is the smallest possible Dockerfile needed to deploy an ASP.NET Core app to
/// App Engine Flex environment. It invokes the entry point .dll given by {1}.
/// The parameters into the string are:
/// {0}, the base image for the app's Docker image.
/// {1}, the entry point .dll for the app.
/// </summary>
private const string DockerfileDefaultContent =
"FROM {0}\n" +
"COPY . /app\n" +
"WORKDIR /app\n" +
"ENTRYPOINT [\"dotnet\", \"{1}.dll\"]\n";
[ImportingConstructor]
public NetCoreAppUtils(Lazy<IProcessService> processService, Lazy<IFileSystem> fileSystem, Lazy<IGCloudWrapper> gcloudWrapper, Lazy<IEnvironment> environment)
{
_processService = processService;
_fileSystem = fileSystem;
_gcloudWrapper = gcloudWrapper;
_environment = environment;
_toolsPathProvider = VsVersionUtils.ToolsPathProvider;
}
/// <summary>
/// Creates an app bundle by publishing it to the given directory.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="stageDirectory">The directory the build output is published to.</param>
/// <param name="outputAction">The callback to call with output from the command.</param>
/// <param name="configuration">The name of the configuration to publish.</param>
public async Task<bool> CreateAppBundleAsync(
IParsedProject project,
string stageDirectory,
Func<string, Task> outputAction,
string configuration)
{
string arguments = $"publish -o \"{stageDirectory}\" -c {configuration}";
string externalTools = _toolsPathProvider.GetExternalToolsPath();
string workingDir = project.DirectoryPath;
var env = new Dictionary<string, string>
{
{ "PATH", $"{Environment.GetEnvironmentVariable("PATH")};{externalTools}" }
};
Debug.WriteLine($"Using tools from {externalTools}");
Debug.WriteLine($"Setting working directory to {workingDir}");
FileSystem.Directory.CreateDirectory(stageDirectory);
await outputAction($"dotnet {arguments}");
bool result = await ProcessService.RunCommandAsync(
file: _toolsPathProvider.GetDotnetPath(),
args: arguments,
handler: outputAction,
workingDir: workingDir,
environment: env);
await GCloudWrapper.GenerateSourceContextAsync(project.DirectoryPath, stageDirectory);
return result;
}
/// <summary>
/// Creates the Dockerfile necessary to package up an ASP.NET Core app if one is not already present at the root
/// path of the project.
/// </summary>
/// <param name="project">The project.</param>
/// <param name="stageDirectory">The directory where to save the Dockerfile.</param>
public void CopyOrCreateDockerfile(IParsedProject project, string stageDirectory)
{
string sourceDockerfile = GetProjectDockerfilePath(project);
string targetDockerfile = Path.Combine(stageDirectory, DockerfileName);
string entryPointName = CommonUtils.GetEntrypointName(stageDirectory) ?? project.Name;
string baseImage = string.Format(RuntimeImageFormat, project.FrameworkVersion);
if (FileSystem.File.Exists(sourceDockerfile))
{
FileSystem.File.Copy(sourceDockerfile, targetDockerfile, overwrite: true);
}
else
{
string content = string.Format(DockerfileDefaultContent, baseImage, entryPointName);
FileSystem.File.WriteAllText(targetDockerfile, content);
}
}
/// <summary>
/// Generates the Dockerfile for this .NET Core project.
/// </summary>
/// <param name="project">The project.</param>
public void GenerateDockerfile(IParsedProject project)
{
string targetDockerfile = GetProjectDockerfilePath(project);
string baseImage = string.Format(RuntimeImageFormat, project.FrameworkVersion);
string content = string.Format(DockerfileDefaultContent, baseImage, project.Name);
FileSystem.File.WriteAllText(targetDockerfile, content);
}
/// <summary>
/// Checks if the Dockerfile for the project was created.
/// </summary>
/// <param name="project">The project.</param>
/// <returns>True if the Dockerfile exists, false otherwise.</returns>
public bool CheckDockerfile(IParsedProject project) => FileSystem.File.Exists(GetProjectDockerfilePath(project));
private static string GetProjectDockerfilePath(IParsedProject project) => Path.Combine(project.DirectoryPath, DockerfileName);
}
}
| 46.217105 | 166 | 0.662064 | [
"Apache-2.0"
] | GoogleCloudPlatform/google-cloud-visualstudio | GoogleCloudExtension/GoogleCloudExtension/Deployment/NetCoreAppUtils.cs | 7,027 | C# |
using UnityEngine;
using System.Collections;
using System;
public class Fire : MonoBehaviour {
int life;
GameObject woodPile;
TimeSpan fireTimer;
// Use this for initialization
void Start () {
life = 300;
woodPile = GameObject.Find("Wood Pile");
InvokeRepeating("FireCountdown", 1.0f, 1.0f);
}
// Update is called once per frame
void Update () {
if (life <= 0) {
Debug.Log("The fire has died!");
Destroy(gameObject);
}
fireTimer = TimeSpan.FromSeconds(life);
string fireTime = string.Format("{0:D2}:{1:D2}:{2:D2}",
fireTimer.Hours,
fireTimer.Minutes,
fireTimer.Seconds
);
gameObject.GetComponentInChildren<TextMesh>().text = fireTime;
}
public void FireCountdown()
{
life--;
}
public void StokeFire(int stokeAmmount) {
life += stokeAmmount;
}
public int secondsLeft()
{
return life;
}
public void setSecondsLeft(int s)
{
life = s;
}
}
| 20.25 | 70 | 0.537919 | [
"MIT"
] | tgbonin/firekeeper | Assets/Scripts/Fire.cs | 1,136 | C# |
using System.Threading.Tasks;
using Abp.Application.Services;
using MyProject.Authorization.Accounts.Dto;
namespace MyProject.Authorization.Accounts
{
public interface IAccountAppService : IApplicationService
{
Task<IsTenantAvailableOutput> IsTenantAvailable(IsTenantAvailableInput input);
Task<RegisterOutput> Register(RegisterInput input);
}
}
| 26.928571 | 86 | 0.785146 | [
"MIT"
] | CadeXu/ABP | abpMySql/aspnet-core/src/MyProject.Application/Authorization/Accounts/IAccountAppService.cs | 379 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// ANTLR Version: 4.7.1
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
// Generated from f:\Private\NetCore.AntlrCodeCompletion\test\NetCore.UnitTestAntlrCodeCompletion\Grammar\Expr.g4 by ANTLR 4.7.1
// Unreachable code detected
#pragma warning disable 0162
// The variable '...' is assigned but its value is never used
#pragma warning disable 0219
// Missing XML comment for publicly visible type or member '...'
#pragma warning disable 1591
// Ambiguous reference in cref attribute
#pragma warning disable 419
namespace Grammar {
using Antlr4.Runtime.Misc;
using IParseTreeListener = Antlr4.Runtime.Tree.IParseTreeListener;
using IToken = Antlr4.Runtime.IToken;
/// <summary>
/// This interface defines a complete listener for a parse tree produced by
/// <see cref="ExprParser"/>.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("ANTLR", "4.7.1")]
[System.CLSCompliant(false)]
public interface IExprListener : IParseTreeListener {
/// <summary>
/// Enter a parse tree produced by <see cref="ExprParser.expression"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterExpression([NotNull] ExprParser.ExpressionContext context);
/// <summary>
/// Exit a parse tree produced by <see cref="ExprParser.expression"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitExpression([NotNull] ExprParser.ExpressionContext context);
/// <summary>
/// Enter a parse tree produced by <see cref="ExprParser.assignment"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterAssignment([NotNull] ExprParser.AssignmentContext context);
/// <summary>
/// Exit a parse tree produced by <see cref="ExprParser.assignment"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitAssignment([NotNull] ExprParser.AssignmentContext context);
/// <summary>
/// Enter a parse tree produced by <see cref="ExprParser.simpleExpression"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterSimpleExpression([NotNull] ExprParser.SimpleExpressionContext context);
/// <summary>
/// Exit a parse tree produced by <see cref="ExprParser.simpleExpression"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitSimpleExpression([NotNull] ExprParser.SimpleExpressionContext context);
/// <summary>
/// Enter a parse tree produced by <see cref="ExprParser.variableRef"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterVariableRef([NotNull] ExprParser.VariableRefContext context);
/// <summary>
/// Exit a parse tree produced by <see cref="ExprParser.variableRef"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitVariableRef([NotNull] ExprParser.VariableRefContext context);
/// <summary>
/// Enter a parse tree produced by <see cref="ExprParser.functionRef"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void EnterFunctionRef([NotNull] ExprParser.FunctionRefContext context);
/// <summary>
/// Exit a parse tree produced by <see cref="ExprParser.functionRef"/>.
/// </summary>
/// <param name="context">The parse tree.</param>
void ExitFunctionRef([NotNull] ExprParser.FunctionRefContext context);
}
} // namespace Grammar
| 41.639535 | 128 | 0.688634 | [
"MIT"
] | jphilipps/NetCore.AntlrCodeCompletion | test/NetCore.UnitTestAntlrCodeCompletion/Generation/ExprListener.cs | 3,581 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
namespace System.Net.Http
{
internal enum Http3SettingType : long
{
/// <summary>
/// SETTINGS_QPACK_MAX_TABLE_CAPACITY
/// The maximum dynamic table size. The default is 0.
/// https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-5
/// </summary>
QPackMaxTableCapacity = 0x1,
// Below are explicitly reserved and should never be sent, per
// https://tools.ietf.org/html/draft-ietf-quic-http-31#section-7.2.4.1
// and
// https://tools.ietf.org/html/draft-ietf-quic-http-31#section-11.2.2
ReservedHttp2EnablePush = 0x2,
ReservedHttp2MaxConcurrentStreams = 0x3,
ReservedHttp2InitialWindowSize = 0x4,
ReservedHttp2MaxFrameSize = 0x5,
/// <summary>
/// SETTINGS_MAX_HEADER_LIST_SIZE
/// The maximum size of headers. The default is unlimited.
/// https://tools.ietf.org/html/draft-ietf-quic-http-24#section-7.2.4.1
/// </summary>
MaxHeaderListSize = 0x6,
/// <summary>
/// SETTINGS_QPACK_BLOCKED_STREAMS
/// The maximum number of request streams that can be blocked waiting for QPack instructions. The default is 0.
/// https://tools.ietf.org/html/draft-ietf-quic-qpack-11#section-5
/// </summary>
QPackBlockedStreams = 0x7,
/// <summary>
/// SETTINGS_ENABLE_WEBTRANSPORT, default is 0 (off)
/// https://www.ietf.org/archive/id/draft-ietf-webtrans-http3-01.html#name-http-3-settings-parameter-r
/// </summary>
EnableWebTransport = 0x2b603742,
/// <summary>
/// H3_DATAGRAM, default is 0 (off)
/// indicates that the server suppprts sending individual datagrams over Http/3
/// rather than just streams.
/// </summary>
H3Datagram = 0xffd277
}
}
| 38.423077 | 119 | 0.630631 | [
"MIT"
] | Akarachudra/kontur-aspnetcore-fork | src/Shared/runtime/Http3/Http3SettingType.cs | 1,998 | C# |
namespace DfESurveyTool.Web.Consts
{
public static class CookieNames
{
public const string CookieConsent = "CookieConsent";
public const string AntiForgery = "Antiforgery";
public const string AzureADLogin = "Login";
// Google Analytics
public const string GA = "_ga";
public const string GId = "_gid";
public const string GTag = "_gat_gtag_";
// Application Insights
public const string AISession = "ai_session";
public const string AIUser = "ai_user";
}
}
| 29.105263 | 60 | 0.636528 | [
"MIT"
] | bryn500/GovTemplate | src/DfESurveyTool.Web/Consts/CookieNames.cs | 555 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AreaAgent : Agent
{
public GameObject area;
public override List<float> CollectState()
{
List<float> state = new List<float>();
Vector3 velocity = GetComponent<Rigidbody>().velocity;
state.Add((transform.position.x - area.transform.position.x));
state.Add((transform.position.y - area.transform.position.y));
state.Add((transform.position.z + 5 - area.transform.position.z));
state.Add(velocity.x);
state.Add(velocity.y);
state.Add(velocity.z);
return state;
}
public void MoveAgent(float[] act) {
float directionX = 0;
float directionZ = 0;
float directionY = 0;
if (brain.brainParameters.actionSpaceType == StateType.continuous)
{
directionX = Mathf.Clamp(act[0], -1f, 1f);
directionZ = Mathf.Clamp(act[1], -1f, 1f);
directionY = Mathf.Clamp(act[2], -1f, 1f);
if (GetComponent<Rigidbody>().velocity.y > 0) { directionY = 0f; }
}
else {
int movement = Mathf.FloorToInt(act[0]);
if (movement == 1) { directionX = -1; }
if (movement == 2) { directionX = 1; }
if (movement == 3) { directionZ = -1; }
if (movement == 4) { directionZ = 1; }
if (movement == 5 && GetComponent<Rigidbody>().velocity.y <= 0) { directionZ = 1; }
}
float edge = 0.499f;
float rayDepth = 0.51f;
//Vector3 fwd = transform.TransformDirection(Vector3.down);
//if (!Physics.Raycast(transform.position, fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(edge, 0f, 0f), fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(-edge, 0f, 0f), fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(0.0f, 0f, edge), fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(0.0f, 0f, -edge), fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(edge, 0f, edge), fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(-edge, 0f, edge), fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(edge, 0f, -edge), fwd, rayDepth) &&
// !Physics.Raycast(transform.position + new Vector3(-edge, 0f, -edge), fwd, rayDepth))
//{
// directionY = 0f;
// directionX = directionX / 5f;
// directionZ = directionZ / 5f;
//}
gameObject.GetComponent<Rigidbody>().AddForce(new Vector3(directionX * 40f, directionY * 0f, directionZ * 40f));
if (GetComponent<Rigidbody>().velocity.sqrMagnitude > 25f)
{
GetComponent<Rigidbody>().velocity *= 0.95f;
}
}
public override void AgentStep(float[] act)
{
reward = -0.005f;
MoveAgent(act);
if (gameObject.transform.position.y < 0.0f /*|| Mathf.Abs(gameObject.transform.position.x - area.transform.position.x) > 8f ||
Mathf.Abs(gameObject.transform.position.z + 5 - area.transform.position.z) > 8*/)
{
done = true;
reward = -1f;
//print("AREA agent DONE!");
}
}
public override void AgentReset()
{
transform.position = new Vector3(Random.Range(-3.5f, 3.5f), 1.1f, -8f) + area.transform.position;
GetComponent<Rigidbody>().velocity = new Vector3(0f, 0f, 0f);
area.GetComponent<Area>().ResetArea();
}
} | 37.446809 | 129 | 0.599716 | [
"Apache-2.0"
] | spiez/unity-ml-trafficDemo | unity-environment/Assets/ML-Agents/Examples/Area/Scripts/AreaAgent.cs | 3,522 | 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 Microsoft.AspNetCore.Http;
using Microsoft.Net.Http.Headers;
namespace Microsoft.AspNetCore.Rewrite.UrlActions
{
internal class RedirectAction : UrlAction
{
public int StatusCode { get; }
public bool QueryStringAppend { get; }
public bool QueryStringDelete { get; }
public bool EscapeBackReferences { get; }
public RedirectAction(
int statusCode,
Pattern pattern,
bool queryStringAppend,
bool queryStringDelete,
bool escapeBackReferences
)
{
StatusCode = statusCode;
Url = pattern;
QueryStringAppend = queryStringAppend;
QueryStringDelete = queryStringDelete;
EscapeBackReferences = escapeBackReferences;
}
public override void ApplyAction(
RewriteContext context,
BackReferenceCollection? ruleBackReferences,
BackReferenceCollection? conditionBackReferences
)
{
var pattern = Url!.Evaluate(context, ruleBackReferences, conditionBackReferences);
var response = context.HttpContext.Response;
var pathBase = context.HttpContext.Request.PathBase;
if (EscapeBackReferences)
{
// because escapebackreferences will be encapsulated by the pattern, just escape the pattern
pattern = Uri.EscapeDataString(pattern);
}
if (string.IsNullOrEmpty(pattern))
{
response.Headers[HeaderNames.Location] = pathBase.HasValue ? pathBase.Value : "/";
return;
}
if (
pattern.IndexOf(Uri.SchemeDelimiter, StringComparison.Ordinal) == -1
&& pattern[0] != '/'
)
{
pattern = '/' + pattern;
}
response.StatusCode = StatusCode;
// url can either contain the full url or the path and query
// always add to location header.
// TODO check for false positives
var split = pattern.IndexOf('?');
if (split >= 0 && QueryStringAppend)
{
var query = context.HttpContext.Request.QueryString.Add(
QueryString.FromUriComponent(pattern.Substring(split))
);
// not using the response.redirect here because status codes may be 301, 302, 307, 308
response.Headers[HeaderNames.Location] =
pathBase + pattern.Substring(0, split) + query;
}
else
{
// If the request url has a query string and the target does not, append the query string
// by default.
if (QueryStringDelete)
{
response.Headers[HeaderNames.Location] = pathBase + pattern;
}
else
{
response.Headers[HeaderNames.Location] =
pathBase + pattern + context.HttpContext.Request.QueryString;
}
}
context.Result = RuleResult.EndResponse;
}
}
}
| 36.393617 | 111 | 0.559193 | [
"Apache-2.0"
] | belav/aspnetcore | src/Middleware/Rewrite/src/UrlActions/RedirectAction.cs | 3,421 | C# |
//-----------------------------------------------------------------------
// <copyright file="UseRoleIgnoredSpec.cs" company="Akka.NET Project">
// Copyright (C) 2009-2019 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2019 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Akka.Actor;
using Akka.Cluster.Routing;
using Akka.Cluster.TestKit;
using Hocon;
using Akka.Event;
using Akka.Remote.TestKit;
using Akka.Routing;
using FluentAssertions;
namespace Akka.Cluster.Tests.MultiNode.Routing
{
public class UseRoleIgnoredSpecConfig : MultiNodeConfig
{
internal interface IRouteeType { }
internal class PoolRoutee : IRouteeType { }
internal class GroupRoutee : IRouteeType { }
internal class Reply
{
public Reply(IRouteeType routeeType, IActorRef actorRef)
{
RouteeType = routeeType;
ActorRef = actorRef;
}
public IRouteeType RouteeType { get; }
public IActorRef ActorRef { get; }
}
internal class SomeActor : ReceiveActor
{
private readonly IRouteeType _routeeType;
private ILoggingAdapter log = Context.GetLogger();
public SomeActor() : this(new PoolRoutee())
{
}
public SomeActor(IRouteeType routeeType)
{
_routeeType = routeeType;
log.Info("Starting on {0}", Self.Path.Address);
Receive<string>(msg =>
{
log.Info("msg = {0}", msg);
Sender.Tell(new Reply(_routeeType, Self));
});
}
}
public RoleName First { get; }
public RoleName Second { get; }
public RoleName Third { get; }
public UseRoleIgnoredSpecConfig()
{
First = Role("first");
Second = Role("second");
Third = Role("third");
CommonConfig = DebugConfig(false)
.WithFallback(MultiNodeClusterSpec.ClusterConfig());
NodeConfig(new List<RoleName> { First }, new List<Config> { ConfigurationFactory.ParseString(@"akka.cluster.roles =[""a"", ""c""]") });
NodeConfig(new List<RoleName> { Second, Third }, new List<Config> { ConfigurationFactory.ParseString(@"akka.cluster.roles =[""b"", ""c""]") });
}
}
public class UseRoleIgnoredSpec : MultiNodeClusterSpec
{
private readonly UseRoleIgnoredSpecConfig _config;
public UseRoleIgnoredSpec() : this(new UseRoleIgnoredSpecConfig())
{
}
protected UseRoleIgnoredSpec(UseRoleIgnoredSpecConfig config)
: base(config, typeof(UseRoleIgnoredSpec))
{
_config = config;
}
private IEnumerable<Routee> CurrentRoutees(IActorRef router)
{
var routerAsk = router.Ask<Routees>(new GetRoutees(), GetTimeoutOrDefault(null));
return routerAsk.Result.Members;
}
private Address FullAddress(IActorRef actorRef)
{
if (string.IsNullOrEmpty(actorRef.Path.Address.Host) || !actorRef.Path.Address.Port.HasValue)
return Cluster.SelfAddress;
return actorRef.Path.Address;
}
private Dictionary<Address, int> ReceiveReplays(UseRoleIgnoredSpecConfig.IRouteeType routeeType,
int expectedReplies)
{
var zero = Roles.Select(c => GetAddress(c)).ToDictionary(c => c, c => 0);
var replays = ReceiveWhile(5.Seconds(), msg =>
{
var routee = msg as UseRoleIgnoredSpecConfig.Reply;
if (routee != null && routee.RouteeType.GetType() == routeeType.GetType())
return FullAddress(routee.ActorRef);
return null;
}, expectedReplies).Aggregate(zero, (replyMap, address) =>
{
replyMap[address]++;
return replyMap;
});
return replays;
}
[MultiNodeFact]
public void UseRoleIgnoredSpecs()
{
A_cluster_must_start_cluster();
A_cluster_must_pool_local_off_roles_off();
A_cluster_must_group_local_off_roles_off();
A_cluster_must_pool_local_on_role_b();
A_cluster_must_group_local_on_role_b();
A_cluster_must_pool_local_on_role_a();
A_cluster_must_group_local_on_role_a();
A_cluster_must_pool_local_on_role_c();
A_cluster_must_group_local_on_role_c();
}
private void A_cluster_must_start_cluster()
{
AwaitClusterUp(_config.First, _config.Second, _config.Third);
RunOn(() =>
{
Log.Info("first, roles: " + Cluster.SelfRoles);
}, _config.First);
RunOn(() =>
{
Log.Info("second, roles: " + Cluster.SelfRoles);
}, _config.Second);
RunOn(() =>
{
Log.Info("third, roles: " + Cluster.SelfRoles);
}, _config.Third);
// routees for the group routers
Sys.ActorOf(Props.Create(() => new UseRoleIgnoredSpecConfig.SomeActor(new UseRoleIgnoredSpecConfig.GroupRoutee())), "foo");
Sys.ActorOf(Props.Create(() => new UseRoleIgnoredSpecConfig.SomeActor(new UseRoleIgnoredSpecConfig.GroupRoutee())), "bar");
EnterBarrier("after-1");
}
private void A_cluster_must_pool_local_off_roles_off()
{
RunOn(() =>
{
var role = "b";
var router = Sys.ActorOf(
new ClusterRouterPool(
new RoundRobinPool(6),
new ClusterRouterPoolSettings(6, 2, allowLocalRoutees: false, useRole: role)).Props(
Props.Create<UseRoleIgnoredSpecConfig.SomeActor>()),
"router-2");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(4));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.PoolRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().Be(0);
replays[GetAddress(_config.Second)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Third)].Should().BeGreaterThan(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-2");
}
private void A_cluster_must_group_local_off_roles_off()
{
RunOn(() =>
{
var role = "b";
var router = Sys.ActorOf(
new ClusterRouterGroup(
new RoundRobinGroup(paths: null),
new ClusterRouterGroupSettings(6, ImmutableHashSet.Create("/user/foo", "/user/bar"), allowLocalRoutees: false, useRole: role)).Props(),
"router-2b");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(4));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.GroupRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().Be(0);
replays[GetAddress(_config.Second)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Third)].Should().BeGreaterThan(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-2b");
}
private void A_cluster_must_pool_local_on_role_b()
{
RunOn(() =>
{
var role = "b";
var router = Sys.ActorOf(
new ClusterRouterPool(
new RoundRobinPool(6),
new ClusterRouterPoolSettings(6, 2, allowLocalRoutees: true, useRole: role)).Props(
Props.Create<UseRoleIgnoredSpecConfig.SomeActor>()),
"router-3");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(4));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.PoolRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().Be(0);
replays[GetAddress(_config.Second)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Third)].Should().BeGreaterThan(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-3");
}
private void A_cluster_must_group_local_on_role_b()
{
RunOn(() =>
{
var role = "b";
var router = Sys.ActorOf(
new ClusterRouterGroup(
new RoundRobinGroup(paths: null),
new ClusterRouterGroupSettings(6, ImmutableHashSet.Create("/user/foo", "/user/bar"), allowLocalRoutees: true, useRole: role)).Props(),
"router-3b");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(4));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.GroupRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().Be(0);
replays[GetAddress(_config.Second)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Third)].Should().BeGreaterThan(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-3b");
}
private void A_cluster_must_pool_local_on_role_a()
{
RunOn(() =>
{
var role = "a";
var router = Sys.ActorOf(
new ClusterRouterPool(
new RoundRobinPool(6),
new ClusterRouterPoolSettings(6, 2, allowLocalRoutees: true, useRole: role)).Props(
Props.Create<UseRoleIgnoredSpecConfig.SomeActor>()),
"router-4");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(2));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.PoolRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Second)].Should().Be(0);
replays[GetAddress(_config.Third)].Should().Be(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-4");
}
private void A_cluster_must_group_local_on_role_a()
{
RunOn(() =>
{
var role = "a";
var router = Sys.ActorOf(
new ClusterRouterGroup(
new RoundRobinGroup(paths: null),
new ClusterRouterGroupSettings(6, ImmutableHashSet.Create("/user/foo", "/user/bar"), allowLocalRoutees: true, useRole: role)).Props(),
"router-4b");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(2));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.GroupRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Second)].Should().Be(0);
replays[GetAddress(_config.Third)].Should().Be(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-4b");
}
private void A_cluster_must_pool_local_on_role_c()
{
RunOn(() =>
{
var role = "c";
var router = Sys.ActorOf(
new ClusterRouterPool(
new RoundRobinPool(6),
new ClusterRouterPoolSettings(6, 2, allowLocalRoutees: true, useRole: role)).Props(
Props.Create<UseRoleIgnoredSpecConfig.SomeActor>()),
"router-5");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(6));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.PoolRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Second)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Third)].Should().BeGreaterThan(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-5");
}
private void A_cluster_must_group_local_on_role_c()
{
RunOn(() =>
{
var role = "c";
var router = Sys.ActorOf(
new ClusterRouterGroup(
new RoundRobinGroup(paths: null),
new ClusterRouterGroupSettings(6, ImmutableHashSet.Create("/user/foo", "/user/bar"), allowLocalRoutees: true, useRole: role)).Props(),
"router-5b");
AwaitAssert(() => CurrentRoutees(router).Count().Should().Be(6));
var iterationCount = 10;
for (int i = 0; i < iterationCount; i++)
{
router.Tell($"hit-{i}");
}
var replays = ReceiveReplays(new UseRoleIgnoredSpecConfig.GroupRoutee(), iterationCount);
// should not be deployed locally, does not have required role
replays[GetAddress(_config.First)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Second)].Should().BeGreaterThan(0);
replays[GetAddress(_config.Third)].Should().BeGreaterThan(0);
replays.Values.Sum().Should().Be(iterationCount);
}, _config.First);
EnterBarrier("after-5b");
}
}
}
| 37.674419 | 159 | 0.531235 | [
"Apache-2.0"
] | hueifeng/akka.net | src/core/Akka.Cluster.Tests.MultiNode/Routing/UseRoleIgnoredSpec.cs | 16,202 | 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;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Transform;
using Aliyun.Acs.Core.Utils;
using Aliyun.Acs.retailcloud.Transform;
using Aliyun.Acs.retailcloud.Transform.V20180313;
namespace Aliyun.Acs.retailcloud.Model.V20180313
{
public class DescribeRdsAccountsRequest : RpcAcsRequest<DescribeRdsAccountsResponse>
{
public DescribeRdsAccountsRequest()
: base("retailcloud", "2018-03-13", "DescribeRdsAccounts", "retailcloud", "openAPI")
{
if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null)
{
this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null);
this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null);
}
}
private string accountName;
private string dbInstanceId;
public string AccountName
{
get
{
return accountName;
}
set
{
accountName = value;
DictionaryUtil.Add(QueryParameters, "AccountName", value);
}
}
public string DbInstanceId
{
get
{
return dbInstanceId;
}
set
{
dbInstanceId = value;
DictionaryUtil.Add(QueryParameters, "DbInstanceId", value);
}
}
public override bool CheckShowJsonItemName()
{
return false;
}
public override DescribeRdsAccountsResponse GetResponse(UnmarshallerContext unmarshallerContext)
{
return DescribeRdsAccountsResponseUnmarshaller.Unmarshall(unmarshallerContext);
}
}
}
| 30.313253 | 134 | 0.696741 | [
"Apache-2.0"
] | bbs168/aliyun-openapi-net-sdk | aliyun-net-sdk-retailcloud/Retailcloud/Model/V20180313/DescribeRdsAccountsRequest.cs | 2,516 | C# |
namespace LeetCode.Impl.Template;
internal class Solution
{
}
| 10.666667 | 34 | 0.78125 | [
"MIT"
] | gdoct/LeetCodeExcercises | LeetCode.Impl/000_Template/Solution.cs | 66 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("WebViewDemo.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("WebViewDemo.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: ComVisible(false)] | 36.103448 | 84 | 0.741165 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter16/WebViewDemo/WebViewDemo/WebViewDemo.UWP/Properties/AssemblyInfo.cs | 1,050 | C# |
using NUnit.Framework;
using SwfLib.Gradients;
using SwfLib.Tests.Asserts;
namespace SwfLib.Tests.Gradients {
[TestFixture]
public class FocalGradientRGBATest : BaseGradientTest<FocalGradientRGBA> {
private readonly byte[] _etalon = new byte[] { 0x92,
0, //Ratio 0
10, 150, 155, 128,// Color 0,
100, // Ratio 1,
120, 50, 55, 192, //Color 2,
51, 0 //Focal point
};
[Test]
public void ReadTest() {
var gradient = ReadGradient(_etalon);
AssertGradients.AreEqual(GetGradient(), gradient, "Gradient");
}
[Test]
public void WriteTest() {
var gradient = GetGradient();
WriteGradient(gradient, _etalon);
}
private static FocalGradientRGBA GetGradient() {
return new FocalGradientRGBA {
InterpolationMode = InterpolationMode.Linear,
SpreadMode = SpreadMode.Repeat,
FocalPoint = (int)(0.2 * 256) / 256.0,
GradientRecords = {
new GradientRecordRGBA {Ratio = 0, Color = {Red = 10, Green = 150, Blue = 155, Alpha = 128}},
new GradientRecordRGBA {Ratio = 100, Color = {Red = 120, Green = 50, Blue = 55, Alpha = 192}},
}
};
}
protected override FocalGradientRGBA Read(ISwfStreamReader reader) {
return reader.ReadFocalGradientRGBA();
}
protected override void Write(ISwfStreamWriter writer, FocalGradientRGBA gradient) {
writer.WriteFocalGradientRGBA(gradient);
}
}
}
| 34.22 | 115 | 0.54588 | [
"MIT"
] | SavchukSergey/SwfLib | SwfLib.Tests/Gradients/FocalGradientRGBATest.cs | 1,713 | C# |
using System;
using System.Collections.Generic;
using System.IO;
namespace I18NPortable
{
public interface ILocaleProvider : IDisposable
{
IEnumerable<Tuple<string, string>> GetAvailableLocales();
Stream GetLocaleStream(string locale);
ILocaleProvider SetLogger(Action<string> logger);
ILocaleProvider Init();
}
} | 25.642857 | 65 | 0.713092 | [
"MIT"
] | enisn/I18N-Portable | I18NPortable/ILocaleProvider.cs | 361 | C# |
using Avalonia;
using Avalonia.Markup.Xaml;
namespace SS14.Launcher;
public class App : Application
{
public override void Initialize()
{
AvaloniaXamlLoader.Load(this);
}
} | 16.166667 | 38 | 0.701031 | [
"MIT"
] | Tomeno/SS14.Launcher | SS14.Launcher/App.xaml.cs | 194 | C# |
/***********************************************************************************************\
* (C) KAL ATM Software GmbH, 2021
* KAL ATM Software GmbH licenses this file to you under the MIT license.
* See the LICENSE file in the project root for more information.
*
* This file was created automatically as part of the XFS4IoT Printer interface.
* NoMediaEvent_g.cs uses automatically generated parts.
* created at 3/18/2021 2:05:35 PM
\***********************************************************************************************/
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using XFS4IoT.Events;
namespace XFS4IoT.Printer.Events
{
[DataContract]
[Event(Name = "Printer.NoMediaEvent")]
public sealed class NoMediaEvent : Event<NoMediaEvent.PayloadData>
{
public NoMediaEvent(string RequestId, PayloadData Payload)
: base(RequestId, Payload)
{ }
[DataContract]
public sealed class PayloadData : MessagePayloadBase
{
public PayloadData(string UserPrompt = null)
: base()
{
this.UserPrompt = UserPrompt;
}
/// <summary>
///The user prompt from the form definition. This will be omitted if either a form does not define a value for the user prompt or the event is being generated as the result of a command that does not use forms.The application may use the this in any manner it sees fit, for example it might display the string to the operator, along with a message that the media should be inserted.
/// </summary>
[DataMember(Name = "userPrompt")]
public string UserPrompt { get; private set; }
}
}
}
| 36.285714 | 394 | 0.591114 | [
"MIT"
] | rajasekaran-ka/KAL | Framework/Core/Printer/Events/NoMediaEvent_g.cs | 1,778 | C# |
//------------------------------------------------------------------------------
/// <copyright file="IVsCodeWindow.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
//---------------------------------------------------------------------------
// IVsCodeWindow.cs
//---------------------------------------------------------------------------
// WARNING: this file autogenerated
//---------------------------------------------------------------------------
// Copyright (c) 1999, Microsoft Corporation All Rights Reserved
// Information Contained Herein Is Proprietary and Confidential.
//---------------------------------------------------------------------------
namespace Microsoft.VisualStudio.Interop {
using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
[
ComImport(),Guid("8560CECD-DFAC-4F7B-9D2A-E6D9810F3443"),
InterfaceTypeAttribute(ComInterfaceType.InterfaceIsIUnknown),
CLSCompliant(false)
]
internal interface IVsCodeWindow {
void SetBuffer(IVsTextLines pBuffer);
void GetBuffer(out IVsTextLines ppBuffer);
IVsTextView GetPrimaryView();
IVsTextView GetSecondaryView();
void SetViewClassID(ref Guid clsidView);
void GetViewClassID(ref Guid pclsidView);
void SetBaseEditorCaption([MarshalAs(UnmanagedType.LPWStr)] string pszBaseEditorCaption);
void GetEditorCaption(
int dwReadOnly,
[MarshalAs(UnmanagedType.BStr)] out string pbstrEditorCaption);
void Close();
void GetLastActiveView(
[MarshalAs(UnmanagedType.Interface)]
object ppView);
}
}
| 34.890909 | 98 | 0.482543 | [
"Unlicense"
] | bestbat/Windows-Server | com/netfx/src/framework/vsdesigner/designer/microsoft/visualstudio/interop/ivscodewindow.cs | 1,919 | C# |
using System;
using System.ComponentModel;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text;
using Elasticsearch.Net;
using FluentAssertions;
using Nest.Searchify.Converters;
using Nest.Searchify.Queries;
using Nest.Searchify.Utils;
using Newtonsoft.Json;
using Xunit;
namespace Nest.Searchify.Tests.GeoLocationTests
{
public class GeoLocationParameterContext
{
public const string SkipMessage = "Broken due to serialisation of GeoLocation within Nest library";
[Theory]
[InlineData("0,0", "0,0", 0.00)]
[InlineData("56.462018,-2.970721000000026", "55.9740046,-3.1883059", 34.75)]
[InlineData("55.9740046,-3.1883059", "56.462018,-2.970721000000026", 34.75)]
public void WhenCalculatingDistanceBetweenTwoPoints(string from, string to, double distance)
{
GeoLocationParameter fromPoint = from;
GeoLocationParameter toPoint = to;
var result = GeoMath.Distance(fromPoint.Latitude, fromPoint.Longitude, toPoint.Latitude, toPoint.Longitude,
GeoMath.MeasureUnits.Miles);
result.Should().Be(distance);
}
public class GeoLocationParameterCreation
{
[Fact]
public void WhenAttemptingToCreateAGeoLocationParameterFromEmptyString()
{
Assert.Throws<ArgumentNullException>(() =>
{
GeoLocationParameter point = "";
});
}
[Theory]
[InlineData("hello")]
[InlineData("1")]
[InlineData("1,2,3")]
public void WhenAttemptingToCreateAGeoLocationParameterFromInvalidString(string input)
{
Action a = () =>
{
GeoLocationParameter point = input;
};
a.Should().Throw<ArgumentException>();
}
[Theory]
[InlineData(-91)]
[InlineData(91)]
[InlineData(90.1)]
[InlineData(-90.1)]
public void WhenAttemptingToCreateAGeoLocationParameterWithInvalidLatitude(double latitude)
{
Action a = () =>
{
var point = new GeoLocationParameter(latitude, 0);
};
a.Should().Throw<ArgumentOutOfRangeException>().And.Message.Should().Contain("latitude");
}
[Theory]
[InlineData(-181)]
[InlineData(181)]
[InlineData(180.1)]
[InlineData(-180.1)]
public void WhenAttemptingToCreateAGeoLocationParameterWithInvalidLongitude(double longitude)
{
Action a = () =>
{
var point = new GeoLocationParameter(0, longitude);
};
a.Should().Throw<ArgumentOutOfRangeException>().And.Message.Should().Contain("longitude");
}
}
public class GeoLocationParameterSerialisationWithJsonNet
{
[Fact(Skip = SkipMessage)]
public void WhenSerialisingAGeoLocationParameterToString()
{
GeoLocationParameter point = "1.1,1.22";
var result = JsonConvert.SerializeObject(point, Formatting.None);
var expected = "{\"lat\":1.1,\"lon\":1.22}";
result.Should().Be(expected);
}
[Fact(Skip = SkipMessage)]
public void WhenDeserialisingAGeoLocationParameterFromString()
{
var input = "{\"lat\":1.1,\"lon\":1.22}";
var result = JsonConvert.DeserializeObject<GeoLocationParameter>(input);
GeoLocationParameter expected = "1.1,1.22";
result.Should().Be(expected);
}
}
public class GeoLocationParameterSerialisationWithNestSerializer
{
[Fact(Skip = SkipMessage)]
public void WhenSerialisingAGeoLocationParameterToString()
{
GeoLocationParameter point = "1.1,1.22";
var stream = new MemoryStream();
var connectionSettings = new ConnectionSettings(new SingleNodeConnectionPool(new Uri("http://localhost:9200")));
var client = new ElasticClient(connectionSettings);
client.SourceSerializer.Serialize(point, stream, SerializationFormatting.None);
stream.Seek(0, SeekOrigin.Begin);
using (var r = new StreamReader(stream))
{
var result = r.ReadToEnd();
var expected = "{\"lat\":1.1,\"lon\":1.22}";
result.Should().Be(expected);
}
}
[Fact(Skip = SkipMessage)]
public void WhenDeserialisingAGeoLocationParameterFromString()
{
var input = "{\"lat\":1.1,\"lon\":1.22}";
var connectionSettings = new ConnectionSettings(new SingleNodeConnectionPool(new Uri("http://localhost:9200")));
var client = new ElasticClient(connectionSettings);
var strm = new MemoryStream(Encoding.UTF8.GetBytes(input));
var result = client.SourceSerializer.Deserialize<GeoLocationParameter>(strm);
GeoLocationParameter expected = "1.1,1.22";
result.Should().Be(expected);
}
}
}
}
| 36.263158 | 128 | 0.560958 | [
"Apache-2.0"
] | stormid/Nest-Searchify | tests/Nest.Searchify.Tests/GeoLocationTests/GeoLocationContext.cs | 5,514 | C# |
using UnityEngine;
using System.Collections;
// <summary>
// Maze generation by dividing area in two, adding spaces in walls and repeating recursively.
// Non-recursive realisation of algorithm.
// </summary>
public class DivisionMazeGenerator : BasicMazeGenerator {
public DivisionMazeGenerator(int row, int column) : base(row, column){ }
// <summary>
// Class representing maze area to be divided
// </summary>
private struct IntRect {
public int left;
public int right;
public int top;
public int bottom;
public override string
ToString()
{
return string.Format("[IntRect {0}-{1} {2}-{3}]", left, right, bottom, top);
}
}
private System.Collections.Generic.Queue<IntRect> rectsToDivide = new System.Collections.Generic.Queue<IntRect> ();
public override void
GenerateMaze()
{
for (int row = 0; row < RowCount; row++) {
GetMazeCell(row, 0).WallLeft = true;
GetMazeCell(row, ColumnCount - 1).WallRight = true;
}
for (int column = 0; column < ColumnCount; column++) {
GetMazeCell(0, column).WallBack = true;
GetMazeCell(RowCount - 1, column).WallFront = true;
}
rectsToDivide.Enqueue(new IntRect(){ left = 0, right = ColumnCount, bottom = 0, top = RowCount });
while (rectsToDivide.Count > 0) {
IntRect currentRect = rectsToDivide.Dequeue();
int width = currentRect.right - currentRect.left;
int height = currentRect.top - currentRect.bottom;
if (width > 1 && height > 1) {
if (width > height) {
divideVertical(currentRect);
} else if (height > width) {
divideHorizontal(currentRect);
} else if (height == width) {
if (Random.Range(0, 100) > 42) {
divideVertical(currentRect);
} else {
divideHorizontal(currentRect);
}
}
} else if (width > 1 && height <= 1) {
divideVertical(currentRect);
} else if (width <= 1 && height > 1) {
divideHorizontal(currentRect);
}
}
} // GenerateMaze
// <summary>
// Divides selected area vertically
// </summary>
private void
divideVertical(IntRect rect)
{
int divCol = Random.Range(rect.left, rect.right - 1);
for (int row = rect.bottom; row < rect.top; row++) {
GetMazeCell(row, divCol).WallRight = true;
GetMazeCell(row, divCol + 1).WallLeft = true;
}
int space = Random.Range(rect.bottom, rect.top);
GetMazeCell(space, divCol).WallRight = false;
if (divCol + 1 < rect.right) {
GetMazeCell(space, divCol + 1).WallLeft = false;
}
rectsToDivide.Enqueue(new IntRect(){
left = rect.left, right = divCol + 1, bottom = rect.bottom, top = rect.top
});
rectsToDivide.Enqueue(new IntRect(){
left = divCol + 1, right = rect.right, bottom = rect.bottom, top = rect.top
});
}
// <summary>
// Divides selected area horiszontally
// </summary>
private void
divideHorizontal(IntRect rect)
{
int divRow = Random.Range(rect.bottom, rect.top - 1);
for (int col = rect.left; col < rect.right; col++) {
GetMazeCell(divRow, col).WallFront = true;
GetMazeCell(divRow + 1, col).WallBack = true;
}
int space = Random.Range(rect.left, rect.right);
GetMazeCell(divRow, space).WallFront = false;
if (divRow + 1 < rect.top) {
GetMazeCell(divRow + 1, space).WallBack = false;
}
rectsToDivide.Enqueue(new IntRect(){
left = rect.left, right = rect.right, bottom = rect.bottom, top = divRow + 1
});
rectsToDivide.Enqueue(new IntRect(){
left = rect.left, right = rect.right, bottom = divRow + 1,
top = rect.top
});
}
}
| 35.512821 | 119 | 0.551865 | [
"MIT"
] | LilyHeAsamiko/Arena-BuildingToolkit | Assets/ArenaSDK/Prefabs/Playgrounds/MazeUtils/Scripts/DivisionMazeGenerator.cs | 4,157 | C# |
namespace Sitecore.Feature.Demo.Models
{
public class Location
{
public string Country { get; set; }
public string City { get; set; }
public string BusinessName { get; set; }
public string Url { get; set; }
public string Latitude { get; set; }
public string Longitude { get; set; }
public string Region { get; set; }
}
} | 28.769231 | 48 | 0.609626 | [
"Apache-2.0"
] | uwe-e/mch.habitat.v91 | src/Feature/Demo/code/Models/Location.cs | 374 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.Text.RegularExpressions;
using System.Web;
using System.IO;
using System.Net;
using System.Web.Security;
using System.Security.Policy;
namespace Kooboo.Drawing
{
public static class MetroImage
{
/// <summary>
/// Read image either from local file or from remote website
/// </summary>
/// <param name="image_path"></param>
/// <param name="target_path"></param>
/// <returns></returns>
public static System.Drawing.Image getImage(string image_path,string target_path="")
{
Image img = null;
if (Regex.IsMatch(image_path, @"^https?"))
{
img = getRemoteImage(image_path, target_path);
}
else
{
img = Image.FromFile(image_path);
}
return img;
}
/// <summary>
/// Get remote image and cache locally
/// </summary>
/// <param name="image_path">Appsolute path to remote image</param>
/// <param name="targetFilePath">targetFilePath where the image should be cached</param>
/// <returns>Image object</returns>
public static Image getRemoteImage(string remote_path, string targetFilePath)
{
remote_path = HttpUtility.UrlDecode(remote_path);
// filename
string filename = FormsAuthentication.HashPasswordForStoringInConfigFile(remote_path, "MD5") + ".jpg";
// cache path
string dir = Path.GetDirectoryName(targetFilePath);
string save_path = Path.Combine(dir,filename);
// debug
//HttpContext.Current.Response.Write(save_path + "- -save_path : dir -" + dir + " targat file path: " + targetFilePath);
//HttpContext.Current.Response.End();
// napravi folder ako ne postoji
if (!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
// ako nismo skinuli tu sliku skini je opet
if (!System.IO.File.Exists(save_path))
{
WebClient WebClient = new WebClient();
byte[] imageBytes;
try
{
imageBytes = WebClient.DownloadData(remote_path);
// Open file for reading
System.IO.FileStream _FileStream = new System.IO.FileStream(save_path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
_FileStream.Write(imageBytes, 0, imageBytes.Length);
_FileStream.Close();
}
catch (WebException ex)
{
//HttpContext.Current.Response.Write("remote-path returned 404:" + remote_path);
//HttpContext.Current.Response.End();
System.IO.FileStream FileStream = new System.IO.FileStream(save_path, System.IO.FileMode.Create, System.IO.FileAccess.Write);
//FileStream.Write(imageBytes, 0, imageBytes.Length);
Stream r_stream = ex.Response.GetResponseStream();
r_stream.CopyTo(FileStream);
r_stream.Close();
FileStream.Close();
}
WebClient.Dispose();
}
// vrati putanju do lokalne slike
return Image.FromFile(save_path);
}
public static bool SmartSize(string sourceFilePath, string targetFilePath, int width, int height, string vAlign, string hAlign = "center")
{
Image img = getImage(sourceFilePath,targetFilePath) ;
Image target = resize(img, width, height,vAlign,hAlign);
img.Dispose();
String extension = System.IO.Path.GetExtension(sourceFilePath).ToLower();
if (extension !=".png")
{
ImageCodecInfo jgpEncoder = ImageTools.GetJpgCodec();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 98L);
myEncoderParameters.Param[0] = myEncoderParameter;
target.Save(targetFilePath, jgpEncoder, myEncoderParameters);
}
else
{
target.Save(targetFilePath, System.Drawing.Imaging.ImageFormat.Png);
}
return true;
}
public static bool CropAndResize(string sourceFilePath, string targetFilePath, int x, int y, int width, int height, int destWidth=0, int destHeight=0 )
{
Image img = getImage(sourceFilePath, targetFilePath);
Image target = ImageCropAndResize(img, x, y, width, height, destWidth, destHeight);
img.Dispose();
String extension = System.IO.Path.GetExtension(sourceFilePath).ToLower();
if (extension != ".png")
{
ImageCodecInfo jgpEncoder = ImageTools.GetJpgCodec();
System.Drawing.Imaging.Encoder myEncoder = System.Drawing.Imaging.Encoder.Quality;
EncoderParameters myEncoderParameters = new EncoderParameters(1);
EncoderParameter myEncoderParameter = new EncoderParameter(myEncoder, 98L);
myEncoderParameters.Param[0] = myEncoderParameter;
target.Save(targetFilePath, jgpEncoder, myEncoderParameters);
}
else
{
target.Save(targetFilePath, System.Drawing.Imaging.ImageFormat.Png);
}
return true;
}
public static System.Drawing.Image resize(System.Drawing.Image imgPhoto, int Width, int Height,string vAlign="center", string hAlign="center")
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int sourceX = 0;
int sourceY = 0;
int destX = 0;
int destY = 0;
float nPercent = 0;
float nPercentW = 0;
float nPercentH = 0;
// max size
if (Width > 1024)
{
Width = 1024;
}
if (Height > 1024)
{
Height = 1024;
}
nPercentW = ((float)Width / (float)sourceWidth);
nPercentH = ((float)Height / (float)sourceHeight);
if (nPercentH > nPercentW) // prvo povecaj manju stranu da nebude bijeloga
{
nPercent = nPercentH;
int w = Width;
if(w==0)
{
w = (int)Math.Floor(sourceWidth * nPercent);
}
if (hAlign != "left" && hAlign != "right")
{
destX = (int)Math.Floor((w - (sourceWidth * nPercent)) / 2);
}
else if (hAlign == "right")
{
destX = (int)Math.Ceiling((w - (sourceWidth * nPercent)));
}
//sourceX = System.Convert.ToInt16((sourceWidth - Width) / 2);
}
else
{
nPercent = nPercentW;
int h = Height;
if (h == 0)
{
h = (int)Math.Floor(sourceHeight * nPercent);
}
if (vAlign != "top" && vAlign != "bottom")
{
destY = (int)Math.Floor((Height - (sourceHeight * nPercent)) / 2);
}
else if (vAlign == "bottom")
{
destY = (int)Math.Ceiling((Height - (sourceHeight * nPercent)) );
}
//sourceY = System.Convert.ToInt16((sourceHeight - Height) / 2);
}
int destWidth = (int)Math.Ceiling(sourceWidth * nPercent);
int destHeight = (int)Math.Ceiling(sourceHeight * nPercent);
int bmpWidth = Width > 0 ? Width : destWidth;
int bmpHeight = Height > 0 ? Height : destHeight;
Bitmap bmPhoto = new Bitmap(bmpWidth, bmpHeight, PixelFormat.Format32bppArgb); ;
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//grPhoto.Clear(Color.Transparent);
grPhoto.CompositingMode = CompositingMode.SourceCopy;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX-1, destY-1, destWidth+1, destHeight+1),
new Rectangle(sourceX, sourceY, sourceWidth, sourceHeight),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
public static System.Drawing.Image ImageCropAndResize(System.Drawing.Image imgPhoto, int x, int y, int Width, int Height, int destWidth=0, int destHeight=0)
{
int sourceWidth = imgPhoto.Width;
int sourceHeight = imgPhoto.Height;
int destX = 0;
int destY = 0;
// zadane dimenzije nesmiju biti vece od izvornih
if (x < 0) { x = 0; }
if (y < 0) { y = 0; }
if (Width > sourceWidth) { Width = sourceWidth; }
if (Height > sourceHeight) { Height = sourceHeight; }
float nPercentW = ((float)destWidth / (float)Width);
float nPercentH = ((float)destHeight / (float)Height);
if (destWidth == 0 && destHeight == 0)
{
destWidth = Width;
destHeight = Height;
}
else
{
nPercentW = ((float)destWidth / (float)Width);
nPercentH = ((float)destHeight / (float)Height);
if (destHeight > 0 && destWidth==0)
{
destWidth = (int)(Width * nPercentH);
} else if (destWidth > 0 && destHeight==0)
{
destHeight = (int)(Height * nPercentW);
}
}
Bitmap bmPhoto = bmPhoto = new Bitmap(destWidth, destHeight, PixelFormat.Format32bppArgb); ;
bmPhoto.SetResolution(imgPhoto.HorizontalResolution, imgPhoto.VerticalResolution);
Graphics grPhoto = Graphics.FromImage(bmPhoto);
//grPhoto.Clear(Color.Transparent);
grPhoto.CompositingMode = CompositingMode.SourceCopy;
grPhoto.InterpolationMode = InterpolationMode.HighQualityBicubic;
grPhoto.DrawImage(imgPhoto,
new Rectangle(destX - 1, destY - 1, destWidth + 2, destHeight + 2),
new Rectangle(x, y, Width, Height),
GraphicsUnit.Pixel);
grPhoto.Dispose();
return bmPhoto;
}
}
}
| 33.787879 | 158 | 0.604883 | [
"BSD-3-Clause"
] | hrvoje-grabusic/CMS | Kooboo.CMS/Kooboo/Drawing/MetroImage.cs | 10,037 | C# |
using System.Data.Entity;
using System.Data.Entity.SqlServer;
namespace BohFoundation.EntityFrameworkBaseClass
{
public class AzureDbConfiguration : DbConfiguration
{
public AzureDbConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient",() => new SqlAzureExecutionStrategy());
}
}
}
| 24.285714 | 96 | 0.694118 | [
"MIT"
] | Sobieck00/BOH-Bulldog-Scholarship-Application-Management | BohFoundation.EntityFrameworkBaseClass/AzureDbConfiguration.cs | 342 | C# |
using Orderio.Domain.Models;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace Orderio.Domain.Interfaces
{
public interface IOrderStatusRepository : IRepository<OrderStatus>
{
Task<List<OrderStatus>> GetAllOrderStatusesAsync(long orderId);
}
}
| 24.166667 | 71 | 0.768966 | [
"MIT"
] | Yaroslav08/Orderio | Orderio/Orderio.Domain/Interfaces/IOrderStatusRepository.cs | 292 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Kartverket.Register.Models;
using Kartverket.Register.Models.Api;
using Kartverket.Register.Services.RegisterItem;
using Kartverket.Register.Services.Register;
using Kartverket.Register.App_Start;
namespace Kartverket.Register.Controllers
{
public class AlertApiController : ApiController
{
private readonly RegisterDbContext _dbContext;
private IRegisterService _registerService;
private IRegisterItemService _registerItemService;
public AlertApiController(RegisterDbContext dbContext, IRegisterItemService registerItemServive, IRegisterService registerService)
{
_dbContext = dbContext;
_registerItemService = registerItemServive;
_registerService = registerService;
}
/// <summary>
/// Add alert
/// </summary>
[System.Web.Http.Authorize(Roles = AuthConfig.RegisterProviderRole)]
[ResponseType(typeof(AlertAdd))]
[ApiExplorerSettings(IgnoreApi = false)]
[System.Web.Http.HttpPost]
public IHttpActionResult PostServiceAlert(AlertAdd alertService)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
string parentRegister = null;
string registerName = "varsler";
Alert serviceAlert = new Alert();
serviceAlert.name = "navn";
serviceAlert.AlertCategory = Constants.AlertCategoryService;
serviceAlert.AlertType = alertService.AlertType;
serviceAlert.Note = alertService.Note;
serviceAlert.UuidExternal = alertService.ServiceUuid;
if (alertService.AlertDate.HasValue)
serviceAlert.AlertDate = alertService.AlertDate.Value;
if (alertService.EffectiveDate.HasValue)
serviceAlert.EffectiveDate = alertService.EffectiveDate.Value;
serviceAlert.register = _registerService.GetRegister(parentRegister, registerName);
if (serviceAlert.register != null)
{
if (ModelState.IsValid)
{
if(string.IsNullOrEmpty(serviceAlert.Owner))
serviceAlert.Owner = "Kartverket";
serviceAlert.GetMetadataByUuid();
serviceAlert.submitterId = new Guid("10087020-F17C-45E1-8542-02ACBCF3D8A3");
serviceAlert.InitializeNewAlert();
serviceAlert.versioningId = _registerItemService.NewVersioningGroup(serviceAlert);
serviceAlert.register.modified = System.DateTime.Now;
_registerItemService.SaveNewRegisterItem(serviceAlert);
}
}
return StatusCode(HttpStatusCode.OK);
}
/// <summary>
/// Get all alerts
/// </summary>
[ResponseType(typeof(List<AlertView>))]
[ApiExplorerSettings(IgnoreApi = false)]
[System.Web.Http.HttpGet]
public IHttpActionResult Get()
{
var alertRegister = _registerService.GetRegister(null, "varsler");
List<AlertView> alerts = new List<AlertView>();
foreach (Alert alert in alertRegister.items)
{
alerts.Add(
new AlertView {
SystemId = alert.systemId.ToString(),
Label = alert.name,
AlertDate = alert.AlertDate,
AlertType = alert.AlertType,
EffectiveDate = alert.EffectiveDate,
Note = alert.Note,
AlertCategory = alert.AlertCategory
});
}
return Ok(alerts);
}
/// <summary>
/// Get alert
/// </summary>
[ResponseType(typeof(AlertView))]
[ApiExplorerSettings(IgnoreApi = false)]
[System.Web.Http.HttpGet]
public IHttpActionResult GetId(string id)
{
var alert = _dbContext.Alerts.Where(a => a.systemId.ToString() == id).FirstOrDefault();
if (alert == null)
return NotFound();
var alertView = new AlertView();
alertView.SystemId = alert.systemId.ToString();
alertView.Label = alert.name;
alertView.AlertCategory = alert.AlertCategory;
alertView.AlertDate = alert.AlertDate;
alertView.AlertType = alert.AlertType;
alertView.DateResolved = alert.DateResolved;
alertView.EffectiveDate = alert.EffectiveDate;
alertView.Department = alert.departmentId;
alertView.Image1 = alert.Image1;
alertView.Image1Thumbnail = alert.Image1Thumbnail;
alertView.Image2 = alert.Image2;
alertView.Image2Thumbnail = alert.Image2Thumbnail;
alertView.Link = alert.Link;
alertView.Note = alert.Note;
alertView.Owner = alert.Owner;
alertView.StationName = alert.StationName;
alertView.StationType = alert.StationType;
alertView.Summary = alert.Summary;
alertView.Tags = alert.Tags.Select(t => t.value).ToList();
alertView.UrlExternal = alert.UrlExternal;
if(alert.AlertCategory != "Driftsmelding")
{
alertView.Type = alert.Type;
alertView.UuidExternal = alert.UuidExternal;
}
return Ok(alertView);
}
/// <summary>
/// Update alert
/// </summary>
[System.Web.Http.Authorize(Roles = AuthConfig.RegisterProviderRole)]
[ApiExplorerSettings(IgnoreApi = false)]
[ResponseType(typeof(void))]
[System.Web.Http.HttpPut]
public IHttpActionResult PutServiceAlert(string id, AlertUpdate alert)
{
var originalAlert = _dbContext.Alerts.Where(a => a.systemId.ToString() == id).FirstOrDefault();
if (originalAlert == null)
return NotFound();
originalAlert.Summary = alert.Summary;
originalAlert.DateResolved = alert.DateResolved;
originalAlert.register.modified = System.DateTime.Now;
_dbContext.Entry(originalAlert).State = EntityState.Modified;
_dbContext.SaveChanges();
return StatusCode(HttpStatusCode.NoContent);
}
[ApiExplorerSettings(IgnoreApi = true)]
[ResponseType(typeof(AlertAdd))]
[System.Web.Http.HttpDelete]
public IHttpActionResult DeleteServiceAlert(Guid id)
{
return StatusCode(HttpStatusCode.MethodNotAllowed);
}
}
} | 38.195652 | 138 | 0.600028 | [
"MIT"
] | kartverket/Geonorge.Register | Kartverket.Register/Controllers/AlertApiController.cs | 7,030 | C# |
using System.Collections.Generic;
using JetBrains.Application.DataContext;
using JetBrains.ReSharper.Feature.Services.Generate.Actions;
namespace JetBrains.ReSharper.Plugins.Unity.CSharp.Feature.Services.Generate
{
[GenerateProvider]
public class GenerateUnityEventFunctionsWorkflowProvider : IGenerateWorkflowProvider
{
public IEnumerable<IGenerateActionWorkflow> CreateWorkflow(IDataContext dataContext)
{
return new[] {new GenerateUnityEventFunctionsWorkflow()};
}
}
} | 34.933333 | 92 | 0.772901 | [
"Apache-2.0"
] | 20chan/resharper-unity | resharper/resharper-unity/src/CSharp/Feature/Services/Generate/GenerateUnityEventFunctionsWorkflowProvider.cs | 524 | C# |
using NUnit.Framework;
using System.Linq;
using System.Net;
namespace StackExchange.Redis.Tests
{
[TestFixture]
public class DefaultPorts
{
[Test]
[TestCase("foo", 6379)]
[TestCase("foo:6379", 6379)]
[TestCase("foo:6380", 6380)]
[TestCase("foo,ssl=false", 6379)]
[TestCase("foo:6379,ssl=false", 6379)]
[TestCase("foo:6380,ssl=false", 6380)]
[TestCase("foo,ssl=true", 6380)]
[TestCase("foo:6379,ssl=true", 6379)]
[TestCase("foo:6380,ssl=true", 6380)]
[TestCase("foo:6381,ssl=true", 6381)]
public void ConfigStringRoundTripWithDefaultPorts(string config, int expectedPort)
{
var options = ConfigurationOptions.Parse(config);
string backAgain = options.ToString();
Assert.AreEqual(config, backAgain.Replace("=True","=true").Replace("=False", "=false"));
options.SetDefaultPorts(); // normally it is the multiplexer that calls this, not us
Assert.AreEqual(expectedPort, ((DnsEndPoint)options.EndPoints.Single()).Port);
}
[Test]
[TestCase("foo", 0, false, 6379)]
[TestCase("foo", 6379, false, 6379)]
[TestCase("foo", 6380, false, 6380)]
[TestCase("foo", 0, true, 6380)]
[TestCase("foo", 6379, true, 6379)]
[TestCase("foo", 6380, true, 6380)]
[TestCase("foo", 6381, true, 6381)]
public void ConfigManualWithDefaultPorts(string host, int port, bool useSsl, int expectedPort)
{
var options = new ConfigurationOptions();
if(port == 0)
{
options.EndPoints.Add(host);
} else
{
options.EndPoints.Add(host, port);
}
if (useSsl) options.Ssl = true;
options.SetDefaultPorts(); // normally it is the multiplexer that calls this, not us
Assert.AreEqual(expectedPort, ((DnsEndPoint)options.EndPoints.Single()).Port);
}
}
}
| 34.389831 | 102 | 0.576639 | [
"Apache-2.0"
] | luberg/StackExchange.Redis | StackExchange.Redis.Tests/DefaultPorts.cs | 2,031 | C# |
namespace Sqlbi.Bravo.Infrastructure.Extensions.DynamicLinq.Parser
{
internal static class Res
{
public const string DuplicateIdentifier = "The identifier '{0}' was defined more than once";
public const string ExpressionTypeMismatch = "Expression of type '{0}' expected";
public const string ExpressionExpected = "Expression expected";
public const string InvalidCharacterLiteral = "Character literal must contain exactly one character";
public const string InvalidIntegerLiteral = "Invalid integer literal '{0}'";
public const string InvalidRealLiteral = "Invalid real literal '{0}'";
public const string UnknownIdentifier = "Unknown identifier '{0}'";
public const string NoItInScope = "No 'it' is in scope";
public const string IifRequiresThreeArgs = "The 'iif' function requires three arguments";
public const string FirstExprMustBeBool = "The first expression must be of type 'Boolean'";
public const string BothTypesConvertToOther = "Both of the types '{0}' and '{1}' convert to the other";
public const string NeitherTypeConvertsToOther = "Neither of the types '{0}' and '{1}' converts to the other";
public const string MissingAsClause = "Expression is missing an 'as' clause";
public const string ArgsIncompatibleWithLambda = "Argument list incompatible with lambda expression";
public const string TypeHasNoNullableForm = "Type '{0}' has no nullable form";
public const string NoMatchingConstructor = "No matching constructor in type '{0}'";
public const string AmbiguousConstructorInvocation = "Ambiguous invocation of '{0}' constructor";
public const string CannotConvertValue = "A value of type '{0}' cannot be converted to type '{1}'";
public const string NoApplicableMethod = "No applicable method '{0}' exists in type '{1}'";
public const string MethodsAreInaccessible = "Methods on type '{0}' are not accessible";
public const string MethodIsVoid = "Method '{0}' in type '{1}' does not return a value";
public const string AmbiguousMethodInvocation = "Ambiguous invocation of method '{0}' in type '{1}'";
public const string UnknownPropertyOrField = "No property or field '{0}' exists in type '{1}'";
public const string NoApplicableAggregate = "No applicable aggregate method '{0}' exists";
public const string CannotIndexMultiDimArray = "Indexing of multi-dimensional arrays is not supported";
public const string InvalidIndex = "Array index must be an integer expression";
public const string NoApplicableIndexer = "No applicable indexer exists in type '{0}'";
public const string AmbiguousIndexerInvocation = "Ambiguous invocation of indexer in type '{0}'";
public const string IncompatibleOperand = "Operator '{0}' incompatible with operand type '{1}'";
public const string IncompatibleOperands = "Operator '{0}' incompatible with operand types '{1}' and '{2}'";
public const string UnterminatedStringLiteral = "Unterminated string literal";
public const string InvalidCharacter = "Syntax error '{0}'";
public const string DigitExpected = "Digit expected";
public const string SyntaxError = "Syntax error";
public const string TokenExpected = "{0} expected";
public const string ParseExceptionFormat = "{0} (at index {1})";
public const string ColonExpected = "':' expected";
public const string OpenParenExpected = "'(' expected";
public const string CloseParenOrOperatorExpected = "')' or operator expected";
public const string CloseParenOrCommaExpected = "')' or ',' expected";
public const string DotOrOpenParenExpected = "'.' or '(' expected";
public const string OpenBracketExpected = "'[' expected";
public const string CloseBracketOrCommaExpected = "']' or ',' expected";
public const string IdentifierExpected = "Identifier expected";
}
}
| 79.137255 | 118 | 0.702428 | [
"MIT"
] | hanaseleb/Bravo | src/Infrastructure/Extensions/DynamicLinq/Parser/ParseConstants.cs | 4,038 | C# |
using System.Web;
using System.Web.Optimization;
namespace IoTSensorPortal
{
public class BundleConfig
{
// For more information on bundling, visit https://go.microsoft.com/fwlink/?LinkId=301862
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js"));
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.validate*"));
bundles.Add(new ScriptBundle("~/bundles/jqueryajax").Include(
"~/Scripts/jquery.unobtrusive-ajax.js"));
// Use the development version of Modernizr to develop with and learn from. Then, when you're
// ready for production, use the build tool at https://modernizr.com to pick only the tests you need.
bundles.Add(new ScriptBundle("~/bundles/modernizr").Include(
"~/Scripts/modernizr-*"));
bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
"~/Scripts/bootstrap.js",
"~/Scripts/respond.js"));
bundles.Add(new StyleBundle("~/Content/css").Include(
"~/Content/bootstrap.css",
"~/Content/site.css"));
}
}
}
| 39.285714 | 113 | 0.578909 | [
"MIT"
] | CecoMilchev/IoTSensorPortal | IoTSensorPortal/App_Start/BundleConfig.cs | 1,377 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Liu.Infra.CrossCutting.Identity")]
[assembly: AssemblyTrademark("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("37c44a01-20fe-4b09-8435-47164f08c0c8")]
| 42.210526 | 84 | 0.779302 | [
"MIT"
] | faugusto90/LiuProject | src/Liu.Infra.CrossCutting.Identity/Properties/AssemblyInfo.cs | 804 | C# |
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information.
//
// ███╗ ██╗ ██████╗ ████████╗██╗ ██████╗███████╗
// ████╗ ██║██╔═══██╗╚══██╔══╝██║██╔════╝██╔════╝
// ██╔██╗ ██║██║ ██║ ██║ ██║██║ █████╗
// ██║╚██╗██║██║ ██║ ██║ ██║██║ ██╔══╝
// ██║ ╚████║╚██████╔╝ ██║ ██║╚██████╗███████╗
// ╚═╝ ╚═══╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝╚══════╝
// ------------------------------------------------
//
// This file is automatically generated.
// Please do not edit these files manually.
//
// ------------------------------------------------
using System;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Text.Json;
using System.Text.Json.Serialization;
#nullable restore
namespace Elastic.Clients.Elasticsearch
{
public partial class ReindexTask
{
[JsonInclude]
[JsonPropertyName("action")]
public string Action { get; init; }
[JsonInclude]
[JsonPropertyName("cancellable")]
public bool Cancellable { get; init; }
[JsonInclude]
[JsonPropertyName("description")]
public string Description { get; init; }
[JsonInclude]
[JsonPropertyName("headers")]
public Dictionary<string, IReadOnlyCollection<string>> Headers { get; init; }
[JsonInclude]
[JsonPropertyName("id")]
public long Id { get; init; }
[JsonInclude]
[JsonPropertyName("node")]
public string Node { get; init; }
[JsonInclude]
[JsonPropertyName("running_time_in_nanos")]
public long RunningTimeInNanos { get; init; }
[JsonInclude]
[JsonPropertyName("start_time_in_millis")]
public long StartTimeInMillis { get; init; }
[JsonInclude]
[JsonPropertyName("status")]
public Elastic.Clients.Elasticsearch.ReindexStatus Status { get; init; }
[JsonInclude]
[JsonPropertyName("type")]
public string Type { get; init; }
}
} | 28.072464 | 79 | 0.578214 | [
"Apache-2.0"
] | SimonCropp/elasticsearch-net | src/Elastic.Clients.Elasticsearch/_Generated/Types/ReindexTask.g.cs | 2,383 | C# |
using System;
using System.Xml.Serialization;
namespace EZOper.NetSiteUtilities.AopApi
{
/// <summary>
/// VoucherLiteInfo Data Structure.
/// </summary>
[Serializable]
public class VoucherLiteInfo : AopObject
{
/// <summary>
/// 发券时间,格式为:yyyy-MM-dd HH:mm:ss
/// </summary>
[XmlElement("send_time")]
public string SendTime { get; set; }
/// <summary>
/// 券状态,可枚举,分别为“可用”(ENABLED)和“不可用”(DISABLED)
/// </summary>
[XmlElement("status")]
public string Status { get; set; }
/// <summary>
/// 券模板ID
/// </summary>
[XmlElement("template_id")]
public string TemplateId { get; set; }
/// <summary>
/// 券ID
/// </summary>
[XmlElement("voucher_id")]
public string VoucherId { get; set; }
}
}
| 23.594595 | 52 | 0.526919 | [
"MIT"
] | erikzhouxin/CSharpSolution | NetSiteUtilities/AopApi/Domain/VoucherLiteInfo.cs | 941 | C# |
namespace WoWCombatLogParser.Models
{
public enum Reaction
{
Neutral,
Friendly,
Hostile
}
public enum UnitType
{
Player,
Pet,
NPC,
}
public enum EnvironmentalType
{
Drowning,
Falling,
Fatigue,
Fire,
Lava,
Slime
}
public enum AuraType
{
BUFF,
DEBUFF
}
public enum MissType
{
ABSORB,
BLOCK,
DEFLECT,
DODGE,
EVADE,
IMMUNE,
MISS,
PARRY,
REFLECT,
RESIST
}
public enum Faction
{
Horde = 0,
Alliance
}
public enum SpellSchool
{
None = 0,
Physical = 0x1,
Holy = 0x2,
HolyStrike = Holy | Physical,
Fire = 0x4,
FlameStrike = Fire | Physical,
Radiant = Holy | Fire,
Nature = 0x8,
Stormstrike = Nature | Physical,
Holystorm = Nature | Holy,
Firestorm = Nature | Fire,
Frost = 0x10,
Froststrike = Frost | Physical,
Holyfrost = Frost | Holy,
Frostfire = Frost | Fire,
Froststorm = Frost | Nature,
Elemental = Frost | Nature | Fire,
Shadow = 0x20,
Shadowstrike = Shadow | Physical,
Twilight = Shadow | Holy,
Shadowflame = Shadow | Fire,
Plague = Shadow | Nature,
Shadowfrost = Shadow | Frost,
Arcane = 0x40,
Spellstrike = Arcane | Physical,
Divine = Arcane | Holy,
Spellfire = Arcane | Fire,
Astral = Arcane | Nature,
Spellfrost = Arcane | Frost,
Spellshadow = Arcane | Shadow,
Chromatic = Spellshadow | Elemental,
Magic = Chromatic | Holy,
Chaos = Magic | Physical
}
public enum PowerType
{
HealthCost = -2,
None,
Mana,
Rage,
Focus,
Energy,
ComboPoints,
Runes,
RunicPower,
SoulShards,
LunaPower,
HolyPower,
Alternate,
Chi,
Insanity,
Obsolete,
Obsolete2,
ArcaneCharges,
Fury,
Pain,
NumPowerTypes
}
}
| 19.382609 | 44 | 0.486765 | [
"Apache-2.0"
] | ranky/WowCombatLogParser | WowCombatLogParser/Models/Enums.cs | 2,231 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Charlotte.Games;
namespace Charlotte.Tests.Games
{
public class WorldGameMasterTest
{
public void Test01()
{
using (new WorldGameMaster())
{
WorldGameMaster.I.Perform();
}
}
public void Test02()
{
using (new WorldGameMaster())
{
WorldGameMaster.I.World = new World("t0001");
WorldGameMaster.I.Status = new GameStatus();
WorldGameMaster.I.Perform();
}
}
public void Test03()
{
string startMapName;
// ---- choose one ----
//startMapName = "t0001";
startMapName = "t0002";
//startMapName = "t0003";
//startMapName = "t0004";
//startMapName = "t0005";
// ----
using (new WorldGameMaster())
{
WorldGameMaster.I.World = new World(startMapName);
WorldGameMaster.I.Status = new GameStatus();
WorldGameMaster.I.Perform();
}
}
}
}
| 17.730769 | 54 | 0.639913 | [
"MIT"
] | soleil-taruto/Elsa | e20210103_YokoActTK_Demo2/Elsa20200001/Elsa20200001/Tests/Games/WorldGameMasterTest.cs | 924 | C# |
using Microsoft.EntityFrameworkCore;
namespace Votify.Api.Models
{
[Owned]
public class PlayerState
{
public bool Paused { get; set; }
public int Duration { get; set; }
public int Position { get; set; }
public string SpotifyTrackId { get; set; }
public string SpotifyTrackName { get; set; }
public string SpotifyTrackArtist { get; set; }
public string SpotifyTrackImageUrl { get; set; }
}
}
| 26.833333 | 57 | 0.604555 | [
"MIT"
] | villor/votify | Votify/Votify.Api/Models/PlayerState.cs | 485 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using Control_Escolar.Context;
namespace Control_Escolar
{
class AccionesAlumnos
{
public AccionesAlumnos()
{
}
public static int Agregar(Alumno pAlumno)
{
int retorno = 0;
MySqlCommand comando = new MySqlCommand(string.Format("Insert into alumno (CURP,Nombre,AMaterno,APaterno,num_control,Numero_Seguro,dia,mes,año,edad,esc_procedencia) values ('{0}','{1}','{2}', '{3}','{4}','{5}','{6}', '{7}','{8}','{9}','{10}')",
pAlumno.CURP, pAlumno.Nombre, pAlumno.AMaterno, pAlumno.APaterno, pAlumno.num_control, pAlumno.Numero_Seguro, pAlumno.dia, pAlumno.mes, pAlumno.año, pAlumno.edad, pAlumno.esc_procedencia), Conexion.ConectarMysql());
retorno = comando.ExecuteNonQuery();
return retorno;
}
public static List<Alumno> Buscar(string pNombre, string pAPaterno, string pAMaterno, string pnum_control)
{
List<Alumno> _lista = new List<Alumno>();
MySqlCommand _comando = new MySqlCommand(String.Format(
"SELECT CURP, Nombre,AMaterno,APaterno,num_control,Numero_Seguro,dia,mes,año,edad,esc_procedencia FROM alumno where Nombre ='{0}' or APaterno='{1}'or AMaterno='{2}'or num_control='{3}'", pNombre,pAPaterno,pAMaterno,pnum_control), Conexion.ConectarMysql());
MySqlDataReader _reader = _comando.ExecuteReader();
while (_reader.Read())
{
Alumno pAlumno = new Alumno();
pAlumno.CURP = _reader.GetString(0);
pAlumno.Nombre = _reader.GetString(1);
pAlumno.AMaterno = _reader.GetString(2);
pAlumno.APaterno = _reader.GetString(3);
pAlumno.num_control = _reader.GetInt32(4);
pAlumno.Numero_Seguro = _reader.GetString(5);
pAlumno.dia = _reader.GetInt32(6);
pAlumno.mes = _reader.GetString(7);
pAlumno.año = _reader.GetInt32(8);
pAlumno.edad = _reader.GetInt32(9);
pAlumno.esc_procedencia = _reader.GetString(10);
_lista.Add(pAlumno);
}
return _lista;
}
public static Alumno ObtenerAlumno(string pCURP)
{
Alumno pAlumno = new Alumno();
MySqlConnection conexion = Conexion.ConectarMysql();
MySqlCommand _comando = new MySqlCommand(String.Format("SELECT CURP, Nombre,AMaterno,APaterno,num_control,Numero_Seguro,dia,mes,año,edad,esc_procedencia FROM alumno where CURP={0}", pCURP), conexion);
MySqlDataReader _reader = _comando.ExecuteReader();
while (_reader.Read())
{
pAlumno.CURP = _reader.GetString(0);
pAlumno.Nombre = _reader.GetString(1);
pAlumno.AMaterno = _reader.GetString(2);
pAlumno.APaterno = _reader.GetString(3);
pAlumno.num_control = _reader.GetInt32(4);
pAlumno.Numero_Seguro = _reader.GetString(5);
pAlumno.dia = _reader.GetInt32(6);
pAlumno.mes = _reader.GetString(7);
pAlumno.año = _reader.GetInt32(8);
pAlumno.edad = _reader.GetInt32(9);
pAlumno.esc_procedencia = _reader.GetString(10);
}
conexion.Close();
return pAlumno;
}
}
}
| 37.677083 | 268 | 0.59248 | [
"BSD-2-Clause"
] | Equipo-6/Gestion | Control Escolar/Control Escolar/AccionesAlumnos.cs | 3,625 | C# |
namespace CRUDreborn.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class vendatotal : DbMigration
{
public override void Up()
{
AddColumn("dbo.Vendas", "Total", c => c.Single(nullable: false));
}
public override void Down()
{
DropColumn("dbo.Vendas", "Total");
}
}
}
| 21.368421 | 77 | 0.541872 | [
"MIT"
] | diguifi/CRUDrelatedEntities | src/CRUDreborn.EntityFramework/Migrations/201803291123486_venda-total.cs | 406 | C# |
using System;
using NServiceBus;
class Program
{
static void Main()
{
Console.Title = "Samples.Callbacks.Sender";
var busConfiguration = new BusConfiguration();
busConfiguration.EndpointName("Samples.Callbacks.Sender");
busConfiguration.UseSerialization<JsonSerializer>();
busConfiguration.UsePersistence<InMemoryPersistence>();
busConfiguration.EnableInstallers();
using (var bus = Bus.Create(busConfiguration).Start())
{
Console.WriteLine("Press 'E' to send a message with an enum return");
Console.WriteLine("Press 'I' to send a message with an int return");
Console.WriteLine("Press 'O' to send a message with an object return");
Console.WriteLine("Press any other key to exit");
while (true)
{
var key = Console.ReadKey();
Console.WriteLine();
if (key.Key == ConsoleKey.E)
{
SendEnumMessage(bus);
continue;
}
if (key.Key == ConsoleKey.I)
{
SendIntMessage(bus);
continue;
}
if (key.Key == ConsoleKey.O)
{
SendObjectMessage(bus);
continue;
}
return;
}
}
}
static void SendEnumMessage(IBus bus)
{
#region SendEnumMessage
var message = new EnumMessage();
bus.Send("Samples.Callbacks.Receiver", message)
.Register<Status>(
callback: status =>
{
Console.WriteLine($"Callback received with status:{status}");
});
#endregion
Console.WriteLine("Message sent");
}
static void SendIntMessage(IBus bus)
{
#region SendIntMessage
var message = new IntMessage();
bus.Send("Samples.Callbacks.Receiver", message)
.Register<int>(
callback: response =>
{
Console.WriteLine($"Callback received with response:{response}");
});
#endregion
Console.WriteLine("Message sent");
}
static void SendObjectMessage(IBus bus)
{
#region SendObjectMessage
var message = new ObjectMessage();
bus.Send("Samples.Callbacks.Receiver", message)
.Register(
callback: asyncResult =>
{
var localResult = (CompletionResult) asyncResult.AsyncState;
var response = (ObjectResponseMessage) localResult.Messages[0];
Console.WriteLine($"Callback received with response property value:{response.Property}");
},
state: null);
#endregion
Console.WriteLine("Message sent");
}
} | 30.475248 | 110 | 0.502924 | [
"Apache-2.0"
] | A-Franklin/docs.particular.net | samples/callbacks/Core_5/Sender/Program.cs | 2,978 | C# |
using System;
using NetRuntimeSystem = System;
using System.ComponentModel;
using NetOffice.Attributes;
namespace NetOffice.OfficeApi
{
/// <summary>
/// DispatchInterface ThemeColor
/// SupportByVersion Office, 12,14,15,16
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.ThemeColor"/> </remarks>
[SupportByVersion("Office", 12,14,15,16)]
[EntityType(EntityType.IsDispatchInterface)]
public class ThemeColor : _IMsoDispObj
{
#pragma warning disable
#region Type Information
/// <summary>
/// Instance Type
/// </summary>
[EditorBrowsable(EditorBrowsableState.Advanced), Browsable(false), Category("NetOffice"), CoreOverridden]
public override Type InstanceType
{
get
{
return LateBindingApiWrapperType;
}
}
private static Type _type;
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public static Type LateBindingApiWrapperType
{
get
{
if (null == _type)
_type = typeof(ThemeColor);
return _type;
}
}
#endregion
#region Ctor
/// <param name="factory">current used factory core</param>
/// <param name="parentObject">object there has created the proxy</param>
/// <param name="proxyShare">proxy share instead if com proxy</param>
public ThemeColor(Core factory, ICOMObject parentObject, COMProxyShare proxyShare) : base(factory, parentObject, proxyShare)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
public ThemeColor(Core factory, ICOMObject parentObject, object comProxy) : base(factory, parentObject, comProxy)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ThemeColor(ICOMObject parentObject, object comProxy) : base(parentObject, comProxy)
{
}
///<param name="factory">current used factory core</param>
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ThemeColor(Core factory, ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(factory, parentObject, comProxy, comProxyType)
{
}
///<param name="parentObject">object there has created the proxy</param>
///<param name="comProxy">inner wrapped COM proxy</param>
///<param name="comProxyType">Type of inner wrapped COM proxy"</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ThemeColor(ICOMObject parentObject, object comProxy, NetRuntimeSystem.Type comProxyType) : base(parentObject, comProxy, comProxyType)
{
}
///<param name="replacedObject">object to replaced. replacedObject are not usable after this action</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ThemeColor(ICOMObject replacedObject) : base(replacedObject)
{
}
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ThemeColor() : base()
{
}
/// <param name="progId">registered progID</param>
[EditorBrowsable(EditorBrowsableState.Never), Browsable(false)]
public ThemeColor(string progId) : base(progId)
{
}
#endregion
#region Properties
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// Get/Set
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.ThemeColor.RGB"/> </remarks>
[SupportByVersion("Office", 12,14,15,16)]
public Int32 RGB
{
get
{
return Factory.ExecuteInt32PropertyGet(this, "RGB");
}
set
{
Factory.ExecuteValuePropertySet(this, "RGB", value);
}
}
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// Get
/// Unknown COM Proxy
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.ThemeColor.Parent"/> </remarks>
[SupportByVersion("Office", 12,14,15,16), ProxyResult]
public object Parent
{
get
{
return Factory.ExecuteReferencePropertyGet(this, "Parent");
}
}
/// <summary>
/// SupportByVersion Office 12, 14, 15, 16
/// Get
/// </summary>
/// <remarks> Docs: <see href="https://docs.microsoft.com/en-us/office/vba/api/Office.ThemeColor.ThemeColorSchemeIndex"/> </remarks>
[SupportByVersion("Office", 12,14,15,16)]
public NetOffice.OfficeApi.Enums.MsoThemeColorSchemeIndex ThemeColorSchemeIndex
{
get
{
return Factory.ExecuteEnumPropertyGet<NetOffice.OfficeApi.Enums.MsoThemeColorSchemeIndex>(this, "ThemeColorSchemeIndex");
}
}
#endregion
#region Methods
#endregion
#pragma warning restore
}
}
| 30.862275 | 165 | 0.688203 | [
"MIT"
] | NetOfficeFw/NetOffice | Source/Office/DispatchInterfaces/ThemeColor.cs | 5,156 | C# |
using System;
using System.CodeDom.Compiler;
using System.Linq;
using CSScriptCompilers;
namespace CSSCodeProvider.Tests
{
class Program
{
static void Main(string[] args)
{
string[] files = new[] { @"E:\cs-script\Samples\hello.cpp" };
var cParams = new CompilerParameters();
cParams.OutputAssembly = @"C:\Users\osh\AppData\Local\Temp\CSSCRIPT\Cache\-727015236\hello.cpp.dll";
cParams.ReferencedAssemblies.Add(@"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Windows.Forms\v4.0_4.0.0.0__b77a5c561934e089\System.Windows.Forms.dll");
cParams.ReferencedAssemblies.Add(@"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Linq\v4.0_4.0.0.0__b03f5f7f11d50a3a\System.Linq.dll");
cParams.ReferencedAssemblies.Add(@"C:\WINDOWS\Microsoft.Net\assembly\GAC_MSIL\System.Core\v4.0_4.0.0.0__b77a5c561934e089\System.Core.dll");
var compiler = new CPPCompiler();
compiler.CompileAssemblyFromFileBatch(cParams, files);
var parser = new CCSharpParser(@"E:\cs-script\engine\CSSCodeProvider.v3.5\Script.cs");
parser.ToTempFile(false);
}
}
}
| 40.827586 | 169 | 0.682432 | [
"MIT"
] | cnark/cs-script | Source/CSSCodeProvider.v4.0/CSSCodeProvider.Tests/Program.cs | 1,186 | C# |
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Text;
namespace Mocktopus.Tests.Mocks.Models
{
public class TestDbContext : DbContext, ITestDbContext
{
public DbSet<Student> Students { get; set; }
}
}
| 20.153846 | 58 | 0.721374 | [
"Apache-2.0"
] | boscoton87/Mocktopus | Mocktopus.Tests/Mocks/Models/TestDbContext.cs | 264 | C# |
// <copyright file="HttpContext.cs" company="APIMatic">
// Copyright (c) APIMatic. All rights reserved.
// </copyright>
namespace Engine.Standard.Http.Client
{
using Engine.Standard.Http.Request;
using Engine.Standard.Http.Response;
/// <summary>
/// Represents the contextual information of HTTP request and response.
/// </summary>
public sealed class HttpContext
{
/// <summary>
/// Initializes a new instance of the <see cref="HttpContext"/> class.
/// </summary>
/// <param name="request">The http request in the current context.</param>
/// <param name="response">The http response in the current context.</param>
public HttpContext(HttpRequest request, HttpResponse response)
{
this.Request = request;
this.Response = response;
}
/// <summary>
/// Gets the http request in the current context.
/// </summary>
public HttpRequest Request { get; }
/// <summary>
/// Gets the http response in the current context.
/// </summary>
public HttpResponse Response { get; }
/// <inheritdoc/>
public override string ToString()
{
return $" Request = {this.Request}, " +
$" Response = {this.Response}";
}
}
}
| 31.395349 | 84 | 0.583704 | [
"MIT"
] | profyoni/ZmanimEngine | Engine.Standard/Http/Client/HttpContext.cs | 1,350 | C# |
using System;
using Android.App;
using Android.Content.PM;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;
namespace AccessibilityTest.Droid
{
[Activity(Label = "AccessibilityTest", Icon = "@drawable/icon", MainLauncher = true, ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
global::Xamarin.Forms.Forms.Init(this, bundle);
LoadApplication(new App());
}
}
}
| 26.84 | 166 | 0.703428 | [
"Apache-2.0"
] | aliozgur/xamarin-forms-book-samples | Chapter05/AccessibilityTest/AccessibilityTest/AccessibilityTest.Droid/MainActivity.cs | 671 | C# |
//-----------------------------------------------------------------------------
//
// Copyright (C) Microsoft Corporation. All Rights Reserved.
//
//-----------------------------------------------------------------------------
using System;
using System.Collections;
using System.Collections.Generic;
namespace Microsoft.Cci.Pdb {
internal class PdbFunction {
static internal readonly Guid msilMetaData = new Guid(0xc6ea3fc9, 0x59b3, 0x49d6, 0xbc, 0x25,
0x09, 0x02, 0xbb, 0xab, 0xb4, 0x60);
static internal readonly IComparer byAddress = new PdbFunctionsByAddress();
static internal readonly IComparer byToken = new PdbFunctionsByToken();
internal uint token;
internal uint slotToken;
internal string name;
internal string module;
internal ushort flags;
internal uint segment;
internal uint address;
internal uint length;
//internal byte[] metadata;
internal PdbScope[] scopes;
internal PdbLines[] lines;
internal ushort[]/*?*/ usingCounts;
internal IEnumerable<INamespaceScope>/*?*/ namespaceScopes;
internal string/*?*/ iteratorClass;
internal List<ILocalScope>/*?*/ iteratorScopes;
private static string StripNamespace(string module) {
int li = module.LastIndexOf('.');
if (li > 0) {
return module.Substring(li + 1);
}
return module;
}
internal static PdbFunction[] LoadManagedFunctions(string module,
BitAccess bits, uint limit,
bool readStrings) {
string mod = StripNamespace(module);
int begin = bits.Position;
int count = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.Position = (int)proc.end;
count++;
break;
case SYM.S_END:
bits.Position = stop;
break;
default:
//Console.WriteLine("{0,6}: {1:x2} {2}",
// bits.Position, rec, (SYM)rec);
bits.Position = stop;
break;
}
}
if (count == 0) {
return null;
}
bits.Position = begin;
PdbFunction[] funcs = new PdbFunction[count];
int func = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_GMANPROC:
case SYM.S_LMANPROC:
ManProcSym proc;
int offset = bits.Position;
bits.ReadUInt32(out proc.parent);
bits.ReadUInt32(out proc.end);
bits.ReadUInt32(out proc.next);
bits.ReadUInt32(out proc.len);
bits.ReadUInt32(out proc.dbgStart);
bits.ReadUInt32(out proc.dbgEnd);
bits.ReadUInt32(out proc.token);
bits.ReadUInt32(out proc.off);
bits.ReadUInt16(out proc.seg);
bits.ReadUInt8(out proc.flags);
bits.ReadUInt16(out proc.retReg);
if (readStrings) {
bits.ReadCString(out proc.name);
} else {
bits.SkipCString(out proc.name);
}
//Console.WriteLine("token={0:X8} [{1}::{2}]", proc.token, module, proc.name);
bits.Position = stop;
funcs[func++] = new PdbFunction(module, proc, bits);
break;
default: {
//throw new PdbDebugException("Unknown SYMREC {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
return funcs;
}
internal static void CountScopesAndSlots(BitAccess bits, uint limit,
out int constants, out int scopes, out int slots, out int usedNamespaces) {
int pos = bits.Position;
BlockSym32 block;
constants = 0;
slots = 0;
scopes = 0;
usedNamespaces = 0;
while (bits.Position < limit) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_BLOCK32: {
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
scopes++;
bits.Position = (int)block.end;
break;
}
case SYM.S_MANSLOT:
slots++;
bits.Position = stop;
break;
case SYM.S_UNAMESPACE:
usedNamespaces++;
bits.Position = stop;
break;
case SYM.S_MANCONSTANT:
constants++;
bits.Position = stop;
break;
default:
bits.Position = stop;
break;
}
}
bits.Position = pos;
}
internal PdbFunction() {
}
internal PdbFunction(string module, ManProcSym proc, BitAccess bits) {
this.token = proc.token;
this.module = module;
this.name = proc.name;
this.flags = proc.flags;
this.segment = proc.seg;
this.address = proc.off;
this.length = proc.len;
this.slotToken = 0;
if (proc.seg != 1) {
throw new PdbDebugException("Segment is {0}, not 1.", proc.seg);
}
if (proc.parent != 0 || proc.next != 0) {
throw new PdbDebugException("Warning parent={0}, next={1}",
proc.parent, proc.next);
}
if (proc.dbgStart != 0 || proc.dbgEnd != 0) {
throw new PdbDebugException("Warning DBG start={0}, end={1}",
proc.dbgStart, proc.dbgEnd);
}
int constantCount;
int scopeCount;
int slotCount;
int usedNamespacesCount;
CountScopesAndSlots(bits, proc.end, out constantCount, out scopeCount, out slotCount, out usedNamespacesCount);
scopes = new PdbScope[scopeCount];
int scope = 0;
while (bits.Position < proc.end) {
ushort siz;
ushort rec;
bits.ReadUInt16(out siz);
int star = bits.Position;
int stop = bits.Position + siz;
bits.Position = star;
bits.ReadUInt16(out rec);
switch ((SYM)rec) {
case SYM.S_OEM: { // 0x0404
OemSymbol oem;
bits.ReadGuid(out oem.idOem);
bits.ReadUInt32(out oem.typind);
// internal byte[] rgl; // user data, force 4-byte alignment
if (oem.idOem == msilMetaData) {
string name = bits.ReadString();
if (name == "MD2") {
byte version;
bits.ReadUInt8(out version);
if (version == 4) {
byte count;
bits.ReadUInt8(out count);
bits.Align(4);
while (count-- > 0)
this.ReadCustomMetadata(bits);
}
}
bits.Position = stop;
break;
} else {
throw new PdbDebugException("OEM section: guid={0} ti={1}",
oem.idOem, oem.typind);
// bits.Position = stop;
}
}
case SYM.S_BLOCK32: {
BlockSym32 block = new BlockSym32();
bits.ReadUInt32(out block.parent);
bits.ReadUInt32(out block.end);
bits.ReadUInt32(out block.len);
bits.ReadUInt32(out block.off);
bits.ReadUInt16(out block.seg);
bits.SkipCString(out block.name);
bits.Position = stop;
this.address = block.off;
scopes[scope] = new PdbScope(this.address, block, bits, out slotToken);
bits.Position = (int)block.end;
break;
}
case SYM.S_UNAMESPACE:
bits.Position = stop;
break;
case SYM.S_END:
bits.Position = stop;
break;
default: {
//throw new PdbDebugException("Unknown SYM: {0}", (SYM)rec);
bits.Position = stop;
break;
}
}
}
if (bits.Position != proc.end) {
throw new PdbDebugException("Not at S_END");
}
ushort esiz;
ushort erec;
bits.ReadUInt16(out esiz);
bits.ReadUInt16(out erec);
if (erec != (ushort)SYM.S_END) {
throw new PdbDebugException("Missing S_END");
}
}
private void ReadCustomMetadata(BitAccess bits) {
int savedPosition = bits.Position;
byte version;
bits.ReadUInt8(out version);
if (version != 4) {
throw new PdbDebugException("Unknown custom metadata item version: {0}", version);
}
byte kind;
bits.ReadUInt8(out kind);
bits.Align(4);
uint numberOfBytesInItem;
bits.ReadUInt32(out numberOfBytesInItem);
switch (kind) {
case 0: this.ReadUsingInfo(bits); break;
case 1: this.ReadForwardInfo(bits); break;
case 2: this.ReadForwardedToModuleInfo(bits); break;
case 3: this.ReadIteratorLocals(bits); break;
case 4: this.ReadForwardIterator(bits); break;
default: throw new PdbDebugException("Unknown custom metadata item kind: {0}", kind);
}
bits.Position = savedPosition+(int)numberOfBytesInItem;
}
private void ReadForwardIterator(BitAccess bits) {
this.iteratorClass = bits.ReadString();
}
private void ReadIteratorLocals(BitAccess bits) {
uint numberOfLocals;
bits.ReadUInt32(out numberOfLocals);
this.iteratorScopes = new List<ILocalScope>((int)numberOfLocals);
while (numberOfLocals-- > 0) {
uint ilStartOffset;
uint ilEndOffset;
bits.ReadUInt32(out ilStartOffset);
bits.ReadUInt32(out ilEndOffset);
this.iteratorScopes.Add(new PdbIteratorScope(ilStartOffset, ilEndOffset-ilStartOffset));
}
}
private void ReadForwardedToModuleInfo(BitAccess bits) {
}
private void ReadForwardInfo(BitAccess bits) {
}
private void ReadUsingInfo(BitAccess bits) {
ushort numberOfNamespaces;
bits.ReadUInt16(out numberOfNamespaces);
this.usingCounts = new ushort[numberOfNamespaces];
for (ushort i = 0; i < numberOfNamespaces; i++) {
bits.ReadUInt16(out this.usingCounts[i]);
}
}
internal class PdbFunctionsByAddress : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.segment < fy.segment) {
return -1;
} else if (fx.segment > fy.segment) {
return 1;
} else if (fx.address < fy.address) {
return -1;
} else if (fx.address > fy.address) {
return 1;
} else {
return 0;
}
}
}
internal class PdbFunctionsByToken : IComparer {
public int Compare(Object x, Object y) {
PdbFunction fx = (PdbFunction)x;
PdbFunction fy = (PdbFunction)y;
if (fx.token < fy.token) {
return -1;
} else if (fx.token > fy.token) {
return 1;
} else {
return 0;
}
}
}
}
}
| 29.922693 | 120 | 0.529794 | [
"Apache-2.0"
] | evincarofautumn/mono | mcs/tools/pdb2mdb/PdbFunction.cs | 11,999 | C# |
using System.Drawing;
using Newtonsoft.Json;
using TriggersTools.CatSystem2.Json;
using TriggersTools.CatSystem2.Structs;
namespace TriggersTools.CatSystem2 {
/// <summary>
/// An attribute attached to an HG-3 frame which includes positioning and color information.
/// </summary>
public sealed class Hg3Attribute {
#region Fields
/// <summary>
/// Gets the HG-3 image that contains this attribute's frame.
/// </summary>
[JsonIgnore]
public HgxImage Hg3Image => Hg3Frame?.HgxImage;
/// <summary>
/// Gets the HG-3 frame that contains this attribute.
/// </summary>
[JsonIgnore]
public HgxFrame Hg3Frame { get; internal set; }
/// <summary>
/// Gets the numeric identifier of the attribute.
/// </summary>
[JsonProperty("id")]
public int Id { get; private set; }
/// <summary>
/// Gets the x coordinate of the attribute.
/// </summary>
[JsonProperty("x")]
public int X { get; private set; }
/// <summary>
/// Gets the y coordinate of the attribute.
/// </summary>
[JsonProperty("y")]
public int Y { get; private set; }
/// <summary>
/// Gets the width of the attribute.
/// </summary>
[JsonProperty("width")]
public int Width { get; private set; }
/// <summary>
/// Gets the height of the attribute.
/// </summary>
[JsonProperty("height")]
public int Height { get; private set; }
/// <summary>
/// Gets the color to display the attribute with.
/// </summary>
[JsonProperty("color")]
[JsonConverter(typeof(JsonColorConverter))]
public Color Color { get; private set; }
#endregion
#region Constructors
/// <summary>
/// Constructs an unassigned HG-3 attribute for use with loading via <see cref="Newtonsoft.Json"/>.
/// </summary>
private Hg3Attribute() { }
/// <summary>
/// Constructs an HG-3 attribute with the specified Id and <see cref="HG3ATS"/>.
/// </summary>
/// <param name="id">The identifier for the attribute.</param>
/// <param name="ats">The HG3ATS struct containing attribute information.</param>
/// <param name="hg3Frame">The HG-3 frame containing this attribute.</param>
internal Hg3Attribute(int id, HG3ATS ats, HgxFrame hg3Frame) {
Hg3Frame = hg3Frame;
Id = id;
X = ats.X;
Y = ats.Y;
Width = ats.Width;
Height = ats.Height;
Color = Color.FromArgb(ats.Color);
}
#endregion
#region ToString Override
/// <summary>
/// Gets the string representation of the HG-3 attribute.
/// </summary>
/// <returns>The string representation of the HG-3 attribute.</returns>
public override string ToString() => $"HG-3 Attribute {X},{Y} {Width}x{Height} #{Color.ToArgb():X8}";
#endregion
}
}
| 28.709677 | 103 | 0.656929 | [
"MIT"
] | AtomCrafty/TriggersTools.CatSystem2 | src/TriggersTools.CatSystem2.Shared/Hg3Attribute.cs | 2,672 | C# |
//------------------------------------------------------------------------------
// <自動生成>
// このコードはツールによって生成されました。
//
// このファイルへの変更は、以下の状況下で不正な動作の原因になったり、
// コードが再生成されるときに損失したりします。
// </自動生成>
//------------------------------------------------------------------------------
namespace WebForms_Sample.Aspx.Common.Master.TestNest {
public partial class rootMasterPage {
/// <summary>
/// Head1 コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlHead Head1;
/// <summary>
/// cphHeaderScripts コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder cphHeaderScripts;
/// <summary>
/// form1 コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// lblMSG コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::Touryo.Infrastructure.CustomControl.WebCustomLabel lblMSG;
/// <summary>
/// lblTest コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::Touryo.Infrastructure.CustomControl.WebCustomLabel lblTest;
/// <summary>
/// btnButton コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::Touryo.Infrastructure.CustomControl.WebCustomButton btnButton;
/// <summary>
/// ContentPlaceHolder_A コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder_A;
/// <summary>
/// ContentPlaceHolder_B コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder_B;
/// <summary>
/// ContentPlaceHolder_C コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder_C;
/// <summary>
/// ChildScreenType コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField ChildScreenType;
/// <summary>
/// ChildScreenUrl コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField ChildScreenUrl;
/// <summary>
/// CloseFlag コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField CloseFlag;
/// <summary>
/// SubmitFlag コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField SubmitFlag;
/// <summary>
/// ScreenGuid コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField ScreenGuid;
/// <summary>
/// FxDialogStyle コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField FxDialogStyle;
/// <summary>
/// BusinessDialogStyle コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField BusinessDialogStyle;
/// <summary>
/// NormalScreenStyle コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField NormalScreenStyle;
/// <summary>
/// NormalScreenTarget コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField NormalScreenTarget;
/// <summary>
/// DialogFrameUrl コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField DialogFrameUrl;
/// <summary>
/// WindowGuid コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField WindowGuid;
/// <summary>
/// RequestTicketGuid コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.HiddenField RequestTicketGuid;
/// <summary>
/// cphFooterScripts コントロール。
/// </summary>
/// <remarks>
/// 自動生成されたフィールド。
/// 変更するには、フィールドの宣言をデザイナー ファイルから分離コード ファイルに移動します。
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder cphFooterScripts;
}
}
| 32.691589 | 92 | 0.540881 | [
"Apache-2.0"
] | OpenTouryoProject/OpenTouryo | root/programs/CS/Samples/WebApp_sample/WebForms_Sample/WebForms_Sample/Aspx/Common/Master/testNest/rootMasterPage.master.designer.cs | 9,938 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
namespace VirtualVoid.Util.ObjectPooling
{
public abstract class PoolObject : MonoBehaviour
{
/// <summary>
/// Called when the object has been spawned from the object pool. Called before the object is set active.
/// </summary>
public abstract void OnObjectSpawn();
/// <summary>
/// Calling this will stop all processes on the object and return it to the pool. Call instead of Destroy();
/// </summary>
public void DestroyPoolObject()
{
gameObject.SetActive(false);
StopAllCoroutines();
CancelInvoke();
}
}
}
| 28.36 | 116 | 0.617772 | [
"MIT"
] | Tobogganeer/VirtualVoid.Util | Utilities/Object Pooling/PoolObject.cs | 711 | 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.Diagnostics;
namespace System.Collections
{
internal static partial class HashHelpers
{
public const int HashCollisionThreshold = 100;
// This is the maximum prime smaller than Array.MaxArrayLength
public const int MaxPrimeArrayLength = 0x7FEFFFFD;
public const int HashPrime = 101;
// Table of prime numbers to use as hash table sizes.
// A typical resize algorithm would pick the smallest prime number in this array
// that is larger than twice the previous capacity.
// Suppose our Hashtable currently has capacity x and enough elements are added
// such that a resize needs to occur. Resizing first computes 2x then finds the
// first prime in the table greater than 2x, i.e. if primes are ordered
// p_1, p_2, ..., p_i, ..., it finds p_n such that p_n-1 < 2x < p_n.
// Doubling is important for preserving the asymptotic complexity of the
// hashtable operations such as add. Having a prime guarantees that double
// hashing does not lead to infinite loops. IE, your hash function will be
// h1(key) + i*h2(key), 0 <= i < size. h2 and the size must be relatively prime.
// We prefer the low computation costs of higher prime numbers over the increased
// memory allocation of a fixed prime number i.e. when right sizing a HashSet.
public static readonly int[] primes = {
3, 7, 11, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 163, 197, 239, 293, 353, 431, 521, 631, 761, 919,
1103, 1327, 1597, 1931, 2333, 2801, 3371, 4049, 4861, 5839, 7013, 8419, 10103, 12143, 14591,
17519, 21023, 25229, 30293, 36353, 43627, 52361, 62851, 75431, 90523, 108631, 130363, 156437,
187751, 225307, 270371, 324449, 389357, 467237, 560689, 672827, 807403, 968897, 1162687, 1395263,
1674319, 2009191, 2411033, 2893249, 3471899, 4166287, 4999559, 5999471, 7199369 };
public static bool IsPrime(int candidate)
{
if ((candidate & 1) != 0)
{
int limit = (int)Math.Sqrt(candidate);
for (int divisor = 3; divisor <= limit; divisor += 2)
{
if ((candidate % divisor) == 0)
return false;
}
return true;
}
return (candidate == 2);
}
public static int GetPrime(int min)
{
if (min < 0)
throw new ArgumentException(SR.Arg_HTCapacityOverflow);
for (int i = 0; i < primes.Length; i++)
{
int prime = primes[i];
if (prime >= min)
return prime;
}
//outside of our predefined table.
//compute the hard way.
for (int i = (min | 1); i < int.MaxValue; i += 2)
{
if (IsPrime(i) && ((i - 1) % HashPrime != 0))
return i;
}
return min;
}
// Returns size of hashtable to grow to.
public static int ExpandPrime(int oldSize)
{
int newSize = 2 * oldSize;
// Allow the hashtables to grow to maximum possible size (~2G elements) before encountering capacity overflow.
// Note that this check works even when _items.Length overflowed thanks to the (uint) cast
if ((uint)newSize > MaxPrimeArrayLength && MaxPrimeArrayLength > oldSize)
{
Debug.Assert(MaxPrimeArrayLength == GetPrime(MaxPrimeArrayLength), "Invalid MaxPrimeArrayLength");
return MaxPrimeArrayLength;
}
return GetPrime(newSize);
}
}
}
| 43.413043 | 122 | 0.579119 | [
"MIT"
] | 3F/coreclr | src/System.Private.CoreLib/shared/System/Collections/HashHelpers.cs | 3,994 | C# |
using Carrotware.CMS.Core;
using Carrotware.CMS.UI.Controls;
using Carrotware.Web.UI.Controls;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
/*
* CarrotCake CMS
* http://www.carrotware.com/
*
* Copyright 2011, Samantha Copeland
* Dual licensed under the MIT or GPL Version 3 licenses.
*
* Date: October 2011
*/
namespace Carrotware.CMS.UI.Admin.c3_admin {
public partial class SiteSkinEdit : AdminBasePage {
protected FileDataHelper helpFile = CMSConfigHelper.GetFileDataHelper();
public string sTemplateFileQS = String.Empty;
protected string sTemplateFile = String.Empty;
protected string sFullFilePath = String.Empty;
protected string sDirectory = String.Empty;
protected string sEditFile = String.Empty;
protected void Page_Load(object sender, EventArgs e) {
Master.ActivateTab(AdminBaseMasterPage.SectionID.ContentSkinEdit);
if (!String.IsNullOrEmpty(Request.QueryString["path"])) {
sTemplateFileQS = Request.QueryString["path"].ToString();
sTemplateFile = CMSConfigHelper.DecodeBase64(sTemplateFileQS);
sFullFilePath = HttpContext.Current.Server.MapPath(sTemplateFile);
sEditFile = sFullFilePath;
}
if (!String.IsNullOrEmpty(Request.QueryString["alt"])) {
string sAltFileQS = Request.QueryString["alt"].ToString();
string sAltFile = CMSConfigHelper.DecodeBase64(sAltFileQS);
sEditFile = HttpContext.Current.Server.MapPath(sAltFile);
}
litSkinFileName.Text = sTemplateFile;
litEditFileName.Text = sEditFile.Replace(Server.MapPath("~"), @"\");
if (File.Exists(sEditFile)) {
if (!IsPostBack) {
using (StreamReader sr = new StreamReader(sEditFile)) {
txtPageContents.Text = sr.ReadToEnd();
}
}
litDateMod.Text = File.GetLastWriteTime(sEditFile).ToString();
if (sFullFilePath.LastIndexOf(@"\") > 0) {
sDirectory = sFullFilePath.Substring(0, sFullFilePath.LastIndexOf(@"\"));
} else {
sDirectory = sFullFilePath.Substring(0, sFullFilePath.LastIndexOf(@"/"));
}
SetSourceFiles(sDirectory);
}
}
protected void btnSubmit_Click(object sender, EventArgs e) {
if (File.Exists(sEditFile)) {
Encoding encode = System.Text.Encoding.Default;
using (var oWriter = new StreamWriter(sEditFile, false, encode)) {
oWriter.Write(txtPageContents.Text);
oWriter.Close();
}
Response.Redirect(SiteData.CurrentScriptName + "?" + Request.QueryString.ToString());
}
}
public string EncodePath(string sIn) {
if (!(sIn.StartsWith(@"\") || sIn.StartsWith(@"/"))) {
sIn = @"/" + sIn;
}
return CMSConfigHelper.EncodeBase64(sIn.ToLowerInvariant());
}
protected void SetSourceFiles(string sDir) {
List<FileData> flsWorking = new List<FileData>();
List<FileData> fldrWorking = new List<FileData>();
List<string> lstFileExtensions = new List<string>();
lstFileExtensions.Add(".css");
lstFileExtensions.Add(".js");
lstFileExtensions.Add(".ascx");
lstFileExtensions.Add(".master");
if (Directory.Exists(sDir)) {
string sDirParent = "";
if (sDir.LastIndexOf(@"\") > 0) {
sDirParent = sDir.Substring(0, sDir.LastIndexOf(@"\"));
} else {
sDirParent = sDir.Substring(0, sDir.LastIndexOf(@"/"));
}
FileData skinFolder = helpFile.GetFolderInfo("/", sDir);
skinFolder.FolderPath = FileDataHelper.MakeWebFolderPath(sDir);
fldrWorking = helpFile.SpiderDeepFoldersFD(FileDataHelper.MakeWebFolderPath(sDir));
fldrWorking.Add(skinFolder);
try {
if (Directory.Exists(Server.MapPath("~/includes"))) {
FileData incFolder = helpFile.GetFolderInfo("/", Server.MapPath("~/includes"));
fldrWorking.Add(incFolder);
}
if (Directory.Exists(Server.MapPath("~/js"))) {
FileData incFolder = helpFile.GetFolderInfo("/", Server.MapPath("~/js"));
fldrWorking.Add(incFolder);
}
if (Directory.Exists(Server.MapPath("~/css"))) {
FileData incFolder = helpFile.GetFolderInfo("/", Server.MapPath("~/css"));
fldrWorking.Add(incFolder);
}
} catch (Exception ex) { }
helpFile.IncludeAllFiletypes();
foreach (FileData f in fldrWorking) {
List<FileData> fls = helpFile.GetFiles(f.FolderPath);
flsWorking = (from m in flsWorking.Union(fls).ToList()
join e in lstFileExtensions on m.FileExtension.ToLowerInvariant() equals e
select m).ToList();
}
flsWorking = flsWorking.Where(x => x.MimeType.StartsWith("text") && (x.FolderPath.ToLowerInvariant().StartsWith(SiteData.AdminFolderPath) == false)).ToList();
GeneralUtilities.BindRepeater(rpFiles, flsWorking.Distinct().OrderBy(x => x.FileName).OrderBy(x => x.FolderPath).ToList());
}
}
}
} | 33.054054 | 163 | 0.673957 | [
"MIT"
] | ninianne98/CarrotCakeCMS | CMSAdmin/c3-admin/SiteSkinEdit.aspx.cs | 4,894 | C# |
using System;
namespace DNFS.Api
{
public class WeatherForecast
{
public DateTime Date { get; set; }
public int TemperatureC { get; set; }
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
public string Summary { get; set; }
}
}
| 18.0625 | 69 | 0.595156 | [
"MIT"
] | WillBrigida/DNFS | src/DNFS/DNFS.Api/WeatherForecast.cs | 289 | C# |
using Game;
using Mirror;
using UnityEngine;
using UnityEngine.Assertions;
namespace UI {
public class StartGameGUI : MonoBehaviour {
public void StartGame() {
Assert.IsTrue(NetworkClient.active);
NetworkClient.Send(new StartGameMsg());
}
}
} | 19.615385 | 44 | 0.74902 | [
"MIT"
] | PsarTech-Shorii/Only-Gane | Assets/Scripts/UI/Game/StartGameGUI.cs | 255 | 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 ssm-2014-11-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using System.Net;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.SimpleSystemsManagement.Model
{
/// <summary>
/// The query result body of the GetServiceSetting API action.
/// </summary>
public partial class GetServiceSettingResponse : AmazonWebServiceResponse
{
private ServiceSetting _serviceSetting;
/// <summary>
/// Gets and sets the property ServiceSetting.
/// <para>
/// The query result of the current service setting.
/// </para>
/// </summary>
public ServiceSetting ServiceSetting
{
get { return this._serviceSetting; }
set { this._serviceSetting = value; }
}
// Check to see if ServiceSetting property is set
internal bool IsSetServiceSetting()
{
return this._serviceSetting != null;
}
}
} | 30.947368 | 102 | 0.650227 | [
"Apache-2.0"
] | philasmar/aws-sdk-net | sdk/src/Services/SimpleSystemsManagement/Generated/Model/GetServiceSettingResponse.cs | 1,764 | C# |
namespace VRAcademy.HttpBasic
{
public static partial class Utility
{
public const string HostName = "http://localhost:5678";
public const string LARGE_FILE_URL = "https://public-cdn.cloud.unity3d.com/hub/prod/UnityHubSetup.exe";
//public const string LARGE_FILE_URL = "https://releases.ubuntu.com/20.04.3/ubuntu-20.04.3-live-server-amd64.iso";
}
[System.Serializable]
public class User
{
public string name;
public string email;
}
}
| 29.588235 | 122 | 0.667992 | [
"MIT"
] | tk-aria/vracademy-serverintegration-unity | Assets/Lesson/Examples/Utility.cs | 503 | C# |
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace OrmTest
{
public partial class NewUnitTest
{
public static SqlSugarScope simpleDb => new SqlSugarScope(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
});
public static ConnectionConfig Config = new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = "server=.;uid=sa;pwd=sasa;database=SQLSUGAR4XTEST",
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
};
public static SqlSugarScope ssDb => new SqlSugarScope(Config);
public static SqlSugarScope singleDb = new SqlSugarScope(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
});
public static SqlSugarScope singleAndSsDb = new SqlSugarScope(new ConnectionConfig()
{
DbType = DbType.SqlServer,
ConnectionString = Config.ConnectionString,
InitKeyType = InitKeyType.Attribute,
IsAutoCloseConnection = true,
AopEvents = new AopEvents
{
OnLogExecuting = (sql, p) =>
{
Console.WriteLine(sql);
Console.WriteLine(string.Join(",", p?.Select(it => it.ParameterName + ":" + it.Value)));
}
}
});
public static void Thread()
{
Simple();
IsShardSameThread();
Single();
SingleAndIsShardSameThread();
SimpleAsync();
IsShardSameThreadAsync();
SingleAsync();
SingleAndIsShardSameThreadAsync();
}
private static void Simple()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
simpleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(1);
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
simpleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(10);
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
simpleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(6);
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
private static void SingleAndIsShardSameThread()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleAndSsDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(1);
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleAndSsDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(10);
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleAndSsDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(6);
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
private static void Single()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(1);
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(10);
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(6);
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
private static void IsShardSameThread()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
Db.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(1);
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
Db.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(10);
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
Db.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommand();
System.Threading.Thread.Sleep(6);
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
private static void SimpleAsync()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
simpleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(1);
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
simpleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait(); ;
System.Threading.Thread.Sleep(10);
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
simpleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(6);
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
private static void SingleAndIsShardSameThreadAsync()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleAndSsDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(1);
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleAndSsDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(10);
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
singleAndSsDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(6);
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
private static void SingleAsync()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
//singleDb.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
//System.Threading.Thread.Sleep(1); No Support
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
//singleDb.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
//System.Threading.Thread.Sleep(10); No Support
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
//singleDb.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
//System.Threading.Thread.Sleep(6); No Support
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
private static void IsShardSameThreadAsync()
{
var t1 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
Db.Insertable(new Order() { Name = "test", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(1);
}
});
var t2 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
Db.Insertable(new Order() { Name = "test2", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(10);
}
});
var t3 = new Task(() =>
{
for (int i = 0; i < 100; i++)
{
Db.Insertable(new Order() { Name = "test3", CreateTime = DateTime.Now }).ExecuteCommandAsync().Wait();
System.Threading.Thread.Sleep(6);
}
});
t1.Start();
t2.Start();
t3.Start();
Task.WaitAll(t1, t2, t3);
}
}
}
| 32.437995 | 133 | 0.421588 | [
"Apache-2.0"
] | 390029659/SqlSugar | Src/Asp.Net/SqlServerTest/UnitTest/UThread.cs | 12,296 | 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 ASC.Web.Studio.UserControls.Management {
public partial class GreetingLogoSettings {
}
}
| 29.75 | 80 | 0.443277 | [
"Apache-2.0"
] | Ektai-Solution-Pty-Ltd/CommunityServer | web/studio/ASC.Web.Studio/UserControls/Management/GreetingSettings/GreetingLogoSettings.ascx.designer.cs | 476 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.