content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
/*
* Copyright (c) 2015, iLearnRW. Licensed under Modified BSD Licence. See licence.txt for details.
*/using UnityEngine;
using System.Collections.Generic;
public class ActiveAutoResizeScript : MonoBehaviour
{
List<Vector3> pointsToNotice;
int axisToNotice;
Vector3 ptOnAxis;
Vector3 restPos;
Vector3 startWorldScale;
Vector3 destWorldScale;
float startFontCharacterSize;
float destFontCharacterSize;
bool usePoints;
bool useAxis;
Vector3 prevPos;
List<TextMesh> textMToUpdate;
bool in2DMode;
void Start()
{
prevPos = new Vector3(transform.position.x,transform.position.y,transform.position.z);
textMToUpdate = new List<TextMesh>();
textMToUpdate = getTextMeshOfChildrenRecursively(this.gameObject);
}
void Update()
{
float minDistanceToTarget = -1f;
float distFromRestToDest = -1f;
if(usePoints)
{
Vector3 minDestinationPt = Vector3.zero;
for(int i=0; i<pointsToNotice.Count; i++)
{
if(in2DMode)
{
Vector3 tmpVar = pointsToNotice[i];
tmpVar.z = transform.position.z;
pointsToNotice[i] = tmpVar;
}
float tmpDist = Vector3.Distance(pointsToNotice[i],transform.position);
if((minDistanceToTarget == -1)||(tmpDist < minDistanceToTarget))
{
minDistanceToTarget = tmpDist;
minDestinationPt = pointsToNotice[i];
}
}
distFromRestToDest = Vector3.Distance(restPos,minDestinationPt);
}
else if(useAxis)
{
switch(axisToNotice)
{
case 0: minDistanceToTarget = Mathf.Abs(transform.position.x - ptOnAxis.x); break;
case 1: minDistanceToTarget = Mathf.Abs(transform.position.y - ptOnAxis.y); break;
case 2: minDistanceToTarget = Mathf.Abs(transform.position.z - ptOnAxis.z); break;
default: minDistanceToTarget = -1; Debug.Log("ActiveAutoResizeScript Error"); break;
}
Vector3 minDestinationPt = ptOnAxis;
if(in2DMode)
{
minDestinationPt.z = restPos.z;
}
distFromRestToDest = Vector3.Distance(restPos,minDestinationPt);
}
if((distFromRestToDest != 0)
&&(Vector3.Equals(prevPos,transform.position) == false))
{
float percFromRest = (1-(minDistanceToTarget/distFromRestToDest));
Vector3 diffScaleVect = (destWorldScale - startWorldScale);
// LocalScale (1,1,1) --> startWorldScale (size vect)
// ? --> reqRenderSizeVect
Vector3 reqRenderSizeVect = (startWorldScale + (diffScaleVect * percFromRest));
Vector3 defaultScaleOfItem = new Vector3(1,1,1);
Vector3 reqScale = divideVecElements(multiplyVecElements(reqRenderSizeVect,defaultScaleOfItem),startWorldScale);
Vector3 oldScale = transform.localScale;
reqScale.z = oldScale.z;
transform.localScale = reqScale;
// Update size of any text on the object.
if((textMToUpdate != null)&&(textMToUpdate.Count > 0))
{
for(int i=0; i<textMToUpdate.Count; i++)
{
TextMesh tmesh = textMToUpdate[i];
tmesh.transform.parent = null;
tmesh.transform.localScale = defaultScaleOfItem;
tmesh.transform.parent = transform;
float changeFactorFontCharacterSize = startFontCharacterSize + ((destFontCharacterSize - startFontCharacterSize) * percFromRest);
tmesh.characterSize = changeFactorFontCharacterSize;
}
}
prevPos.x = transform.position.x;
prevPos.y = transform.position.y;
prevPos.z = transform.position.z;
}
}
private List<TextMesh> getTextMeshOfChildrenRecursively(GameObject para_tmpObj)
{
List<TextMesh> localList = new List<TextMesh>();
TextMesh tmpTMesh = null;
tmpTMesh = para_tmpObj.GetComponent<TextMesh>();
if(tmpTMesh != null)
{
localList.Add(tmpTMesh);
}
for(int i=0; i<para_tmpObj.transform.childCount; i++)
{
List<TextMesh> tmpRecList = getTextMeshOfChildrenRecursively((para_tmpObj.transform.GetChild(i)).gameObject);
localList.AddRange(tmpRecList);
}
return localList;
}
public void init(List<Vector3> para_ptsToNotice,
Vector3 para_startWorldScale,
Vector3 para_destWorldScale,
float para_startFontCharacterSize,
float para_destFontCharacterSize,
bool para_2dMode)
{
restPos = new Vector3(transform.position.x,transform.position.y,transform.position.z);
usePoints = true;
useAxis = false;
pointsToNotice = para_ptsToNotice;
axisToNotice = -1;
ptOnAxis = Vector3.zero;
startWorldScale = para_startWorldScale;
destWorldScale = para_destWorldScale;
startFontCharacterSize = para_startFontCharacterSize;
destFontCharacterSize = para_destFontCharacterSize;
in2DMode = para_2dMode;
}
public void init(int para_axisToNotice,
Vector3 para_ptOnAxis,
Vector3 para_startWorldScale,
Vector3 para_destWorldScale,
float para_startFontCharacterSize,
float para_destFontCharacterSize,
bool para_2dMode)
{
restPos = new Vector3(transform.position.x,transform.position.y,transform.position.z);
usePoints = false;
useAxis = true;
pointsToNotice = null;
axisToNotice = para_axisToNotice;
ptOnAxis = para_ptOnAxis;
startWorldScale = para_startWorldScale;
destWorldScale = para_destWorldScale;
startFontCharacterSize = para_startFontCharacterSize;
destFontCharacterSize = para_destFontCharacterSize;
in2DMode = para_2dMode;
}
private Vector3 multiplyVecElements(Vector3 para_v1, Vector3 para_v2)
{
Vector3 retVec = new Vector3( para_v1.x * para_v2.x,
para_v1.y * para_v2.y,
para_v1.z * para_v2.z );
return retVec;
}
private Vector3 divideVecElements(Vector3 para_v1, Vector3 para_v2)
{
Vector3 retVec = new Vector3( para_v1.x / para_v2.x,
para_v1.y / para_v2.y,
para_v1.z / para_v2.z );
return retVec;
}
}
| 26.334821 | 134 | 0.692999 | [
"BSD-3-Clause"
] | TAPeri/WordsMatter | Assets/Ac_SerenadeHero/Code/Scripts/ActiveAutoResizeScript.cs | 5,901 | C# |
using System;
namespace MyCompany.Crm.TechnicalStuff.Metadata
{
[AttributeUsage(AttributeTargets.Class)]
public class StatelessAttribute : Attribute { }
} | 23.285714 | 51 | 0.779141 | [
"MIT"
] | Magicianred/DDD-starter-dotnet | Sources/TechnicalStuff/TechnicalStuff.Metadata/StatelessAttribute.cs | 163 | C# |
using System;
using NUnit.Framework;
using NUnit.Framework.Interfaces;
using Outracks.Diagnostics;
namespace Outracks.Common.Tests
{
public class RestrictToAttribute : Attribute, ITestAction
{
private readonly OS _os;
public RestrictToAttribute(OS os)
{
_os = os;
}
public void BeforeTest(ITest test)
{
if (Platform.OperatingSystem != _os)
{
Assert.Ignore("Ignoring on " + Platform.OperatingSystem);
}
}
public void AfterTest(ITest test) { }
public ActionTargets Targets { get { return new ActionTargets(); } }
}
} | 19.206897 | 70 | 0.710952 | [
"MIT"
] | fuse-open/fuse-studio | Source/Common/Tests/RestrictToAttribute.cs | 559 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
using System.Collections.Generic;
namespace Azure.AI.FormRecognizer.Training
{
/// <summary>
/// Represents a submodel that extracts fields from a specific type of form.
/// </summary>
public class CustomFormSubmodel
{
/// <summary>
/// Initializes a new instance of the <see cref="CustomFormSubmodel"/> class.
/// </summary>
/// <param name="formType">The type of form this submodel recognizes.</param>
/// <param name="accuracy">The mean of the accuracies of this model's <see cref="CustomFormModelField"/> instances.</param>
/// <param name="fields">A dictionary of the fields that this submodel will recognize from the input document.</param>
/// <param name="modelId">The unique identifier of the submodel.</param>
internal CustomFormSubmodel(string formType, float? accuracy, IReadOnlyDictionary<string, CustomFormModelField> fields, string modelId)
{
FormType = formType;
Accuracy = accuracy;
Fields = fields;
ModelId = modelId;
}
/// <summary>
/// The unique identifier of the submodel.
/// </summary>
public string ModelId { get; }
/// <summary>
/// The type of form this submodel recognizes.
/// </summary>
public string FormType { get; }
/// <summary>
/// The mean of the accuracies of this model's <see cref="CustomFormModelField"/>
/// instances.
/// </summary>
public float? Accuracy { get; }
/// <summary>
/// A dictionary of the fields that this submodel will recognize from the
/// input document. The key is the <see cref="CustomFormModelField.Name"/>
/// of the field. For models trained with labels, this is the training-time
/// label of the field. For models trained with forms only, a unique name is
/// generated for each field.
/// </summary>
public IReadOnlyDictionary<string, CustomFormModelField> Fields { get; }
}
}
| 40.148148 | 143 | 0.623155 | [
"MIT"
] | 0rland0Wats0n/azure-sdk-for-net | sdk/formrecognizer/Azure.AI.FormRecognizer/src/CustomFormSubmodel.cs | 2,170 | C# |
using System;
using System.Data.Entity.ModelConfiguration.Configuration;
namespace C3D.Core.DataAccess.Extensions
{
internal abstract class TypeConfigurationInfo : TypeInfo
{
public static implicit operator Type(TypeConfigurationInfo typeInfo) => typeInfo.TypeConfigurationType;
public Type TypeConfigurationType { get; }
public Type GenericType { get; }
public override Type ModelType { get; }
private ConfigurationRegistrar registrar;
protected abstract Type BaseGenericType { get; }
protected TypeConfigurationInfo(ConfigurationRegistrar registrar, Type type)
{
this.registrar = registrar;
TypeConfigurationType = type;
GenericType = type.GetBaseGenericType(BaseGenericType);
ModelType = GenericType.GetGenericArguments()[0];
}
private object CreateEntity() => Activator.CreateInstance(TypeConfigurationType);
public override void Add() => AddMethod().Invoke(registrar, new[] { CreateEntity() });
public override bool InNamespace(string nameSpace) =>
base.InNamespace(nameSpace) || TypeConfigurationType.InNamespace(nameSpace);
public override string ToString() => TypeConfigurationType.AssemblyQualifiedName;
}
}
| 36.194444 | 111 | 0.702993 | [
"MIT"
] | CZEMacLeod/C3D.Core.DataAccess.Extensions.EF6 | src/TypeConfigurationInfo/TypeConfigurationInfo.cs | 1,305 | C# |
//*********************************************************
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
//
//
//
//
//*********************************************************
namespace Bio
{
/// <summary>
/// Interface to virtual sequence data.
/// Classes which implement this interface should hold virtual data of sequence.
/// </summary>
public interface IVirtualQualitativeSequenceProvider : IVirtualSequenceProvider
{
/// <summary>
/// Get the quality scores of a particular sequence.
/// </summary>
/// <returns>The quality scores.</returns>
byte[] GetScores();
}
}
| 23.892857 | 84 | 0.506726 | [
"Apache-2.0"
] | jdm7dv/Microsoft-Biology-Foundation | eLMM/CodePlex/MBF/IVirtualQualitativeSequenceProvider.cs | 669 | C# |
using System;
public class Dummy : ITarget
{
private int health;
private int experience;
public Dummy(int health, int experience)
{
this.health = health;
this.experience = experience;
}
public int Health
{
get { return this.health; }
}
public void TakeAttack(int attackPoints)
{
if (this.IsDead())
{
throw new InvalidOperationException("Dummy is dead.");
}
this.health -= attackPoints;
}
public int GiveExperience()
{
if (!this.IsDead())
{
throw new InvalidOperationException("Target is not dead.");
}
return this.experience;
}
public bool IsDead()
{
return this.health <= 0;
}
}
| 17.681818 | 71 | 0.547558 | [
"MIT"
] | Avarea/OOP-Advanced | UnitTesting/Skeleton/Dummy.cs | 780 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Safe_Note.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.0.3.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
| 39.407407 | 151 | 0.580827 | [
"MIT"
] | parsakhatibzadeh/SafeNote | SafeNote/Safe Note/note pad/Properties/Settings.Designer.cs | 1,066 | C# |
#if UNITY_NATIVE
using System.Runtime.CompilerServices;
using Svelto.Common;
using Svelto.DataStructures;
using Svelto.ECS.Internal;
namespace Svelto.ECS
{
public static class UnityEntityDBExtensions
{
internal static NativeEGIDMapper<T> ToNativeEGIDMapper<T>(this TypeSafeDictionary<T> dic,
ExclusiveGroupStruct groupStructId) where T : unmanaged, IEntityComponent
{
var mapper = new NativeEGIDMapper<T>(groupStructId, dic.implUnmgd);
return mapper;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static NativeEGIDMapper<T> QueryNativeMappedEntities<T>(this EntitiesDB entitiesDb, ExclusiveGroupStruct groupStructId)
where T : unmanaged, IEntityComponent
{
if (entitiesDb.SafeQueryEntityDictionary<T>(groupStructId, out var typeSafeDictionary) == false)
throw new EntityGroupNotFoundException(typeof(T), groupStructId.ToName());
return (typeSafeDictionary as TypeSafeDictionary<T>).ToNativeEGIDMapper(groupStructId);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryQueryNativeMappedEntities<T>(this EntitiesDB entitiesDb, ExclusiveGroupStruct groupStructId,
out NativeEGIDMapper<T> mapper)
where T : unmanaged, IEntityComponent
{
mapper = default;
if (entitiesDb.SafeQueryEntityDictionary<T>(groupStructId, out var typeSafeDictionary) == false ||
typeSafeDictionary.count == 0)
return false;
mapper = (typeSafeDictionary as TypeSafeDictionary<T>).ToNativeEGIDMapper(groupStructId);
return true;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static NativeEGIDMultiMapper<T> QueryNativeMappedEntities<T>(this EntitiesDB entitiesDb,
LocalFasterReadOnlyList<ExclusiveGroupStruct> groups)
where T : unmanaged, IEntityComponent
{
var dictionary =
new SveltoDictionary<ExclusiveGroupStruct, SveltoDictionary<uint, T,
NativeStrategy<FasterDictionaryNode<uint>>,
NativeStrategy<T>,
NativeStrategy<int>>,
NativeStrategy<FasterDictionaryNode<ExclusiveGroupStruct>>,
NativeStrategy<SveltoDictionary<uint, T,
NativeStrategy<FasterDictionaryNode<uint>>,
NativeStrategy<T>,
NativeStrategy<int>>>,
NativeStrategy<int>>
((uint) groups.count, Allocator.TempJob);
foreach (var group in groups)
{
if (entitiesDb.SafeQueryEntityDictionary<T>(group, out var typeSafeDictionary) == true)
if (typeSafeDictionary.count > 0)
dictionary.Add(group, ((TypeSafeDictionary<T>)typeSafeDictionary).implUnmgd);
}
return new NativeEGIDMultiMapper<T>(dictionary);
}
}
}
#endif | 44.109589 | 135 | 0.617702 | [
"MIT"
] | The-Paladin-Forge-Studio/Svelto-ECS-Filters | Svelto.ECS/Svelto.ECS/Extensions/Unity/DOTS/UnityEntityDBExtensions.cs | 3,220 | C# |
/*
* Copyright 2010-2014 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 macie2-2020-01-01.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.Macie2.Model
{
/// <summary>
/// Provides information about an account that's associated with an Amazon Macie master
/// account.
/// </summary>
public partial class Member
{
private string _accountId;
private string _arn;
private string _email;
private DateTime? _invitedAt;
private string _masterAccountId;
private RelationshipStatus _relationshipStatus;
private Dictionary<string, string> _tags = new Dictionary<string, string>();
private DateTime? _updatedAt;
/// <summary>
/// Gets and sets the property AccountId.
/// <para>
/// The AWS account ID for the account.
/// </para>
/// </summary>
public string AccountId
{
get { return this._accountId; }
set { this._accountId = value; }
}
// Check to see if AccountId property is set
internal bool IsSetAccountId()
{
return this._accountId != null;
}
/// <summary>
/// Gets and sets the property Arn.
/// <para>
/// The Amazon Resource Name (ARN) of the account.
/// </para>
/// </summary>
public string Arn
{
get { return this._arn; }
set { this._arn = value; }
}
// Check to see if Arn property is set
internal bool IsSetArn()
{
return this._arn != null;
}
/// <summary>
/// Gets and sets the property Email.
/// <para>
/// The email address for the account.
/// </para>
/// </summary>
public string Email
{
get { return this._email; }
set { this._email = value; }
}
// Check to see if Email property is set
internal bool IsSetEmail()
{
return this._email != null;
}
/// <summary>
/// Gets and sets the property InvitedAt.
/// <para>
/// The date and time, in UTC and extended ISO 8601 format, when an Amazon Macie membership
/// invitation was last sent to the account. This value is null if a Macie invitation
/// hasn't been sent to the account.
/// </para>
/// </summary>
public DateTime InvitedAt
{
get { return this._invitedAt.GetValueOrDefault(); }
set { this._invitedAt = value; }
}
// Check to see if InvitedAt property is set
internal bool IsSetInvitedAt()
{
return this._invitedAt.HasValue;
}
/// <summary>
/// Gets and sets the property MasterAccountId.
/// <para>
/// The AWS account ID for the master account.
/// </para>
/// </summary>
public string MasterAccountId
{
get { return this._masterAccountId; }
set { this._masterAccountId = value; }
}
// Check to see if MasterAccountId property is set
internal bool IsSetMasterAccountId()
{
return this._masterAccountId != null;
}
/// <summary>
/// Gets and sets the property RelationshipStatus.
/// <para>
/// The current status of the relationship between the account and the master account.
/// </para>
/// </summary>
public RelationshipStatus RelationshipStatus
{
get { return this._relationshipStatus; }
set { this._relationshipStatus = value; }
}
// Check to see if RelationshipStatus property is set
internal bool IsSetRelationshipStatus()
{
return this._relationshipStatus != null;
}
/// <summary>
/// Gets and sets the property Tags.
/// <para>
/// A map of key-value pairs that identifies the tags (keys and values) that are associated
/// with the account in Amazon Macie.
/// </para>
/// </summary>
public Dictionary<string, string> Tags
{
get { return this._tags; }
set { this._tags = value; }
}
// Check to see if Tags property is set
internal bool IsSetTags()
{
return this._tags != null && this._tags.Count > 0;
}
/// <summary>
/// Gets and sets the property UpdatedAt.
/// <para>
/// The date and time, in UTC and extended ISO 8601 format, of the most recent change
/// to the status of the relationship between the account and the master account.
/// </para>
/// </summary>
public DateTime UpdatedAt
{
get { return this._updatedAt.GetValueOrDefault(); }
set { this._updatedAt = value; }
}
// Check to see if UpdatedAt property is set
internal bool IsSetUpdatedAt()
{
return this._updatedAt.HasValue;
}
}
} | 30.34359 | 104 | 0.564475 | [
"Apache-2.0"
] | DetlefGolze/aws-sdk-net | sdk/src/Services/Macie2/Generated/Model/Member.cs | 5,917 | C# |
using System;
using Serilog.Events;
using Serilog.Formatting;
namespace Sentry.Serilog
{
/// <summary>
/// Sentry Options for Serilog logging
/// </summary>
/// <inheritdoc />
public class SentrySerilogOptions : SentryOptions
{
/// <summary>
/// Whether to initialize this SDK through this integration
/// </summary>
public bool InitializeSdk { get; set; } = true;
/// <summary>
/// Minimum log level to send an event.
/// </summary>
/// <remarks>
/// Events with this level or higher will be sent to Sentry.
/// </remarks>
/// <value>
/// The minimum event level.
/// </value>
public LogEventLevel MinimumEventLevel { get; set; } = LogEventLevel.Error;
/// <summary>
/// Minimum log level to record a breadcrumb.
/// </summary>
/// <remarks>Events with this level or higher will be stored as <see cref="Breadcrumb"/></remarks>
/// <value>
/// The minimum breadcrumb level.
/// </value>
public LogEventLevel MinimumBreadcrumbLevel { get; set; } = LogEventLevel.Information;
/// <summary>
/// Optional <see cref="IFormatProvider"/>
/// </summary>
public IFormatProvider? FormatProvider { get; set; }
/// <summary>
/// Optional <see cref="ITextFormatter"/>
/// </summary>
public ITextFormatter? TextFormatter { get; set; }
}
}
| 30.571429 | 106 | 0.567423 | [
"MIT"
] | kanadaj/sentry-dotnet | src/Sentry.Serilog/SentrySerilogOptions.cs | 1,498 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using AuthPermissions.AdminCode;
using AuthPermissions.BaseCode.CommonCode;
using AuthPermissions.BaseCode.PermissionsCode;
using Example4.MvcWebApp.IndividualAccounts.Models;
using ExamplesCommonCode.CommonAdmin;
namespace Example4.MvcWebApp.IndividualAccounts.Controllers
{
public class LoggedInUserController : Controller
{
public IActionResult Index()
{
return View(User);
}
public async Task<IActionResult> AuthUserInfo([FromServices]IAuthUsersAdminService service)
{
if (User.Identity?.IsAuthenticated == true)
{
var userId = User.GetUserIdFromUser();
var status = await service.FindAuthUserByUserIdAsync(userId);
if (status.HasErrors)
return RedirectToAction("ErrorDisplay", "AuthUsers",
new { errorMessage = status.GetAllErrors() });
return View(AuthUserDisplay.DisplayUserInfo(status.Result));
}
return View((AuthUserDisplay)null);
}
public IActionResult UserPermissions([FromServices] IUsersPermissionsService service)
{
return View(service.PermissionsFromUser(HttpContext.User));
}
}
}
| 32.136364 | 99 | 0.668317 | [
"MIT"
] | mohamed-azhar/AuthPermissions.AspNetCore | Example4.MvcWebApp.IndividualAccounts/Controllers/LoggedInUserController.cs | 1,416 | C# |
using System.Collections.Generic;
namespace HLHML.Dictionnaire
{
public class Q : List<Terme>
{
public Q() : base()
{
Add(new Terme
{
Mots = "que",
Type = TypeTerme.Complement
});
Add(new Terme
{
Mots = "quatre",
Type = TypeTerme.Adjectif,
ValeurNumérique = 4
});
}
}
}
| 20 | 43 | 0.404348 | [
"MIT"
] | freddycoder/HLHML | HLHML/Dictionnaire/Q.cs | 463 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CarStorageLibrary.StorageImpl
{
class CsvStorage:AbstractStorage
{
protected override List<Car> Load()
{
throw new NotImplementedException();
}
protected override bool Save( List<Car> cars )
{
throw new NotImplementedException();
}
}
}
| 17.545455 | 48 | 0.746114 | [
"Apache-2.0"
] | Anastasia-Rybak/oop-examples | course-work/CarStorageLibrary/StorageImpl/CsvStorage.cs | 388 | C# |
using AuthServer.Core.Provider;
using AuthServer.Core.Handler;
using AuthServer.Core.Network;
using AuthServer.Core.Performance;
using AuthServer.Core.Security;
using AuthServer.Core.Server;
using AuthServer.Core.Settings;
using Autofac;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using AuthServer.Core.Protocol;
namespace AuthServer.Console
{
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
var settings = JsonSettings.LoadSettings();
builder.Register(c => settings).As<ISettings>();
builder.RegisterType<LdapProvider>().As<IUserProvider>();
builder.RegisterType<JsonProtocol>().As<IProtocol>();
builder.RegisterType<EventCountersPerformanceMonitor>().As<IPerformanceMonitor>();
builder.RegisterType<FileCertificateProvider>().As<ICertificateProvider>();
builder.RegisterType<NetworkServer>().As<IServer>();
builder.RegisterType<TlsTransport>().As<INetworkTransport>();
builder.RegisterAssemblyTypes(typeof(IRequestHandler).Assembly)
.Where(x => x.IsAssignableTo<IRequestHandler>())
.AsImplementedInterfaces();
builder.RegisterType<ProtocolHandler>().As<IProtocolHandler>().SingleInstance();
builder.RegisterGeneric(typeof(Logger<>)).As(typeof(ILogger<>));
builder.RegisterType<NLogLoggerFactory>().AsImplementedInterfaces().InstancePerLifetimeScope();
var container = builder.Build();
var server = container.Resolve<IServer>();
server.Start();
while (true) { }
}
}
}
| 36.446809 | 107 | 0.670753 | [
"MIT"
] | SchulIT/adauth-server | AuthServer.Console/Program.cs | 1,715 | C# |
using System.IO;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using deVoid.UIFramework;
using deVoid.Utils;
using Mirror;
public class GuideSetupWindowController : AWindowController
{
[SerializeField] private GameObject guideProfileListContainer;
[SerializeField] private GuideProfileListEntry guideProfileListEntryPrefab;
public void CreateNewTour()
{
var newTour = TourHelpers.NewTour();
newTour.profileName = "Your Name";
App.uiFrame.OpenWindow(ScreenList.profileNameWindow, new ProfileNameWindowControllerProperties(newTour));
}
protected override void OnPropertiesSet() {
NetworkManager.singleton.StopHost();
foreach(var entry in guideProfileListContainer.GetComponentsInChildren<GuideProfileListEntry>())
Destroy(entry.gameObject);
foreach(var tour in TourHelpers.LoadTours())
{
var newEntry = Instantiate(guideProfileListEntryPrefab);
newEntry.transform.SetParent(guideProfileListContainer.transform, false);
newEntry.transform.SetAsFirstSibling();
// it is important to set as first sibling because of unity ui restrictions
// ie having dynamically sized children of a layout group is very buggy if working at all
// and we want a new profile button as last entry
newEntry.SetName(tour.profileName);
newEntry.startWithProfileButton.onClick.AddListener(() => StartTour(tour));
newEntry.editProfileButton.onClick.AddListener(() => EditProfile(tour));
newEntry.deleteProfileButton.onClick.AddListener(() => DeleteProfile(tour, newEntry));
}
}
void StartTour(Tour tour)
{
NetworkManager.singleton.StartHost();
App.discovery.serverName = tour.profileName;
App.discovery.AdvertiseServer();
StartCoroutine(WaitForLocalConnection(tour));
}
void EditProfile(Tour tour)
{
App.uiFrame.OpenWindow(ScreenList.profileEditWindow, new ProfileEditWindowControllerProperties(tour));
}
void DeleteProfile(Tour tour, GuideProfileListEntry entry)
{
Destroy(entry.gameObject);
try
{
TourHelpers.DeleteTour(tour);
}
catch
{
Debug.Log("Could not delete tour with uniqueId: " + tour.uniqueId);
}
}
IEnumerator WaitForLocalConnection(Tour tour)
{
yield return new WaitUntil(() => NetworkServer.localConnection.isReady);
App.activeTour = tour; // TODO make this irrelevant - we're passing the tour to the content window already
// App.guideSync.ShowContent(App.activeTour.GetFirstFile());
var props = new ContentWindowControllerProperties() { startWithFile = tour.GetFirstFile(false), tour = tour };
App.uiFrame.OpenWindow(ScreenList.guideContentWindow, props);
}
} | 35.795181 | 118 | 0.685964 | [
"MIT"
] | museum4punkt0/AR-Interactive-Guide-Tool | ar_interactive_tour_guide_unity/Assets/Scripts/Screens/GuideSetupWindowController.cs | 2,973 | C# |
using UnityEngine;
using System.Collections;
public static class StartingVariables
{
public const int shipHP = 30;
public const int shipShieldHP = 2;
public const float shipShieldReactivationTime = 5.0f;
public const int shipDamage = 30;
public const float shipSpeed = 2.0f;
public const float shipTurnSpeed = 1.75f;
public const float shipDetectionRadius = 1.0f;
public const float projectileSpeed = 3.5f;
public const float projectileTravelTime = 1.5f; //seconds.
public const float weaponFireRate = 1.0f;
public const float weaponFireArc = 60.0f; //degrees from forward
public const float aiUpdateTicks = 0.25f;
}
| 29.73913 | 77 | 0.71345 | [
"MIT"
] | GrathnMi/MyWork | UnityGameProjects/FleetCommandMonkey/Assets/c#/StartingVariables.cs | 686 | C# |
using AutoFixture;
using Bogus;
using SocialCareCaseViewerApi.Tests.V1.Helpers;
using SocialCareCaseViewerApi.V1.Infrastructure;
#nullable enable
namespace SocialCareCaseViewerApi.Tests.V1.IntegrationTests.HistoricalData
{
public static class HistoricalE2ETestHelpers
{
public static HistoricalCaseNote AddCaseNoteForASpecificPersonToDb(HistoricalDataContext context, long personId, bool includeNoteContent = true)
{
var faker = new Faker();
var noteTypeCode = faker.Random.String2(5);
var noteTypeDescription = faker.Random.String2(15);
var noteType = HistoricalTestHelper.CreateDatabaseNoteType(noteTypeCode, noteTypeDescription);
context.HistoricalNoteTypes.Add(noteType);
var savedWorker = HistoricalTestHelper.CreateDatabaseWorker();
context.HistoricalWorkers.Add(savedWorker);
var caseNoteId = faker.Random.Long(min: 1);
var savedCaseNote = HistoricalTestHelper.CreateDatabaseCaseNote(caseNoteId, personId, savedWorker, noteType);
context.HistoricalCaseNotes.Add(savedCaseNote);
context.SaveChanges();
return new HistoricalCaseNote
{
CreatedBy = $"{savedWorker.FirstNames} {savedWorker.LastNames}",
CreatedByWorker = savedCaseNote.CreatedByWorker,
Id = savedCaseNote.Id,
LastUpdatedBy = savedCaseNote.LastUpdatedBy,
Note = includeNoteContent == true ? savedCaseNote.Note : null,
PersonId = savedCaseNote.PersonId,
Title = savedCaseNote.Title,
CreatedOn = savedCaseNote.CreatedOn,
NoteType = noteType.Description,
HistoricalNoteType = noteType
};
}
public static HistoricalCaseNote AddCaseNoteWithNoteTypeAndWorkerToDatabase(HistoricalDataContext socialCareContext)
{
var noteType = HistoricalTestHelper.CreateDatabaseNoteType();
var worker = HistoricalTestHelper.CreateDatabaseWorker();
var caseNote = HistoricalTestHelper.CreateDatabaseCaseNote(createdWorker: worker, noteType: noteType);
socialCareContext.HistoricalWorkers.Add(worker);
socialCareContext.HistoricalCaseNotes.Add(caseNote);
socialCareContext.SaveChanges();
return new HistoricalCaseNote
{
CreatedBy = $"{worker.FirstNames} {worker.LastNames}",
CreatedByWorker = caseNote.CreatedByWorker,
Id = caseNote.Id,
LastUpdatedBy = caseNote.LastUpdatedBy,
Note = caseNote.Note,
PersonId = caseNote.PersonId,
Title = caseNote.Title,
CreatedOn = caseNote.CreatedOn,
NoteType = noteType.Type,
HistoricalNoteType = noteType
};
}
public static HistoricalVisit AddVisitToDatabase(HistoricalDataContext socialCareContext, HistoricalWorker? worker = null)
{
var visitInformation = HistoricalTestHelper.CreateDatabaseVisit(worker: worker);
socialCareContext.HistoricalVisits.Add(visitInformation);
socialCareContext.SaveChanges();
return visitInformation;
}
public static HistoricalWorker AddWorkerToDatabase(HistoricalDataContext socialCareContext)
{
var worker = HistoricalTestHelper.CreateDatabaseWorker();
socialCareContext.HistoricalWorkers.Add(worker);
socialCareContext.SaveChanges();
return worker;
}
}
}
| 42.298851 | 152 | 0.655707 | [
"MIT"
] | JohnFarrellDev/social-care-case-viewer-api-fork | SocialCareCaseViewerApi.Tests/V1/IntegrationTests/HistoricalData/HistoricalE2ETestHelpers.cs | 3,680 | C# |
using Orchard.Environment.Extensions;
using Orchard.UI.Navigation;
namespace Orchard.Localization {
[OrchardFeature("Orchard.Localization.Transliteration")]
public class AdminMenu : INavigationProvider {
public Localizer T { get; set; }
public string MenuName { get { return "admin"; } }
public void GetNavigation(NavigationBuilder builder) {
builder
.Add(T("Settings"), menu => menu
.Add(T("Transliteration"), "10.0", subMenu => subMenu.Action("Index", "TransliterationAdmin", new { area = "Orchard.Localization" })
.Add(T("Settings"), "10.0", item => item.Action("Index", "TransliterationAdmin", new { area = "Orchard.Localization" }).LocalNav())
));
}
}
} | 45.166667 | 156 | 0.594096 | [
"BSD-3-Clause"
] | Lombiq/Associativy | src/Orchard.Web/Modules/Orchard.Localization/AdminMenu.cs | 813 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Newtonsoft.Json;
namespace ProjectWebServer.Models
{
// Models used as parameters to AccountController actions.
public class ChangePasswordBindingModel
{
[Required]
[DataType(DataType.Password)]
[Display(Name = "Current password")]
public string OldPassword { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class RegisterBindingModel
{
[Required]
[Display(Name = "Email")]
public string Email { get; set; }
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "Password")]
public string Password { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm password")]
[Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
public class SetPasswordBindingModel
{
[Required]
[StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
[DataType(DataType.Password)]
[Display(Name = "New password")]
public string NewPassword { get; set; }
[DataType(DataType.Password)]
[Display(Name = "Confirm new password")]
[Compare("NewPassword", ErrorMessage = "The new password and confirmation password do not match.")]
public string ConfirmPassword { get; set; }
}
}
| 34.916667 | 110 | 0.633413 | [
"MIT"
] | nbradbury138/SIT313-Project2-CloudGroup8 | Project2/ProjectWebServer/Models/AccountBindingModels.cs | 2,097 | C# |
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)
using System;
using ICSharpCode.NRefactory.Editor;
namespace ICSharpCode.AvalonEdit.Folding
{
/// <summary>
/// Helper class used for <see cref="FoldingManager.UpdateFoldings"/>.
/// </summary>
public class NewFolding : ISegment
{
/// <summary>
/// Gets/Sets the start offset.
/// </summary>
public int StartOffset { get; set; }
/// <summary>
/// Gets/Sets the end offset.
/// </summary>
public int EndOffset { get; set; }
/// <summary>
/// Gets/Sets the name displayed for the folding.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/Sets whether the folding is closed by default.
/// </summary>
public bool DefaultClosed { get; set; }
/// <summary>
/// Gets/Sets whether the folding is considered to be a definition.
/// This has an effect on the 'Show Definitions only' command.
/// </summary>
public bool IsDefinition { get; set; }
/// <summary>
/// Creates a new NewFolding instance.
/// </summary>
public NewFolding()
{
}
/// <summary>
/// Creates a new NewFolding instance.
/// </summary>
public NewFolding(int start, int end)
{
if (!(start <= end))
throw new ArgumentException("'start' must be less than 'end'");
this.StartOffset = start;
this.EndOffset = end;
this.Name = null;
this.DefaultClosed = false;
}
int ISegment.Offset {
get { return this.StartOffset; }
}
int ISegment.Length {
get { return this.EndOffset - this.StartOffset; }
}
}
}
| 24.623188 | 103 | 0.645674 | [
"MIT"
] | GlobalcachingEU/GSAKWrapper | ICSharpCode.AvalonEdit/Folding/NewFolding.cs | 1,701 | C# |
[CipherSuite ECDHE_ECDSA AES_128_CBC_SHA256,CipherSuite ECDHE_ECDSA AES_128_CBC_SHA,CipherSuite ECDHE_RSA AES_128_CBC_SHA256,CipherSuite ECDHE_RSA AES_128_CBC_SHA,CipherSuite DHE_RSA AES_128_CBC_SHA256,CipherSuite DHE_RSA AES_128_CBC_SHA,CipherSuite RSA AES_128_CBC_SHA256,CipherSuite RSA AES_128_CBC_SHA]
| 153 | 305 | 0.915033 | [
"BSD-3-Clause"
] | YoshikuniJujo/forest | subprojects/tls-analysis/server/test/1T1POQbO-5Tp.cs | 306 | C# |
// <auto-generated/>
#pragma warning disable 1591
namespace Test
{
#line hidden
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components;
#nullable restore
#line 1 "x:\dir\subdir\Test\TestComponent.cshtml"
using Microsoft.AspNetCore.Components.Web;
#line default
#line hidden
#nullable disable
public class TestComponent : Microsoft.AspNetCore.Components.ComponentBase
{
#pragma warning disable 219
private void __RazorDirectiveTokenHelpers__() {
}
#pragma warning restore 219
#pragma warning disable 0414
private static System.Object __o = null;
#pragma warning restore 0414
#pragma warning disable 1998
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder)
{
__o = Microsoft.AspNetCore.Components.BindConverter.FormatValue(
#nullable restore
#line 3 "x:\dir\subdir\Test\TestComponent.cshtml"
text
#line default
#line hidden
#nullable disable
);
__o = Microsoft.AspNetCore.Components.EventCallback.Factory.CreateBinder(this, __value => text = __value, text);
}
#pragma warning restore 1998
#nullable restore
#line 5 "x:\dir\subdir\Test\TestComponent.cshtml"
private string text = "hi";
#line default
#line hidden
#nullable disable
}
}
#pragma warning restore 1591
| 28.830189 | 124 | 0.688482 | [
"Apache-2.0"
] | Therzok/AspNetCore-Tooling | src/Razor/test/RazorLanguage.Test/TestFiles/IntegrationTests/ComponentDesignTimeCodeGenerationTest/DuplicateMarkupAttributes_DifferentCasing_IsAnError_BindValue/TestComponent.codegen.cs | 1,528 | C# |
using System;
using System.Threading;
public class Beta
{
public static int Main(string[] args)
{
int rValue = 100;
Console.WriteLine("Setup an Infinite Wait with negative value other than -1");
Console.WriteLine("This can't be done on WaitAny and WaitAll");
WaitHandle Waiter;
Waiter = (WaitHandle) new AutoResetEvent(false);
try{
Waiter.WaitOne(-2);
Console.WriteLine("ERROR -- Enabled a wait with -2");
rValue = 10;
}catch(ArgumentOutOfRangeException){}
try{
Waiter.WaitOne(Int32.MinValue);
Console.WriteLine("ERROR -- Enabled a wait with {0}",Int32.MinValue);
rValue = 20;
}catch(ArgumentOutOfRangeException){}
try{
Waiter.WaitOne(-1000000);
Console.WriteLine("ERROR -- Enabled a wait with -1000000");
rValue = 20;
}catch(ArgumentOutOfRangeException){}
Console.WriteLine("Test {0}",rValue == 100 ? "Passed":"Failed");
return rValue;
}
}
| 23.769231 | 80 | 0.677454 | [
"MIT"
] | CyberSys/coreclr-mono | tests/src/baseservices/threading/regressions/6906/repro.cs | 927 | C# |
using System;
using System.Collections.Generic;
using System.Text;
using Unification.Application;
namespace Unification
{
public class ApplicationsManager
{
private AvaibleApplications _avaibleApps;
public ApplicationsManager()
{
_avaibleApps = new AvaibleApplications();
}
public void StartApplicationForUser(int appNumber, List<string> _userValuesForApp)
{
switch (appNumber)
{
case 1:
_avaibleApps.StartAnagramsApp(_userValuesForApp);
break;
case 2:
_avaibleApps.StartDiversionApp(_userValuesForApp);
break;
case 3:
_avaibleApps.StartBattleShipsApp();
break;
}
}
}
}
| 23.486486 | 90 | 0.53855 | [
"MIT"
] | Matthew-1/Projects | UnifiedKatasAndBattleShip/Unification/Unification/Application/ApplicationsManager.cs | 871 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using SMC.Utilities.Queues;
using System;
using System.Collections.Generic;
namespace ItemQueueLib.Tests
{
[TestClass]
public class ActionQueueTests
{
// ReSharper disable once InconsistentNaming
private const string QUEUE_NAME = "action_queue_name";
[TestMethod]
public void ConstructorWithQueueNameTest()
{
var sum = 0;
var actionQueue = new ActionQueue<int>(QUEUE_NAME);
actionQueue.SetAction(value => sum += value);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
Assert.IsTrue(sum == 3);
Assert.AreEqual(actionQueue.Name, QUEUE_NAME, false);
}
[TestMethod]
public void ConstructorWithActionTest()
{
var sum = 0;
var actionQueue = new ActionQueue<int>(value => sum += value);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
Assert.IsTrue(sum == 3);
}
[TestMethod]
public void ConstructorWithActionCallbackTest()
{
var sum = 0;
var callbackSum = 0;
var actionQueue = new ActionQueue<int>(value => sum += value, value => callbackSum += value);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
Assert.IsTrue(sum == 3);
Assert.IsTrue(callbackSum == 3);
}
[TestMethod]
public void ConstructorWithActionQueueNameTest()
{
var sum = 0;
var actionQueue = new ActionQueue<int>(value => sum += value, QUEUE_NAME);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
Assert.IsTrue(sum == 3);
Assert.AreEqual(actionQueue.Name, QUEUE_NAME, false);
}
[TestMethod]
public void ConstructorWithAllParametersTest()
{
var sum = 0;
var callbackSum = 0;
var actionQueue = new ActionQueue<int>(value => sum += value, value=>callbackSum+=value, QUEUE_NAME);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
Assert.IsTrue(sum == 3);
Assert.IsTrue(callbackSum == 3);
Assert.AreEqual(actionQueue.Name, QUEUE_NAME, false);
}
[TestMethod]
public void SummationTest()
{
var sum = 0;
var actionQueue = new ActionQueue<int>();
actionQueue.SetAction(value => sum += value);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
Assert.IsTrue(sum == 3);
}
[TestMethod]
public void IDisposableSummationTest()
{
var sum = 0;
using(var actionQueue = new ActionQueue<int>())
{
actionQueue.SetAction(value => sum += value);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
}
Assert.IsTrue(sum == 3);
}
[TestMethod]
public void SummationListTest()
{
var sum = 0;
var actionQueue = new ActionQueue<int>();
actionQueue.SetAction(value => sum += value);
actionQueue.Start();
actionQueue.Enqueue(new List<int>() { 1 });
actionQueue.Stop(true);
Assert.IsTrue(sum == 1);
}
[TestMethod]
public void MultipleSummationTest()
{
var sum = 0;
var actionQueue = new ActionQueue<int>();
actionQueue.SetAction(value => sum += value);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Enqueue(3);
actionQueue.Enqueue(4);
actionQueue.Enqueue(5);
actionQueue.Stop(true);
Assert.IsTrue(sum == 15);
}
[TestMethod]
public void MultipleSummationListTest()
{
var sum = 0;
var actionQueue = new ActionQueue<int>();
actionQueue.SetAction(value => sum += value);
actionQueue.Start();
actionQueue.Enqueue(new List<int>() { 1, 2, 3, 4, 5 });
actionQueue.Stop(true);
Assert.IsTrue(sum == 15);
}
[TestMethod]
public void MultiplicationTest()
{
var result = 2;
var actionQueue = new ActionQueue<int>();
actionQueue.SetAction(value => result *= value);
actionQueue.Start();
actionQueue.Enqueue(4);
actionQueue.Stop(true);
Assert.IsTrue(result == 8);
}
[TestMethod]
public void StringConcatTest()
{
var result = string.Empty;
var actionQueue = new ActionQueue<string>();
actionQueue.SetAction(value => result = string.Concat(result, value));
actionQueue.Start();
actionQueue.Enqueue("Hello");
actionQueue.Enqueue(", World!");
actionQueue.Stop(true);
Assert.AreEqual(result, "Hello, World!", false);
}
[TestMethod]
public void StringConcatListTest()
{
var result = string.Empty;
var actionQueue = new ActionQueue<string>();
actionQueue.SetAction(value => result = string.Concat(result, value));
actionQueue.Start();
actionQueue.Enqueue(new List<string>() { "Hello", ", World!" });
actionQueue.Stop(true);
Assert.AreEqual(result, "Hello, World!", false);
}
[TestMethod]
public void CallbackTest()
{
var sum = 0;
var callbackSum = 0;
var actionQueue = new ActionQueue<int>();
actionQueue.SetAction(value => sum += value);
actionQueue.SetCallback(value => callbackSum += value);
actionQueue.Start();
actionQueue.Enqueue(1);
actionQueue.Enqueue(2);
actionQueue.Stop(true);
Assert.IsTrue(sum == 3);
Assert.IsTrue(callbackSum == 3);
}
[TestMethod]
[ExpectedException(typeof(NoActionException))]
public void NoActionSetTest()
{
var actionQueue = new ActionQueue<int>();
actionQueue.Start();
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullActionSetTest()
{
var actionQueue = new ActionQueue<int>();
//actionQueue.SetAction(value => value++);
actionQueue.SetAction(null);
}
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void NullCallbackSetTest()
{
var actionQueue = new ActionQueue<int>();
actionQueue.SetCallback(null);
}
}
} | 30.818182 | 113 | 0.531912 | [
"Apache-2.0"
] | dmarciano/ItemQueue | src/ItemQueueLib.Tests/ActionQueueTests.cs | 7,460 | C# |
using System.Collections.Generic;
using System.Data.Entity.Infrastructure;
using System.Threading;
using System.Threading.Tasks;
namespace EntityFrameworkMock
{
// From https://msdn.microsoft.com/en-us/library/dn314429(v=vs.113).aspx
public class DbAsyncEnumerator<TEntity> : IDbAsyncEnumerator<TEntity>
{
private readonly IEnumerator<TEntity> _inner;
public DbAsyncEnumerator(IEnumerator<TEntity> inner)
{
_inner = inner;
}
public void Dispose() => _inner.Dispose();
public Task<bool> MoveNextAsync(CancellationToken cancellationToken) => Task.FromResult(_inner.MoveNext());
public TEntity Current => _inner.Current;
object IDbAsyncEnumerator.Current => Current;
}
}
| 28.407407 | 115 | 0.70013 | [
"Apache-2.0"
] | huysentruitw/entity-framework-mock | src/EntityFrameworkMock.Shared/DbAsyncEnumerator.cs | 769 | C# |
// ---------------------------------------------------------------------------------------------------------------------
// <copyright file="MilpInSpanPart.cs" company="Czech Technical University in Prague">
// Copyright (c) 2018 Czech Technical University in Prague
// </copyright>
// ---------------------------------------------------------------------------------------------------------------------
namespace Iirc.EnergyLimitsScheduling.Shared.Solvers
{
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using Gurobi;
using Iirc.EnergyLimitsScheduling.Shared.DataStructs;
using Iirc.EnergyLimitsScheduling.Shared.Input;
using Iirc.Utils.Collections;
using Iirc.Utils.Gurobi;
using Iirc.Utils.Math;
using Iirc.Utils.SolverFoundations;
public class MilpInSpanPart : BaseSolver<MilpInSpanPart.SpecializedSolverConfig>
{
protected GRBEnv env;
protected GRBModel model;
protected MeteringIntervalsSubset modelMeteringIntervals;
private Variables vars;
protected override Status Solve()
{
this.env = new GRBEnv();
this.model = new GRBModel(this.env);
this.SetModelParameters();
switch (this.specializedSolverConfig.HorizonOptimizationStrategy)
{
case HorizonOptimizationStrategy.Whole:
return this.WholeHorizonOptimizationStrategy();
case HorizonOptimizationStrategy.Decreasing:
return this.DecreasingOptimizationStrategy();
default:
throw new ArgumentException($"Invalid optimization strategy {this.specializedSolverConfig.HorizonOptimizationStrategy}");
}
}
private Status WholeHorizonOptimizationStrategy()
{
this.modelMeteringIntervals = new MeteringIntervalsSubset(
this.instance.FirstMeteringIntervalIndex(),
this.instance.LastMeteringIntervalIndex(),
this.instance.LengthMeteringInterval);
this.CreateVariables();
this.CreateConstraints();
this.CreateObjective();
this.SetInitStartTimes();
this.model.SetTimeLimit(this.RemainingTime);
this.model.Optimize();
return this.model.GetResultStatus();
}
private Status DecreasingOptimizationStrategy()
{
var comparer = NumericComparer.Default;
StartTimes initStartTimes = null;
var numMeteringIntervals = this.instance.NumMeteringIntervals;
if (this.solverConfig.InitStartTimes != null)
{
initStartTimes = new StartTimes(this.instance, this.solverConfig.InitStartTimes);
numMeteringIntervals = (int)(((int)Math.Round(initStartTimes.Makespan) - 1) / this.instance.LengthMeteringInterval) + 1;
}
this.modelMeteringIntervals = new MeteringIntervalsSubset(
this.instance.FirstMeteringIntervalIndex(),
initStartTimes == null ?
this.instance.LastMeteringIntervalIndex()
: Math.Min(
this.instance.LastMeteringIntervalIndex(),
this.instance.FirstMeteringIntervalIndex() + numMeteringIntervals - 1),
this.instance.LengthMeteringInterval);
Status? previousStatus = null;
while (true)
{
Console.WriteLine($"Current horizon: 0 - {this.modelMeteringIntervals.Horizon}");
this.CreateVariables();
this.CreateConstraints();
this.CreateObjective();
this.SetInitStartTimes(initStartTimes);
this.model.SetTimeLimit(this.RemainingTime);
this.model.Optimize();
var resultStatus = this.model.GetResultStatus();
if (resultStatus == Status.Optimal)
{
if (comparer.Greater(this.model.ObjVal, 0.0))
{
// i.e. LB>0
return Status.Optimal;
}
}
else if (resultStatus == Status.Heuristic)
{
Debug.Assert(this.TimeLimitReached());
return Status.Heuristic;
}
else if (resultStatus == Status.NoSolution)
{
Debug.Assert(this.TimeLimitReached());
// In case of time out, gurobi should at least return the start solution if set.
Debug.Assert(previousStatus.HasValue == false);
return Status.NoSolution;
}
else if (resultStatus == Status.Infeasible)
{
return Status.Infeasible;
}
Debug.Assert(resultStatus == Status.Optimal);
previousStatus = Status.Optimal;
initStartTimes = this.GetStartTimes();
if (this.modelMeteringIntervals.Count <= this.specializedSolverConfig.OptimizationWindow)
{
return Status.Optimal;
}
// Decrease the considered metering intervals.
this.modelMeteringIntervals = new MeteringIntervalsSubset(
this.modelMeteringIntervals.FirstMeteringIntervalIndex,
this.modelMeteringIntervals.LastMeteringIntervalIndex - this.specializedSolverConfig.OptimizationWindow,
this.instance.LengthMeteringInterval);
}
}
private void SetModelParameters()
{
this.model.Parameters.FeasibilityTol = NumericComparer.DefaultTolerance;
this.model.Parameters.Threads = Math.Max(0, this.solverConfig.NumWorkers);
if (this.specializedSolverConfig.LazyEnergyConstraints)
{
this.model.Parameters.LazyConstraints = 1;
}
}
protected override void CheckInstanceValidity()
{
if (this.instance.Jobs.Any(job => job.Operations.Length >= 2))
{
throw new ArgumentException("Solver cannot handle instances with jobs having more than one operation.");
}
if (this.specializedSolverConfig.OptimizationWindow > 1
&& this.solverConfig.ContinuousStartTimes
&& this.specializedSolverConfig.BigMObjectiveConstraints == false)
{
throw new ArgumentException("Solver cannot handle larger optimization window than 1 if continuous start times are required.");
}
}
protected override void CheckConfigValidity()
{
if (this.specializedSolverConfig.BigMObjectiveConstraints
&& this.specializedSolverConfig.HorizonOptimizationStrategy != HorizonOptimizationStrategy.Whole)
{
throw new ArgumentException($"Does not make sense to use different horizon optimization strategy than ${HorizonOptimizationStrategy.Whole} if BigM objective is used.");
}
}
private void CreateVariables()
{
this.vars = new Variables();
this.vars.Obj = this.model.AddVar(0, GRB.INFINITY, 0,
this.solverConfig.ContinuousStartTimes ? GRB.CONTINUOUS : GRB.INTEGER, "obj");
this.vars.NonZeroOverlap = new Dictionary<Operation, GRBVar[]>();
if (this.specializedSolverConfig.OnBoundaryMaxThreeConstraint == false)
{
this.vars.OnBoundary = new Dictionary<Operation, GRBVar[]>();
}
this.vars.Overlap = new Dictionary<Operation, GRBVar[]>();
this.vars.StartIn = new Dictionary<Operation, GRBVar[]>();
if (this.specializedSolverConfig.BigMObjectiveConstraints)
{
this.vars.HasOverlappingOperation = new Dictionary<int, GRBVar[]>();
}
foreach (var operation in this.instance.AllOperations())
{
if (this.specializedSolverConfig.OnBoundaryMaxThreeConstraint == false)
{
this.vars.OnBoundary[operation] = new GRBVar[this.modelMeteringIntervals.Count];
}
this.vars.Overlap[operation] = new GRBVar[this.modelMeteringIntervals.Count];
this.vars.NonZeroOverlap[operation] = new GRBVar[this.modelMeteringIntervals.Count];
if (this.IsSpannable(operation))
{
this.vars.StartIn[operation] = new GRBVar[this.modelMeteringIntervals.Count];
}
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
if (this.specializedSolverConfig.OnBoundaryMaxThreeConstraint == false)
{
this.vars.OnBoundary[operation][meteringIntervalIndex] =
this.model.AddVar(0, 1, 0, GRB.BINARY,
$"onBoundary_{operation.Id}{meteringIntervalIndex}");
this.vars.OnBoundary[operation][meteringIntervalIndex].BranchPriority = 0;
}
this.vars.Overlap[operation][meteringIntervalIndex] =
this.model.AddVar(
0, GRB.INFINITY, 0,
this.solverConfig.ContinuousStartTimes ? GRB.CONTINUOUS : GRB.INTEGER,
$"overlap_{operation.Id}{meteringIntervalIndex}");
this.vars.Overlap[operation][meteringIntervalIndex].BranchPriority = 0;
this.vars.NonZeroOverlap[operation][meteringIntervalIndex] =
this.model.AddVar(0, 1, 0, GRB.BINARY,
$"nonZeroOverlap_{operation.Id}{meteringIntervalIndex}");
this.vars.NonZeroOverlap[operation][meteringIntervalIndex].BranchPriority = 1000;
if (this.IsSpannable(operation))
{
this.vars.StartIn[operation][meteringIntervalIndex] =
this.model.AddVar(0, 1, 0, GRB.BINARY,
$"startIn_{operation.Id}{meteringIntervalIndex}");
this.vars.StartIn[operation][meteringIntervalIndex].BranchPriority = 2000;
}
}
}
foreach (var machineIndex in this.instance.Machines())
{
if (this.specializedSolverConfig.BigMObjectiveConstraints)
{
this.vars.HasOverlappingOperation[machineIndex] = new GRBVar[this.modelMeteringIntervals.Count];
}
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
if (this.specializedSolverConfig.BigMObjectiveConstraints)
{
this.vars.HasOverlappingOperation[machineIndex][meteringIntervalIndex] =
this.model.AddVar(0, 1, 0, GRB.BINARY,
$"hasOverlappingOperation_{machineIndex}{meteringIntervalIndex}");
}
}
}
}
private void CreateConstraints()
{
this.model.Remove(this.model.GetConstrs());
this.model.Remove(this.model.GetSOSs());
this.model.Update();
var optimizationMeteringIntervals = this.GetOptimizationMeteringIntervals();
if (this.specializedSolverConfig.BigMObjectiveConstraints)
{
foreach (var machineIndex in this.instance.Machines())
{
var machineOperations = this.instance.MachineOperations(machineIndex).ToArray();
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
model.AddConstr(
meteringIntervalIndex * this.instance.LengthMeteringInterval * this.vars.HasOverlappingOperation[machineIndex][meteringIntervalIndex]
+ machineOperations
.Quicksum(operation => this.vars.Overlap[operation][meteringIntervalIndex])
<=
this.vars.Obj,
$"obj_{machineIndex}{meteringIntervalIndex}");
model.AddConstr(
machineOperations
.Quicksum(operation => this.vars.NonZeroOverlap[operation][meteringIntervalIndex])
<=
this.instance.LengthMeteringInterval * this.vars.HasOverlappingOperation[machineIndex][meteringIntervalIndex],
$"obj_{machineIndex}{meteringIntervalIndex}");
}
}
}
else
{
foreach (var machineIndex in this.instance.Machines())
{
var runningMultiplier = 1.0;
foreach (var meteringIntervalIndex in optimizationMeteringIntervals)
{
model.AddConstr(
runningMultiplier *
this.instance.MachineOperations(machineIndex)
.Quicksum(operation => this.vars.Overlap[operation][meteringIntervalIndex])
<=
this.vars.Obj,
$"obj_{machineIndex}");
runningMultiplier *= this.instance.LengthMeteringInterval;
}
}
}
foreach (var machineIndex in this.instance.Machines())
{
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
this.model.AddConstr(
this.instance.MachineOperations(machineIndex)
.Quicksum(operation => this.vars.Overlap[operation][meteringIntervalIndex])
<=
this.instance.LengthMeteringInterval,
$"totalOverlap_{meteringIntervalIndex}{machineIndex}");
}
}
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
this.model.AddConstr(
this.instance.AllOperations()
.Quicksum(operation =>
this.vars.Overlap[operation][meteringIntervalIndex] * operation.PowerConsumption)
<=
this.instance.EnergyLimit,
$"energyLimit_{meteringIntervalIndex}");
}
foreach (var operation in this.instance.AllOperations())
{
this.model.AddConstr(
this.modelMeteringIntervals
.Quicksum(meteringIntervalIndex => this.vars.Overlap[operation][meteringIntervalIndex])
==
operation.ProcessingTime,
$"totalOverlapIsProcessingTime_{operation.Id}");
}
foreach (var operation in this.instance.AllOperations().Where(this.NotSpannable))
{
// Problems with SOS constraints when containing only one variable.
// Moreover, if we have only one variable, then this constraint is already enforced by
// totalOverlapIsProcessingTime_
if (this.modelMeteringIntervals.Count > 1)
{
var vars = this.modelMeteringIntervals
.Select(meteringIntervalIndex => this.vars.Overlap[operation][meteringIntervalIndex])
.ToArray();
this.model.AddSOS(
vars,
Enumerable.Range(1, vars.Length).Select(x => (double)x).ToArray(),
GRB.SOS_TYPE2);
}
}
foreach (var operation in this.instance.AllOperations().Where(this.IsSpannable))
{
this.model.AddConstr(
this.modelMeteringIntervals
.Quicksum(meteringIntervalIndex => this.vars.StartIn[operation][meteringIntervalIndex])
==
1,
$"spannableStartsSomewhere_{operation.Id}")
.SetLazy(this.specializedSolverConfig.LazyEnergyConstraints);
}
foreach (var operation in this.instance.AllOperations().Where(this.IsSpannable))
{
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
this.model.AddConstr(
this.vars.Overlap[operation][meteringIntervalIndex]
<=
this.instance.LengthMeteringInterval *
EnumerableExtensions
.RangeTo(
Math.Max(this.modelMeteringIntervals.FirstMeteringIntervalIndex,
meteringIntervalIndex - operation.MaxNumNonZeroOvelapIntervals(this.instance) +
1),
meteringIntervalIndex)
.Quicksum(meteringIntervalIndexOther =>
this.vars.StartIn[operation][meteringIntervalIndexOther]),
$"spannableSlackedOverlap_{operation.Id}{meteringIntervalIndex}")
.SetLazy(this.specializedSolverConfig.LazyEnergyConstraints);
}
}
foreach (var operation in this.instance.AllOperations().Where(this.IsSpannable))
{
foreach (var meteringIntervalIndex in this.modelMeteringIntervals.SkipFirst().SkipLast())
{
this.model.AddConstr(
this.instance.LengthMeteringInterval *
(this.vars.NonZeroOverlap[operation][meteringIntervalIndex - 1] +
this.vars.NonZeroOverlap[operation][meteringIntervalIndex + 1] - 1)
<=
this.vars.Overlap[operation][meteringIntervalIndex],
$"spanOverlapLb_{operation.Id}{meteringIntervalIndex}")
.SetLazy(this.specializedSolverConfig.LazyEnergyConstraints);
}
}
foreach (var operation in this.instance.AllOperations())
{
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
var bigM = Math.Min(this.instance.LengthMeteringInterval, operation.ProcessingTime);
this.model.AddConstr(
this.vars.Overlap[operation][meteringIntervalIndex]
<=
bigM * this.vars.NonZeroOverlap[operation][meteringIntervalIndex],
$"nonZeroOverlapLb_{operation.Id}{meteringIntervalIndex}")
.SetLazy(this.specializedSolverConfig.LazyEnergyConstraints);
}
}
if (this.specializedSolverConfig.OnBoundaryMaxThreeConstraint)
{
foreach (var machineIndex in this.instance.Machines())
{
var machineOperations = this.instance.MachineOperations(machineIndex);
foreach (var (operation, operationOther) in machineOperations.OrderedPairs())
{
if (operation.ProcessingTime >= 2
&& operationOther.ProcessingTime >= 2
&& (operation.ProcessingTime + operationOther.ProcessingTime) <= 2*this.instance.LengthMeteringInterval)
{
foreach (var meteringIntervalIndex in this.modelMeteringIntervals.SkipLast())
{
this.model.AddConstr(
this.vars.NonZeroOverlap[operation][meteringIntervalIndex] +
this.vars.NonZeroOverlap[operation][meteringIntervalIndex + 1] +
this.vars.NonZeroOverlap[operationOther][meteringIntervalIndex] +
this.vars.NonZeroOverlap[operationOther][meteringIntervalIndex + 1]
<=
3,
$"onBoundaryUb_{machineIndex}{operation.Id}{operationOther.Id}{meteringIntervalIndex}")
.SetLazy(this.specializedSolverConfig.LazyEnergyConstraints);
}
}
}
}
}
else
{
foreach (var operation in this.instance.AllOperations())
{
foreach (var meteringIntervalIndex in this.modelMeteringIntervals.SkipLast())
{
this.model.AddConstr(
this.vars.NonZeroOverlap[operation][meteringIntervalIndex] +
this.vars.NonZeroOverlap[operation][meteringIntervalIndex + 1] - 1
<=
this.vars.OnBoundary[operation][meteringIntervalIndex],
$"onBoundaryLb_{operation.Id}{meteringIntervalIndex}")
.SetLazy(this.specializedSolverConfig.LazyEnergyConstraints);
}
}
foreach (var machineIndex in this.instance.Machines())
{
var machineOperations = this.instance.MachineOperations(machineIndex);
foreach (var meteringIntervalIndex in this.modelMeteringIntervals.SkipLast())
{
this.model.AddConstr(
machineOperations.Quicksum(operation => this.vars.OnBoundary[operation][meteringIntervalIndex])
<=
1,
$"atMostOneBoundary_{machineIndex}{meteringIntervalIndex}");
}
}
}
}
private void CreateObjective()
{
this.model.SetObjective(this.vars.Obj + 0, GRB.MINIMIZE);
}
private MeteringIntervalsSubset GetOptimizationMeteringIntervals()
{
switch (this.specializedSolverConfig.HorizonOptimizationStrategy)
{
case HorizonOptimizationStrategy.Whole:
return this.modelMeteringIntervals;
case HorizonOptimizationStrategy.Decreasing:
return new MeteringIntervalsSubset(
Math.Max(
this.modelMeteringIntervals.FirstMeteringIntervalIndex,
this.modelMeteringIntervals.LastMeteringIntervalIndex - this.specializedSolverConfig.OptimizationWindow + 1),
this.modelMeteringIntervals.LastMeteringIntervalIndex,
this.instance.LengthMeteringInterval);
default:
throw new ArgumentException($"Invalid optimization strategy {this.specializedSolverConfig.HorizonOptimizationStrategy}");
}
}
private void PrintNonZeroOverlaps()
{
var s = new StringBuilder();
foreach (var operation in this.instance.AllOperations())
{
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
s.Append($"{operation.JobIndex} {operation.Index} {meteringIntervalIndex} {this.vars.NonZeroOverlap[operation][meteringIntervalIndex].ToInt()}");
s.Append(",");
}
}
Console.WriteLine(s.ToString());
}
protected override void CheckSolution(StartTimes startTimes)
{
var comparer = NumericComparer.Default;
// Overlaps.
foreach (var operation in this.instance.AllOperations())
{
var startTimesOverlaps = operation.Overlaps(startTimes[operation], this.instance).ToArray();
var modelOverlaps = this.vars.Overlap[operation].ToDoubles().ToArray();
foreach (var meteringIntervalIndex in this.modelMeteringIntervals)
{
var startTimesOverlap = startTimesOverlaps[meteringIntervalIndex];
var modelOverlap = modelOverlaps[meteringIntervalIndex];
Debug.Assert(comparer.AreEqual(startTimesOverlap, modelOverlap));
}
}
}
protected override double? GetLowerBound()
{
switch (this.specializedSolverConfig.HorizonOptimizationStrategy)
{
case HorizonOptimizationStrategy.Whole:
return this.model.ObjBound;
case HorizonOptimizationStrategy.Decreasing:
var modelBound = this.model.ObjBound;
return NumericComparer.Default.AreEqual(0.0, modelBound) ?
(double?)null
: modelBound + this.instance.MeteringIntervalStart(this.modelMeteringIntervals.LastMeteringIntervalIndex);
default:
throw new ArgumentException($"Invalid optimization strategy {this.specializedSolverConfig.HorizonOptimizationStrategy}");
}
}
protected override StartTimes GetStartTimes()
{
var startTimes = new StartTimes();
var comparer = NumericComparer.Default;
// TODO (refactor): change to earliest start times
var shifts = this.instance.Machines()
.Select(_ => this.modelMeteringIntervals
.Select(meteringIntervalIndex =>
(double)this.instance.MeteringIntervalStart(meteringIntervalIndex))
.ToArray())
.ToArray();
// Start times should be computed using only overlap variables.
var inOperations = new List<Operation>();
foreach (var operation in this.instance.AllOperations())
{
var overlaps = this.vars.Overlap[operation].Select(overlap => overlap.ToDouble()).ToArray();
if (overlaps.SkipLast().TryWhereNonZero(out var firstNonZeroOverlapMeteringIntervalIndex))
{
if (comparer.Greater(overlaps[firstNonZeroOverlapMeteringIntervalIndex + 1], 0.0))
{
startTimes[operation] =
this.instance.MeteringIntervalEnd(firstNonZeroOverlapMeteringIntervalIndex) -
overlaps[firstNonZeroOverlapMeteringIntervalIndex];
for (var meteringIntervalIndex = firstNonZeroOverlapMeteringIntervalIndex + 1;
meteringIntervalIndex <= this.modelMeteringIntervals.LastMeteringIntervalIndex;
meteringIntervalIndex++)
{
var overlap = overlaps[meteringIntervalIndex];
if (comparer.AreEqual(overlap, 0.0))
{
break;
}
shifts[operation.MachineIndex][meteringIntervalIndex] += overlap;
}
}
else
{
inOperations.Add(operation);
}
}
else
{
inOperations.Add(operation);
}
}
foreach (var operation in inOperations)
{
if (this.vars.Overlap[operation].TryWhereNonZero(out var meteringIntervalIndex))
{
startTimes[operation] = shifts[operation.MachineIndex][meteringIntervalIndex];
shifts[operation.MachineIndex][meteringIntervalIndex] += operation.ProcessingTime;
}
}
return startTimes;
}
private void SetInitStartTimes()
{
if (this.solverConfig.InitStartTimes == null)
{
return;
}
this.SetInitStartTimes(new StartTimes(this.instance, this.solverConfig.InitStartTimes));
}
private void SetInitStartTimes(StartTimes initStartTimes)
{
if (initStartTimes == null)
{
return;
}
foreach (var (operation, startTime) in initStartTimes)
{
foreach (var (meteringIntervalIndex, overlap) in operation.NonZeroOverlaps(startTime, this.instance))
{
this.vars.Overlap[operation][meteringIntervalIndex].Start = overlap;
}
}
}
protected override void Cleanup()
{
this.model.Dispose();
this.env.Dispose();
}
protected override bool TimeLimitReached()
{
return this.model.TimeLimitReached();
}
private bool IsSpannable(Operation operation)
{
return operation.ProcessingTime > this.instance.LengthMeteringInterval;
}
private bool NotSpannable(Operation operation)
{
return this.IsSpannable(operation) == false;
}
public class Variables
{
public GRBVar Obj { get; set; }
public Dictionary<Operation, GRBVar[]> NonZeroOverlap { get; set; }
public Dictionary<Operation, GRBVar[]> OnBoundary { get; set; }
public Dictionary<Operation, GRBVar[]> Overlap { get; set; }
public Dictionary<Operation, GRBVar[]> StartIn { get; set; }
public Dictionary<int, GRBVar[]> HasOverlappingOperation { get; set; }
}
public enum HorizonOptimizationStrategy
{
Whole = 0,
Decreasing = 1
}
public class SpecializedSolverConfig
{
[DefaultValue(5)]
public int OptimizationWindow { get; set; }
[DefaultValue(HorizonOptimizationStrategy.Decreasing)]
public HorizonOptimizationStrategy HorizonOptimizationStrategy { get; set; }
[DefaultValue(false)]
public bool LazyEnergyConstraints { get; set; }
[DefaultValue(true)]
public bool OnBoundaryMaxThreeConstraint { get; set; }
[DefaultValue(false)]
public bool BigMObjectiveConstraints { get; set; }
}
}
} | 45.165498 | 185 | 0.526938 | [
"MIT"
] | CTU-IIG/EnergyLimitsScheduling | Iirc.EnergyLimitsScheduling.Shared/Solvers/MilpInSpanPart.cs | 32,205 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Threading.Tasks;
using Windows.Storage;
using Xamarin.Forms.Internals;
#if WINDOWS_UWP
namespace Xamarin.Forms.Platform.UWP
#else
namespace Xamarin.Forms.Platform.WinRT
#endif
{
internal sealed class WindowsSerializer : IDeserializer
{
const string PropertyStoreFile = "PropertyStore.forms";
public async Task<IDictionary<string, object>> DeserializePropertiesAsync()
{
try
{
StorageFile file = await ApplicationData.Current.RoamingFolder.GetFileAsync(PropertyStoreFile).DontSync();
using (Stream stream = (await file.OpenReadAsync().DontSync()).AsStreamForRead())
{
if (stream.Length == 0)
return new Dictionary<string, object>(4);
try
{
var serializer = new DataContractSerializer(typeof(IDictionary<string, object>));
return (IDictionary<string, object>)serializer.ReadObject(stream);
}
catch (Exception e)
{
Debug.WriteLine("Could not deserialize properties: " + e.Message);
Log.Warning("Xamarin.Forms PropertyStore", $"Exception while reading Application properties: {e}");
}
return null;
}
}
catch (FileNotFoundException)
{
return new Dictionary<string, object>(4);
}
}
public async Task SerializePropertiesAsync(IDictionary<string, object> properties)
{
StorageFile file = await ApplicationData.Current.RoamingFolder.CreateFileAsync(PropertyStoreFile, CreationCollisionOption.ReplaceExisting).DontSync();
using (StorageStreamTransaction transaction = await file.OpenTransactedWriteAsync().DontSync())
{
try
{
Stream stream = transaction.Stream.AsStream();
var serializer = new DataContractSerializer(typeof(IDictionary<string, object>));
serializer.WriteObject(stream, properties);
await transaction.CommitAsync().DontSync();
}
catch (Exception e)
{
Debug.WriteLine("Could not move new serialized property file over old: " + e.Message);
}
}
}
}
} | 29.394366 | 153 | 0.723527 | [
"MIT"
] | Acidburn0zzz/Xamarin.Forms | Xamarin.Forms.Platform.WinRT/WindowsSerializer.cs | 2,089 | C# |
namespace MiniGalaxyBirds
{
class PlayerBullet : IComponent
{
}
}
| 10 | 32 | 0.728571 | [
"Apache-2.0"
] | amadron/FinalProject_ShaderProg | examples/experimental/MiniGalaxyBirds/PlayerBullet.cs | 72 | C# |
using System;
using System.Collections.Generic;
using Orchard.Layouts.Framework.Drivers;
using Orchard.Layouts.Framework.Elements;
namespace Orchard.Layouts.Services {
public interface IElementManager : IDependency {
IEnumerable<ElementDescriptor> DescribeElements(DescribeElementsContext context);
IEnumerable<CategoryDescriptor> GetCategories(DescribeElementsContext context);
ElementDescriptor GetElementDescriptorByTypeName(DescribeElementsContext context, string typeName);
ElementDescriptor GetElementDescriptorByType<T>(DescribeElementsContext context) where T : Element;
ElementDescriptor GetElementDescriptorByType<T>() where T : Element;
Element ActivateElement(ElementDescriptor descriptor, Action<Element> initialize = null);
T ActivateElement<T>(ElementDescriptor descriptor, Action<T> initialize = null) where T : Element;
T ActivateElement<T>(Action<T> initialize = null) where T : Element;
IEnumerable<IElementDriver> GetDrivers<TElement>() where TElement : Element;
IEnumerable<IElementDriver> GetDrivers(ElementDescriptor descriptor);
IEnumerable<IElementDriver> GetDrivers(Element element);
IEnumerable<IElementDriver> GetDrivers(Type elementType);
IEnumerable<IElementDriver> GetDrivers();
EditorResult BuildEditor(ElementEditorContext context);
EditorResult UpdateEditor(ElementEditorContext context);
void Saving(LayoutSavingContext context);
void Removing(LayoutSavingContext context);
void Exporting(IEnumerable<Element> elements, ExportLayoutContext context);
void Exported(IEnumerable<Element> elements, ExportLayoutContext context);
void Importing(IEnumerable<Element> elements, ImportLayoutContext context);
void Imported(IEnumerable<Element> elements, ImportLayoutContext context);
void ImportCompleted(IEnumerable<Element> elements, ImportLayoutContext context);
}
} | 64.903226 | 108 | 0.761431 | [
"BSD-3-Clause"
] | Lombiq/Associativy | src/Orchard.Web/Modules/Orchard.Layouts/Services/IElementManager.cs | 2,014 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Akka.TestKit.Xunit;
using Akka.Util.Internal;
using AkkaSim.Logging;
using Master40.DB.Data.Context;
using Master40.DB.Data.Initializer;
using Master40.DB.GanttPlanModel;
using Master40.DB.Nominal;
using Master40.DB.Nominal.Model;
using Master40.Simulation.CLI;
using Master40.SimulationCore;
using Master40.SimulationCore.Environment.Options;
using Master40.SimulationCore.Helper;
using Master40.Tools.Connectoren.Ganttplan;
using Microsoft.EntityFrameworkCore;
using Xunit;
using NLog;
namespace Master40.XUnitTest.SimulationEnvironment
{
public class CentralSystem : TestKit
{
// local Context
private const string masterCtxString = "Server=(localdb)\\mssqllocaldb;Database=Master40;Trusted_Connection=True;MultipleActiveResultSets=true";
private const string masterResultCtxString = "Server=(localdb)\\mssqllocaldb;Database=Master40Results;Trusted_Connection=True;MultipleActiveResultSets=true";
// local TEST Context
private const string testCtxString = "Server=(localdb)\\mssqllocaldb;Database=TestContext;Trusted_Connection=True;MultipleActiveResultSets=true";
private const string testResultCtxString = "Server=(localdb)\\mssqllocaldb;Database=TestResultContext;Trusted_Connection=True;MultipleActiveResultSets=true";
// remote Context
private const string remoteMasterCtxString = "Server=141.56.137.25,1433;Persist Security Info=False;User ID=SA;Password=123*Start#;Initial Catalog=Master40;MultipleActiveResultSets=true";
private const string remoteResultCtxString = "Server=141.56.137.25,1433;Persist Security Info=False;User ID=SA;Password=123*Start#;Initial Catalog=Master40Result;MultipleActiveResultSets=true";
private const string hangfireCtxString = "Server=141.56.137.25;Database=Hangfire;Persist Security Info=False;User ID=SA;Password=123*Start#;MultipleActiveResultSets=true";
// only for local usage
private const string GanttPlanCtxString = "SERVER=(localdb)\\MSSQLLocalDB;DATABASE=DBGP;Trusted_connection=Yes;UID=;PWD=;MultipleActiveResultSets=true";
private ProductionDomainContext _masterDBContext = ProductionDomainContext.GetContext(remoteMasterCtxString);
private ResultContext _ctxResult = ResultContext.GetContext(resultCon: testResultCtxString);
[Fact]
public void TestDateUpdate()
{
GanttPlanOptRunner.RunOptAndExport("Init");
var ganttPlanContext = GanttPlanDBContext.GetContext(GanttPlanCtxString);
var modelparameter = ganttPlanContext.GptblModelparameter.FirstOrDefault();
if (modelparameter != null)
{
modelparameter.ActualTime = new DateTime(year: 2020, day: 2, month: 1);
ganttPlanContext.Entry(modelparameter).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
ganttPlanContext.SaveChanges();
}
GanttPlanOptRunner.RunOptAndExport("Continuous");
var modelparameter1 = ganttPlanContext.GptblModelparameter.FirstOrDefault();
if (modelparameter != null)
{
modelparameter1.ActualTime = new DateTime(year: 2020, day: 3, month: 1);
ganttPlanContext.Entry(modelparameter1).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
ganttPlanContext.SaveChanges();
}
GanttPlanOptRunner.RunOptAndExport("Continuous");
var modelparameter2 = ganttPlanContext.GptblModelparameter.FirstOrDefault();
if (modelparameter != null)
{
modelparameter2.ActualTime = new DateTime(year: 2020, day: 3, month: 1);
ganttPlanContext.Entry(modelparameter2).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
ganttPlanContext.SaveChanges();
}
}
[Fact]
public void ResetGanttPlanDB()
{
//Reset GanttPLan DB?
var ganttPlanContext = GanttPlanDBContext.GetContext(GanttPlanCtxString);
ganttPlanContext.Database.ExecuteSqlRaw("EXEC sp_MSforeachtable 'DELETE FROM ? '");
}
[Fact]
//[InlineData(SimulationType.DefaultSetup, 1, Int32.MaxValue, 1920, 169, ModelSize.Small, ModelSize.Small)]
public async Task CentralSystemTest()
{
//LogConfiguration.LogTo(TargetTypes.Debugger, TargetNames.LOG_AGENTS, LogLevel.Trace, LogLevel.Trace);
LogConfiguration.LogTo(TargetTypes.Debugger, TargetNames.LOG_AGENTS, LogLevel.Info, LogLevel.Info);
//LogConfiguration.LogTo(TargetTypes.Debugger, TargetNames.LOG_AGENTS, LogLevel.Debug, LogLevel.Debug);
LogConfiguration.LogTo(TargetTypes.Debugger, TargetNames.LOG_AGENTS, LogLevel.Warn, LogLevel.Warn);
var simtulationType = SimulationType.Central;
var seed = 169;
var throughput = 1920;
var arrivalRate = 0.015;
//Create Master40Data
var masterPlanContext = ProductionDomainContext.GetContext(masterCtxString);
masterPlanContext.Database.EnsureDeleted();
masterPlanContext.Database.EnsureCreated();
MasterDBInitializerTruck.DbInitialize(masterPlanContext, ModelSize.Medium, ModelSize.Medium, ModelSize.Small, 3,false);
//CreateMaster40Result
var masterPlanResultContext = ResultContext.GetContext(masterResultCtxString);
masterPlanResultContext.Database.EnsureDeleted();
masterPlanResultContext.Database.EnsureCreated();
ResultDBInitializerBasic.DbInitialize(masterPlanResultContext);
//Reset GanttPLan DB?
var ganttPlanContext = GanttPlanDBContext.GetContext(GanttPlanCtxString);
ganttPlanContext.Database.ExecuteSqlRaw("EXEC sp_MSforeachtable 'DELETE FROM ? '");
//Synchronisation GanttPlan
GanttPlanOptRunner.RunOptAndExport("Init");
var simContext = new GanttSimulation(GanttPlanCtxString, masterCtxString, messageHub: new ConsoleHub());
var simConfig = ArgumentConverter.ConfigurationConverter(masterPlanResultContext, 1);
// update customized Items
simConfig.AddOption(new DBConnectionString(masterResultCtxString));
simConfig.ReplaceOption(new KpiTimeSpan(240));
simConfig.ReplaceOption(new TimeConstraintQueueLength(480));
simConfig.ReplaceOption(new SimulationKind(value: simtulationType));
simConfig.ReplaceOption(new OrderArrivalRate(value: arrivalRate));
simConfig.ReplaceOption(new OrderQuantity(value: 141));
simConfig.ReplaceOption(new EstimatedThroughPut(value: throughput));
simConfig.ReplaceOption(new TimePeriodForThroughputCalculation(value: 4000));
simConfig.ReplaceOption(new Seed(value: seed));
simConfig.ReplaceOption(new SettlingStart(value: 2880));
simConfig.ReplaceOption(new SimulationEnd(value: 10080));
simConfig.ReplaceOption(new SaveToDB(value: true));
simConfig.ReplaceOption(new DebugSystem(value: false));
simConfig.ReplaceOption(new WorkTimeDeviation(0.2));
var simulation = await simContext.InitializeSimulation(configuration: simConfig);
//emtpyResultDBbySimulationNumber(simNr: simConfig.GetOption<SimulationNumber>());
var simWasReady = false;
if (simulation.IsReady())
{
// set for Assert
simWasReady = true;
// Start simulation
var sim = simulation.RunAsync();
simContext.StateManager.ContinueExecution(simulation);
await sim;
}
Assert.True(condition: simWasReady);
}
[Fact(Skip = "Offline")]
public void AggreteResults()
{
var _resultContext = ResultContext.GetContext(remoteResultCtxString);
var aggregator = new ResultAggregator(_resultContext);
aggregator.BuildResults(1);
}
[Fact]
public void TestGanttPlanApi()
{
ProductionDomainContext master40Context = ProductionDomainContext.GetContext(masterCtxString);
GanttPlanDBContext ganttPlanContext = GanttPlanDBContext.GetContext(GanttPlanCtxString);
var prod = ganttPlanContext.GptblProductionorder
.Include(x => x.ProductionorderOperationActivities)
.ThenInclude(x => x.ProductionorderOperationActivityMaterialrelation)
.Include(x => x.ProductionorderOperationActivities)
.ThenInclude(x => x.ProductionorderOperationActivityResources)
.Include(x => x.ProductionorderOperationActivities)
.ThenInclude(x => x.ProductionorderOperationActivityResources)
.ThenInclude(x => x.ProductionorderOperationActivityResourceInterval)
.Single(x => x.ProductionorderId == "000030");
// System.Diagnostics.Debug.WriteLine("First ID: " + prod.ProductionorderId);
// var activity = prod.ProductionorderOperationActivities.ToArray()[1];
// System.Diagnostics.Debug.WriteLine("First Activity ID: " + activity.ActivityId);
// var materialRelation = activity.ProductionorderOperationActivityMaterialrelation.ToArray()[0];
// System.Diagnostics.Debug.WriteLine("First Activity Material Relation ID: " + materialRelation.ChildId);
// var ress = activity.ProductionorderOperationActivityResources.ToArray()[0];
// System.Diagnostics.Debug.WriteLine("First Resource: " + ress.Worker.Name);
// System.Diagnostics.Debug.WriteLine("First Resource Intervall: " + ress.ProductionorderOperationActivityResourceInterval.DateFrom);
var activities = ganttPlanContext.GptblProductionorderOperationActivity
.Include(x => x.ProductionorderOperationActivityResources)
.Where(x => x.ProductionorderId == "000029").ToList();
activities.ForEach(act =>
{
System.Diagnostics.Debug.WriteLine("Activity:" + act.Name);
act.ProductionorderOperationActivityResources.ForEach(res =>
{
System.Diagnostics.Debug.WriteLine("Activity Resource:" + res.ResourceId);
switch (res.ResourceType)
{
case 1:
res.Resource =
ganttPlanContext.GptblWorkcenter.Single(x => x.WorkcenterId == res.ResourceId);
break;
case 3:
res.Resource =
ganttPlanContext.GptblWorker.Single(x => x.WorkerId == res.ResourceId);
break;
case 5:
res.Resource =
ganttPlanContext.GptblPrt.Single(x => x.PrtId == res.ResourceId);
break;
}
System.Diagnostics.Debug.WriteLine("Activity Resource Name:" + res.Resource.Name);
});
}
);
Assert.True(ganttPlanContext.GptblMaterial.Any());
}
[Fact]
public void GanttPlanInsertConfirmationAndReplan()
{
ProductionDomainContext master40Context = ProductionDomainContext.GetContext(masterCtxString);
master40Context.CustomerOrders.RemoveRange(master40Context.CustomerOrders);
master40Context.CustomerOrderParts.RemoveRange(master40Context.CustomerOrderParts);
master40Context.SaveChanges();
master40Context.CreateNewOrder(10115, 1, 0, 250);
master40Context.SaveChanges();
GanttPlanDBContext ganttPlanContext = GanttPlanDBContext.GetContext(GanttPlanCtxString);
ganttPlanContext.Database.ExecuteSqlRaw("EXEC sp_MSforeachtable 'DELETE FROM ? '");
GanttPlanOptRunner.RunOptAndExport("Init");
Assert.True(ganttPlanContext.GptblProductionorder.Any());
ganttPlanContext.GptblConfirmation.RemoveRange(ganttPlanContext.GptblConfirmation);
var productionorder = ganttPlanContext.GptblProductionorder.Single(x => x.ProductionorderId.Equals("000004"));
ganttPlanContext.GptblConfirmation.RemoveRange(ganttPlanContext.GptblConfirmation);
var activities = ganttPlanContext.GptblProductionorderOperationActivity.Where(x =>
x.ProductionorderId.Equals(productionorder.ProductionorderId));
var activity = activities.Single(x => x.OperationId.Equals("10") && x.ActivityId.Equals(2));
var confirmation = CreateConfirmation(activity, productionorder, 1);
ganttPlanContext.GptblConfirmation.Add(confirmation);
ganttPlanContext.SaveChanges();
GanttPlanOptRunner.RunOptAndExport("Continuous");
Assert.True(ganttPlanContext.GptblConfirmation.Any());
confirmation = ganttPlanContext.GptblConfirmation.SingleOrDefault(x =>
x.ConfirmationId.Equals(confirmation.ConfirmationId));
//ganttPlanContext.GptblConfirmation.Remove(confirmation);
var finishConfirmation = CreateConfirmation(activity, productionorder, 16);
ganttPlanContext.SaveChanges();
ganttPlanContext.GptblConfirmation.Add(finishConfirmation);
activity = activities.Single(x => x.OperationId.Equals("10") && x.ActivityId.Equals(3));
confirmation = CreateConfirmation(activity, productionorder, 16);
ganttPlanContext.GptblConfirmation.Add(confirmation);
activity = activities.Single(x => x.OperationId.Equals("20") && x.ActivityId.Equals(2));
confirmation = CreateConfirmation(activity, productionorder, 16);
ganttPlanContext.GptblConfirmation.Add(confirmation);
ganttPlanContext.SaveChanges();
GanttPlanOptRunner.RunOptAndExport("Continuous");
Assert.True(ganttPlanContext.GptblProductionorder.Count().Equals(10));
}
private GptblConfirmation CreateConfirmation(GptblProductionorderOperationActivity activity,
GptblProductionorder productionorder, int confirmationType)
{
var newConf = new GptblConfirmation();
newConf.ProductionorderId = activity.ProductionorderId;
newConf.ActivityEnd = activity.DateEnd;
newConf.ActivityStart = activity.DateStart;
newConf.ClientId = string.Empty;
newConf.ConfirmationDate = activity.DateEnd;
newConf.ConfirmationId = Guid.NewGuid().ToString();
newConf.ProductionorderActivityId = activity.ActivityId;
newConf.ProductionorderOperationId = activity.OperationId;
newConf.QuantityFinished = confirmationType == 16 ? productionorder.QuantityNet : 0;
newConf.QuantityFinishedUnitId = productionorder.QuantityUnitId;
newConf.ProductionorderSplitId = 0;
newConf.ConfirmationType = confirmationType; // 16 = beendet
return newConf;
}
[Fact]
public void TestMaterialRelations()
{
using (var localGanttPlanDbContext = GanttPlanDBContext.GetContext(GanttPlanCtxString))
{
var materialId = "10115";
var activities = new Queue<GptblProductionorderOperationActivityResourceInterval>(
localGanttPlanDbContext.GptblProductionorderOperationActivityResourceInterval
.Include(x => x.ProductionorderOperationActivityResource)
.ThenInclude(x => x.ProductionorderOperationActivity)
.ThenInclude(x => x.ProductionorderOperationActivityMaterialrelation)
.Include(x => x.ProductionorderOperationActivityResource)
.ThenInclude(x => x.ProductionorderOperationActivity)
.ThenInclude(x => x.Productionorder)
.Include(x => x.ProductionorderOperationActivityResource)
.ThenInclude(x => x.ProductionorderOperationActivity)
.ThenInclude(x => x.ProductionorderOperationActivityResources)
.Where(x => x.ProductionorderOperationActivityResource.ProductionorderOperationActivity
.Productionorder.MaterialId.Equals(materialId)
&& x.IntervalAllocationType.Equals(1))
.OrderBy(x => x.DateFrom)
.ToList());
} // filter Done and in Progress?
}
}
}
| 49.386167 | 201 | 0.659625 | [
"Apache-2.0"
] | MaxWeickert/ng-erp-4.0 | Master40.XUnitTest/SimulationEnvironment/CentralSystem.cs | 17,139 | C# |
#region MigraDoc - Creating Documents on the Fly
//
// Authors:
// Stefan Lange
// Klaus Potzesny
// David Stephensen
//
// Copyright (c) 2001-2017 empira Software GmbH, Cologne Area (Germany)
//
// http://www.pdfsharp.com
// http://www.migradoc.com
// http://sourceforge.net/projects/pdfsharp
//
// 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 MigraDoc.DocumentObjectModel.Internals;
namespace MigraDoc.DocumentObjectModel
{
/// <summary>
/// A ParagraphFormat represents the formatting of a paragraph.
/// </summary>
public class ParagraphFormat : DocumentObject
{
/// <summary>
/// Initializes a new instance of the ParagraphFormat class that can be used as a template.
/// </summary>
public ParagraphFormat()
{ }
/// <summary>
/// Initializes a new instance of the ParagraphFormat class with the specified parent.
/// </summary>
internal ParagraphFormat(DocumentObject parent) : base(parent) { }
#region Methods
/// <summary>
/// Creates a deep copy of this object.
/// </summary>
public new ParagraphFormat Clone()
{
return (ParagraphFormat)DeepCopy();
}
/// <summary>
/// Implements the deep copy of the object.
/// </summary>
protected override object DeepCopy()
{
ParagraphFormat format = (ParagraphFormat)base.DeepCopy();
if (format._font != null)
{
format._font = format._font.Clone();
format._font._parent = format;
}
if (format._shading != null)
{
format._shading = format._shading.Clone();
format._shading._parent = format;
}
if (format._borders != null)
{
format._borders = format._borders.Clone();
format._borders._parent = format;
}
if (format._tabStops != null)
{
format._tabStops = format._tabStops.Clone();
format._tabStops._parent = format;
}
if (format._listInfo != null)
{
format._listInfo = format._listInfo.Clone();
format._listInfo._parent = format;
}
return format;
}
/// <summary>
/// Adds a TabStop object to the collection.
/// </summary>
public TabStop AddTabStop(Unit position)
{
return TabStops.AddTabStop(position);
}
/// <summary>
/// Adds a TabStop object to the collection and sets its alignment and leader.
/// </summary>
public TabStop AddTabStop(Unit position, TabAlignment alignment, TabLeader leader)
{
return TabStops.AddTabStop(position, alignment, leader);
}
/// <summary>
/// Adds a TabStop object to the collection and sets its leader.
/// </summary>
public TabStop AddTabStop(Unit position, TabLeader leader)
{
return TabStops.AddTabStop(position, leader);
}
/// <summary>
/// Adds a TabStop object to the collection and sets its alignment.
/// </summary>
public TabStop AddTabStop(Unit position, TabAlignment alignment)
{
return TabStops.AddTabStop(position, alignment);
}
/// <summary>
/// Adds a TabStop object to the collection marked to remove the tab stop at
/// the given position.
/// </summary>
public void RemoveTabStop(Unit position)
{
TabStops.RemoveTabStop(position);
}
/// <summary>
/// Adds a TabStop object to the collection.
/// </summary>
public void Add(TabStop tabStop)
{
TabStops.AddTabStop(tabStop);
}
/// <summary>
/// Clears all TapStop objects from the collection. Additionally 'TabStops = null'
/// is written to the DDL stream when serialized.
/// </summary>
public void ClearAll()
{
TabStops.ClearAll();
}
#endregion
#region Properties
/// <summary>
/// Gets or sets the Alignment of the paragraph.
/// </summary>
public ParagraphAlignment Alignment
{
get { return (ParagraphAlignment)_alignment.Value; }
set { _alignment.Value = (int)value; }
}
[DV(Type = typeof(ParagraphAlignment))]
internal NEnum _alignment = NEnum.NullValue(typeof(ParagraphAlignment));
/// <summary>
/// Gets the Borders object.
/// </summary>
public Borders Borders
{
get { return _borders ?? (_borders = new Borders(this)); }
set
{
SetParent(value);
_borders = value;
}
}
public bool BordersIsNull { get => _borders == null || _borders.IsNull(); }
[DV]
internal Borders _borders;
/// <summary>
/// Gets or sets the indent of the first line in the paragraph.
/// </summary>
public Unit FirstLineIndent
{
get { return _firstLineIndent; }
set { _firstLineIndent = value; }
}
public bool FirstLineIndentIsNull { get => _firstLineIndent.IsNull; }
[DV]
internal Unit _firstLineIndent = Unit.NullValue;
/// <summary>
/// Gets or sets the Font object.
/// </summary>
public Font Font
{
get { return _font ?? (_font = new Font(this)); }
set
{
SetParent(value);
_font = value;
}
}
[DV]
internal Font _font;
/// <summary>
/// Gets or sets a value indicating whether to keep all the paragraph's lines on the same page.
/// </summary>
public bool KeepTogether
{
get { return _keepTogether.Value; }
set { _keepTogether.Value = value; }
}
[DV]
internal NBool _keepTogether = NBool.NullValue;
/// <summary>
/// Gets or sets a value indicating whether this and the next paragraph stay on the same page.
/// </summary>
public bool KeepWithNext
{
get { return _keepWithNext.Value; }
set { _keepWithNext.Value = value; }
}
[DV]
internal NBool _keepWithNext = NBool.NullValue;
/// <summary>
/// Gets or sets the left indent of the paragraph.
/// </summary>
public Unit LeftIndent
{
get { return _leftIndent; }
set { _leftIndent = value; }
}
[DV]
internal Unit _leftIndent = Unit.NullValue;
/// <summary>
/// Gets or sets the space between lines on the paragraph.
/// </summary>
public Unit LineSpacing
{
get { return _lineSpacing; }
set { _lineSpacing = value; }
}
[DV]
internal Unit _lineSpacing = Unit.NullValue;
/// <summary>
/// Gets or sets the rule which is used to define the line spacing.
/// </summary>
public LineSpacingRule LineSpacingRule
{
get { return (LineSpacingRule)_lineSpacingRule.Value; }
set { _lineSpacingRule.Value = (int)value; }
}
[DV(Type = typeof(LineSpacingRule))]
internal NEnum _lineSpacingRule = NEnum.NullValue(typeof(LineSpacingRule));
/// <summary>
/// Gets or sets the ListInfo object of the paragraph.
/// </summary>
public ListInfo ListInfo
{
get { return _listInfo ?? (_listInfo = new ListInfo(this)); }
set
{
SetParent(value);
_listInfo = value;
}
}
public bool ListInfoIsNull { get => _listInfo == null || _listInfo.IsNull(); }
[DV]
internal ListInfo _listInfo;
/// <summary>
/// Gets or sets the out line level of the paragraph.
/// </summary>
public OutlineLevel OutlineLevel
{
get { return (OutlineLevel)_outlineLevel.Value; }
set { _outlineLevel.Value = (int)value; }
}
[DV(Type = typeof(OutlineLevel))]
internal NEnum _outlineLevel = NEnum.NullValue(typeof(OutlineLevel));
/// <summary>
/// Gets or sets a value indicating whether a page break is inserted before the paragraph.
/// </summary>
public bool PageBreakBefore
{
get { return _pageBreakBefore.Value; }
set { _pageBreakBefore.Value = value; }
}
[DV]
internal NBool _pageBreakBefore = NBool.NullValue;
/// <summary>
/// Gets or sets the right indent of the paragraph.
/// </summary>
public Unit RightIndent
{
get { return _rightIndent; }
set { _rightIndent = value; }
}
[DV]
internal Unit _rightIndent = Unit.NullValue;
/// <summary>
/// Gets the shading object.
/// </summary>
public Shading Shading
{
get { return _shading ?? (_shading = new Shading(this)); }
set
{
SetParent(value);
_shading = value;
}
}
public bool ShadingIsNull { get => _shading == null || _shading.IsNull(); }
[DV]
internal Shading _shading;
/// <summary>
/// Gets or sets the space that's inserted after the paragraph.
/// </summary>
public Unit SpaceAfter
{
get { return _spaceAfter; }
set { _spaceAfter = value; }
}
[DV]
internal Unit _spaceAfter = Unit.NullValue;
/// <summary>
/// Gets or sets the space that's inserted before the paragraph.
/// </summary>
public Unit SpaceBefore
{
get { return _spaceBefore; }
set { _spaceBefore = value; }
}
[DV]
internal Unit _spaceBefore = Unit.NullValue;
/// <summary>
/// Indicates whether the ParagraphFormat has a TabStops collection.
/// </summary>
public bool HasTabStops
{
get { return _tabStops != null; }
}
/// <summary>
/// Get the TabStops collection.
/// </summary>
public TabStops TabStops
{
get { return _tabStops ?? (_tabStops = new TabStops(this)); }
set
{
SetParent(value);
_tabStops = value;
}
}
[DV]
internal TabStops _tabStops;
/// <summary>
/// Gets or sets a value indicating whether a line from the paragraph stays alone in a page.
/// </summary>
public bool WidowControl
{
get { return _widowControl.Value; }
set { _widowControl.Value = value; }
}
[DV]
internal NBool _widowControl = NBool.NullValue;
#endregion
#region Internal
/// <summary>
/// Converts ParagraphFormat into DDL.
/// </summary>
internal override void Serialize(Serializer serializer)
{
if (_parent is Style)
Serialize(serializer, "ParagraphFormat", null);
else
Serialize(serializer, "Format", null);
}
/// <summary>
/// Converts ParagraphFormat into DDL.
/// </summary>
internal void Serialize(Serializer serializer, string name, ParagraphFormat refFormat)
{
int pos = serializer.BeginContent(name);
if (!IsNull("Font") && Parent.GetType() != typeof(Style))
Font.Serialize(serializer);
// If a refFormat is specified, it is important to compare the fields and not the properties.
// Only the fields holds the internal information whether a value is NULL. In contrast to the
// Efw.Application framework the nullable values and all the meta stuff is kept internal to
// give the user the illusion of simplicity.
if (!_alignment.IsNull && (refFormat == null || (_alignment != refFormat._alignment)))
serializer.WriteSimpleAttribute("Alignment", Alignment);
if (!_leftIndent.IsNull && (refFormat == null || (_leftIndent != refFormat._leftIndent)))
serializer.WriteSimpleAttribute("LeftIndent", LeftIndent);
if (!_firstLineIndent.IsNull && (refFormat == null || _firstLineIndent != refFormat._firstLineIndent))
serializer.WriteSimpleAttribute("FirstLineIndent", FirstLineIndent);
if (!_rightIndent.IsNull && (refFormat == null || _rightIndent != refFormat._rightIndent))
serializer.WriteSimpleAttribute("RightIndent", RightIndent);
if (!_spaceBefore.IsNull && (refFormat == null || _spaceBefore != refFormat._spaceBefore))
serializer.WriteSimpleAttribute("SpaceBefore", SpaceBefore);
if (!_spaceAfter.IsNull && (refFormat == null || _spaceAfter != refFormat._spaceAfter))
serializer.WriteSimpleAttribute("SpaceAfter", SpaceAfter);
if (!_lineSpacingRule.IsNull && (refFormat == null || _lineSpacingRule != refFormat._lineSpacingRule))
serializer.WriteSimpleAttribute("LineSpacingRule", LineSpacingRule);
if (!_lineSpacing.IsNull && (refFormat == null || _lineSpacing != refFormat._lineSpacing))
serializer.WriteSimpleAttribute("LineSpacing", LineSpacing);
if (!_keepTogether.IsNull && (refFormat == null || _keepTogether != refFormat._keepTogether))
serializer.WriteSimpleAttribute("KeepTogether", KeepTogether);
if (!_keepWithNext.IsNull && (refFormat == null || _keepWithNext != refFormat._keepWithNext))
serializer.WriteSimpleAttribute("KeepWithNext", KeepWithNext);
if (!_widowControl.IsNull && (refFormat == null || _widowControl != refFormat._widowControl))
serializer.WriteSimpleAttribute("WidowControl", WidowControl);
if (!_pageBreakBefore.IsNull && (refFormat == null || _pageBreakBefore != refFormat._pageBreakBefore))
serializer.WriteSimpleAttribute("PageBreakBefore", PageBreakBefore);
if (!_outlineLevel.IsNull && (refFormat == null || _outlineLevel != refFormat._outlineLevel))
serializer.WriteSimpleAttribute("OutlineLevel", OutlineLevel);
if (!IsNull("ListInfo"))
ListInfo.Serialize(serializer);
if (!IsNull("TabStops"))
_tabStops.Serialize(serializer);
if (!IsNull("Borders"))
{
if (refFormat != null)
_borders.Serialize(serializer, refFormat.Borders);
else
_borders.Serialize(serializer, null);
}
if (!IsNull("Shading"))
_shading.Serialize(serializer);
serializer.EndContent(pos);
}
/// <summary>
/// Returns the meta object of this instance.
/// </summary>
internal override Meta Meta
{
get { return _meta ?? (_meta = new Meta(typeof(ParagraphFormat))); }
}
static Meta _meta;
#endregion
}
}
| 34.576446 | 114 | 0.564326 | [
"MIT"
] | PdfSharpCore/PdfSharpCore | src/MigraDoc.DocumentObjectModel/DocumentObjectModel/ParagraphFormat.cs | 16,735 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
#pragma warning disable CS8618
[JsiiByValue(fqn: "aws.LambdaAliasConfig")]
public class LambdaAliasConfig : aws.ILambdaAliasConfig
{
[JsiiProperty(name: "functionName", typeJson: "{\"primitive\":\"string\"}", isOverride: true)]
public string FunctionName
{
get;
set;
}
[JsiiProperty(name: "functionVersion", typeJson: "{\"primitive\":\"string\"}", isOverride: true)]
public string FunctionVersion
{
get;
set;
}
[JsiiProperty(name: "name", typeJson: "{\"primitive\":\"string\"}", isOverride: true)]
public string Name
{
get;
set;
}
[JsiiOptional]
[JsiiProperty(name: "description", typeJson: "{\"primitive\":\"string\"}", isOptional: true, isOverride: true)]
public string? Description
{
get;
set;
}
/// <summary>routing_config block.</summary>
[JsiiOptional]
[JsiiProperty(name: "routingConfig", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"aws.LambdaAliasRoutingConfig\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public aws.ILambdaAliasRoutingConfig[]? RoutingConfig
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "count", typeJson: "{\"primitive\":\"number\"}", isOptional: true, isOverride: true)]
public double? Count
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "dependsOn", typeJson: "{\"collection\":{\"elementtype\":{\"fqn\":\"cdktf.ITerraformDependable\"},\"kind\":\"array\"}}", isOptional: true, isOverride: true)]
public HashiCorp.Cdktf.ITerraformDependable[]? DependsOn
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "lifecycle", typeJson: "{\"fqn\":\"cdktf.TerraformResourceLifecycle\"}", isOptional: true, isOverride: true)]
public HashiCorp.Cdktf.ITerraformResourceLifecycle? Lifecycle
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "provider", typeJson: "{\"fqn\":\"cdktf.TerraformProvider\"}", isOptional: true, isOverride: true)]
public HashiCorp.Cdktf.TerraformProvider? Provider
{
get;
set;
}
}
}
| 30.884211 | 191 | 0.546012 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/LambdaAliasConfig.cs | 2,934 | C# |
using System;
namespace VisualStudioLauncher
{
class Program
{
[STAThread]
static void Main(string[] args)
{
try
{
var launcher = new Launcher();
try
{
launcher.ParseArguments(args);
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
ExitWithCode(403);
}
launcher.ExecuteParameterCommand();
}
catch (Exception e)
{
Console.Error.WriteLine(e.Message);
Console.Error.WriteLine(e.StackTrace);
ExitWithCode(500);
}
}
static void ExitWithCode(int errorCode)
{
Environment.Exit(errorCode);
}
}
} | 22.162791 | 58 | 0.43022 | [
"MIT"
] | Wortex17/VisualStudioLauncher | Program.cs | 955 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace _1186
{
class Program
{
static void Main(string[] args)
{
int[][] xs = new int[11175][];
int[] x = new int[11175];
int cnt = 0;
for (int i = 1; i <= 150; i++)
{
for (int j = 1; j < i; j++)
{
int[] tmp = { j, i };
xs[cnt] = tmp;
x[cnt] = (i * i + j * j) * 1000 + j;
cnt += 1;
}
}
Array.Sort(x, xs);
for (; ; )
{
string[] str = Console.ReadLine().Split(' ');
int a = int.Parse(str[0]);
int b = int.Parse(str[1]);
if (a == 0 && b == 0)
{
return;
}
int[] p = { a, b };
for (int i = 0; i < xs.Length - 1; i++)
{
if (p[0] == xs[i][0] && p[1] == xs[i][1])
{
Console.WriteLine("{0} {1}", xs[i + 1][0], xs[i + 1][1]);
break;
}
}
}
}
}
}
| 27.041667 | 81 | 0.288906 | [
"MIT"
] | yu3mars/procon | aoj/1100s/1186/1186/Program.cs | 1,300 | C# |
//#define SWITCH_BLOCK_MANAGER
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using CommonsHelper;
using CommonsPattern;
public class SwitchBlockManager : SingletonManager<SwitchBlockManager> {
/* Events */
public delegate void SwitchActiveColorHandler(GameColor newActiveColor);
public static event SwitchActiveColorHandler switchActiveColorEvent;
/* Sibling components */
private AudioSource audioSource;
/* Parameters */
[SerializeField, Tooltip("The switch blocks of this color will start as Ground, the others as Wall")]
private GameColor initActiveColor = GameColor.None;
[SerializeField, Tooltip("Minimal time interval required between two successive color change, in sec")]
private float colorChangeTimeBreak = 1f;
#if UNITY_EDITOR
[SerializeField, Tooltip("Should the object set itself up by itself? (for test with independent objects placed directly in the scene)")]
private bool debug_SetupOnStart = false;
#endif
/* State */
/// Dictionary of registered switch blocks, per color
private readonly Dictionary<GameColor, List<SwitchBlock>> m_SwitchBlocksDict = new Dictionary<GameColor, List<SwitchBlock>>();
/// The current active color (designates grounded switch blocks)
private GameColor m_ActiveColor;
public GameColor ActiveColor => m_ActiveColor;
/// Decreasing timer variable to prevent successive active color changes in sec (when 0, color can change)
private float m_TimeRemainingWithoutColorSwitch;
/// Set on Pause to allow sound resume
private bool m_WasAudioSourcePlaying;
protected override void Init () {
audioSource = this.GetComponentOrFail<AudioSource>();
foreach (GameColor color in GameData.colors) {
m_SwitchBlocksDict[color] = new List<SwitchBlock>();
}
}
private void Start () {
#if UNITY_EDITOR
// We will progressively stop calling Setup from Start by default, for more control.
if (debug_SetupOnStart)
Setup();
#endif
}
private void Reset () {
Clear();
Setup();
}
public void Clear () {
}
public void Setup () {
// immediately switch to the initial color
// this means there will be animations for blocks moving from the default state
// and players will not be able to switch blocks before some time after this has been called
// in practice, the Start message is longer than the delay between two switches so it does not matter
#if SWITCH_BLOCK_MANAGER
Debug.Log("(SwitchBlockManager) Activating initial color");
#endif
m_ActiveColor = GameColor.None;
m_TimeRemainingWithoutColorSwitch = 0f;
m_WasAudioSourcePlaying = false;
SwitchActiveColor(initActiveColor);
}
public void RegisterSwitchBlock(SwitchBlock switchBlock) {
if (switchBlock.Color == GameColor.None) {
#if SWITCH_BLOCK_MANAGER
Debug.LogFormat(switchBlock, "Switch Block {0} has color None, cannot be registered by SwitchBlockManager.",
switchBlock);
#endif
return;
}
m_SwitchBlocksDict[switchBlock.Color].Add(switchBlock);
}
public void SwitchActiveColor (GameColor newActiveColor) {
#if SWITCH_BLOCK_MANAGER
Debug.LogFormat("Switch color action triggered for: {0}", newActiveColor);
#endif
// don't mind switching the active color if it is already the one you want
// for the initialization we start from the None color so it will never be true
if (m_ActiveColor == newActiveColor) {
#if SWITCH_BLOCK_MANAGER
Debug.Log("... but the wanted color is already active!");
#endif
return;
}
// don't switch to the new active color if the last color change is too recent
if (m_TimeRemainingWithoutColorSwitch > 0) {
#if SWITCH_BLOCK_MANAGER
Debug.Log("... but color switch is still in cooldown!");
#endif
return;
}
// else, conditions are fulfilled, activate the new color
// set the timer to prevent immediate re-change
m_TimeRemainingWithoutColorSwitch = colorChangeTimeBreak;
// update the active color
m_ActiveColor = newActiveColor;
// if there are listeners (and there should be, the switch blocks), send the switch active color event
switchActiveColorEvent?.Invoke(newActiveColor);
// play SFX
audioSource.Play();
}
void FixedUpdate () {
if (m_TimeRemainingWithoutColorSwitch > 0) {
m_TimeRemainingWithoutColorSwitch -= Time.deltaTime;
if (m_TimeRemainingWithoutColorSwitch < 0) {
m_TimeRemainingWithoutColorSwitch = 0;
}
}
}
public void Pause () {
if (audioSource.isPlaying) {
audioSource.Pause();
m_WasAudioSourcePlaying = true;
}
foreach (GameColor color in GameData.colors) {
foreach (SwitchBlock switchBlock in m_SwitchBlocksDict[color]) {
switchBlock.enabled = false;
}
}
}
public void Resume () {
if (m_WasAudioSourcePlaying) {
audioSource.Play();
m_WasAudioSourcePlaying = false;
}
foreach (GameColor color in GameData.colors) {
foreach (SwitchBlock switchBlock in m_SwitchBlocksDict[color]) {
switchBlock.enabled = true;
}
}
}
}
| 28.321839 | 137 | 0.748985 | [
"BSD-3-Clause"
] | hsandt/scavenger-dogs | Assets/Scripts/Block/SwitchBlockManager.cs | 4,928 | C# |
// Copyright Keysight Technologies 2012-2019
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, you can obtain one at http://mozilla.org/MPL/2.0/.
using System;
using System.IO;
using System.Text.RegularExpressions;
using OpenTap.Cli;
using System.Threading;
using Tap.Shared;
namespace OpenTap.Package
{
/// <summary>
/// CLI sub command `tap sdk create` that can create a *.TapPackage from a definition in a package.xml file.
/// </summary>
[Display("create", Group: "package", Description: "Create a package based on an XML description file.")]
public class PackageCreateAction : PackageAction
{
private static readonly char[] IllegalPackageNameChars = {'"', '<', '>', '|', '\0', '\u0001', '\u0002', '\u0003', '\u0004', '\u0005', '\u0006', '\a', '\b',
'\t', '\n', '\v', '\f', '\r', '\u000e', '\u000f', '\u0010', '\u0011', '\u0012', '\u0013', '\u0014', '\u0015', '\u0016', '\u0017', '\u0018',
'\u0019', '\u001a', '\u001b', '\u001c', '\u001d', '\u001e', '\u001f', ':', '*', '?', '\\'};
/// <summary>
/// The default file extension for OpenTAP packages.
/// </summary>
public static string DefaultEnding = "TapPackage";
/// <summary>
/// The default file name for the created OpenTAP package.
/// Not used anymore, a default file name is now generated from the package name and version.
/// </summary>
public static string DefaultFileName = "Package";
/// <summary>
/// Represents an unnamed command line argument which specifies the package.xml file that defines the package that should be generated.
/// </summary>
[UnnamedCommandLineArgument("PackageXmlFile", Required = true)]
public string PackageXmlFile { get; set; }
/// <summary>
/// Represents the --project-directory command line argument, which specifies the directory containing the git repository used to get values for version/branch macros.
/// </summary>
[CommandLineArgument("project-directory", Description = "The directory containing the git repository.\nUsed to get values for version/branch macros.")]
public string ProjectDir { get; set; }
/// <summary>
/// Represents the --install command line argument. When true, this action will also install the created package.
/// </summary>
[CommandLineArgument("install", Description = "Install the created package. It will not overwrite the files \nalready in the target installation (e.g., debug binaries).")]
public bool Install { get; set; } = false;
/// <summary>
/// Obsolete, use Install property instead.
/// </summary>
[CommandLineArgument("fake-install", Visible = false, Description = "Install the created package. It will not overwrite files \nalready in the target installation (e.g. debug binaries).")]
public bool FakeInstall { get; set; } = false;
/// <summary>
/// Represents the --out command line argument which specifies the path to the output file.
/// </summary>
[CommandLineArgument("out", Description = "Path to the output file.", ShortName = "o")]
public string[] OutputPaths { get; set; }
/// <summary>
/// Constructs new action with default values for arguments.
/// </summary>
public PackageCreateAction()
{
ProjectDir = Directory.GetCurrentDirectory();
}
/// <summary>
/// Executes this action.
/// </summary>
public override int Execute(CancellationToken cancellationToken)
{
if (PackageXmlFile == null)
throw new Exception("No packages definition file specified.");
return Process(OutputPaths, cancellationToken);
}
private int Process(string[] OutputPaths, CancellationToken cancellationToken)
{
try
{
PackageDef pkg = null;
if (!File.Exists(PackageXmlFile))
{
log.Error("Cannot locate XML file '{0}'", PackageXmlFile);
return (int)ExitCodes.ArgumentError;
}
if (!Directory.Exists(ProjectDir))
{
log.Error("Project directory '{0}' does not exist.", ProjectDir);
return (int)ExitCodes.ArgumentError;
}
try
{
var fullpath = Path.GetFullPath(PackageXmlFile);
pkg = PackageDefExt.FromInputXml(fullpath, ProjectDir);
// Check if package name has invalid characters or is not a valid path
var illegalCharacter = pkg.Name.IndexOfAny(IllegalPackageNameChars);
if (illegalCharacter >= 0)
{
log.Error("Package name cannot contain invalid file path characters: '{0}'.", pkg.Name[illegalCharacter]);
return (int)PackageExitCodes.InvalidPackageName;
}
// Check for invalid package metadata
const string validMetadataPattern = "^[_a-zA-Z][_a-zA-Z0-9]*";
var validMetadataRegex = new Regex(validMetadataPattern);
foreach (var metaDataKey in pkg.MetaData.Keys)
{
var match = validMetadataRegex.Match(metaDataKey);
if (match.Success == false || match.Length != metaDataKey.Length)
{
if (metaDataKey.Length > 0)
log.Error($"Found invalid character '{metaDataKey[match.Length]}' in package metadata key '{metaDataKey}' at position {match.Length + 1}.");
else
log.Error($"Metadata key cannot be empty.");
return (int)PackageExitCodes.InvalidPackageDefinition;
}
}
}
catch (AggregateException aex)
{
foreach (var inner in aex.InnerExceptions)
{
if (inner is FileNotFoundException ex)
{
log.Error("File not found: '{0}'", ex.FileName);
}
else
{
log.Error(inner.ToString());
}
}
log.Error("Caught errors while loading package definition.");
return (int)PackageExitCodes.InvalidPackageDefinition;
}
var tmpFile = PathUtils.GetTempFileName(".opentap_package_tmp.zip"); ;
// If user omitted the Version XML attribute or put Version="", lets inform.
if(string.IsNullOrEmpty(pkg.RawVersion))
log.Warning($"Package version is {pkg.Version} due to blank or missing 'Version' XML attribute in 'Package' element");
using (var str = new FileStream(tmpFile, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite, 4096, FileOptions.DeleteOnClose))
{
pkg.CreatePackage(str);
if (OutputPaths == null || OutputPaths.Length == 0)
OutputPaths = new string[1] {""};
foreach (var outputPath in OutputPaths)
{
var path = outputPath;
if (String.IsNullOrEmpty(path))
{
path = GetRealFilePathFromName(pkg.Name, pkg.Version.ToString(), DefaultEnding);
// Package names support path separators now -- avoid writing the newly created package into a nested folder and
// replace the path separators with dots instead
path = path.Replace('/', '.');
}
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(path)));
ProgramHelper.FileCopy(tmpFile, path);
log.Info("OpenTAP plugin package '{0}' containing '{1}' successfully created.", path, pkg.Name);
}
}
if (FakeInstall)
{
log.Warning("--fake-install argument is obsolete, use --install instead");
Install = FakeInstall;
}
if (Install)
{
var path = PackageDef.GetDefaultPackageMetadataPath(pkg, Directory.GetCurrentDirectory());
Directory.CreateDirectory(Path.GetDirectoryName(path));
using (FileStream fs = new FileStream(path, FileMode.OpenOrCreate))
{
pkg.SaveTo(fs);
}
log.Info($"Installed '{pkg.Name}' ({Path.GetFullPath(path)})");
}
}
catch (ArgumentException ex)
{
log.Error("Caught exception: {0}", ex.Message);
return (int)PackageExitCodes.PackageCreateError;
}
catch (InvalidDataException ex)
{
log.Error("Caught invalid data exception: {0}", ex.Message);
return (int)PackageExitCodes.InvalidPackageDefinition;
}
return (int)ExitCodes.Success;
}
/// <summary>
/// Obsolete. Do not use.
/// </summary>
[Obsolete("Will be removed in OpenTAP 10.")]
public static string GetRealFilePath(string path, string version, string extension)
{
return GetRealFilePathFromName(Path.GetFileNameWithoutExtension(path), version, extension);
}
internal static string GetRealFilePathFromName(string name, string version, string extension)
{
string toInsert;
if (String.IsNullOrEmpty(version))
{
toInsert = "."; //just separate with '.'
}
else
{
toInsert = "." + version + "."; // insert version between ext and path
}
return name + toInsert + extension;
}
}
}
| 45.948276 | 196 | 0.533959 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | Keysight/opentap | Package/PackageActions/Create.cs | 10,662 | C# |
//-----------------------------------------------------------------------
// <copyright file="ServiceProvider.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.Configuration;
using Akka.Event;
using Microsoft.Extensions.DependencyInjection;
namespace Akka.DependencyInjection
{
/// <summary>
/// Provides users with immediate access to the <see cref="IDependencyResolver"/> bound to
/// this <see cref="ActorSystem"/>, if any.
/// </summary>
public sealed class DependencyResolver : IExtension
{
public DependencyResolver(IDependencyResolver resolver)
{
Resolver = resolver;
}
/// <summary>
/// The globally scoped <see cref="IDependencyResolver"/>.
/// </summary>
/// <remarks>
/// Per https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines - please use
/// the appropriate <see cref="IServiceScope"/> for your actors and the dependencies they consume. DI is typically
/// not used for long-lived, stateful objects such as actors.
///
/// Therefore, injecting transient dependencies via constructors is a bad idea in most cases. You'd be far better off
/// creating a local "request scope" each time your actor processes a message that depends on a transient dependency,
/// such as a database connection, and disposing that scope once the operation is complete.
///
/// Actors are not MVC Controllers. Actors can live forever, have the ability to restart, and are often stateful.
/// Be mindful of this as you use this feature or bad things will happen. Akka.NET does not magically manage scopes
/// for you.
/// </remarks>
public IDependencyResolver Resolver { get; }
public static DependencyResolver For(ActorSystem actorSystem)
{
return actorSystem.WithExtension<DependencyResolver, DependencyResolverExtension>();
}
/// <summary>
/// Uses a delegate to dynamically instantiate an actor where some of the constructor arguments are populated via dependency injection
/// and others are not.
/// </summary>
/// <remarks>
/// YOU ARE RESPONSIBLE FOR MANAGING THE LIFECYCLE OF YOUR OWN DEPENDENCIES. AKKA.NET WILL NOT ATTEMPT TO DO IT FOR YOU.
/// </remarks>
/// <typeparam name="T">The type of actor to instantiate.</typeparam>
/// <param name="args">Optional. Any constructor arguments that will be passed into the actor's constructor directly without being resolved by DI first.</param>
/// <returns>A new <see cref="Akka.Actor.Props"/> instance which uses DI internally.</returns>
public Props Props<T>(params object[] args) where T : ActorBase
{
return Resolver.Props<T>(args);
}
/// <summary>
/// Used to dynamically instantiate an actor where some of the constructor arguments are populated via dependency injection
/// and others are not.
/// </summary>
/// <remarks>
/// YOU ARE RESPONSIBLE FOR MANAGING THE LIFECYCLE OF YOUR OWN DEPENDENCIES. AKKA.NET WILL NOT ATTEMPT TO DO IT FOR YOU.
/// </remarks>
/// <typeparam name="T">The type of actor to instantiate.</typeparam>
/// <returns>A new <see cref="Akka.Actor.Props"/> instance which uses DI internally.</returns>
public Props Props<T>() where T : ActorBase
{
return Resolver.Props<T>();
}
/// <summary>
/// Used to dynamically instantiate an actor where some of the constructor arguments are populated via dependency injection
/// and others are not.
/// </summary>
/// <remarks>
/// YOU ARE RESPONSIBLE FOR MANAGING THE LIFECYCLE OF YOUR OWN DEPENDENCIES. AKKA.NET WILL NOT ATTEMPT TO DO IT FOR YOU.
/// </remarks>
/// <param name="type">The type of actor to instantiate.</param>
/// <returns>A new <see cref="Akka.Actor.Props"/> instance which uses DI internally.</returns>
public Props Props(Type type)
{
return Resolver.Props(type);
}
/// <summary>
/// Used to dynamically instantiate an actor where some of the constructor arguments are populated via dependency injection
/// and others are not.
/// </summary>
/// <remarks>
/// YOU ARE RESPONSIBLE FOR MANAGING THE LIFECYCLE OF YOUR OWN DEPENDENCIES. AKKA.NET WILL NOT ATTEMPT TO DO IT FOR YOU.
/// </remarks>
/// <param name="type">The type of actor to instantiate.</param>
/// <param name="args">Optional. Any constructor arguments that will be passed into the actor's constructor directly without being resolved by DI first.</param>
/// <returns>A new <see cref="Akka.Actor.Props"/> instance which uses DI internally.</returns>
public Props Props(Type type, params object[] args)
{
return Resolver.Props(type, args);
}
}
/// <summary>
/// INTERNAL API
/// </summary>
public sealed class DependencyResolverExtension : ExtensionIdProvider<DependencyResolver>
{
public override DependencyResolver CreateExtension(ExtendedActorSystem system)
{
var setup = system.Settings.Setup.Get<DependencyResolverSetup>();
if (setup.HasValue) return new DependencyResolver(setup.Value.DependencyResolver);
var exception = new ConfigurationException("Unable to find [DependencyResolverSetup] included in ActorSystem settings." +
" Please specify one before attempting to use dependency injection inside Akka.NET.");
system.EventStream.Publish(new Error(exception, "Akka.DependencyInjection", typeof(DependencyResolverExtension), exception.Message));
throw exception;
}
}
}
| 49.674603 | 168 | 0.630931 | [
"Apache-2.0"
] | Aaronontheweb/akka.net | src/contrib/dependencyinjection/Akka.DependencyInjection/DependencyResolver.cs | 6,261 | C# |
using System.Threading.Tasks;
using Shouldly;
using Xunit;
using HealthCare.Sessions;
namespace HealthCare.Tests.Sessions
{
public class SessionAppService_Tests : HealthCareTestBase
{
private readonly ISessionAppService _sessionAppService;
public SessionAppService_Tests()
{
_sessionAppService = Resolve<ISessionAppService>();
}
[MultiTenantFact]
public async Task Should_Get_Current_User_When_Logged_In_As_Host()
{
// Arrange
LoginAsHostAdmin();
// Act
var output = await _sessionAppService.GetCurrentLoginInformations();
// Assert
var currentUser = await GetCurrentUserAsync();
output.User.ShouldNotBe(null);
output.User.Name.ShouldBe(currentUser.Name);
output.User.Surname.ShouldBe(currentUser.Surname);
output.Tenant.ShouldBe(null);
}
[Fact]
public async Task Should_Get_Current_User_And_Tenant_When_Logged_In_As_Tenant()
{
// Act
var output = await _sessionAppService.GetCurrentLoginInformations();
// Assert
var currentUser = await GetCurrentUserAsync();
var currentTenant = await GetCurrentTenantAsync();
output.User.ShouldNotBe(null);
output.User.Name.ShouldBe(currentUser.Name);
output.Tenant.ShouldNotBe(null);
output.Tenant.Name.ShouldBe(currentTenant.Name);
}
}
}
| 28.962264 | 87 | 0.630619 | [
"MIT"
] | pickituup/HealthCare_collaboration | aspnet-core/test/HealthCare.Tests/Sessions/SessionAppService_Tests.cs | 1,537 | C# |
using ModelWrapper;
using BAYSOFT.Core.Domain.Entities.StockWallet;
namespace BAYSOFT.Core.Application.StockWallet.Samples.Commands.PatchSample
{
public class PatchSampleCommandResponse : ApplicationResponse<Sample>
{
public PatchSampleCommandResponse(WrapRequest<Sample> request, object data, string message = "Successful operation!", long? resultCount = null)
: base(request, data, message, resultCount)
{
}
}
}
| 33.071429 | 151 | 0.730022 | [
"MIT"
] | BAYSOFT-001/baysoft-stockwallet | src/BAYSOFT.Core.Application/StockWallet/Samples/Commands/PatchSample/PatchSampleCommandResponse.cs | 463 | C# |
/*
* Copyright 2010-2014 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 application-autoscaling-2016-02-06.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Net;
using System.Text;
using System.Xml.Serialization;
using Amazon.ApplicationAutoScaling.Model;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
using Amazon.Runtime.Internal.Transform;
using Amazon.Runtime.Internal.Util;
using ThirdParty.Json.LitJson;
namespace Amazon.ApplicationAutoScaling.Model.Internal.MarshallTransformations
{
/// <summary>
/// Response Unmarshaller for DescribeScalableTargets operation
/// </summary>
public class DescribeScalableTargetsResponseUnmarshaller : JsonResponseUnmarshaller
{
/// <summary>
/// Unmarshaller the response from the service to the response class.
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context)
{
DescribeScalableTargetsResponse response = new DescribeScalableTargetsResponse();
context.Read();
int targetDepth = context.CurrentDepth;
while (context.ReadAtDepth(targetDepth))
{
if (context.TestExpression("NextToken", targetDepth))
{
var unmarshaller = StringUnmarshaller.Instance;
response.NextToken = unmarshaller.Unmarshall(context);
continue;
}
if (context.TestExpression("ScalableTargets", targetDepth))
{
var unmarshaller = new ListUnmarshaller<ScalableTarget, ScalableTargetUnmarshaller>(ScalableTargetUnmarshaller.Instance);
response.ScalableTargets = unmarshaller.Unmarshall(context);
continue;
}
}
return response;
}
/// <summary>
/// Unmarshaller error response to exception.
/// </summary>
/// <param name="context"></param>
/// <param name="innerException"></param>
/// <param name="statusCode"></param>
/// <returns></returns>
public override AmazonServiceException UnmarshallException(JsonUnmarshallerContext context, Exception innerException, HttpStatusCode statusCode)
{
ErrorResponse errorResponse = JsonErrorResponseUnmarshaller.GetInstance().Unmarshall(context);
if (errorResponse.Code != null && errorResponse.Code.Equals("ConcurrentUpdateException"))
{
return new ConcurrentUpdateException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InternalServiceException"))
{
return new InternalServiceException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("InvalidNextTokenException"))
{
return new InvalidNextTokenException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
if (errorResponse.Code != null && errorResponse.Code.Equals("ValidationException"))
{
return new ValidationException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
return new AmazonApplicationAutoScalingException(errorResponse.Message, innerException, errorResponse.Type, errorResponse.Code, errorResponse.RequestId, statusCode);
}
private static DescribeScalableTargetsResponseUnmarshaller _instance = new DescribeScalableTargetsResponseUnmarshaller();
internal static DescribeScalableTargetsResponseUnmarshaller GetInstance()
{
return _instance;
}
/// <summary>
/// Gets the singleton.
/// </summary>
public static DescribeScalableTargetsResponseUnmarshaller Instance
{
get
{
return _instance;
}
}
}
} | 42.529412 | 177 | 0.664493 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/ApplicationAutoScaling/Generated/Model/Internal/MarshallTransformations/DescribeScalableTargetsResponseUnmarshaller.cs | 5,061 | C# |
// ---------------------------------------------------------------------------------------------
#region // Copyright (c) 2005-2015, SIL International.
// <copyright from='2005' to='2015' company='SIL International'>
// Copyright (c) 2005-2015, SIL International.
//
// This software is distributed under the MIT License, as specified in the LICENSE.txt file.
// </copyright>
#endregion
//
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;
using L10NSharp;
using SIL.Pa.Model;
using SilTools;
namespace SIL.Pa.UI.Controls
{
public class FieldSelectorGrid : SilGrid
{
/// <summary>Handler for the AfterUserChangedValue event</summary>
public delegate void AfterUserChangedValueHandler(PaField field,
bool selectAllValueChanged, bool newValue);
/// <summary>
/// This event is fired when the user has changed one of the check box values in the
/// list. This event is not fired when a check box's value is changed programmatically.
/// </summary>
public event AfterUserChangedValueHandler AfterUserChangedValue;
private const int kIndeterminate = -1;
private const string kCheckCol = "check";
private const string kOrderCol = "order";
private const string kFieldCol = "field";
private DataGridViewRow m_phoneticRow;
private int m_currRowIndex = -1;
private bool m_ignoreRowEnter;
private IEnumerable<PaField> m_fieldList;
/// ------------------------------------------------------------------------------------
public FieldSelectorGrid()
{
RowHeadersVisible = false;
ColumnHeadersVisible = false;
AllowUserToOrderColumns = false;
AllowUserToResizeColumns = false;
CellBorderStyle = DataGridViewCellBorderStyle.None;
App.SetGridSelectionColors(this, false);
if (App.DesignMode)
return;
// Add the column for the check box.
DataGridViewColumn col = CreateCheckBoxColumn(kCheckCol);
Columns.Add(col);
// Add the column for the field name.
col = CreateTextBoxColumn(kFieldCol);
col.ReadOnly = true;
col.CellTemplate.Style.Font = FontHelper.UIFont;
Columns.Add(col);
// Add a column for a value on which to sort. This column is not visible.
col = CreateTextBoxColumn(kOrderCol);
col.ReadOnly = true;
col.Visible = false;
col.ValueType = typeof(int);
col.SortMode = DataGridViewColumnSortMode.Automatic;
Columns.Add(col);
App.SetGridSelectionColors(this, false);
}
/// ------------------------------------------------------------------------------------
public void Load(IEnumerable<KeyValuePair<PaField, bool>> fieldsInList)
{
Rows.Clear();
var order = 0;
// Add the select all item, make it a tri-state cell and
// set its order so it always sorts to the top of the list.
// Note for Mono Linux, this must preceed the foreach() loop because
// Rows.Insert() has a bug--http://bugzilla.xamarin.com/show_bug.cgi?id=821
Rows.Add(new object[] { false, LocalizationManager.GetString(
"DialogBoxes.DataSourcePropertiesDialogs.FieldSelectorGrid.SelectAllText", "Select All"), -100 });
foreach (var rowData in fieldsInList)
{
int i = Rows.Add(new object[] { rowData.Value, rowData.Key.DisplayName, order++ } );
if (rowData.Key.Type == FieldType.Phonetic)
m_phoneticRow = Rows[i];
}
m_fieldList = fieldsInList.Select(kvp => kvp.Key);
((DataGridViewCheckBoxCell)Rows[0].Cells[kCheckCol]).ThreeState = true;
((DataGridViewCheckBoxCell)Rows[0].Cells[kCheckCol]).IndeterminateValue = kIndeterminate;
((DataGridViewCheckBoxCell)Rows[0].Cells[kCheckCol]).TrueValue = true;
((DataGridViewCheckBoxCell)Rows[0].Cells[kCheckCol]).FalseValue = false;
SetSelectAllItemsValue();
AutoResizeColumns();
AutoResizeRows();
CurrentCell = this[0, 0];
IsDirty = false;
OnResize(null);
}
/// ------------------------------------------------------------------------------------
private void SetSelectAllItemsValue()
{
if (AreAllItemsChecked)
Rows[0].Cells[kCheckCol].Value = true;
else if (AnyItemsChecked)
Rows[0].Cells[kCheckCol].Value = kIndeterminate;
else
Rows[0].Cells[kCheckCol].Value = false;
InvalidateCell(0, 0);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Eat the double-click because it allows the state of the "Select All" to get out
/// of sync. with the rest of the items.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnCellContentDoubleClick(DataGridViewCellEventArgs e)
{
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Handle the user clicking on check box. This will make sure the state of the select
/// all item is correct and that, if the select all item is the one clicked on, the
/// state of the rest of the items is correct.
/// </summary>
/// ------------------------------------------------------------------------------------
protected override void OnCellContentClick(DataGridViewCellEventArgs e)
{
base.OnCellContentClick(e);
if (e.ColumnIndex != 0)
{
// Don't allow the field name cell to become current.
CurrentCell = this[0, e.RowIndex];
return;
}
// Force commital of the click's change.
CommitEdit(DataGridViewDataErrorContexts.Commit);
// When the new value of the Select All item is indeterminate, force it to
// false since the user clicking on it should never make it indeterminate.
if (e.RowIndex == 0 && Rows[0].Cells[kCheckCol].Value is int)
{
Rows[0].Cells[kCheckCol].Value = false;
// Do this because I can't get the indeterminate value to go away
// without changing the current cell. So change it and restore it.
CurrentCell = this[1, e.RowIndex];
CurrentCell = this[0, e.RowIndex];
}
if (e.RowIndex > 0)
SetSelectAllItemsValue();
else
{
if ((bool)Rows[0].Cells[kCheckCol].Value)
CheckAll();
else
UncheckAll();
}
if (AfterUserChangedValue != null)
{
var fieldDisplayName = this[kFieldCol, e.RowIndex].Value as string;
AfterUserChangedValue(m_fieldList.SingleOrDefault(f => f.DisplayName == fieldDisplayName),
e.RowIndex == 0, (bool)Rows[e.RowIndex].Cells[0].Value);
}
}
/// ------------------------------------------------------------------------------------
protected override void OnResize(EventArgs e)
{
if (e != null)
base.OnResize(e);
if (Columns[kFieldCol] == null)
return;
// Adjust the field name's column width so it extends all the way to the grid'
// right edge. Account for the vertical scroll bar if it's showing.
Columns[kFieldCol].Width = (ClientSize.Width - Columns[kCheckCol].Width -
(DisplayedRowCount(false) < Rows.Count ?
SystemInformation.VerticalScrollBarWidth : 0) - 5);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a collection of the checked fields.
/// </summary>
/// ------------------------------------------------------------------------------------
public IEnumerable<PaField> GetCheckedFields()
{
return from row in GetRows()
where row.Index > 0 && (bool)row.Cells[kCheckCol].Value
select m_fieldList.Single(f => f.DisplayName == row.Cells[kFieldCol].Value as string);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Returns a collection of field names with their corresponding check value.
/// </summary>
/// ------------------------------------------------------------------------------------
public IEnumerable<KeyValuePair<string, bool>> GetSelections()
{
return from row in GetRows()
where row.Index > 0
select new KeyValuePair<string, bool>(row.Cells[kFieldCol].Value as string,
(bool)row.Cells[kCheckCol].Value);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether or not the phonetic column is selected.
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool IsPhoneticChecked
{
get
{
if (m_phoneticRow != null)
return (bool)m_phoneticRow.Cells[kCheckCol].Value;
var field = m_fieldList.SingleOrDefault(f => f.Type == FieldType.Phonetic);
if (field == null)
return false;
foreach (var row in GetRows().Where(r => r.Cells[kFieldCol].Value as string == field.DisplayName))
{
m_phoneticRow = row;
return (bool)row.Cells[kCheckCol].Value;
}
return false;
}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets the index in the checked list box of the phonetic item. If it's not in the
/// list then -1 is returned.
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int PhoneticItemIndex
{
get {return (m_phoneticRow != null ? m_phoneticRow.Index : -1);}
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether or not any items are checked.
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AnyItemsChecked
{
get { return (CheckedItemCount > 0); }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether or not all the items are checked. The "Select All"
/// item is not counted.
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool AreAllItemsChecked
{
get { return (CheckedItemCount == RowCount - 1); }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating how many items are checked. The "Select All" item is not
/// included in the count.
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public int CheckedItemCount
{
get { return GetCheckedFields().Count(); }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether or not the selected item can be moved up.
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool CanMoveSelectedItemUp
{
get { return (m_currRowIndex > 1); }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Gets a value indicating whether or not the selected item can be moved down.
/// </summary>
/// ------------------------------------------------------------------------------------
[Browsable(false)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
public bool CanMoveSelectedItemDown
{
get { return (m_currRowIndex > 0 && m_currRowIndex < Rows.Count - 1); }
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Selects all the items in the list.
/// </summary>
/// ------------------------------------------------------------------------------------
public void CheckAll()
{
foreach (var row in GetRows())
row.Cells[kCheckCol].Value = true;
InvalidateColumn(0);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Unselects all the items in the list.
/// </summary>
/// ------------------------------------------------------------------------------------
public void UncheckAll()
{
foreach (var row in GetRows())
row.Cells[kCheckCol].Value = false;
InvalidateColumn(0);
}
/// ------------------------------------------------------------------------------------
protected override void OnRowEnter(DataGridViewCellEventArgs e)
{
m_currRowIndex = e.RowIndex;
if (!m_ignoreRowEnter)
base.OnRowEnter(e);
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Moves the selected item in the list up by one.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool MoveSelectedItemUp()
{
// Selected item must be after the "Select All" item and
// after the item right after it.
if (CanMoveSelectedItemUp)
{
int index = CurrentCellAddress.Y;
int order = (int)Rows[index].Cells[kOrderCol].Value;
Rows[index].Cells[kOrderCol].Value = Rows[index - 1].Cells[kOrderCol].Value;
Rows[index - 1].Cells[kOrderCol].Value = order;
m_ignoreRowEnter = true;
Sort(Columns[kOrderCol], ListSortDirection.Ascending);
m_ignoreRowEnter = false;
CurrentCell = this[0, index - 1];
IsDirty = true;
try
{
if (!CurrentRow.Displayed || CurrentRow.Index == 1)
FirstDisplayedScrollingRowIndex = (CurrentRow.Index == 1 ? 0 : CurrentRow.Index);
}
catch { }
}
return CanMoveSelectedItemUp;
}
/// ------------------------------------------------------------------------------------
/// <summary>
/// Moves the selected item in the list down by one.
/// </summary>
/// ------------------------------------------------------------------------------------
public bool MoveSelectedItemDown()
{
// Selected item must be after the "Select All" item and
// after the item right after it.
if (CanMoveSelectedItemDown)
{
int index = CurrentCellAddress.Y;
int order = (int)Rows[index].Cells[kOrderCol].Value;
Rows[index].Cells[kOrderCol].Value = Rows[index + 1].Cells[kOrderCol].Value;
Rows[index + 1].Cells[kOrderCol].Value = order;
m_ignoreRowEnter = true;
Sort(Columns[kOrderCol], ListSortDirection.Ascending);
m_ignoreRowEnter = false;
CurrentCell = this[0, index + 1];
IsDirty = true;
try
{
while (!CurrentRow.Displayed)
FirstDisplayedScrollingRowIndex++;
// Because the Displayed property for the row is true even when only part
// of the row is visible, we need to make sure all of the row is visible.
var rc1 = GetRowDisplayRectangle(CurrentRow.Index, true);
var rc2 = GetRowDisplayRectangle(CurrentRow.Index, false);
if (rc1 != rc2)
FirstDisplayedScrollingRowIndex++;
}
catch { }
}
return CanMoveSelectedItemDown;
}
}
}
| 36.09589 | 103 | 0.528526 | [
"MIT"
] | sillsdev/phonology-assistant | src/Pa/UI/Controls/FieldRelatedControls/FieldSelectorGrid.cs | 15,810 | C# |
namespace RedBlackAvl.Implementation.Contracts
{
public interface IAvlNode<TKey, TValue>
{
IAvlNode<TKey, TValue> Parent { get; set; }
IAvlNode<TKey, TValue> Left { get; set; }
IAvlNode<TKey, TValue> Right { get; set; }
TKey Key { get; set; }
TValue Value { get; set; }
int Balance { get; set; }
}
} | 21.470588 | 51 | 0.572603 | [
"MIT"
] | GeorgiNik/RedBlack-AVL | RedBlackAvl/RedBlackAvl.Implementation/Contracts/IAvlNode.cs | 367 | C# |
using System;
using System.Collections.Generic;
using RawRabbit.Configuration.Exchange;
namespace RawRabbit.Extensions.TopologyUpdater.Model
{
public class ExchangeUpdateResult
{
public ExchangeConfiguration Exchange { get; set; }
public List<Binding> Bindings { get; set; }
public TimeSpan ExecutionTime { get; set; }
}
}
| 23.857143 | 53 | 0.775449 | [
"MIT"
] | aignas/RawRabbit | src/RawRabbit.Extensions/TopologyUpdater/Model/ExchangeUpdateResult.cs | 336 | 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.
//
// Generated on 2020 October 09 05:00:00 UTC
// </auto-generated>
//---------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using static go.builtin;
using encoding = go.encoding_package;
using errors = go.errors_package;
using fmt = go.fmt_package;
using os = go.os_package;
using reflect = go.reflect_package;
using sync = go.sync_package;
using atomic = go.sync.atomic_package;
using unicode = go.unicode_package;
using utf8 = go.unicode.utf8_package;
using go;
#nullable enable
namespace go {
namespace encoding
{
public static partial class gob_package
{
[GeneratedCode("go2cs", "0.1.0.0")]
[PromotedStruct(typeof(CommonType))]
private partial struct gobEncoderType
{
// CommonType structure promotion - sourced from value copy
private readonly ptr<CommonType> m_CommonTypeRef;
private ref CommonType CommonType_val => ref m_CommonTypeRef.Value;
public ref @string Name => ref m_CommonTypeRef.Value.Name;
public ref typeId Id => ref m_CommonTypeRef.Value.Id;
// Constructors
public gobEncoderType(NilType _)
{
this.m_CommonTypeRef = new ptr<CommonType>(new CommonType(nil));
}
public gobEncoderType(CommonType CommonType = default)
{
this.m_CommonTypeRef = new ptr<CommonType>(CommonType);
}
// Enable comparisons between nil and gobEncoderType struct
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(gobEncoderType value, NilType nil) => value.Equals(default(gobEncoderType));
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(gobEncoderType value, NilType nil) => !(value == nil);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator ==(NilType nil, gobEncoderType value) => value == nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool operator !=(NilType nil, gobEncoderType value) => value != nil;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator gobEncoderType(NilType nil) => default(gobEncoderType);
}
[GeneratedCode("go2cs", "0.1.0.0")]
private static gobEncoderType gobEncoderType_cast(dynamic value)
{
return new gobEncoderType(value.CommonType);
}
}
}} | 35.888889 | 119 | 0.639835 | [
"MIT"
] | GridProtectionAlliance/go2cs | src/go-src-converted/encoding/gob/type_gobEncoderTypeStruct.cs | 2,907 | C# |
using RazzleServer.Game.Maple.Characters;
using RazzleServer.Game.Maple.Scripting;
namespace RazzleServer.Game.Scripts.Commands
{
public sealed class KickCommand : ACommandScript
{
public override string Name => "kick";
public override string Parameters => "[character]";
public override bool IsRestricted => true;
public override void Execute(GameCharacter caller, string[] args)
{
if (args.Length == 0)
{
ShowSyntax(caller);
}
else
{
var name = args[0];
if (!(caller.Client.Server.World.GetCharacterByName(name) is GameCharacter target))
{
caller.Notify($"[Command] Character '{name}' could not be found.");
return;
}
if (target.Name == caller.Name)
{
caller.Notify("You cannot kick yourself");
return;
}
if (target.IsMaster)
{
caller.Notify("You cannot kick a GM");
return;
}
target.Client.Terminate($"Player was kicked by {caller.Name}");
}
}
}
}
| 27.744681 | 99 | 0.485429 | [
"MIT"
] | razfriman/RazzleServer | RazzleServer.Game/Scripts/Commands/KickCommand.cs | 1,306 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EntityMotor : MonoBehaviour
{
public float maxMoveSpeed = 5;
public float acceleration = .5f;
public float slowDownAcceleration = .8f;
public float changeDirectionAcceleration = .3f;
public float offHandMovementModifier = .5f;
public float horizontalMoveDirection = 0f;
public float verticalMoveDirection = 0f;
public Vector2 newVelocity;
public Rigidbody2D myRigidbody;
//public BoxCollider2D myBoxCollider;
//various data for external scripts
public bool isMoving = false;
public bool isMovingVertically = false;
public bool isMovingHorizontally = false;
public bool isMovingLeft = false;
public bool isMovingRight = false;
public bool isMovingDown = false;
public bool isMovingUp = false;
public bool changingVerticalDirection = false;
public bool changingHorizontalDirection = false;
//current direction the player is facing
public bool facingLeft = false;
public bool facingRight = false;
public bool facingUp = false;
public bool facingDown = true;
//current direction that is in charge of player movement, set to none when not moving
public Direction directionInControl;
public enum Direction
{
None,
Up,
Down,
Left,
Right
}
//local pause for entitys movement
public bool movementPaused = false;
//sets the current facing direction based on the last directionInCharge
private void UpdateFacingDirections(Direction directionFacing)
{
if (directionFacing == Direction.Left)
{
facingLeft = true;
facingRight = false;
facingUp = false;
facingDown = false;
}
else if(directionFacing == Direction.Right)
{
facingLeft = false;
facingRight = true;
facingUp = false;
facingDown = false;
}
else if(directionFacing == Direction.Up)
{
facingLeft = false;
facingRight = false;
facingUp = true;
facingDown = false;
}
else if (directionFacing == Direction.Down)
{
facingLeft = false;
facingRight = false;
facingUp = false;
facingDown = true;
}
}
//slowdown acceleration horizontally
public void PerformHorizontalSlowDown()
{
changingHorizontalDirection = false;
if (myRigidbody.velocity.x < 0)
{
newVelocity.x = Mathf.Min(newVelocity.x + slowDownAcceleration, 0);
}
else if (myRigidbody.velocity.x > 0)
{
newVelocity.x = Mathf.Max(newVelocity.x - slowDownAcceleration, 0);
}
}
//slowdown acceleration vertically
public void PerformVerticalSlowDown()
{
changingVerticalDirection = false;
if (myRigidbody.velocity.y < 0)
{
newVelocity.y = Mathf.Min(newVelocity.y + slowDownAcceleration, 0);
}
else if (myRigidbody.velocity.y > 0)
{
newVelocity.y = Mathf.Max(newVelocity.y - slowDownAcceleration, 0);
}
}
// Start is called before the first frame update
void Start()
{
myRigidbody = GetComponent<Rigidbody2D>();
}
//process the movement from input, set the velocity based on those calculations, and pause movement if locally or globally paused
void FixedUpdate()
{
ProcessMovement();
newVelocity = Vector2.ClampMagnitude(newVelocity, maxMoveSpeed);
myRigidbody.velocity = new Vector2(newVelocity.x, newVelocity.y);
if (movementPaused || PauseManager.paused)
PauseEntityMovement();
}
//sets the appropriate data variables for starting horizontal movement based on input, once set movement is processed based on that data
public void StartHorizontalMove(float direction)
{
isMoving = true;
isMovingHorizontally = true;
horizontalMoveDirection = direction;
if (direction < 0)
{
isMovingLeft = true;
isMovingRight = false;
if (directionInControl == Direction.None)
{
directionInControl = Direction.Left;
UpdateFacingDirections(directionInControl);
}
}
else if (direction > 0)
{
isMovingLeft = false;
isMovingRight = true;
if (directionInControl == Direction.None)
{
directionInControl = Direction.Right;
UpdateFacingDirections(directionInControl);
}
}
else
{
isMovingLeft = false;
isMovingRight = false;
directionInControl = Direction.None;
}
}
//sets the appropriate data variables for starting vertical movement based on input, once set movement is processed based on that data
public void StartVerticalMove(float direction)
{
isMoving = true;
isMovingVertically = true;
verticalMoveDirection = direction;
if (direction < 0)
{
isMovingDown = true;
isMovingUp = false;
if (directionInControl == Direction.None)
{
directionInControl = Direction.Down;
UpdateFacingDirections(directionInControl);
}
}
else if (direction > 0)
{
isMovingDown = false;
isMovingUp = true;
if (directionInControl == Direction.None)
{
directionInControl = Direction.Up;
UpdateFacingDirections(directionInControl);
}
}
else
{
isMovingDown = false;
isMovingUp = false;
directionInControl = Direction.None;
}
}
//sets the appropriate data variables for stopping horizontal movement based on input, once set movement is processed based on that data
public void StopHorizontalMove()
{
if (!isMovingVertically)
{
isMoving = false;
directionInControl = Direction.None;
}
else
{
if (isMovingUp)
{
directionInControl = Direction.Up;
UpdateFacingDirections(directionInControl);
}
if (isMovingDown)
{
directionInControl = Direction.Down;
UpdateFacingDirections(directionInControl);
}
}
isMovingHorizontally = false;
isMovingLeft = false;
isMovingRight = false;
}
//sets the appropriate data variables for stopping vertical movement based on input, once set movement is processed based on that data
public void StopVerticalMove()
{
if (!isMovingHorizontally)
{
isMoving = false;
directionInControl = Direction.None;
}
else
{
if (isMovingLeft)
{
directionInControl = Direction.Left;
UpdateFacingDirections(directionInControl);
}
if (isMovingRight)
{
directionInControl = Direction.Right;
UpdateFacingDirections(directionInControl);
}
}
isMovingVertically = false;
isMovingUp = false;
isMovingDown = false;
}
//calculate movement velocity based on set data
public void ProcessMovement()
{
if (isMoving && !PauseManager.paused)
{
if (isMovingHorizontally)
{
if (isMovingLeft)
{
if (facingUp || facingDown)
{
if (myRigidbody.velocity.x > 0)
{
newVelocity.x = (myRigidbody.velocity.x - changeDirectionAcceleration) * offHandMovementModifier;
changingHorizontalDirection = true;
}
else
{
newVelocity.x = (Mathf.Clamp((horizontalMoveDirection) * Mathf.Abs(myRigidbody.velocity.x - acceleration), -maxMoveSpeed, maxMoveSpeed)) * offHandMovementModifier;
changingHorizontalDirection = false;
}
}
else
{
if (myRigidbody.velocity.x > 0)
{
newVelocity.x = myRigidbody.velocity.x - changeDirectionAcceleration;
changingHorizontalDirection = true;
}
else
{
newVelocity.x = Mathf.Clamp((horizontalMoveDirection) * Mathf.Abs(myRigidbody.velocity.x - acceleration), -maxMoveSpeed, maxMoveSpeed);
changingHorizontalDirection = false;
}
}
}
else if (isMovingRight)
{
if (facingUp || facingDown)
{
if (myRigidbody.velocity.x < 0)
{
newVelocity.x = (myRigidbody.velocity.x + changeDirectionAcceleration) * offHandMovementModifier;
changingHorizontalDirection = true;
}
else
{
newVelocity.x = (Mathf.Clamp((horizontalMoveDirection) * Mathf.Abs(myRigidbody.velocity.x + acceleration), -maxMoveSpeed, maxMoveSpeed)) * offHandMovementModifier;
changingHorizontalDirection = false;
}
}
else
{
if (myRigidbody.velocity.x < 0)
{
newVelocity.x = myRigidbody.velocity.x + changeDirectionAcceleration;
changingHorizontalDirection = true;
}
else
{
newVelocity.x = Mathf.Clamp((horizontalMoveDirection) * Mathf.Abs(myRigidbody.velocity.x + acceleration), -maxMoveSpeed, maxMoveSpeed);
changingHorizontalDirection = false;
}
}
}
}
else
{
PerformHorizontalSlowDown();
}
if (isMovingVertically)
{
if (isMovingDown)
{
if (facingLeft || facingRight)
{
if (myRigidbody.velocity.y > 0)
{
newVelocity.y = (myRigidbody.velocity.y - changeDirectionAcceleration) * offHandMovementModifier;
changingVerticalDirection = true;
}
else
{
newVelocity.y = (Mathf.Clamp((verticalMoveDirection) * Mathf.Abs(myRigidbody.velocity.y - acceleration), -maxMoveSpeed, maxMoveSpeed)) * offHandMovementModifier;
changingVerticalDirection = false;
}
}
else
{
if (myRigidbody.velocity.y > 0)
{
newVelocity.y = myRigidbody.velocity.y - changeDirectionAcceleration;
changingVerticalDirection = true;
}
else
{
newVelocity.y = Mathf.Clamp((verticalMoveDirection) * Mathf.Abs(myRigidbody.velocity.y - acceleration), -maxMoveSpeed, maxMoveSpeed);
changingVerticalDirection = false;
}
}
}
else if (isMovingUp)
{
if (facingLeft || facingRight)
{
if (myRigidbody.velocity.y < 0)
{
newVelocity.y = (myRigidbody.velocity.y + changeDirectionAcceleration) * offHandMovementModifier;
changingVerticalDirection = true;
}
else
{
newVelocity.y = (Mathf.Clamp((verticalMoveDirection) * Mathf.Abs(myRigidbody.velocity.y + acceleration), -maxMoveSpeed, maxMoveSpeed)) * offHandMovementModifier;
changingVerticalDirection = false;
}
}
else
{
if (myRigidbody.velocity.y < 0)
{
newVelocity.y = myRigidbody.velocity.y + changeDirectionAcceleration;
changingVerticalDirection = true;
}
else
{
newVelocity.y = Mathf.Clamp((verticalMoveDirection) * Mathf.Abs(myRigidbody.velocity.y + acceleration), -maxMoveSpeed, maxMoveSpeed);
changingVerticalDirection = false;
}
}
}
}
else
{
PerformVerticalSlowDown();
}
}
else
{
PerformHorizontalSlowDown();
PerformVerticalSlowDown();
}
}
//resets entity's velocities and the newVelocity variable
public void ResetEntityMomentum()
{
myRigidbody.velocity = Vector3.zero;
myRigidbody.angularVelocity = 0f;
newVelocity = Vector3.zero;
}
//****need to rework how this works****
//stops current movements (sets all data to false), and resets the entity's velocities
public void PauseEntityMovement()
{
StopHorizontalMove();
StopVerticalMove();
ResetEntityMomentum();
}
}
| 34.607656 | 191 | 0.512996 | [
"MIT"
] | The-Pretenders/MyFirstAdventure | The Adventures of Dud/Assets/Scripts/Motor/EntityMotor.cs | 14,466 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors;
using System;
using System.Diagnostics.Contracts;
using Common;
using Common.Interfaces;
using Microsoft.VisualStudio.TestPlatform.Common.Utilities;
using Microsoft.VisualStudio.TestPlatform.Utilities;
using CommandLineResources = Resources.Resources;
/// <summary>
/// Argument Executor for the "-e|--Environment|/e|/Environment" command line argument.
/// </summary>
internal class EnvironmentArgumentProcessor : IArgumentProcessor
{
#region Constants
/// <summary>
/// The short name of the command line argument that the EnvironmentArgumentProcessor handles.
/// </summary>
public const string ShortCommandName = "/e";
/// <summary>
/// The name of the command line argument that the EnvironmentArgumentProcessor handles.
/// </summary>
public const string CommandName = "/Environment";
#endregion
private Lazy<IArgumentProcessorCapabilities> _metadata;
private Lazy<IArgumentExecutor> _executor;
public Lazy<IArgumentExecutor> Executor
{
get
{
if (_executor == null)
{
_executor = new Lazy<IArgumentExecutor>(
() => new ArgumentExecutor(CommandLineOptions.Instance, RunSettingsManager.Instance, ConsoleOutput.Instance)
);
}
return _executor;
}
set
{
_executor = value;
}
}
public Lazy<IArgumentProcessorCapabilities> Metadata
{
get
{
if (_metadata == null)
{
_metadata = new Lazy<IArgumentProcessorCapabilities>(() => new ArgumentProcessorCapabilities());
}
return _metadata;
}
}
internal class ArgumentProcessorCapabilities : BaseArgumentProcessorCapabilities
{
public override string CommandName => EnvironmentArgumentProcessor.CommandName;
public override string ShortCommandName => EnvironmentArgumentProcessor.ShortCommandName;
public override bool AllowMultiple => true;
public override bool IsAction => false;
public override string HelpContentResourceName => CommandLineResources.EnvironmentArgumentHelp;
public override ArgumentProcessorPriority Priority => ArgumentProcessorPriority.Normal;
public override HelpContentPriority HelpPriority => HelpContentPriority.EnvironmentArgumentProcessorHelpPriority;
}
internal class ArgumentExecutor : IArgumentExecutor
{
#region Fields
/// <summary>
/// Used when warning about overriden environment variables.
/// </summary>
private readonly IOutput _output;
/// <summary>
/// Used when setting Environemnt variables.
/// </summary>
private readonly IRunSettingsProvider _runSettingsProvider;
/// <summary>
/// Used when checking and forcing InIsolation mode.
/// </summary>
private readonly CommandLineOptions _commandLineOptions;
#endregion
public ArgumentExecutor(CommandLineOptions commandLineOptions, IRunSettingsProvider runSettingsProvider, IOutput output)
{
_commandLineOptions = commandLineOptions;
_output = output;
_runSettingsProvider = runSettingsProvider;
}
/// <summary>
/// Set the environment variables in RunSettings.xml
/// </summary>
/// <param name="argument">
/// Environment variable to set.
/// </param>
public void Initialize(string argument)
{
Contract.Assert(!string.IsNullOrWhiteSpace(argument));
Contract.Assert(_output != null);
Contract.Assert(_commandLineOptions != null);
Contract.Assert(!string.IsNullOrWhiteSpace(_runSettingsProvider.ActiveRunSettings.SettingsXml));
Contract.EndContractBlock();
var key = argument;
var value = string.Empty;
if (key.Contains("="))
{
value = key.Substring(key.IndexOf("=") + 1);
key = key.Substring(0, key.IndexOf("="));
}
var node = _runSettingsProvider.QueryRunSettingsNode($"RunConfiguration.EnvironmentVariables.{key}");
if (node != null)
{
_output.Warning(true, CommandLineResources.EnvironmentVariableXIsOverriden, key);
}
_runSettingsProvider.UpdateRunSettingsNode($"RunConfiguration.EnvironmentVariables.{key}", value);
if (!_commandLineOptions.InIsolation)
{
_commandLineOptions.InIsolation = true;
_runSettingsProvider.UpdateRunSettingsNode(InIsolationArgumentExecutor.RunSettingsPath, "true");
}
}
// Nothing to do here, the work was done in initialization.
public ArgumentProcessorResult Execute() => ArgumentProcessorResult.Success;
}
} | 35.060811 | 128 | 0.6508 | [
"MIT"
] | lbussell/vstest | src/vstest.console/Processors/EnvironmentArgumentProcessor.cs | 5,191 | C# |
/*
* Copyright 2010-2014 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 mediapackage-2017-10-12.normal.json service model.
*/
using System;
using System.Net;
using Amazon.Runtime;
namespace Amazon.MediaPackage.Model
{
///<summary>
/// MediaPackage exception
/// </summary>
#if !PCL && !NETSTANDARD
[Serializable]
#endif
public class TooManyRequestsException : AmazonMediaPackageException
{
/// <summary>
/// Constructs a new TooManyRequestsException with the specified error
/// message.
/// </summary>
/// <param name="message">
/// Describes the error encountered.
/// </param>
public TooManyRequestsException(string message)
: base(message) {}
/// <summary>
/// Construct instance of TooManyRequestsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
public TooManyRequestsException(string message, Exception innerException)
: base(message, innerException) {}
/// <summary>
/// Construct instance of TooManyRequestsException
/// </summary>
/// <param name="innerException"></param>
public TooManyRequestsException(Exception innerException)
: base(innerException) {}
/// <summary>
/// Construct instance of TooManyRequestsException
/// </summary>
/// <param name="message"></param>
/// <param name="innerException"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public TooManyRequestsException(string message, Exception innerException, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, innerException, errorType, errorCode, requestId, statusCode) {}
/// <summary>
/// Construct instance of TooManyRequestsException
/// </summary>
/// <param name="message"></param>
/// <param name="errorType"></param>
/// <param name="errorCode"></param>
/// <param name="requestId"></param>
/// <param name="statusCode"></param>
public TooManyRequestsException(string message, ErrorType errorType, string errorCode, string requestId, HttpStatusCode statusCode)
: base(message, errorType, errorCode, requestId, statusCode) {}
#if !PCL && !NETSTANDARD
/// <summary>
/// Constructs a new instance of the TooManyRequestsException class with serialized data.
/// </summary>
/// <param name="info">The <see cref="T:System.Runtime.Serialization.SerializationInfo" /> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="T:System.Runtime.Serialization.StreamingContext" /> that contains contextual information about the source or destination.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="info" /> parameter is null. </exception>
/// <exception cref="T:System.Runtime.Serialization.SerializationException">The class name is null or <see cref="P:System.Exception.HResult" /> is zero (0). </exception>
protected TooManyRequestsException(System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context)
: base(info, context)
{
}
#endif
}
} | 43.14433 | 178 | 0.650179 | [
"Apache-2.0"
] | FoxBearBear/aws-sdk-net | sdk/src/Services/MediaPackage/Generated/Model/TooManyRequestsException.cs | 4,185 | C# |
#region BSD License
/*
Copyright (c) 2004-2005 Matthew Holmes (matthew@wildfiregames.com), Dan Moorehead (dan05a@gmail.com)
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions
and the following disclaimer in the documentation and/or other materials provided with the
distribution.
* The name of the author may not be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#endregion
using System;
using System.Xml;
namespace Prebuild.Core.Interfaces
{
/// <summary>
///
/// </summary>
public interface IDataNode
{
/// <summary>
/// Gets or sets the parent.
/// </summary>
/// <value>The parent.</value>
IDataNode Parent { get; set; }
/// <summary>
/// Parses the specified node.
/// </summary>
/// <param name="node">The node.</param>
void Parse(XmlNode node);
}
}
| 40.791667 | 104 | 0.730848 | [
"BSD-3-Clause"
] | SignpostMarv/opensim | Prebuild/src/Core/Interfaces/IDataNode.cs | 1,958 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using JetBrains.Annotations;
using Microsoft.EntityFrameworkCore.Diagnostics;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using Microsoft.EntityFrameworkCore.Utilities;
namespace Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class InversePropertyAttributeConvention :
NavigationAttributeEntityTypeConvention<InversePropertyAttribute>, IModelBuiltConvention
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public InversePropertyAttributeConvention(
[NotNull] IMemberClassifier memberClassifier,
[NotNull] IDiagnosticsLogger<DbLoggerCategory.Model> logger)
: base(memberClassifier, logger)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public const string InverseNavigationsAnnotationName = "InversePropertyAttributeConvention:InverseNavigations";
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override InternalEntityTypeBuilder Apply(
InternalEntityTypeBuilder entityTypeBuilder,
PropertyInfo navigationPropertyInfo,
Type targetClrType,
InversePropertyAttribute attribute)
{
Check.NotNull(entityTypeBuilder, nameof(entityTypeBuilder));
Check.NotNull(navigationPropertyInfo, nameof(navigationPropertyInfo));
Check.NotNull(attribute, nameof(attribute));
if (!entityTypeBuilder.CanAddOrReplaceNavigation(
navigationPropertyInfo.GetSimpleMemberName(), ConfigurationSource.DataAnnotation))
{
return entityTypeBuilder;
}
var targetEntityTypeBuilder = RelationshipDiscoveryConvention.GetTargetEntityTypeBuilder(
entityTypeBuilder, targetClrType, navigationPropertyInfo, ConfigurationSource.DataAnnotation);
if (targetEntityTypeBuilder == null)
{
return entityTypeBuilder;
}
ConfigureInverseNavigation(entityTypeBuilder, navigationPropertyInfo, targetEntityTypeBuilder, attribute);
return entityTypeBuilder;
}
private InternalRelationshipBuilder ConfigureInverseNavigation(
InternalEntityTypeBuilder entityTypeBuilder,
MemberInfo navigationMemberInfo,
InternalEntityTypeBuilder targetEntityTypeBuilder,
InversePropertyAttribute attribute)
{
var entityType = entityTypeBuilder.Metadata;
var targetClrType = targetEntityTypeBuilder.Metadata.ClrType;
var inverseNavigationPropertyInfo = targetEntityTypeBuilder.Metadata.GetRuntimeProperties().Values
.FirstOrDefault(p => string.Equals(p.GetSimpleMemberName(), attribute.Property, StringComparison.OrdinalIgnoreCase));
if (inverseNavigationPropertyInfo == null
|| !FindCandidateNavigationPropertyType(inverseNavigationPropertyInfo).GetTypeInfo()
.IsAssignableFrom(entityType.ClrType.GetTypeInfo()))
{
throw new InvalidOperationException(
CoreStrings.InvalidNavigationWithInverseProperty(
navigationMemberInfo.Name, entityType.DisplayName(), attribute.Property, targetClrType.ShortDisplayName()));
}
if (Equals(inverseNavigationPropertyInfo, navigationMemberInfo))
{
throw new InvalidOperationException(
CoreStrings.SelfReferencingNavigationWithInverseProperty(
navigationMemberInfo.Name,
entityType.DisplayName(),
navigationMemberInfo.Name,
entityType.DisplayName()));
}
// Check for InversePropertyAttribute on the inverseNavigation to verify that it matches.
if (Attribute.IsDefined(inverseNavigationPropertyInfo, typeof(InversePropertyAttribute)))
{
var inverseAttribute = inverseNavigationPropertyInfo.GetCustomAttribute<InversePropertyAttribute>(true);
if (inverseAttribute.Property != navigationMemberInfo.GetSimpleMemberName())
{
throw new InvalidOperationException(
CoreStrings.InversePropertyMismatch(
navigationMemberInfo.Name,
entityType.DisplayName(),
inverseNavigationPropertyInfo.Name,
targetEntityTypeBuilder.Metadata.DisplayName()));
}
}
var referencingNavigationsWithAttribute =
AddInverseNavigation(entityType, navigationMemberInfo, targetEntityTypeBuilder.Metadata, inverseNavigationPropertyInfo);
var ambiguousInverse = FindAmbiguousInverse(
navigationMemberInfo, entityType, entityType.Model, referencingNavigationsWithAttribute);
if (ambiguousInverse != null)
{
var existingInverse = targetEntityTypeBuilder.Metadata.FindNavigation(inverseNavigationPropertyInfo)?.FindInverse();
var existingInverseType = existingInverse?.DeclaringEntityType;
if (existingInverse != null
&& IsAmbiguousInverse(
existingInverse.GetIdentifyingMemberInfo(), existingInverseType, entityType.Model,
referencingNavigationsWithAttribute))
{
var fk = existingInverse.ForeignKey;
if (fk.IsOwnership
|| fk.DeclaringEntityType.Builder.RemoveForeignKey(fk, ConfigurationSource.DataAnnotation) == null)
{
fk.Builder.HasNavigations(
existingInverse.IsDependentToPrincipal() ? PropertyIdentity.None : (PropertyIdentity?)null,
existingInverse.IsDependentToPrincipal() ? (PropertyIdentity?)null : PropertyIdentity.None,
ConfigurationSource.DataAnnotation);
}
}
var existingNavigation = entityType.FindNavigation(navigationMemberInfo);
if (existingNavigation != null)
{
var fk = existingNavigation.ForeignKey;
if (fk.IsOwnership
|| fk.DeclaringEntityType.Builder.RemoveForeignKey(fk, ConfigurationSource.DataAnnotation) == null)
{
fk.Builder.HasNavigations(
existingNavigation.IsDependentToPrincipal() ? PropertyIdentity.None : (PropertyIdentity?)null,
existingNavigation.IsDependentToPrincipal() ? (PropertyIdentity?)null : PropertyIdentity.None,
ConfigurationSource.DataAnnotation);
}
}
var existingAmbiguousNavigation = entityType.Model.FindActualEntityType(ambiguousInverse.Value.Item2)
.FindNavigation(ambiguousInverse.Value.Item1);
if (existingAmbiguousNavigation != null)
{
var fk = existingAmbiguousNavigation.ForeignKey;
if (fk.IsOwnership
|| fk.DeclaringEntityType.Builder.RemoveForeignKey(fk, ConfigurationSource.DataAnnotation) == null)
{
fk.Builder.HasNavigations(
existingAmbiguousNavigation.IsDependentToPrincipal() ? PropertyIdentity.None : (PropertyIdentity?)null,
existingAmbiguousNavigation.IsDependentToPrincipal() ? (PropertyIdentity?)null : PropertyIdentity.None,
ConfigurationSource.DataAnnotation);
}
}
return entityType.FindNavigation(navigationMemberInfo)?.ForeignKey.Builder;
}
var ownership = entityType.FindOwnership();
if (ownership != null
&& ownership.PrincipalEntityType == targetEntityTypeBuilder.Metadata
&& ownership.PrincipalToDependent?.GetIdentifyingMemberInfo() != inverseNavigationPropertyInfo)
{
Logger.NonOwnershipInverseNavigationWarning(
entityType, navigationMemberInfo,
targetEntityTypeBuilder.Metadata, inverseNavigationPropertyInfo,
ownership.PrincipalToDependent.GetIdentifyingMemberInfo());
return null;
}
if (entityType.DefiningEntityType != null
&& entityType.DefiningEntityType == targetEntityTypeBuilder.Metadata
&& entityType.DefiningNavigationName != inverseNavigationPropertyInfo.GetSimpleMemberName())
{
Logger.NonDefiningInverseNavigationWarning(
entityType, navigationMemberInfo,
targetEntityTypeBuilder.Metadata, inverseNavigationPropertyInfo,
entityType.DefiningEntityType.GetRuntimeProperties()[entityType.DefiningNavigationName]);
return null;
}
return entityType.Model.ShouldBeOwned(entityType.ClrType)
&& !entityType.IsInOwnershipPath(targetEntityTypeBuilder.Metadata)
? targetEntityTypeBuilder.HasOwnership(
entityTypeBuilder.Metadata.ClrType,
inverseNavigationPropertyInfo,
navigationMemberInfo,
ConfigurationSource.Convention)
: targetEntityTypeBuilder.HasRelationship(
entityType,
inverseNavigationPropertyInfo,
navigationMemberInfo,
ConfigurationSource.DataAnnotation);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override bool Apply(
InternalModelBuilder modelBuilder,
Type type,
PropertyInfo navigationPropertyInfo,
Type targetClrType,
InversePropertyAttribute attribute)
{
var declaringType = navigationPropertyInfo.DeclaringType;
Debug.Assert(declaringType != null);
if (modelBuilder.Metadata.FindEntityType(declaringType) != null)
{
return true;
}
var leastDerivedEntityTypes = modelBuilder.Metadata.FindLeastDerivedEntityTypes(
declaringType,
t => !t.Builder.IsIgnored(navigationPropertyInfo.GetSimpleMemberName(), ConfigurationSource.DataAnnotation));
foreach (var leastDerivedEntityType in leastDerivedEntityTypes)
{
Apply(leastDerivedEntityType.Builder, navigationPropertyInfo, targetClrType, attribute);
}
return true;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override InternalRelationshipBuilder Apply(
InternalRelationshipBuilder relationshipBuilder, Navigation navigation, InversePropertyAttribute attribute)
{
return relationshipBuilder.Metadata.DeclaringEntityType.HasDefiningNavigation()
|| relationshipBuilder.Metadata.DeclaringEntityType.IsOwned()
|| relationshipBuilder.Metadata.PrincipalEntityType.HasDefiningNavigation()
|| relationshipBuilder.Metadata.PrincipalEntityType.IsOwned()
? relationshipBuilder
: ConfigureInverseNavigation(
navigation.DeclaringEntityType.Builder, navigation.GetIdentifyingMemberInfo(), navigation.GetTargetType().Builder,
attribute);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override bool Apply(
InternalEntityTypeBuilder entityTypeBuilder,
EntityType oldBaseType,
PropertyInfo navigationPropertyInfo,
Type targetClrType,
InversePropertyAttribute attribute)
{
var entityClrType = entityTypeBuilder.Metadata.ClrType;
if (navigationPropertyInfo.DeclaringType != entityClrType)
{
var newBaseType = entityTypeBuilder.Metadata.BaseType;
if (newBaseType == null)
{
Apply(entityTypeBuilder, navigationPropertyInfo, targetClrType, attribute);
}
else
{
var targetEntityType = entityTypeBuilder.Metadata.Model.FindEntityType(targetClrType);
if (targetEntityType == null)
{
return true;
}
RemoveInverseNavigation(entityTypeBuilder.Metadata, navigationPropertyInfo, targetEntityType);
}
}
return true;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public override bool ApplyIgnored(
InternalEntityTypeBuilder entityTypeBuilder,
PropertyInfo navigationPropertyInfo,
Type targetClrType,
InversePropertyAttribute attribute)
{
var targetEntityType = RelationshipDiscoveryConvention.GetTargetEntityTypeBuilder(
entityTypeBuilder, targetClrType, navigationPropertyInfo, null)?.Metadata;
if (targetEntityType == null)
{
return true;
}
RemoveInverseNavigation(entityTypeBuilder.Metadata, navigationPropertyInfo, targetEntityType);
return true;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public virtual InternalModelBuilder Apply(InternalModelBuilder modelBuilder)
{
var model = modelBuilder.Metadata;
foreach (var entityType in model.GetEntityTypes())
{
var inverseNavigations = GetInverseNavigations(entityType);
if (inverseNavigations == null)
{
continue;
}
foreach (var inverseNavigation in inverseNavigations)
{
foreach (var referencingNavigationWithAttribute in inverseNavigation.Value)
{
var ambiguousInverse = FindAmbiguousInverse(
referencingNavigationWithAttribute.Item1,
referencingNavigationWithAttribute.Item2,
model,
inverseNavigation.Value);
if (ambiguousInverse != null)
{
Logger.MultipleInversePropertiesSameTargetWarning(
new[]
{
Tuple.Create(
referencingNavigationWithAttribute.Item1, referencingNavigationWithAttribute.Item2.ClrType),
Tuple.Create(ambiguousInverse.Value.Item1, ambiguousInverse.Value.Item2.ClrType)
},
inverseNavigation.Key,
entityType.ClrType);
break;
}
}
}
}
return modelBuilder;
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public static bool IsAmbiguous(
[NotNull] EntityType entityType, [NotNull] MemberInfo navigation, [NotNull] EntityType targetEntityType)
{
var inverseNavigations = GetInverseNavigations(targetEntityType);
if (inverseNavigations == null)
{
return false;
}
foreach (var inverseNavigation in inverseNavigations)
{
if (inverseNavigation.Key.GetMemberType().IsAssignableFrom(entityType.ClrType)
&& IsAmbiguousInverse(navigation, entityType, entityType.Model, inverseNavigation.Value))
{
return true;
}
}
return false;
}
private static bool IsAmbiguousInverse(
MemberInfo navigation,
EntityType entityType,
Model model,
List<(MemberInfo, EntityType)> referencingNavigationsWithAttribute)
=> FindAmbiguousInverse(navigation, entityType, model, referencingNavigationsWithAttribute) != null;
private static (MemberInfo, EntityType)? FindAmbiguousInverse(
MemberInfo navigation,
EntityType entityType,
Model model,
List<(MemberInfo, EntityType)> referencingNavigationsWithAttribute)
{
if (referencingNavigationsWithAttribute.Count == 1)
{
return null;
}
List<(MemberInfo, EntityType)> tuplesToRemove = null;
(MemberInfo, EntityType)? ambiguousTuple = null;
foreach (var referencingTuple in referencingNavigationsWithAttribute)
{
var inverseTargetEntityType = model.FindActualEntityType(referencingTuple.Item2);
if ((inverseTargetEntityType?.Builder.IsIgnored(
referencingTuple.Item1.GetSimpleMemberName(), ConfigurationSource.DataAnnotation) != false))
{
if (tuplesToRemove == null)
{
tuplesToRemove = new List<(MemberInfo, EntityType)>();
}
tuplesToRemove.Add(referencingTuple);
continue;
}
if (!referencingTuple.Item1.IsSameAs(navigation)
|| !entityType.IsSameHierarchy(inverseTargetEntityType))
{
ambiguousTuple = referencingTuple;
break;
}
}
if (tuplesToRemove != null)
{
foreach (var tuple in tuplesToRemove)
{
referencingNavigationsWithAttribute.Remove(tuple);
}
}
return ambiguousTuple;
}
private static List<(MemberInfo, EntityType)> AddInverseNavigation(
EntityType entityType, MemberInfo navigation, EntityType targetEntityType, MemberInfo inverseNavigation)
{
var inverseNavigations = GetInverseNavigations(targetEntityType);
if (inverseNavigations == null)
{
inverseNavigations = new Dictionary<MemberInfo, List<(MemberInfo, EntityType)>>();
SetInverseNavigations(targetEntityType.Builder, inverseNavigations);
}
if (!inverseNavigations.TryGetValue(inverseNavigation, out var referencingNavigationsWithAttribute))
{
referencingNavigationsWithAttribute = new List<(MemberInfo, EntityType)>();
inverseNavigations[inverseNavigation] = referencingNavigationsWithAttribute;
}
foreach (var referencingTuple in referencingNavigationsWithAttribute)
{
if (referencingTuple.Item1.IsSameAs(navigation)
&& referencingTuple.Item2.ClrType == entityType.ClrType
&& entityType.Model.FindActualEntityType(referencingTuple.Item2) == entityType)
{
return referencingNavigationsWithAttribute;
}
}
referencingNavigationsWithAttribute.Add((navigation, entityType));
return referencingNavigationsWithAttribute;
}
private static void RemoveInverseNavigation(
EntityType entityType,
MemberInfo navigation,
EntityType targetEntityType)
{
var inverseNavigations = GetInverseNavigations(targetEntityType);
if (inverseNavigations == null)
{
return;
}
foreach (var inverseNavigationPair in inverseNavigations)
{
var inverseNavigation = inverseNavigationPair.Key;
var referencingNavigationsWithAttribute = inverseNavigationPair.Value;
for (var index = 0; index < referencingNavigationsWithAttribute.Count; index++)
{
var referencingTuple = referencingNavigationsWithAttribute[index];
if (referencingTuple.Item1.IsSameAs(navigation)
&& referencingTuple.Item2.ClrType == entityType.ClrType
&& entityType.Model.FindActualEntityType(referencingTuple.Item2) == entityType)
{
referencingNavigationsWithAttribute.RemoveAt(index);
if (referencingNavigationsWithAttribute.Count == 0)
{
inverseNavigations.Remove(inverseNavigation);
}
if (referencingNavigationsWithAttribute.Count == 1)
{
var otherEntityType = entityType.Model.FindActualEntityType(referencingNavigationsWithAttribute[0].Item2);
if (otherEntityType != null)
{
targetEntityType.Builder.HasRelationship(
otherEntityType,
(PropertyInfo)inverseNavigation,
(PropertyInfo)referencingNavigationsWithAttribute[0].Item1,
ConfigurationSource.DataAnnotation);
}
}
return;
}
}
}
}
private static Dictionary<MemberInfo, List<(MemberInfo, EntityType)>> GetInverseNavigations(
ConventionAnnotatable entityType)
=> entityType.FindAnnotation(InverseNavigationsAnnotationName)?.Value
as Dictionary<MemberInfo, List<(MemberInfo, EntityType)>>;
private static void SetInverseNavigations(
InternalAnnotatableBuilder entityTypeBuilder,
Dictionary<MemberInfo, List<(MemberInfo, EntityType)>> inverseNavigations)
=> entityTypeBuilder.HasAnnotation(InverseNavigationsAnnotationName, inverseNavigations, ConfigurationSource.Convention);
}
}
| 50.154827 | 136 | 0.60868 | [
"Apache-2.0"
] | jzabroski/EntityFrameworkCore | src/EFCore/Metadata/Conventions/Internal/InversePropertyAttributeConvention.cs | 27,535 | C# |
using Microsoft.Management.Infrastructure;
using System;
using System.Collections.Generic;
using System.Linq;
using SimCim.Core;
namespace SimCim.Root.V2
{
public class MSFTNCProvNewQuery : MSFTNCProvEvent
{
public MSFTNCProvNewQuery()
{
}
public MSFTNCProvNewQuery(IInfrastructureObjectScope scope, CimInstance instance): base(scope, instance)
{
}
public System.UInt32? ID
{
get
{
System.UInt32? result;
this.GetProperty("ID", out result);
return result;
}
set
{
this.SetProperty("ID", value);
}
}
public System.String Query
{
get
{
System.String result;
this.GetProperty("Query", out result);
return result;
}
set
{
this.SetProperty("Query", value);
}
}
public System.String QueryLanguage
{
get
{
System.String result;
this.GetProperty("QueryLanguage", out result);
return result;
}
set
{
this.SetProperty("QueryLanguage", value);
}
}
}
} | 22.6875 | 113 | 0.442149 | [
"Apache-2.0"
] | simonferquel/simcim | SimCim.Root.V2/ClassMSFTNCProvNewQuery.cs | 1,454 | C# |
using WebDriverManager.DriverConfigs;
using WebDriverManager.Helpers;
using WebDriverManager.Services;
using WebDriverManager.Services.Impl;
namespace WebDriverManager
{
public class DriverManager
{
static readonly object _object = new object();
private readonly IBinaryService _binaryService;
private readonly IVariableService _variableService;
public DriverManager()
{
_binaryService = new BinaryService();
_variableService = new VariableService();
}
public DriverManager(IBinaryService binaryService, IVariableService variableService)
{
_binaryService = binaryService;
_variableService = variableService;
}
public void SetUpDriver(string url, string binaryPath, string binaryName)
{
var zipPath = FileHelper.GetZipDestination(url);
binaryPath = _binaryService.SetupBinary(url, zipPath, binaryPath, binaryName);
_variableService.SetupVariable(binaryPath);
}
public void SetUpDriver(IDriverConfig config, string version = "Latest",
Architecture architecture = Architecture.Auto)
{
lock (_object)
{
architecture = architecture.Equals(Architecture.Auto)
? ArchitectureHelper.GetArchitecture()
: architecture;
version = version.Equals("Latest") ? config.GetLatestVersion() : version;
var url = architecture.Equals(Architecture.X32) ? config.GetUrl32() : config.GetUrl64();
url = UrlHelper.BuildUrl(url, version);
var binaryPath = FileHelper.GetBinDestination(config.GetName(), version, architecture,
config.GetBinaryName());
SetUpDriver(url, binaryPath, config.GetBinaryName());
}
}
}
}
| 37.75 | 105 | 0.616403 | [
"MIT"
] | sinanerkan/WebDriverManager.Net | WebDriverManager/DriverManager.cs | 1,914 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FruitGameManager : MonoBehaviour
{
ScoreManagerFruit smf;
[SerializeField] GameObject button;
button_animation ba;
[SerializeField] GameObject spawnerPrefab;
GameObject spawnerInstance;
Spawner spScript;
bool gameStarted = false;
void Start()
{
smf = GetComponent<ScoreManagerFruit>();
ba = button.GetComponentInChildren<button_animation>();
}
// Update is called once per frame
void Update()
{
if(ba.isButtonPushed() && !gameStarted)
{
print("aaa");
spawnerInstance = Instantiate(spawnerPrefab);
gameStarted = true;
spScript = spawnerInstance.GetComponent<Spawner>();
smf.reset();
}
if (gameStarted)
{
if (!ba.isButtonPushed())
{
button.SetActive(false);
}
if (spScript._stop)
{
Destroy(spawnerInstance);
button.SetActive(true);
gameStarted = false;
}
}
}
}
| 22.596154 | 63 | 0.560851 | [
"MIT"
] | Zargith/Keimyung_3DGA_Spring2021 | Assets/Scripts/FruitNinja/FruitGameManager.cs | 1,175 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Cms20190101.Models
{
public class DescribeMonitorGroupInstancesRequest : TeaModel {
[NameInMap("PageSize")]
[Validation(Required=false)]
public int? PageSize { get; set; }
[NameInMap("PageNumber")]
[Validation(Required=false)]
public int? PageNumber { get; set; }
[NameInMap("GroupId")]
[Validation(Required=true)]
public long GroupId { get; set; }
[NameInMap("Category")]
[Validation(Required=false)]
public string Category { get; set; }
[NameInMap("Keyword")]
[Validation(Required=false)]
public string Keyword { get; set; }
[NameInMap("InstanceIds")]
[Validation(Required=false)]
public string InstanceIds { get; set; }
}
}
| 24.282051 | 66 | 0.621964 | [
"Apache-2.0"
] | atptro/alibabacloud-sdk | cms-20190101/csharp/core/Models/DescribeMonitorGroupInstancesRequest.cs | 947 | C# |
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace Northwnd
{
public class Product
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.None)]
public int ProductID { get; set; }
[Required]
[StringLength(40)]
public string ProductName { get; set; }
[ForeignKey(nameof(SupplierLink))]
public int? SupplierID { get; set; }
[ForeignKey(nameof(CategoryLink))]
public int? CategoryID { get; set; }
[StringLength(20)]
public string QuantityPerUnit { get; set; }
public double? UnitPrice { get; set; }
public short? UnitsInStock { get; set; }
public short? UnitsOnOrder { get; set; }
public short? ReorderLevel { get; set; }
public bool Discontinued { get; set; }
public virtual Supplier SupplierLink { get; set; }
public virtual Category CategoryLink { get; set; }
public virtual ICollection<OrderDetail> OrderDetails { get; set; }
}
}
| 27.275 | 74 | 0.63978 | [
"MIT"
] | zmjack/Northwnd | NorthwndCore/Northwnd/Product.cs | 1,091 | C# |
using System;
using System.IO;
using GroupDocs.Conversion.Options.Convert;
namespace GroupDocs.Conversion.Examples.CSharp.BasicUsage
{
/// <summary>
/// This example demonstrates how to convert OTS file into XLS format.
/// For more details about OpenDocument Spreadsheet Template (.ots) to Microsoft Excel Binary File Format (.xls) conversion please check this documentation article
/// https://docs.groupdocs.com/conversion/net/convert-ots-to-xls
/// </summary>
internal static class ConvertOtsToXls
{
public static void Run()
{
string outputFolder = Constants.GetOutputDirectoryPath();
string outputFile = Path.Combine(outputFolder, "ots-converted-to.xls");
// Load the source OTS file
using (var converter = new GroupDocs.Conversion.Converter(Constants.SAMPLE_OTS))
{
SpreadsheetConvertOptions options = new SpreadsheetConvertOptions { Format = GroupDocs.Conversion.FileTypes.SpreadsheetFileType.Xls };
// Save converted XLS file
converter.Convert(outputFile, options);
}
Console.WriteLine("\nConversion to xls completed successfully. \nCheck output in {0}", outputFolder);
}
}
}
| 41.548387 | 168 | 0.666925 | [
"MIT"
] | groupdocs-conversion/GroupDocs.Conversion-for-.NET | Examples/GroupDocs.Conversion.Examples.CSharp/BasicUsage/ConvertToSpreadsheet/ConvertToXls/ConvertOtsToXls.cs | 1,288 | C# |
namespace AuthZyin.Authorization
{
using System;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.DependencyInjection;
/// <summary>
/// Auth extensions
/// </summary>
public static class AuthorizationExtensions
{
/// <summary>
/// Add authorization
/// </summary>
/// <param name="services">service collection</param>
/// <param name="cofigure">authorization options configuration action</param>
/// <returns>service collection</returns>
public static IServiceCollection AddAuthZyinAuthorization(this IServiceCollection services, Action<AuthZyinAuthorizationOptions> configure)
{
if (configure == null)
{
throw new ArgumentNullException(nameof(configure));
}
// Add current assembly as an ApplicationPart for the controller to work
services.AddControllers().AddApplicationPart(typeof(AuthorizationExtensions).Assembly);
// Add http context accessor - needed by AuthZyinContext registration
services.AddHttpContextAccessor();
// Configure authorization options. Use our own AuthZyinAuthorizationOptions to:
// 1. Expose the list of policies
// 2. Generate a new configue action to use against AuthorizationOptions.
var authZyinOptions = new AuthZyinAuthorizationOptions();
configure(authZyinOptions);
// Register IAuthorizationPolicyList and enable authoriztion
services.AddSingleton<IAuthorizationPolicyList>(authZyinOptions);
services.AddAuthorization(authZyinOptions.CapturedConfigureAction);
// Add authorization handler - must be registered as scoped
services.AddScoped<IAuthorizationHandler, AuthZyinHandler>();
return services;
}
}
}
| 39.770833 | 147 | 0.665794 | [
"MIT"
] | sidecus/authzyin | lib/Authorization/AuthorizationExtensions.cs | 1,911 | C# |
// Machine generated by peg-sharp 0.4.702.0 from benchmark/Benchmark.peg.
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using System.Security.Permissions;
[Serializable]
internal sealed class ParserException : Exception
{
public ParserException()
{
}
public ParserException(string message) : base(message)
{
}
public ParserException(int line, int col, int offset, string file, string input, string message) : base(string.Format("{0} at line {1} col {2}{3}", message, line, col, file != null ? (" in " + file) : "."))
{
}
[SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
private ParserException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
// Thread safe if Parser instances are not shared across threads.
internal sealed partial class Benchmark
{
public Benchmark()
{
m_nonterminals.Add("Program", new ParseMethod[]{this.DoParseProgramRule});
m_nonterminals.Add("Assignment", new ParseMethod[]{this.DoParseAssignmentRule});
m_nonterminals.Add("If", new ParseMethod[]{this.DoParseIfRule});
m_nonterminals.Add("Statement", new ParseMethod[]{this.DoParseStatementRule});
m_nonterminals.Add("Statements", new ParseMethod[]{this.DoParseStatementsRule});
m_nonterminals.Add("While", new ParseMethod[]{this.DoParseWhileRule});
m_nonterminals.Add("Compare", new ParseMethod[]{this.DoParseCompareRule});
m_nonterminals.Add("Expression", new ParseMethod[]{this.DoParseExpressionRule});
m_nonterminals.Add("Identifier", new ParseMethod[]{this.DoParseIdentifierRule});
m_nonterminals.Add("Sum", new ParseMethod[]{this.DoParseSumRule});
m_nonterminals.Add("Product", new ParseMethod[]{this.DoParseProductRule});
m_nonterminals.Add("Value", new ParseMethod[]{this.DoParseValue1Rule, this.DoParseValue2Rule, this.DoParseValue3Rule});
m_nonterminals.Add("Keywords", new ParseMethod[]{this.DoParseKeywordsRule});
m_nonterminals.Add("S", new ParseMethod[]{this.DoParseSRule});
m_nonterminals.Add("Space", new ParseMethod[]{this.DoParseSpaceRule});
OnCtorEpilog();
}
public string Parse(string input)
{
return DoParseFile(input, null, "Program");
}
// File is used for error reporting.
public string Parse(string input, string file)
{
return DoParseFile(input, file, "Program");
}
#region Non-Terminal Parse Methods
// Program := S Statements
private State DoParseProgramRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParse(s, r, "S");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Statements");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
value = results[0].Text;
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Assignment := Identifier '=' S Expression
private State DoParseAssignmentRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParse(s, r, "Identifier");},
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "=");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Expression");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// If := 'if' S Expression 'then' S Statements 'else' S Statements 'end' S
private State DoParseIfRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "if");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Expression");},
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "then");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Statements");},
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "else");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Statements");},
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "end");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Statement := If / While / Assignment / Expression
private State DoParseStatementRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoChoice(_state, results,
delegate (State s, List<Result> r) {return DoParse(s, r, "If");},
delegate (State s, List<Result> r) {return DoParse(s, r, "While");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Assignment");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Expression");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Statements := Statement+
private State DoParseStatementsRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoRepetition(_state, results, 1, 2147483647,
delegate (State s, List<Result> r) {return DoParse(s, r, "Statement");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// While := 'while' S Expression 'do' S Statements 'end' S
private State DoParseWhileRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "while");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Expression");},
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "do");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Statements");},
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "end");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Compare := Sum (('<=' / '>=' / '==' / '!=' / '<' / '>') S Sum)?
private State DoParseCompareRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParse(s, r, "Sum");},
delegate (State s, List<Result> r) {return DoRepetition(s, r, 0, 1,
delegate (State s2, List<Result> r2) {return DoSequence(s2, r2,
delegate (State s3, List<Result> r3) {return DoChoice(s3, r3,
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "<=");},
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, ">=");},
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "==");},
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "!=");},
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "<");},
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, ">");});},
delegate (State s3, List<Result> r3) {return DoParse(s3, r3, "S");},
delegate (State s3, List<Result> r3) {return DoParse(s3, r3, "Sum");});});});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Expression := Compare
private State DoParseExpressionRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoParse(_state, results, "Compare");
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Identifier := !Keywords [a-zA-Z] [a-zA-Z0-9]* S
private State DoParseIdentifierRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoNAssert(s, r,
delegate (State s2, List<Result> r2) {return DoParse(s2, r2, "Keywords");});},
delegate (State s, List<Result> r) {return DoParseRange(s, r, false, string.Empty, "azAZ", null, "[a-zA-Z]");},
delegate (State s, List<Result> r) {return DoRepetition(s, r, 0, 2147483647,
delegate (State s2, List<Result> r2) {return DoParseRange(s2, r2, false, string.Empty, "azAZ09", null, "[a-zA-Z0-9]");});},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Sum := Product (('+' / '-') S Product)*
private State DoParseSumRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParse(s, r, "Product");},
delegate (State s, List<Result> r) {return DoRepetition(s, r, 0, 2147483647,
delegate (State s2, List<Result> r2) {return DoSequence(s2, r2,
delegate (State s3, List<Result> r3) {return DoChoice(s3, r3,
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "+");},
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "-");});},
delegate (State s3, List<Result> r3) {return DoParse(s3, r3, "S");},
delegate (State s3, List<Result> r3) {return DoParse(s3, r3, "Product");});});});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Product := Value (('*' / '/') S Value)*
private State DoParseProductRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParse(s, r, "Value");},
delegate (State s, List<Result> r) {return DoRepetition(s, r, 0, 2147483647,
delegate (State s2, List<Result> r2) {return DoSequence(s2, r2,
delegate (State s3, List<Result> r3) {return DoChoice(s3, r3,
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "*");},
delegate (State s4, List<Result> r4) {return DoParseLiteral(s4, r4, "/");});},
delegate (State s3, List<Result> r3) {return DoParse(s3, r3, "S");},
delegate (State s3, List<Result> r3) {return DoParse(s3, r3, "Value");});});});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Value := [0-9]+ S
private State DoParseValue1Rule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoRepetition(s, r, 1, 2147483647,
delegate (State s2, List<Result> r2) {return DoParseRange(s2, r2, false, string.Empty, "09", null, "[0-9]");});},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Value := Identifier
private State DoParseValue2Rule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoParse(_state, results, "Identifier");
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Value := '(' Expression ')' S
private State DoParseValue3Rule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, "(");},
delegate (State s, List<Result> r) {return DoParse(s, r, "Expression");},
delegate (State s, List<Result> r) {return DoParseLiteral(s, r, ")");},
delegate (State s, List<Result> r) {return DoParse(s, r, "S");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Keywords := ('do' / 'else' / 'end' / 'if' / 'then' / 'while') ![a-zA-Z0-9]
private State DoParseKeywordsRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoSequence(_state, results,
delegate (State s, List<Result> r) {return DoChoice(s, r,
delegate (State s2, List<Result> r2) {return DoParseLiteral(s2, r2, "do");},
delegate (State s2, List<Result> r2) {return DoParseLiteral(s2, r2, "else");},
delegate (State s2, List<Result> r2) {return DoParseLiteral(s2, r2, "end");},
delegate (State s2, List<Result> r2) {return DoParseLiteral(s2, r2, "if");},
delegate (State s2, List<Result> r2) {return DoParseLiteral(s2, r2, "then");},
delegate (State s2, List<Result> r2) {return DoParseLiteral(s2, r2, "while");});},
delegate (State s, List<Result> r) {return DoNAssert(s, r,
delegate (State s2, List<Result> r2) {return DoParseRange(s2, r2, false, string.Empty, "azAZ09", null, "[a-zA-Z0-9]");});});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// S := Space*
private State DoParseSRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoRepetition(_state, results, 0, 2147483647,
delegate (State s, List<Result> r) {return DoParse(s, r, "Space");});
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
// Space := [ \t\r\n]
private State DoParseSpaceRule(State _state, List<Result> _outResults)
{
State _start = _state;
List<Result> results = new List<Result>();
_state = DoParseRange(_state, results, false, " \t\r\n", string.Empty, null, "[ \t\r\n]");
if (_state.Parsed)
{
string value = results.Count > 0 ? results[0].Value : default(string);
_outResults.Add(new Result(this, _start.Index, _state.Index - _start.Index, m_input, value));
}
return _state;
}
#endregion
#region Private Helper Methods
partial void OnCtorEpilog();
partial void OnParseProlog();
partial void OnParseEpilog(State state);
private string DoParseFile(string input, string file, string rule)
{
m_file = file;
m_input = m_file; // we need to ensure that m_file is used or we will (in some cases) get a compiler warning
m_input = input + "\x0"; // add a sentinel so we can avoid range checks
m_cache.Clear();
State state = new State(0, true);
List<Result> results = new List<Result>();
OnParseProlog();
state = DoParse(state, results, rule);
int i = state.Index;
if (!state.Parsed)
DoThrow(state.Errors.Index, state.Errors.ToString());
else if (i < input.Length)
if (state.Errors.Expected.Length > 0)
DoThrow(state.Errors.Index, state.Errors.ToString());
else
DoThrow(state.Errors.Index, "Not all input was consumed starting from '" + input.Substring(i, Math.Min(16, input.Length - i)) + "'");
OnParseEpilog(state);
return results[0].Value;
}
public string DoEscapeAll(string s)
{
System.Text.StringBuilder builder = new System.Text.StringBuilder(s.Length);
foreach (char ch in s)
{
if (ch == '\n')
builder.Append("\\n");
else if (ch == '\r')
builder.Append("\\r");
else if (ch == '\t')
builder.Append("\\t");
else if (ch < ' ')
builder.AppendFormat("\\x{0:X2}", (int) ch);
else
builder.Append(ch);
}
return builder.ToString();
}
// This is normally only used for error handling so it doesn't need to be too
// fast. If it somehow does become a bottleneck for some parsers they can
// replace it with the custom-methods setting.
private int DoGetLine(int index)
{
int line = 1;
int i = 0;
while (i < index)
{
char ch = m_input[i++];
if (ch == '\r' && m_input[i] == '\n')
{
++i;
++line;
}
else if (ch == '\r')
{
++line;
}
else if (ch == '\n')
{
++line;
}
}
return line;
}
private int DoGetCol(int index)
{
int start = index;
while (index > 0 && m_input[index - 1] != '\n' && m_input[index - 1] != '\r')
{
--index;
}
return start - index;
}
private void DoThrow(int index, string format, params object[] args)
{
int line = DoGetLine(index);
int col = DoGetCol(index) + 1; // editors seem to usually use 1-based cols so that's what we will report
// We need this retarded if or string.Format will throw an error if it
// gets a format string like "Expected { or something".
if (args != null && args.Length > 0)
throw new ParserException(line, col, index, m_file, m_input, DoEscapeAll(string.Format(format, args)));
else
throw new ParserException(line, col, index, m_file, m_input, DoEscapeAll(format));
}
private State DoParseLiteral(State state, List<Result> results, string literal)
{
State result;
if (string.Compare(m_input, state.Index, literal, 0, literal.Length) == 0)
{
results.Add(new Result(this, state.Index, literal.Length, m_input, default(string)));
result = new State(state.Index + literal.Length, true, state.Errors);
}
else
{
result = new State(state.Index, false, ErrorSet.Combine(state.Errors, new ErrorSet(state.Index, literal)));
}
return result;
}
private State DoParse(State state, List<Result> results, string nonterminal)
{
State start = state;
CacheValue cache;
CacheKey key = new CacheKey(nonterminal, start.Index);
if (!m_cache.TryGetValue(key, out cache))
{
ParseMethod[] methods = m_nonterminals[nonterminal];
int oldCount = results.Count;
state = DoChoice(state, results, methods);
bool hasResult = state.Parsed && results.Count > oldCount;
string value = hasResult ? results[results.Count - 1].Value : default(string);
cache = new CacheValue(state, value, hasResult);
m_cache.Add(key, cache);
}
else
{
if (cache.HasResult)
results.Add(new Result(this, start.Index, cache.State.Index - start.Index, m_input, cache.Value));
}
return cache.State;
}
private State DoChoice(State state, List<Result> results, params ParseMethod[] methods)
{
State start = state;
int startResult = results.Count;
foreach (ParseMethod method in methods)
{
State temp = method(state, results);
if (temp.Parsed)
{
state = temp;
break;
}
else
{
state = new State(start.Index, false, ErrorSet.Combine(state.Errors, temp.Errors));
results.RemoveRange(startResult, results.Count - startResult);
}
}
return state;
}
private State DoSequence(State state, List<Result> results, params ParseMethod[] methods)
{
State start = state;
int startResult = results.Count;
foreach (ParseMethod method in methods)
{
State temp = method(state, results);
if (temp.Parsed)
{
state = temp;
}
else
{
state = new State(start.Index, false, ErrorSet.Combine(start.Errors, temp.Errors));
results.RemoveRange(startResult, results.Count - startResult);
break;
}
}
return state;
}
private State DoRepetition(State state, List<Result> results, int min, int max, ParseMethod method)
{
State start = state;
int count = 0;
while (count <= max)
{
State temp = method(state, results);
if (temp.Parsed && temp.Index > state.Index)
{
state = temp;
++count;
}
else
{
state = new State(state.Index, true, ErrorSet.Combine(state.Errors, temp.Errors));
break;
}
}
if (count < min || count > max)
state = new State(start.Index, false, ErrorSet.Combine(start.Errors, state.Errors));
return state;
}
private State DoParseRange(State state, List<Result> results, bool inverted, string chars, string ranges, UnicodeCategory[] categories, string label)
{
char ch = m_input[state.Index];
bool matched = chars.IndexOf(ch) >= 0;
for (int i = 0; i < ranges.Length && !matched; i += 2)
{
matched = ranges[i] <= ch && ch <= ranges[i + 1];
}
for (int i = 0; categories != null && i < categories.Length && !matched; ++i)
{
matched = char.GetUnicodeCategory(ch) == categories[i];
}
if (inverted)
matched = !matched && ch != '\x0';
if (matched)
{
results.Add(new Result(this, state.Index, 1, m_input, default(string)));
return new State(state.Index + 1, true, state.Errors);
}
return new State(state.Index, false, ErrorSet.Combine(state.Errors, new ErrorSet(state.Index, label)));
}
private State DoNAssert(State state, List<Result> results, ParseMethod method)
{
State temp = method(state, results);
state = new State(state.Index, !temp.Parsed, state.Errors);
return state;
}
#endregion
#region Private Types
private struct CacheKey : IEquatable<CacheKey>
{
public CacheKey(string rule, int index)
{
m_rule = rule;
m_index = index;
}
public override bool Equals(object obj)
{
if (obj == null)
return false;
if (GetType() != obj.GetType())
return false;
CacheKey rhs = (CacheKey) obj;
return this == rhs;
}
public bool Equals(CacheKey rhs)
{
return this == rhs;
}
public static bool operator==(CacheKey lhs, CacheKey rhs)
{
if (lhs.m_rule != rhs.m_rule)
return false;
if (lhs.m_index != rhs.m_index)
return false;
return true;
}
public static bool operator!=(CacheKey lhs, CacheKey rhs)
{
return !(lhs == rhs);
}
public override int GetHashCode()
{
int hash = 0;
unchecked
{
hash += m_rule.GetHashCode();
hash += m_index.GetHashCode();
}
return hash;
}
private string m_rule;
private int m_index;
}
private struct CacheValue
{
public CacheValue(State state, string value, bool hasResult)
{
State = state;
Value = value;
HasResult = hasResult;
}
public State State;
public string Value;
public bool HasResult;
}
private delegate State ParseMethod(State state, List<Result> results);
// These are either an error that caused parsing to fail or the reason a
// successful parse stopped.
private struct ErrorSet
{
public ErrorSet(int index, string expected)
{
Index = index;
Expected = new string[]{expected};
}
public ErrorSet(int index, string[] expected)
{
Index = index;
Expected = expected;
}
// The location associated with the errors. For a failed parse this will be the
// same as State.Index. For a successful parse it will be State.Index or later.
public int Index;
// This will be the name of something which was expected, but not found.
public string[] Expected;
public static ErrorSet Combine(ErrorSet lhs, ErrorSet rhs)
{
if (lhs.Index > rhs.Index)
{
return lhs;
}
else if (lhs.Index < rhs.Index)
{
return rhs;
}
else
{
List<string> errors = new List<string>(lhs.Expected.Length + rhs.Expected.Length);
errors.AddRange(lhs.Expected);
foreach (string err in rhs.Expected)
{
if (errors.IndexOf(err) < 0)
errors.Add(err);
}
return new ErrorSet(lhs.Index, errors.ToArray());
}
}
public override string ToString()
{
if (Expected.Length > 0)
return string.Format("Expected {0}", string.Join(" or ", Expected));
else
return "<none>";
}
}
// The state of the parser.
private struct State
{
public State(int index, bool parsed)
{
Index = index;
Parsed = parsed;
Errors = new ErrorSet(index, new string[0]);
}
public State(int index, bool parsed, ErrorSet errors)
{
Index = index;
Parsed = parsed;
Errors = errors;
}
// Index of the first unconsumed character.
public int Index;
// True if the expression associated with the state successfully parsed.
public bool Parsed;
// If Parsed is false then this will explain why. If Parsed is true it will
// say why the parse stopped.
public ErrorSet Errors;
}
// The result of parsing a literal or non-terminal.
private struct Result
{
public Result(Benchmark parser, int index, int length, string input, string value)
{
m_parser = parser;
m_index = index;
m_length = length;
m_input = input;
Value = value;
}
// The text which was parsed by the terminal or non-terminal.
public string Text {get {return m_input.Substring(m_index, m_length);}}
// The 0-based character index the (non)terminal started on.
public int Index {get {return m_index;}}
// The 1-based line number the (non)terminal started on.
public int Line {get {return m_parser.DoGetLine(m_index);}}
// The 1-based column number the (non)terminal started on.
public int Col {get {return m_parser.DoGetCol(m_index);}}
// For non-terminals this will be the result of the semantic action,
// otherwise it will be the default value.
public string Value;
private Benchmark m_parser;
private int m_index;
private int m_length;
private string m_input;
}
#endregion
#region Fields
private string m_input;
private string m_file;
private Dictionary<string, ParseMethod[]> m_nonterminals = new Dictionary<string, ParseMethod[]>();
private Dictionary<CacheKey, CacheValue> m_cache = new Dictionary<CacheKey, CacheValue>();
#endregion
}
| 30.89357 | 207 | 0.662384 | [
"MIT"
] | louisukiri/peg-sharp | benchmark/Benchmark.cs | 27,866 | 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("LargestPrimeFactor")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("LargestPrimeFactor")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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("9a41cc5a-3b4d-4e8f-97f7-6cdfe809cc78")]
// 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")]
| 38.081081 | 84 | 0.747339 | [
"MIT"
] | vladislav-karamfilov/TelerikAcademy | C# Projects/ConsoleApplication2/LargestPrimeFactor/Properties/AssemblyInfo.cs | 1,412 | C# |
using System;
namespace Nyan.Core.Modules.Diagnostics {
[AttributeUsage(AttributeTargets.Method)]
public sealed class DiagnosticsEvaluationSetupAttribute : Attribute
{
public string Name;
public string Category;
public bool Critical;
}
} | 25.363636 | 71 | 0.706093 | [
"MIT"
] | bucknellu/Nyan | Core/Modules/Diagnostics/DiagnosticsEvaluationSetupAttribute.cs | 281 | C# |
/*
* Copyright (c) 2014 Universal Technical Resource Services, Inc.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using ATMLCommonLibrary.controls.awb;
namespace ATMLCommonLibrary.controls
{
partial class UUTDescriptionControl
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(UUTDescriptionControl));
this.edtName = new System.Windows.Forms.TextBox();
this.edtUUID = new ATMLCommonLibrary.controls.awb.AWBTextBox(this.components);
this.edtVersion = new ATMLCommonLibrary.controls.awb.AWBTextBox(this.components);
this.btnAddUUID = new System.Windows.Forms.Button();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.rbSoftware = new System.Windows.Forms.RadioButton();
this.rbHardware = new System.Windows.Forms.RadioButton();
this.panelUUT = new System.Windows.Forms.Panel();
this.softwareUUTControl = new ATMLCommonLibrary.controls.uut.SoftwareUUTControl();
this.hardwareUUTControl = new ATMLCommonLibrary.controls.uut.HardwareUUTControl();
this.securityClassificationControl = new WindowsFormsApplication10.SecurityClassificationControl();
this.label2 = new ATMLCommonLibrary.controls.HelpLabel(this.components);
this.label1 = new ATMLCommonLibrary.controls.HelpLabel(this.components);
this.label3 = new ATMLCommonLibrary.controls.HelpLabel(this.components);
this.label6 = new ATMLCommonLibrary.controls.HelpLabel(this.components);
this.requiredUUIDValidator = new ATMLCommonLibrary.controls.validators.RequiredFieldValidator();
this.errorProvider = new System.Windows.Forms.ErrorProvider(this.components);
this.groupBox1.SuspendLayout();
this.panelUUT.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit();
this.SuspendLayout();
//
// edtName
//
this.edtName.Location = new System.Drawing.Point(62, 10);
this.edtName.Name = "edtName";
this.edtName.Size = new System.Drawing.Size(489, 20);
this.edtName.TabIndex = 1;
//
// edtUUID
//
this.edtUUID.AttributeName = null;
this.edtUUID.Location = new System.Drawing.Point(62, 62);
this.edtUUID.Name = "edtUUID";
this.edtUUID.Size = new System.Drawing.Size(488, 20);
this.edtUUID.TabIndex = 7;
this.edtUUID.Value = null;
this.edtUUID.ValueType = ATMLCommonLibrary.controls.awb.AWBTextBox.eValueType.xsString;
//
// edtVersion
//
this.edtVersion.AttributeName = null;
this.edtVersion.Location = new System.Drawing.Point(62, 36);
this.edtVersion.Name = "edtVersion";
this.edtVersion.Size = new System.Drawing.Size(100, 20);
this.edtVersion.TabIndex = 3;
this.edtVersion.Value = null;
this.edtVersion.ValueType = ATMLCommonLibrary.controls.awb.AWBTextBox.eValueType.xsString;
//
// btnAddUUID
//
this.btnAddUUID.BackColor = System.Drawing.Color.Transparent;
this.btnAddUUID.FlatAppearance.BorderSize = 0;
this.btnAddUUID.FlatStyle = System.Windows.Forms.FlatStyle.Flat;
this.btnAddUUID.Image = ((System.Drawing.Image)(resources.GetObject("btnAddUUID.Image")));
this.btnAddUUID.Location = new System.Drawing.Point(530, 62);
this.btnAddUUID.Name = "btnAddUUID";
this.btnAddUUID.Size = new System.Drawing.Size(20, 20);
this.btnAddUUID.TabIndex = 8;
this.btnAddUUID.UseVisualStyleBackColor = false;
this.btnAddUUID.Click += new System.EventHandler(this.btnAddUUID_Click);
//
// groupBox1
//
this.groupBox1.Controls.Add(this.rbSoftware);
this.groupBox1.Controls.Add(this.rbHardware);
this.groupBox1.Location = new System.Drawing.Point(587, 5);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(141, 77);
this.groupBox1.TabIndex = 9;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "UUT Type";
//
// rbSoftware
//
this.rbSoftware.AutoSize = true;
this.rbSoftware.Location = new System.Drawing.Point(15, 46);
this.rbSoftware.Name = "rbSoftware";
this.rbSoftware.Size = new System.Drawing.Size(67, 17);
this.rbSoftware.TabIndex = 1;
this.rbSoftware.TabStop = true;
this.rbSoftware.Text = "Software";
this.rbSoftware.UseVisualStyleBackColor = true;
this.rbSoftware.CheckedChanged += new System.EventHandler(this.rbSoftware_CheckedChanged);
//
// rbHardware
//
this.rbHardware.AutoSize = true;
this.rbHardware.Location = new System.Drawing.Point(15, 22);
this.rbHardware.Name = "rbHardware";
this.rbHardware.Size = new System.Drawing.Size(71, 17);
this.rbHardware.TabIndex = 0;
this.rbHardware.TabStop = true;
this.rbHardware.Text = "Hardware";
this.rbHardware.UseVisualStyleBackColor = true;
this.rbHardware.CheckedChanged += new System.EventHandler(this.rbHardware_CheckedChanged);
//
// panelUUT
//
this.panelUUT.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.panelUUT.Controls.Add(this.hardwareUUTControl);
this.panelUUT.Controls.Add(this.softwareUUTControl);
this.panelUUT.Location = new System.Drawing.Point(0, 89);
this.panelUUT.Name = "panelUUT";
this.panelUUT.Size = new System.Drawing.Size(739, 429);
this.panelUUT.TabIndex = 10;
//
// softwareUUTControl
//
this.softwareUUTControl.BackColor = System.Drawing.Color.AliceBlue;
this.softwareUUTControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.softwareUUTControl.Location = new System.Drawing.Point(0, 0);
this.softwareUUTControl.Name = "softwareUUTControl";
this.softwareUUTControl.Size = new System.Drawing.Size(739, 429);
this.softwareUUTControl.SoftwareUUT = null;
this.softwareUUTControl.TabIndex = 1;
//
// hardwareUUTControl
//
this.hardwareUUTControl.BackColor = System.Drawing.Color.AliceBlue;
this.hardwareUUTControl.Dock = System.Windows.Forms.DockStyle.Fill;
this.hardwareUUTControl.Location = new System.Drawing.Point(0, 0);
this.hardwareUUTControl.Name = "hardwareUUTControl";
this.hardwareUUTControl.SchemaTypeName = null;
this.hardwareUUTControl.Size = new System.Drawing.Size(739, 429);
this.hardwareUUTControl.TabIndex = 0;
this.hardwareUUTControl.TargetNamespace = null;
//
// securityClassificationControl
//
this.securityClassificationControl.Classified = false;
this.securityClassificationControl.Location = new System.Drawing.Point(170, 36);
this.securityClassificationControl.Name = "securityClassificationControl";
this.securityClassificationControl.SchemaTypeName = null;
this.securityClassificationControl.SecurityClassification = null;
this.securityClassificationControl.Size = new System.Drawing.Size(380, 21);
this.securityClassificationControl.TabIndex = 4;
this.securityClassificationControl.TargetNamespace = null;
//
// label2
//
this.label2.AutoSize = true;
this.label2.HelpMessageKey = "UUTDescription.uuid";
this.label2.Location = new System.Drawing.Point(22, 65);
this.label2.Name = "label2";
this.label2.RequiredField = false;
this.label2.RequiredFieldMarkerFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Size = new System.Drawing.Size(34, 13);
this.label2.TabIndex = 6;
this.label2.Text = "UUID";
//
// label1
//
this.label1.AutoSize = true;
this.label1.HelpMessageKey = "UUTDescription.version";
this.label1.Location = new System.Drawing.Point(14, 39);
this.label1.Name = "label1";
this.label1.RequiredField = false;
this.label1.RequiredFieldMarkerFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Size = new System.Drawing.Size(42, 13);
this.label1.TabIndex = 2;
this.label1.Text = "Version";
//
// label3
//
this.label3.AutoSize = true;
this.label3.HelpMessageKey = "UUTDescription.name";
this.label3.Location = new System.Drawing.Point(21, 13);
this.label3.Name = "label3";
this.label3.RequiredField = false;
this.label3.RequiredFieldMarkerFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Size = new System.Drawing.Size(35, 13);
this.label3.TabIndex = 0;
this.label3.Text = "Name";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Arial Black", 12.75F, System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.ForeColor = System.Drawing.Color.Red;
this.label6.HelpMessageKey = null;
this.label6.Location = new System.Drawing.Point(9, 63);
this.label6.Name = "label6";
this.label6.RequiredField = false;
this.label6.RequiredFieldMarkerFont = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Size = new System.Drawing.Size(19, 23);
this.label6.TabIndex = 5;
this.label6.Text = "*";
//
// requiredUUIDValidator
//
this.requiredUUIDValidator.ControlToValidate = this.edtUUID;
this.requiredUUIDValidator.ErrorMessage = "A UUID is required.";
this.requiredUUIDValidator.ErrorProvider = this.errorProvider;
this.requiredUUIDValidator.Icon = null;
this.requiredUUIDValidator.InitialValue = null;
this.requiredUUIDValidator.IsEnabled = true;
//
// errorProvider
//
this.errorProvider.ContainerControl = this;
//
// UUTDescriptionControl
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.AliceBlue;
this.Controls.Add(this.panelUUT);
this.Controls.Add(this.securityClassificationControl);
this.Controls.Add(this.edtName);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
this.Controls.Add(this.edtVersion);
this.Controls.Add(this.btnAddUUID);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.label3);
this.Controls.Add(this.label6);
this.Controls.Add(this.edtUUID);
this.MinimumSize = new System.Drawing.Size(742, 428);
this.Name = "UUTDescriptionControl";
this.Size = new System.Drawing.Size(742, 521);
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.panelUUT.ResumeLayout(false);
((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.TextBox edtName;
private ATMLCommonLibrary.controls.HelpLabel label2;
private AWBTextBox edtUUID;
private ATMLCommonLibrary.controls.HelpLabel label1;
private AWBTextBox edtVersion;
private System.Windows.Forms.Button btnAddUUID;
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.RadioButton rbSoftware;
private System.Windows.Forms.RadioButton rbHardware;
private ATMLCommonLibrary.controls.HelpLabel label3;
private ATMLCommonLibrary.controls.HelpLabel label6;
private WindowsFormsApplication10.SecurityClassificationControl securityClassificationControl;
private System.Windows.Forms.Panel panelUUT;
private uut.HardwareUUTControl hardwareUUTControl;
private uut.SoftwareUUTControl softwareUUTControl;
private validators.RequiredFieldValidator requiredUUIDValidator;
private System.Windows.Forms.ErrorProvider errorProvider;
}
}
| 51.675676 | 188 | 0.612252 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | UtrsSoftware/ATMLWorkBench | ATMLLibraries/ATMLCommonLibrary/controls/uut/UUTDescriptionControl.Designer.cs | 15,298 | C# |
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using GestorONG.DAL;
using GestorONG.DataModel;
namespace GestorONG.Controllers
{
public class PeriodicidadesController : Controller
{
private GestorONGDContext db = new GestorONGDContext();
// GET: Periodicidades
public ActionResult Index()
{
return View(db.periodicidades.ToList());
}
// GET: Periodicidades/Create
public ActionResult Create()
{
return View();
}
// POST: Periodicidades/Create
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,nombre")] periodicidades periodicidades)
{
if (ModelState.IsValid)
{
db.periodicidades.Add(periodicidades);
db.SaveChanges();
TempData["Acierto"] = "La periodicidad " + periodicidades.nombre + " ha sido creada correctamente.";
return RedirectToAction("Index");
}
TempData["Error"] = "Error al crear la periodicidad. Por favor, inténtalo de nuevo.";
return View(periodicidades);
}
// GET: Periodicidades/Edit/5
public ActionResult Edit(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
periodicidades periodicidades = db.periodicidades.Find(id);
if (periodicidades == null)
{
return HttpNotFound();
}
return View(periodicidades);
}
// POST: Periodicidades/Edit/5
// Para protegerse de ataques de publicación excesiva, habilite las propiedades específicas a las que desea enlazarse. Para obtener
// más información vea http://go.microsoft.com/fwlink/?LinkId=317598.
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Edit([Bind(Include = "id,nombre")] periodicidades periodicidades)
{
if (ModelState.IsValid)
{
db.Entry(periodicidades).State = EntityState.Modified;
db.SaveChanges();
TempData["Acierto"] = "La periodicidad " + periodicidades.nombre + " ha sido editada correctamente.";
return RedirectToAction("Index");
}
TempData["Error"] = "Error al editar la periodicidad. Por favor, inténtalo de nuevo.";
return View(periodicidades);
}
// GET: Periodicidades/Delete/5
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
periodicidades periodicidades = db.periodicidades.Find(id);
if (periodicidades == null)
{
return HttpNotFound();
}
return View(periodicidades);
}
// POST: Periodicidades/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
periodicidades periodicidades = db.periodicidades.Find(id);
db.periodicidades.Remove(periodicidades);
db.SaveChanges();
TempData["Acierto"] = "La periodicidad " + periodicidades.nombre + " ha sido eliminada correctamente.";
return RedirectToAction("Index");
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
}
}
| 34.40678 | 140 | 0.58202 | [
"MIT"
] | joakDA/gestor-ongd-sps | GestorONG/Controllers/PeriodicidadesController.cs | 4,072 | C# |
namespace EstateManagment.Data.Models
{
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using static DataConstants;
public class Company
{
public int Id { get; set; }
[Required]
[RegularExpression(RegexLatinCompanyNames)]
[MinLength(CompanyNameMinLength)]
[MaxLength(CompanyNameMaxLength)]
public string Name { get; set; }
[Required]
[MinLength(PropertyAddressMinLength)]
[MaxLength(PropertyAddressMaxLength)]
public string Address { get; set; }
[Required]
[MinLength(CompanyBulstatMinLength)]
[MaxLength(CompanyBulstatMaxLength)]
[RegularExpression(RegexBulstat)]
public string Bulstat { get; set; }
[Required]
[RegularExpression(RegexLatinNames)]
[MinLength(ClientNameMinLength)]
[MaxLength(ClientNameMaxLength)]
public string AccountablePerson { get; set; }
public virtual ICollection<Property> Properties { get; set; } = new HashSet<Property>();
//public virtual ICollection<ParkingSlot> ParkingSlots { get; set; } = new HashSet<ParkingSlot>();
}
}
| 29.121951 | 106 | 0.657454 | [
"MIT"
] | LuGeorgiev/CSharpSelfLearning | ASP.Core.SelfLearning/EstateManagment/EstateManagment.Data.Model/Company.cs | 1,196 | C# |
using System;
using OpenTelemetry.ClrProfiler.Managed.Logging;
namespace OpenTelemetry.ClrProfiler.Managed.Util
{
/// <summary>
/// Helpers to access environment variables
/// </summary>
internal static class EnvironmentHelpers
{
private static readonly ILogger Logger = ConsoleLogger.Create(typeof(EnvironmentHelpers));
/// <summary>
/// Safe wrapper around Environment.GetEnvironmentVariable
/// </summary>
/// <param name="key">Name of the environment variable to fetch</param>
/// <param name="defaultValue">Value to return in case of error</param>
/// <returns>The value of the environment variable, or the default value if an error occured</returns>
public static string GetEnvironmentVariable(string key, string defaultValue = null)
{
try
{
return Environment.GetEnvironmentVariable(key);
}
catch (Exception ex)
{
Logger.Warning(ex, "Error while reading environment variable {EnvironmentVariable}", key);
}
return defaultValue;
}
}
}
| 34.235294 | 110 | 0.628007 | [
"Apache-2.0"
] | mic-max/opentelemetry-dotnet-instrumentation | src/OpenTelemetry.ClrProfiler.Managed/Util/EnvironmentHelpers.cs | 1,164 | C# |
// -----------------------------------------------------------------------
// Copyright (c) David Kean. All rights reserved.
// -----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;
namespace AudioSwitcher.ComponentModel
{
// Provides the base class for observable objects
internal abstract class ObservableObject : INotifyPropertyChanged
{
protected ObservableObject()
{
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged([CallerMemberName]string propertyName = null)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs e)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, e);
}
}
}
}
| 29.676471 | 89 | 0.553023 | [
"MIT"
] | Black-Sunlight/audio-switcher | src/AudioSwitcher/ComponentModel/ObservableObject.cs | 1,011 | C# |
using System;
using Newtonsoft.Json.Linq;
namespace Beyova
{
/// <summary>
///
/// </summary>
public class EntityObjectAudit : BaseAuditObject<Guid?, JToken>, IIdentifier
{
}
} | 16.833333 | 80 | 0.628713 | [
"Apache-2.0"
] | JTOne123/CommonFoundation | development/Beyova.StandardContract/Model/Audit/EntityObjectAudit.cs | 204 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Utilities;
using Microsoft.Extensions.DependencyInjection;
namespace Microsoft.EntityFrameworkCore.Query
{
/// <summary>
/// <para>
/// Service dependencies parameter class for <see cref="CompiledQueryCacheKeyGenerator" />
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// <para>
/// Do not construct instances of this class directly from either provider or application code as the
/// constructor signature may change as new dependencies are added. Instead, use this type in
/// your constructor so that an instance will be created and injected automatically by the
/// dependency injection container. To create an instance with some dependent services replaced,
/// first resolve the object from the dependency injection container, then replace selected
/// services using the 'With...' methods. Do not call the constructor at any point in this process.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
public sealed record CompiledQueryCacheKeyGeneratorDependencies
{
/// <summary>
/// <para>
/// Creates the service dependencies parameter object for a <see cref="CompiledQueryCacheKeyGenerator" />.
/// </para>
/// <para>
/// This type is typically used by database providers (and other extensions). It is generally
/// not used in application code.
/// </para>
/// <para>
/// Do not call this constructor directly from either provider or application code as it may change
/// as new dependencies are added. Instead, use this type in your constructor so that an instance
/// will be created and injected automatically by the dependency injection container. To create
/// an instance with some dependent services replaced, first resolve the object from the dependency
/// injection container, then replace selected services using the 'With...' methods. Do not call
/// the constructor at any point in this process.
/// </para>
/// <para>
/// The service lifetime is <see cref="ServiceLifetime.Scoped" />. This means that each
/// <see cref="DbContext" /> instance will use its own instance of this service.
/// The implementation may depend on other services registered with any lifetime.
/// The implementation does not need to be thread-safe.
/// </para>
/// </summary>
[EntityFrameworkInternal]
public CompiledQueryCacheKeyGeneratorDependencies(
IModel model,
ICurrentDbContext currentContext,
IExecutionStrategyFactory executionStrategyFactory)
{
Check.NotNull(model, nameof(model));
Check.NotNull(currentContext, nameof(currentContext));
Check.NotNull(executionStrategyFactory, nameof(executionStrategyFactory));
Model = model;
CurrentContext = currentContext;
IsRetryingExecutionStrategy = executionStrategyFactory.Create().RetriesOnFailure;
}
/// <summary>
/// The model that queries will be written against.
/// </summary>
public IModel Model { get; init; }
/// <summary>
/// The context that queries will be executed for.
/// </summary>
public ICurrentDbContext CurrentContext { get; init; }
/// <summary>
/// Whether the configured execution strategy can retry.
/// </summary>
public bool IsRetryingExecutionStrategy { get; init; }
}
}
| 50.593407 | 122 | 0.629018 | [
"MIT"
] | FelicePollano/efcore | src/EFCore/Query/CompiledQueryCacheKeyGeneratorDependencies.cs | 4,604 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Emit;
using Roslyn.Test.Utilities;
using Cci = Microsoft.Cci;
namespace Roslyn.Test.Utilities
{
internal static class CompilationTestDataExtensions
{
internal static void VerifyIL(
this CompilationTestData.MethodData method,
string expectedIL,
[CallerLineNumber]int expectedValueSourceLine = 0,
[CallerFilePath]string expectedValueSourcePath = null)
{
const string moduleNamePlaceholder = "{#Module#}";
string actualIL = GetMethodIL(method);
if (expectedIL.IndexOf(moduleNamePlaceholder) >= 0)
{
var module = method.Method.ContainingModule;
var moduleName = Path.GetFileNameWithoutExtension(module.Name);
expectedIL = expectedIL.Replace(moduleNamePlaceholder, moduleName);
}
AssertEx.AssertEqualToleratingWhitespaceDifferences(expectedIL, actualIL, escapeQuotes: true, expectedValueSourcePath: expectedValueSourcePath, expectedValueSourceLine: expectedValueSourceLine);
}
internal static CompilationTestData.MethodData GetMethodData(this CompilationTestData data, string qualifiedMethodName)
{
var methodData = default(CompilationTestData.MethodData);
var map = data.Methods;
if (!map.TryGetValue(qualifiedMethodName, out methodData))
{
// caller may not have specified parameter list, so try to match parameterless method
if (!map.TryGetValue(qualifiedMethodName + "()", out methodData))
{
// now try to match single method with any parameter list
var keys = map.Keys.Where(k => k.StartsWith(qualifiedMethodName + "(", StringComparison.Ordinal));
if (keys.Count() == 1)
{
methodData = map[keys.First()];
}
else if (keys.Count() > 1)
{
throw new AmbiguousMatchException(
"Could not determine best match for method named: " + qualifiedMethodName + Environment.NewLine +
string.Join(Environment.NewLine, keys.Select(s => " " + s)) + Environment.NewLine);
}
}
}
if (methodData.ILBuilder == null)
{
throw new KeyNotFoundException("Could not find ILBuilder matching method '" + qualifiedMethodName + "'. Existing methods:\r\n" + string.Join("\r\n", map.Keys));
}
return methodData;
}
internal static string GetMethodIL(this CompilationTestData.MethodData method)
{
return ILBuilderVisualizer.ILBuilderToString(method.ILBuilder);
}
internal static EditAndContinueMethodDebugInformation GetEncDebugInfo(this CompilationTestData.MethodData methodData)
{
// TODO:
return new EditAndContinueMethodDebugInformation(
0,
Cci.MetadataWriter.GetLocalSlotDebugInfos(methodData.ILBuilder.LocalSlotManager.LocalsInOrder()),
closures: ImmutableArray<ClosureDebugInfo>.Empty,
lambdas: ImmutableArray<LambdaDebugInfo>.Empty);
}
internal static Func<MethodDefinitionHandle, EditAndContinueMethodDebugInformation> EncDebugInfoProvider(this CompilationTestData.MethodData methodData)
{
return _ => methodData.GetEncDebugInfo();
}
}
}
| 43.847826 | 206 | 0.63411 | [
"Apache-2.0"
] | 0x53A/roslyn | src/Test/Utilities/Shared/Compilation/CompilationTestDataExtensions.cs | 4,036 | 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.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using AngleSharp.Dom.Html;
namespace Microsoft.AspNetCore.Identity.FunctionalTests.Account.Manage
{
public class SetPassword : DefaultUIPage
{
private readonly IHtmlFormElement _setPasswordForm;
public SetPassword(HttpClient client, IHtmlDocument setPassword, DefaultUIContext context)
: base(client, setPassword, context)
{
_setPasswordForm = HtmlAssert.HasForm("#set-password-form", setPassword);
}
public async Task<SetPassword> SetPasswordAsync(string newPassword)
{
await Client.SendAsync(_setPasswordForm, new Dictionary<string, string>
{
["Input_NewPassword"] = newPassword,
["Input_ConfirmPassword"] = newPassword
});
return this;
}
}
}
| 32.636364 | 111 | 0.673166 | [
"Apache-2.0"
] | 06b/AspNetCore | src/Identity/test/Identity.FunctionalTests/Pages/Account/Manage/SetPassword.cs | 1,079 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace knearest
{
interface IPriorityQueue<T>
{
T MaxItem { get; }
float MaxPriority { get; }
void Enqueue(T node, float priority);
IEnumerable<T> Items { get; }
IEnumerable<float> Priorities { get; }
}
class ListPriorityQueue<T> : IPriorityQueue<T>
{
private struct Entry
{
public T data;
public float priority;
}
private Entry[] items;
public ListPriorityQueue(int maxSize)
{
this.items = new Entry[maxSize];
for (int i = 0; i < this.items.Length; i++)
{
this.items[i] = new Entry { priority = float.PositiveInfinity };
}
}
public T MaxItem
{
get { return items[items.Length - 1].data; }
}
public float MaxPriority
{
get { return items[items.Length - 1].priority; }
}
public void Enqueue(T node, float priority)
{
// don't add if it's larger than the entire list
if (priority > MaxPriority)
{
return;
}
// otherwise, shift things up to make a spot for it
int i;
for (i = this.items.Length - 1; i > 0; i--)
{
if (this.items[i - 1].priority > priority)
{
this.items[i] = this.items[i - 1];
}
else
{
break;
}
}
// place it in it's sorted spot
this.items[i] = new Entry { data = node, priority = priority };
}
public IEnumerable<T> Items
{
get { return this.items.Select(e => e.data); }
}
public IEnumerable<float> Priorities
{
get { return this.items.Select(e => e.priority); }
}
}
}
| 23.613636 | 80 | 0.471607 | [
"MIT"
] | Marjapuuro/Skeletal-data-fusion-of-Kinect-v2-sensors | Assets/Scripts/ICP/knearest/IPriorityQueue.cs | 2,080 | 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.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using Microsoft.Extensions.FileProviders.Embedded.Manifest;
namespace Microsoft.Extensions.FileProviders
{
internal class TestAssembly : Assembly
{
public TestAssembly(string manifest, string manifestName = "Microsoft.Extensions.FileProviders.Embedded.Manifest.xml")
{
ManifestStream = new MemoryStream();
using (var writer = new StreamWriter(ManifestStream, Encoding.UTF8, 1024, leaveOpen: true))
{
writer.Write(manifest);
}
ManifestStream.Seek(0, SeekOrigin.Begin);
ManifestName = manifestName;
}
public TestAssembly(TestEntry entry, string manifestName = "Microsoft.Extensions.FileProviders.Embedded.Manifest.xml")
{
ManifestName = manifestName;
var manifest = new XDocument(
new XDeclaration("1.0", "utf-8", "yes"),
new XElement("Manifest",
new XElement("ManifestVersion", "1.0"),
new XElement("FileSystem", entry.Children.Select(c => c.ToXElement()))));
ManifestStream = new MemoryStream();
using (var writer = XmlWriter.Create(ManifestStream, new XmlWriterSettings { CloseOutput = false }))
{
manifest.WriteTo(writer);
}
ManifestStream.Seek(0, SeekOrigin.Begin);
Files = entry.GetFiles().Select(f => f.ResourcePath).ToArray();
}
public string ManifestName { get; }
public MemoryStream ManifestStream { get; private set; }
public string[] Files { get; private set; }
public override Stream GetManifestResourceStream(string name)
{
if (string.Equals(ManifestName, name))
{
return ManifestStream;
}
return Files.Contains(name) ? Stream.Null : null;
}
public override string Location => null;
public override AssemblyName GetName()
{
return new AssemblyName("TestAssembly");
}
}
}
| 33.885714 | 126 | 0.61172 | [
"Apache-2.0"
] | 1175169074/aspnetcore | src/FileProviders/Embedded/test/TestAssembly.cs | 2,374 | C# |
using System;
using System.Collections.Generic;
namespace NeoSmart.SecureStore
{
sealed internal class Vault
{
internal const int SCHEMAVERSION = 1;
public int VaultVersion;
public byte[] IV;
public SortedDictionary<string, EncryptedBlob> Data;
}
}
| 19.733333 | 60 | 0.675676 | [
"MIT"
] | JamesJoyceGit/SecureStore | SecureStore/Vault.cs | 298 | C# |
// <auto-generated>
// Generated by the protocol buffer compiler. DO NOT EDIT!
// source: google/ads/googleads/v3/enums/proximity_radius_units.proto
// </auto-generated>
#pragma warning disable 1591, 0612, 3021
#region Designer generated code
using pb = global::Google.Protobuf;
using pbc = global::Google.Protobuf.Collections;
using pbr = global::Google.Protobuf.Reflection;
using scg = global::System.Collections.Generic;
namespace Google.Ads.GoogleAds.V3.Enums {
/// <summary>Holder for reflection information generated from google/ads/googleads/v3/enums/proximity_radius_units.proto</summary>
public static partial class ProximityRadiusUnitsReflection {
#region Descriptor
/// <summary>File descriptor for google/ads/googleads/v3/enums/proximity_radius_units.proto</summary>
public static pbr::FileDescriptor Descriptor {
get { return descriptor; }
}
private static pbr::FileDescriptor descriptor;
static ProximityRadiusUnitsReflection() {
byte[] descriptorData = global::System.Convert.FromBase64String(
string.Concat(
"Cjpnb29nbGUvYWRzL2dvb2dsZWFkcy92My9lbnVtcy9wcm94aW1pdHlfcmFk",
"aXVzX3VuaXRzLnByb3RvEh1nb29nbGUuYWRzLmdvb2dsZWFkcy52My5lbnVt",
"cxocZ29vZ2xlL2FwaS9hbm5vdGF0aW9ucy5wcm90byJrChhQcm94aW1pdHlS",
"YWRpdXNVbml0c0VudW0iTwoUUHJveGltaXR5UmFkaXVzVW5pdHMSDwoLVU5T",
"UEVDSUZJRUQQABILCgdVTktOT1dOEAESCQoFTUlMRVMQAhIOCgpLSUxPTUVU",
"RVJTEANC7gEKIWNvbS5nb29nbGUuYWRzLmdvb2dsZWFkcy52My5lbnVtc0IZ",
"UHJveGltaXR5UmFkaXVzVW5pdHNQcm90b1ABWkJnb29nbGUuZ29sYW5nLm9y",
"Zy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMvdjMvZW51bXM7",
"ZW51bXOiAgNHQUGqAh1Hb29nbGUuQWRzLkdvb2dsZUFkcy5WMy5FbnVtc8oC",
"HUdvb2dsZVxBZHNcR29vZ2xlQWRzXFYzXEVudW1z6gIhR29vZ2xlOjpBZHM6",
"Okdvb2dsZUFkczo6VjM6OkVudW1zYgZwcm90bzM="));
descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData,
new pbr::FileDescriptor[] { global::Google.Api.AnnotationsReflection.Descriptor, },
new pbr::GeneratedClrTypeInfo(null, null, new pbr::GeneratedClrTypeInfo[] {
new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V3.Enums.ProximityRadiusUnitsEnum), global::Google.Ads.GoogleAds.V3.Enums.ProximityRadiusUnitsEnum.Parser, null, null, new[]{ typeof(global::Google.Ads.GoogleAds.V3.Enums.ProximityRadiusUnitsEnum.Types.ProximityRadiusUnits) }, null, null)
}));
}
#endregion
}
#region Messages
/// <summary>
/// Container for enum describing unit of radius in proximity.
/// </summary>
public sealed partial class ProximityRadiusUnitsEnum : pb::IMessage<ProximityRadiusUnitsEnum>
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
, pb::IBufferMessage
#endif
{
private static readonly pb::MessageParser<ProximityRadiusUnitsEnum> _parser = new pb::MessageParser<ProximityRadiusUnitsEnum>(() => new ProximityRadiusUnitsEnum());
private pb::UnknownFieldSet _unknownFields;
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pb::MessageParser<ProximityRadiusUnitsEnum> Parser { get { return _parser; } }
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static pbr::MessageDescriptor Descriptor {
get { return global::Google.Ads.GoogleAds.V3.Enums.ProximityRadiusUnitsReflection.Descriptor.MessageTypes[0]; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
pbr::MessageDescriptor pb::IMessage.Descriptor {
get { return Descriptor; }
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProximityRadiusUnitsEnum() {
OnConstruction();
}
partial void OnConstruction();
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProximityRadiusUnitsEnum(ProximityRadiusUnitsEnum other) : this() {
_unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public ProximityRadiusUnitsEnum Clone() {
return new ProximityRadiusUnitsEnum(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override bool Equals(object other) {
return Equals(other as ProximityRadiusUnitsEnum);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public bool Equals(ProximityRadiusUnitsEnum other) {
if (ReferenceEquals(other, null)) {
return false;
}
if (ReferenceEquals(other, this)) {
return true;
}
return Equals(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override int GetHashCode() {
int hash = 1;
if (_unknownFields != null) {
hash ^= _unknownFields.GetHashCode();
}
return hash;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public override string ToString() {
return pb::JsonFormatter.ToDiagnosticString(this);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void WriteTo(pb::CodedOutputStream output) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
output.WriteRawMessage(this);
#else
if (_unknownFields != null) {
_unknownFields.WriteTo(output);
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalWriteTo(ref pb::WriteContext output) {
if (_unknownFields != null) {
_unknownFields.WriteTo(ref output);
}
}
#endif
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public int CalculateSize() {
int size = 0;
if (_unknownFields != null) {
size += _unknownFields.CalculateSize();
}
return size;
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(ProximityRadiusUnitsEnum other) {
if (other == null) {
return;
}
_unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields);
}
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public void MergeFrom(pb::CodedInputStream input) {
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
input.ReadRawMessage(this);
#else
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input);
break;
}
}
#endif
}
#if !GOOGLE_PROTOBUF_REFSTRUCT_COMPATIBILITY_MODE
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
void pb::IBufferMessage.InternalMergeFrom(ref pb::ParseContext input) {
uint tag;
while ((tag = input.ReadTag()) != 0) {
switch(tag) {
default:
_unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, ref input);
break;
}
}
}
#endif
#region Nested types
/// <summary>Container for nested types declared in the ProximityRadiusUnitsEnum message type.</summary>
[global::System.Diagnostics.DebuggerNonUserCodeAttribute]
public static partial class Types {
/// <summary>
/// The unit of radius distance in proximity (e.g. MILES)
/// </summary>
public enum ProximityRadiusUnits {
/// <summary>
/// Not specified.
/// </summary>
[pbr::OriginalName("UNSPECIFIED")] Unspecified = 0,
/// <summary>
/// Used for return value only. Represents value unknown in this version.
/// </summary>
[pbr::OriginalName("UNKNOWN")] Unknown = 1,
/// <summary>
/// Miles
/// </summary>
[pbr::OriginalName("MILES")] Miles = 2,
/// <summary>
/// Kilometers
/// </summary>
[pbr::OriginalName("KILOMETERS")] Kilometers = 3,
}
}
#endregion
}
#endregion
}
#endregion Designer generated code
| 36.624434 | 316 | 0.699283 | [
"Apache-2.0"
] | PierrickVoulet/google-ads-dotnet | src/V3/Types/ProximityRadiusUnits.cs | 8,094 | C# |
using System;
namespace Com.GitHub.ZachDeibert.ProxyConfigurer.Proxy {
public enum ProxyType : byte {
EndOfList,
Direct,
Proxy,
Socks
}
}
| 16.272727 | 56 | 0.603352 | [
"MIT"
] | zachdeibert/proxy-configurer | Proxy/ProxyType.cs | 179 | C# |
using Serenity;
using Serenity.Extensibility;
namespace Advocate
{
[NestedLocalTexts]
public static partial class Texts
{
public static class Db
{
public static class Administration
{
public static class Translation
{
public static LocalText EntityPlural = "Translations";
public static LocalText Key = "Local Text Key";
public static LocalText SourceLanguage = "Source Language";
public static LocalText SourceText = "Effective Translation in Source Language";
public static LocalText TargetLanguage = "Target Language";
public static LocalText TargetText = "Effective Translation in Target Language";
public static LocalText CustomText = "User Translation in Target Language";
public static LocalText OverrideConfirmation = "Overwrite user translation with clicked text?";
public static LocalText SaveChangesButton = "Save Changes";
}
}
}
public static class Forms
{
public static class Membership
{
public static class ChangePassword
{
public static LocalText FormTitle = "Change Password";
public static LocalText SubmitButton = "Change Password";
public static LocalText Success = "Your password is changed.";
}
public static class ForgotPassword
{
public static LocalText FormInfo = "Please enter the e-mail you used to signup.";
public static LocalText FormTitle = "Forgot My Password";
public static LocalText SubmitButton = "Reset My Password";
public static LocalText Success = "An e-mail with password reset instructions is sent to your e-mail address.";
}
public static class ResetPassword
{
public static LocalText EmailSubject = "Reset Your Advocate Password";
public static LocalText FormTitle = "Reset Password";
public static LocalText SubmitButton = "Reset Password";
public static LocalText Success = "Your password is changed. Please login with your new password.";
}
public static class Login
{
public static LocalText FormTitle = "Welcome to SERENE (Serenity Application Template)";
public static LocalText SignInButton = "Sign In";
public static LocalText ForgotPassword = "forgot password?";
public static LocalText SignUpButton = "register a new account";
}
public static class SignUp
{
public static LocalText ActivateEmailSubject = "Activate Your Advocate Account";
public static LocalText ActivationCompleteMessage = "Your account is now activated. " +
"Use the e-mail and password you used while signing up to login.";
public static LocalText FormInfo = "Enter your details to create a free account.";
public static LocalText FormTitle = "Sign up for Advocate";
public static LocalText SubmitButton = "Sign Up";
public static LocalText Success = "An e-mail with instructions to active your account is " +
"sent to your e-mail address. Please check your e-mails.";
public static LocalText DisplayName = "Full Name";
public static LocalText Email = "E-mail";
public static LocalText ConfirmEmail = "Confirm Email";
public static LocalText Password = "Password";
public static LocalText ConfirmPassword = "Confirm Password";
}
}
}
public static class Navigation
{
public static LocalText LogoutLink = "Logout";
public static LocalText SiteTitle = "Advocate";
}
public static class Site
{
public static class Dashboard
{
public static LocalText ContentDescription =
"a sample with random data (from free <em><a href = \"https://almsaeedstudio.com/\" target= \"_blank\">" +
"AdminLTE theme</a></em>)";
}
public static class BasicProgressDialog
{
public static LocalText CancelTitle = "Operation cancelled. Waiting for in progress calls to complete...";
public static LocalText PleaseWait = "Please wait...";
}
public static class BulkServiceAction
{
public static LocalText AllHadErrorsFormat = "All {0} record(s) that are processed had errors!";
public static LocalText AllSuccessFormat = "Finished processing on {0} record(s) with success.";
public static LocalText ConfirmationFormat = "Perform this operation on {0} selected record(s)?";
public static LocalText ErrorCount = "{0} error(s)";
public static LocalText NothingToProcess = "Please select some records to process!";
public static LocalText SomeHadErrorsFormat = "Finished processing on {0} record(s) with success. {1} record(s) had errors!";
public static LocalText SuccessCount = "{0} done";
}
public static class UserDialog
{
public static LocalText EditPermissionsButton = "Edit Permissions";
public static LocalText EditRolesButton = "Edit Roles";
}
public static class UserRoleDialog
{
public static LocalText DialogTitle = "Edit User Roles ({0})";
public static LocalText SaveSuccess = "Updated user roles.";
}
public static class UserPermissionDialog
{
public static LocalText DialogTitle = "Edit User Permissions ({0})";
public static LocalText SaveSuccess = "Updated user permissions.";
public static LocalText Permission = "Permission";
public static LocalText Grant = "Grant";
public static LocalText Revoke = "Revoke";
}
public static class RolePermissionDialog
{
public static LocalText EditButton = "Edit Permissions";
public static LocalText DialogTitle = "Edit Role Permissions ({0})";
public static LocalText SaveSuccess = "Updated role permissions.";
}
public static class Layout
{
public static LocalText FooterCopyright = "Copyright (c) 2015.";
public static LocalText FooterInfo = "Serenity Platform";
public static LocalText FooterRights = "All rights reserved.";
public static LocalText GeneralSettings = "General Settings";
public static LocalText Language = "Language";
public static LocalText Theme = "Theme";
public static LocalText ThemeBlack = "Black";
public static LocalText ThemeBlackLight = "Black Light";
public static LocalText ThemeBlue = "Blue";
public static LocalText ThemeBlueLight = "Blue Light";
public static LocalText ThemeGreen = "Green";
public static LocalText ThemeGreenLight = "Green Light";
public static LocalText ThemePurple = "Purple";
public static LocalText ThemePurpleLight = "Purple Light";
public static LocalText ThemeRed = "Red";
public static LocalText ThemeRedLight = "Red Light";
public static LocalText ThemeYellow = "Yellow";
public static LocalText ThemeYellowLight = "Yellow Light";
}
public static class ValidationError
{
public static LocalText Title = "ERROR";
}
}
public static class Validation
{
public static LocalText AuthenticationError = "Invalid username or password!";
public static LocalText CurrentPasswordMismatch = "Your current password is not valid!";
public static LocalText MinRequiredPasswordLength = "Entered password doesn't have enough characters (min {0})!";
public static LocalText InvalidResetToken = "Your token to reset your password is invalid or has expired!";
public static LocalText InvalidActivateToken = "Your token to activate your account is invalid or has expired!";
public static LocalText CantFindUserWithEmail = "Can't find a user with that e-mail adress!";
public static LocalText EmailInUse = "Another user with this e-mail exists!";
public static LocalText EmailConfirm = "Emails entered doesn't match!";
public static LocalText DeleteForeignKeyError = "Can't delete record. '{0}' table has " +
"records that depends on this one!";
public static LocalText NorthwindPhone = "Phone numbers should be entered in format '(503) 555-9831'.";
public static LocalText NorthwindPhoneMultiple = "Phone numbers should be entered in format '(503) 555-9831. " +
"Multiple numbers can be separated with comma.";
public static LocalText SavePrimaryKeyError = "Can't save record. There is another record with the same {1} value!";
}
}
} | 52.386243 | 141 | 0.589738 | [
"MIT"
] | Jgorsick/ChildAdvocate | Advocate/Advocate.Web/Modules/Texts.cs | 9,903 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CallFastIk : MonoBehaviour
{
private DitzelGames.FastIK.FastIKFabric[] _allIk;
private int _index = 0;
// Start is called before the first frame update
void Start()
{
_allIk = FindObjectsOfType<DitzelGames.FastIK.FastIKFabric>();
}
// Update is called once per frame
void LateUpdate()
{
int length = _allIk.Length / 8;
for (int i = 0; i < length; i++)
{
ResolveOne();
}
}
private void ResolveOne()
{
if (_index == _allIk.Length)
{
_index = 0;
}
_allIk[_index].ResolveIK();
_index++;
}
}
| 21.114286 | 70 | 0.571042 | [
"MIT"
] | xfac11/Bug-Game | Assets/Scripts/CallFastIk.cs | 741 | C# |
using Microsoft.AspNetCore.Identity;
public class ApplicationUser : IdentityUser
{
} | 17.8 | 44 | 0.786517 | [
"MIT"
] | polatengin/B05277 | Chapter17/2-FacebookGoogleAuthenticationSample/Models/ApplicationUser.cs | 89 | C# |
namespace MComponents.MGrid
{
public class BeginAddArgs<T> : RowEventArgs<T>, ICancelableEvent
{
public bool Cancelled { get; set; }
}
}
| 19.75 | 68 | 0.651899 | [
"MIT"
] | BlazorUI/MComponents | MComponents/MGrid/EventArgs/BeginAddArgs.cs | 160 | C# |
using System;
using Jasper.Util;
namespace Jasper.Messaging.Transports
{
public static class TransportConstants
{
public const string Durable = "durable";
public static readonly string Loopback = "loopback";
public static readonly string Default = "default";
public static readonly string Replies = "replies";
public static readonly string Retries = "retries";
public static readonly Uri RetryUri = "loopback://retries".ToUri();
public static readonly Uri RepliesUri = "loopback://replies".ToUri();
public static readonly Uri ScheduledUri = "loopback://delayed".ToUri();
public static readonly Uri DurableLoopbackUri = "loopback://durable".ToUri();
public static readonly Uri LoopbackUri = "loopback://".ToUri();
public static readonly string PingMessageType = "jasper-ping";
public static readonly string Scheduled = "Scheduled";
public static readonly string Incoming = "Incoming";
public static readonly string Outgoing = "Outgoing";
public static readonly int AnyNode = 0;
}
}
| 36.16129 | 85 | 0.682426 | [
"MIT"
] | SVemulapalli/jasper | src/Jasper/Messaging/Transports/TransportConstants.cs | 1,123 | C# |
namespace Miruken.Mvc
{
using System;
using Callback;
using Concurrency;
using Context;
public static class HandlerNavigateExtensions
{
public static Promise<Context> Next<C>(
this IHandler handler, Action<C> action)
where C : IController
{
return handler.Navigate(NavigationStyle.Next, action);
}
#if NETFULL
public static C Next<C>(this IHandler handler)
where C : class, IController
{
return handler.Navigate<C>(NavigationStyle.Next);
}
#endif
public static TargetActionBuilder<C, Promise<Context>> NextBlock<C>(
this IHandler handler)
where C : IController
{
return handler.NavigateBlock<C>(NavigationStyle.Next);
}
public static Promise<Context> Push<C>(
this IHandler handler, Action<C> action)
where C : IController
{
return handler.Navigate(NavigationStyle.Push, action);
}
#if NETFULL
public static C Push<C>(this IHandler handler)
where C : class, IController
{
return handler.Navigate<C>(NavigationStyle.Push);
}
#endif
public static TargetActionBuilder<C, Promise<Context>> PushBlock<C>(
this IHandler handler)
where C : IController
{
return handler.NavigateBlock<C>(NavigationStyle.Push);
}
public static Promise<Context> Partial<C>(
this IHandler handler, Action<C> action)
where C : IController
{
return handler.Navigate(NavigationStyle.Partial, action);
}
#if NETFULL
public static C Partial<C>(this IHandler handler)
where C : class, IController
{
return handler.Navigate<C>(NavigationStyle.Partial);
}
#endif
public static TargetActionBuilder<C, Promise<Context>> PartialBlock<C>(
this IHandler handler)
where C : IController
{
return handler.NavigateBlock<C>(NavigationStyle.Partial);
}
public static TargetActionBuilder<C, Promise<Context>> NavigateBlock<C>(
this IHandler handler, NavigationStyle style)
where C : IController
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
return new TargetActionBuilder<C, Promise<Context>>(action =>
{
var navigation = new Navigation<C>(action, style);
return handler.CommandAsync<Context>(navigation);
});
}
public static Promise<Context> Navigate<C>(
this IHandler handler, NavigationStyle style, Action<C> action)
where C : IController
{
return handler.NavigateBlock<C>(style).Invoke(action);
}
#if NETFULL
public static C Navigate<C>(this IHandler handler, NavigationStyle style)
where C : class, IController
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
return (C)new NavigateInterceptor<C>(handler, style)
.GetTransparentProxy();
}
#endif
public static Promise<Context> GoBack(this IHandler handler)
{
if (handler == null)
throw new ArgumentNullException(nameof(handler));
return handler.CommandAsync<Context>(new Navigation.GoBack());
}
}
} | 30.470085 | 81 | 0.584292 | [
"MIT"
] | Miruken-DotNet/miruken.mvc | Source/Miruken.Mvc/Handler.Navigate.cs | 3,567 | C# |
using DocumentsApi.V1.UseCase;
using FluentAssertions;
using NUnit.Framework;
namespace DocumentsApi.Tests.V1.UseCase
{
[TestFixture]
public class ThrowOpsErrorUsecaseTests
{
[Test]
public void ThrowsTestOpsErrorException()
{
var ex = Assert.Throws<TestOpsErrorException>(
delegate { ThrowOpsErrorUsecase.Execute(); });
var expected = "This is a test exception to test our integrations";
ex.Message.Should().BeEquivalentTo(expected);
}
}
}
| 24.681818 | 79 | 0.646409 | [
"MIT"
] | LBHackney-IT/documents-api | DocumentsApi.Tests/V1/UseCase/ThrowOpsErrorUsecaseTests.cs | 543 | C# |
// Copyright (c) Aghyad khlefawi. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
using System;
using System.Collections;
using System.Collections.Generic;
namespace Coddee
{
/// <summary>
/// Mapper to convert between types with same properties
/// </summary>
public interface IObjectMapper
{
/// <summary>
/// Register a manual mapping information from source to target
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TTarget">Target type</typeparam>
void RegisterMap<TSource, TTarget>(Action<TSource, TTarget> convert);
/// <summary>
/// Register mapping information from source to target
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TTarget">Target type</typeparam>
void RegisterMap<TSource, TTarget>();
/// <summary>
/// Register mapping information from source to target
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TTarget">Target type</typeparam>
void RegisterAutoMap<TSource, TTarget>(Action<TSource, TTarget> additionalMapping=null);
/// <summary>
/// Register mapping information between two types
/// </summary>
/// <typeparam name="TType1">Type1</typeparam>
/// <typeparam name="TType2">Type2</typeparam>
void RegisterTwoWayMap<TType1, TType2>(Action<TType1, TType2> additionalMappingT1T2 = null, Action<TType2, TType1> additionalMappingT2T1 = null);
/// <summary>
/// Map an object to a specific type
/// </summary>
/// <typeparam name="TTarget">Target type</typeparam>
/// <param name="item">object to map</param>
/// <returns>A new object of the target type with the source object values</returns>
TTarget Map<TTarget>(object item) where TTarget : new();
/// <summary>
/// Map a collection of objects to a specific type
/// </summary>
/// <typeparam name="TTarget">Target type</typeparam>
/// <param name="source">the source collection</param>
/// <returns>A new collection of the target type with the source object values</returns>
IEnumerable<TTarget> MapCollection<TTarget>(IList source) where TTarget : new();
/// <summary>
/// Maps the values of the source object to the target object
/// </summary>
/// <typeparam name="TSource">Source type</typeparam>
/// <typeparam name="TTarget">Target type</typeparam>
/// <param name="source">Source object</param>
/// <param name="target">Target object</param>
void MapInstance<TSource, TTarget>(TSource source, TTarget target);
}
}
| 39.90411 | 153 | 0.629591 | [
"MIT"
] | Aghyad-Khlefawi/Coddee | src/Coddee.Core/Mapper/IObjectMapper.cs | 2,915 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace SigningPortalDemo.AuthApi
{
public class TokenResponse
{
public string Access_token { get; set; }
public int Expires_in { get; set; }
}
}
| 18.4 | 48 | 0.695652 | [
"MIT"
] | technologynexus/nexusgo-signingportaldemo | SigningPortalDemo/AuthApi/TokenResponse.cs | 278 | C# |
using ManageCourse.Core.Data.Common;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ManageCourse.Core.Data
{
public class Course: Audit, IHasId
{
public int Id { get; set; }
public int SubjectId { get; set; }
public int GradeId { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public string CourseCode { get; set; }
public int Credits { get; set; }
public string Schedule { get; set; }
public ICollection<Course_User> Course_Users { get; set; }
public ICollection<Course_Student> Course_Students { get; set; }
public virtual ICollection<Assignments> Assignments { get; set; }
}
}
| 30.807692 | 73 | 0.654182 | [
"MIT"
] | hdh-se/classroom-api | ManageCourse.Core/Data/Course.cs | 803 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Ce code a été généré à partir d'un modèle.
//
// Des modifications manuelles apportées à ce fichier peuvent conduire à un comportement inattendu de votre application.
// Les modifications manuelles apportées à ce fichier sont remplacées si le code est régénéré.
// </auto-generated>
//------------------------------------------------------------------------------
namespace UnitTestProject.Model
{
using System;
using System.Collections.Generic;
public partial class Reservation
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Reservation()
{
this.Facture = new HashSet<Facture>();
this.Loge = new HashSet<Loge>();
}
public int Code_Reservation { get; set; }
public System.DateTime Date_Debut { get; set; }
public System.DateTime Date_Fin { get; set; }
public bool Est_Paye { get; set; }
public int Code_Personne { get; set; }
public int Code_Facture { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Facture> Facture { get; set; }
public virtual Facture Facture1 { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Loge> Loge { get; set; }
public virtual Personne Personne { get; set; }
}
}
| 43.333333 | 128 | 0.613609 | [
"Apache-2.0"
] | Minestro/DUTS4-PT-Camping | UnitTestProject1/Model/Reservation.cs | 1,707 | C# |
// Copyright (c) Microsoft Corporation.// Licensed under the MIT license.
namespace Microsoft.SCIM
{
using System.Collections.Generic;
using System.Net.Http;
public sealed class QueryRequest :
SystemForCrossDomainIdentityManagementRequest<IQueryParameters>
{
public QueryRequest(
HttpRequestMessage request,
IQueryParameters payload,
string correlationIdentifier,
IReadOnlyCollection<IExtension> extensions)
: base(request, payload, correlationIdentifier, extensions)
{
}
}
}
| 28.095238 | 73 | 0.671186 | [
"MIT"
] | Aplenty/SCIMReferenceCode | Microsoft.SystemForCrossDomainIdentityManagement/Service/QueryRequest.cs | 590 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace QuanLyTuyenSinh.ValueObject
{
class ValueHoSoThiSinh
{
public string sbd;
public string hodem;
public string ten;
public DateTime ngaysinh;
public string gioitinh;
public string tenhuyen;
public string tentinh;
public string doituong;
public string dantoc;
public double toan;
public double ly;
public double hoa;
public double sinh;
public double van;
public double su;
public double dia;
public double anhvan;
public ValueHoSoThiSinh(string sbd, string hodem, string ten, DateTime ngaysinh, string gioitinh, string tenhuyen, string tentinh, string doituong, string dantoc, double toan, double ly, double hoa, double sinh, double van, double su, double dia, double anhvan)
{
this.sbd = sbd;
this.hodem = hodem;
this.ten = ten;
this.ngaysinh = ngaysinh;
this.gioitinh = gioitinh;
this.tenhuyen = tenhuyen;
this.tentinh = tentinh;
this.doituong = doituong;
this.dantoc = dantoc;
this.toan = toan;
this.ly = ly;
this.hoa = hoa;
this.sinh = sinh;
this.van = van;
this.su = su;
this.dia = dia;
this.anhvan = anhvan;
}
public ValueHoSoThiSinh(string sbd)
{
this.sbd = sbd;
}
}
}
| 28.857143 | 269 | 0.571782 | [
"Apache-2.0"
] | hqhoangvuong/OOSD_FinalProject | QuanLyTuyenSinh/ValueObject/ValueHoSoThiSinh.cs | 1,618 | C# |
using NBitcoin;
using Stratis.Bitcoin.Base.Deployments;
using Stratis.Bitcoin.Consensus.Rules;
namespace Stratis.Bitcoin.Features.Consensus.Rules.CommonRules
{
/// <summary>A base skeleton class that is implemented by networks to define and verify the version of blocks.</summary>
public abstract class HeaderVersionRule : HeaderValidationConsensusRule
{
/// <summary>
/// Computes what the block version of a newly created block should be, given a previous header and the
/// current set of BIP9 deployments defined in the consensus.
/// </summary>
/// <param name="prevChainedHeader">The header of the previous block in the chain.</param>
/// <remarks>This method is currently used during block creation only. Different nodes may not implement
/// BIP9, or may disagree about what the current valid set of deployments are. It is therefore not strictly
/// possible to validate a block version number in anything more than general terms.</remarks>
/// <returns>The block version.</returns>
public int ComputeBlockVersion(ChainedHeader prevChainedHeader)
{
uint version = ThresholdConditionCache.VersionbitsTopBits;
var thresholdConditionCache = new ThresholdConditionCache(this.Parent.Network.Consensus);
for (int deployment = 0; deployment < thresholdConditionCache.ArraySize; deployment++)
{
ThresholdState state = thresholdConditionCache.GetState(prevChainedHeader, deployment);
if ((state == ThresholdState.LockedIn) || (state == ThresholdState.Started))
version |= thresholdConditionCache.Mask(deployment);
}
return (int)version;
}
}
} | 52.382353 | 124 | 0.688377 | [
"MIT"
] | SatyaKarki/StratisFullNode | src/Stratis.Bitcoin.Features.Consensus/Rules/CommonRules/HeaderVersionRule.cs | 1,783 | C# |
using System;
using System.CodeDom.Compiler;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Xml.Schema;
using System.Xml.Serialization;
namespace Workday.AbsenceManagement
{
[GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")]
[Serializable]
public class Event_Attachment_CategoryObjectIDType : INotifyPropertyChanged
{
private string typeField;
private string valueField;
[method: CompilerGenerated]
[CompilerGenerated]
public event PropertyChangedEventHandler PropertyChanged;
[XmlAttribute(Form = XmlSchemaForm.Qualified)]
public string type
{
get
{
return this.typeField;
}
set
{
this.typeField = value;
this.RaisePropertyChanged("type");
}
}
[XmlText]
public string Value
{
get
{
return this.valueField;
}
set
{
this.valueField = value;
this.RaisePropertyChanged("Value");
}
}
protected void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler propertyChanged = this.PropertyChanged;
if (propertyChanged != null)
{
propertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
| 20.934426 | 136 | 0.730619 | [
"MIT"
] | matteofabbri/Workday.WebServices | Workday.AbsenceManagement/Event_Attachment_CategoryObjectIDType.cs | 1,277 | C# |
namespace _3_ModernizedTemplates.AspNetMvc.Models;
public class ErrorViewModel
{
public string? RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
| 21.666667 | 66 | 0.764103 | [
"Unlicense"
] | Djohnnie/DotNet6-DevDay-2021 | 3-ModernizedTemplates/3-ModernizedTemplates.AspNetMvc/Models/ErrorViewModel.cs | 195 | C# |
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Newtonsoft.Json;
namespace shopapp.webui.Extensions
{
public static class TempDataExtensions
{
public static void Put<T>(this ITempDataDictionary tempData, string key, T value) where T:class
{
tempData[key] = JsonConvert.SerializeObject(value);
}
public static T Get<T>(this ITempDataDictionary tempData, string key) where T:class
{
object o;
tempData.TryGetValue(key, out o);
return o==null?null:JsonConvert.DeserializeObject<T>((string)o);
}
}
} | 30.5 | 103 | 0.647541 | [
"MIT"
] | sametkoyuncu/shopapp-udemy | shopapp.webui/Extensions/TempDataExtensions.cs | 610 | C# |
using System.Linq;
using System.Threading.Tasks;
using NUnit.Framework;
namespace ShikimoriSharp.Tests.Information
{
[TestFixture]
public class StatsAndStudiosTest : TestBase
{
[Test]
public async Task GetActiveUsersTest()
{
Assert.IsNotEmpty(await Client.Stats.GetActiveUsers());
}
[Test]
public async Task GetStudios()
{
var studio = await Client.Studios.GetStudios();
var studiosn = studio.Where(it => !(it.Image is null));
Assert.IsNotEmpty(studio);
}
}
} | 24.583333 | 67 | 0.601695 | [
"MIT"
] | ColinFL/ShikimoriSharp | ShikimoriSharp.Tests/Information/StatsAndStudiosTest.cs | 592 | C# |
using System;
using System.Text;
namespace ETHotfix
{
public static class RandomHelper
{
public static int GenerateRandomCode(int length)
{
var result = new StringBuilder();
for (var i = 0; i < length; i++)
{
var r = new Random(Guid.NewGuid().GetHashCode());
result.Append(r.Next(0, 10));
}
return int.Parse(result.ToString());
}
public static Random GetRandom()
{
var buffer = Guid.NewGuid().ToByteArray();
return new Random(BitConverter.ToInt32(buffer, 0));
}
}
}
| 22.344828 | 65 | 0.520062 | [
"MIT"
] | lantuma/DDZ | Unity/Assets/Hotfix/_GameLobby/Helper/RandomHelper.cs | 650 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
namespace coreJson
{
public class JsonParser : IDisposable
{
enum ParseToken
{
None = -1, // Used to denote no Lookahead available
Curly_Open,
Curly_Close,
Squared_Open,
Squared_Close,
Colon,
Comma,
String,
UnprotectedString,
Number,
True,
False,
Null
}
#region constants
// tokens char
static readonly Dictionary<byte, ParseToken> _tokens = new Dictionary<byte, ParseToken>()
{
{ 123, ParseToken.Curly_Open },
{ 125, ParseToken.Curly_Close },
{ 91, ParseToken.Squared_Open },
{ 93, ParseToken.Squared_Close }
};
static readonly Dictionary<byte, ParseToken> _stringDelimiter = new Dictionary<byte, ParseToken>()
{
{ 34, ParseToken.String },
{ 39, ParseToken.String }
};
// delimiters/separators char
static readonly Dictionary<byte, ParseToken> _separators = new Dictionary<byte, ParseToken>()
{
{ 44, ParseToken.Comma},
{ 58, ParseToken.Colon}
};
// invisible char
static readonly Dictionary<byte, string> _invisibles = new Dictionary<byte, string>()
{
{ 32, "space"},
{ 9, "tab"},
{ 10, "line feed"},
{ 13, "carriage return"}
};
static readonly Dictionary<byte, KeyValuePair<byte[], ParseToken>> _constants = new Dictionary<byte, KeyValuePair<byte[], ParseToken>>()
{
{ 102, new KeyValuePair<byte[], ParseToken>( new byte[] {102,97,108,115,101 }, ParseToken.False)},
{ 116, new KeyValuePair<byte[], ParseToken>( new byte[] {116,114,117,101 }, ParseToken.True)},
{ 110, new KeyValuePair<byte[], ParseToken>( new byte[] {110,117,108,108 }, ParseToken.Null)}
};
#endregion
ByteQueue _rawData;
ParseToken _nextToken = ParseToken.None;
public JsonParser(){ }
public object Parse(System.IO.Stream input)
{
_rawData = new ByteQueue(input);
return parseValue();
}
public object Parse(string input)
{
_rawData = new ByteQueue(System.Text.Encoding.UTF8.GetBytes(input));
return parseValue();
}
private object parseValue()
{
switch (getNextToken())
{
case ParseToken.Number:
return parseNumber();
case ParseToken.String:
case ParseToken.UnprotectedString:
return parseString();
case ParseToken.Curly_Open:
return parseObject();
case ParseToken.Squared_Open:
return parseArray();
case ParseToken.True:
consumeToken();
return true;
case ParseToken.False:
consumeToken();
return false;
case ParseToken.Null:
consumeToken();
return null;
}
throw new Exception("Unrecognized token at index");
}
private object parseNumber()
{
consumeToken();
string number = parseString(true);
try
{
if (number.IndexOf('.') > -1)
return float.Parse(number, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
return long.Parse(number, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
}
catch(Exception e)
{
System.Diagnostics.Debug.WriteLine(string.Format("error :{1} {0}", e.Message, number));
return 0;
}
}
private string parseString(bool include_comma = false)
{
Func<byte, bool> condition = null;
Action<byte> consumeDelimiter = null;
byte delimiter = _rawData.Peek(-1); // should be 34 or 39
if (include_comma || getNextToken() == ParseToken.UnprotectedString)
{
condition = (b) => { return !_tokens.ContainsKey(b) && !_separators.ContainsKey(b) && !_stringDelimiter.ContainsKey(b); };
consumeDelimiter = (b) =>
{
if (_stringDelimiter.ContainsKey(b))
_rawData.Skip();
};
}
else
{
condition = (b) =>
{
return b != delimiter || (b == delimiter && _rawData.Peek(-1) == 92);
//this should be the normal parsing. Start delimiter is end delimiter
//return !_stringDelimiter.ContainsKey(b) || (_stringDelimiter.ContainsKey(b) && _rawData.ReversePeek() == 92);
};
consumeDelimiter = (b) =>
{
if (b == delimiter)
_rawData.Skip();
};
}
List<byte> result = new List<byte>();
consumeToken();
byte c = _rawData.Peek();
consumeDelimiter(c);
while (condition(c))
{
result.Add(_rawData.Read());
c = _rawData.Peek();
}
c = _rawData.Peek();
consumeDelimiter(c);
return System.Text.RegularExpressions.Regex.Unescape(System.Text.Encoding.UTF8.GetString(result.ToArray(),0,result.Count).ToString());
}
private object parseObject()
{
Dictionary<string, object> table = new Dictionary<string, object>();
consumeToken(); // {
while (true)
{
switch (getNextToken())
{
case ParseToken.Comma:
consumeToken();
break;
case ParseToken.Curly_Close:
consumeToken();
return table;
default:
{
// name
string name = parseString();
//if (_ignorecase)
// name = name.ToLower();
// :
if (getNextToken() != ParseToken.Colon)
throw new Exception("Expected colon at index ");
consumeToken();
// value
object value = parseValue();
table[name] = value;
}
break;
}
}
}
private object parseArray()
{
List<object> array = new List<object>();
consumeToken(); // [
while (true)
{
switch (getNextToken())
{
case ParseToken.Comma:
if (_rawData.Peek(-2) == 91)
array.Add(null);
consumeToken();
if (getNextToken() == ParseToken.Comma)
{
array.Add(null);
//consumeToken();
}
break;
case ParseToken.Squared_Close:
consumeToken();
return array;
default:
array.Add(parseValue());
break;
}
}
}
void consumeToken()
{
_nextToken = ParseToken.None;
}
ParseToken getNextToken()
{
if (_nextToken != ParseToken.None)
return _nextToken;
_nextToken = gotoNextToken();
if (_nextToken != ParseToken.None && _nextToken != ParseToken.UnprotectedString && _nextToken != ParseToken.Number)
_rawData.Skip();
return _nextToken;
}
ParseToken gotoNextToken()
{
byte c;
do
{
c = _rawData.Peek();
if (!_invisibles.ContainsKey(c))
break;
_rawData.Skip();
} while (_rawData.Count > 0);
if(_rawData.Count == 0)
throw new Exception("Reached end of string unexpectedly");
// if token
if (_tokens.ContainsKey(c))
return _tokens[c];
// if string
if (_stringDelimiter.ContainsKey(c))
return _stringDelimiter[c];
// if separator
if (_separators.ContainsKey(c))
return _separators[c];
// if number
if ((c >= 48 && c <= 57) || c == 43 || c == 45 || c == 46)
return ParseToken.Number;
// if constant
if(_constants.ContainsKey(c))
{
byte[] buffer = _rawData.Read(_constants[c].Key.Length);
if (buffer.SequenceEqual(_constants[c].Key))
{
//_rawData.Skip(buffer.Length -1);
return _constants[c].Value;
}
}
//default set string if not detected
return ParseToken.UnprotectedString;
}
public void Dispose()
{
_rawData.Dispose();
}
}
}
| 29.389381 | 146 | 0.448058 | [
"MIT"
] | madagaga/WTalk | WTalk/coreJson/JsonParser.cs | 9,965 | C# |
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Linq;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Smallscord.WebSockets.Entities;
using Smallscord.Events;
namespace Smallscord.WebSockets
{
public class WebSocketController
{
private const int HEARTBEAT_INTERVAL = 1000;
private WebSocket socket;
private WebSocketService service;
private ILogger<WebSocketController> websocketLogger;
private IList<GatewayDispatch> events;
public WebSocketController(WebSocketService controllerService, WebSocket _socket, ILoggerFactory factory)
{
socket = _socket;
service = controllerService;
SessionId = Environment.TickCount.ToString();
websocketLogger = factory.CreateLogger<WebSocketController>();
events = new List<GatewayDispatch>();
}
public bool Connected => socket.State == WebSocketState.Open;
public bool Closed => socket.State == WebSocketState.Closed ||
socket.State == WebSocketState.CloseReceived ||
socket.State == WebSocketState.CloseSent;
public int Sequence { get; internal set; }
public string SessionId { get; }
public async Task Run()
{
await SendHello();
var buffer = new byte[4096];
var read = 0;
int lastCheck = 0;
int eventsSent = 0;
while (socket.State == WebSocketState.Open)
{
var result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer, read, 4096), CancellationToken.None);
if (result.EndOfMessage)
{
read += result.Count;
websocketLogger.LogDebug("Received {0} bytes, message type {1}", read, result.MessageType);
// TODO: implement better ratelimiting
if (Environment.TickCount - lastCheck > 60000)
{
if (eventsSent > 120)
{
websocketLogger.LogWarning("Disconnecting client for surpassing rate limit");
await SendClose(4008);
break;
}
eventsSent = 0;
lastCheck = Environment.TickCount;
}
if (result.MessageType == WebSocketMessageType.Text)
{
eventsSent++;
var message = Encoding.UTF8.GetString(buffer, 0, read);
await HandleClientMessageString(message);
}
else if (result.MessageType == WebSocketMessageType.Binary)
{
// TODO: handle binary message
}
// empty the buffer and reset read offset
buffer.Initialize();
read = 0;
}
else
{
websocketLogger.LogWarning("Maximum payload size exceeded.");
await SendClose(4002);
break;
}
}
}
public Task SendRaw(byte[] data, WebSocketMessageType type, CancellationToken token)
{
return socket.SendAsync(new ArraySegment<byte>(data), type, true, token);
}
public Task SendString(string data) => SendString(data, WebSocketMessageType.Text, CancellationToken.None);
public Task SendString(string data, CancellationToken token) => SendString(data, WebSocketMessageType.Text, token);
public Task SendString(string data, WebSocketMessageType type, CancellationToken token) => SendRaw(Encoding.UTF8.GetBytes(data), type, token);
public Task SendEntity(GatewayEntity entity) => SendEntity(entity, WebSocketMessageType.Text, CancellationToken.None);
public Task SendEntity(GatewayEntity entity, CancellationToken token) => SendEntity(entity, WebSocketMessageType.Text, token);
public Task SendEntity(GatewayEntity entity, WebSocketMessageType type, CancellationToken token) => SendString(entity.ToString(), type, token);
public Task SendClose(ushort reason) => SendClose(reason, "", CancellationToken.None);
public Task SendClose(ushort reason, string message) => SendClose(reason, message, CancellationToken.None);
public Task SendClose(ushort reason, string message, CancellationToken token)
{
return socket.CloseAsync((WebSocketCloseStatus)reason, "", token);
}
public Task SendDispatch(GatewayEvent eventInfo) => SendDispatch(eventInfo, WebSocketMessageType.Text, CancellationToken.None);
public Task SendDispatch(GatewayEvent eventInfo, WebSocketMessageType type) => SendDispatch(eventInfo, type, CancellationToken.None);
public Task SendDispatch(GatewayEvent eventInfo, WebSocketMessageType type, CancellationToken token)
{
var dispatch = new GatewayDispatch(++Sequence, eventInfo);
events.Add(dispatch);
return SendEntity(dispatch);
}
private async Task HandleClientMessageString(string message)
{
try
{
var data = JsonConvert.DeserializeObject<GatewayEntity>(message);
var opcode = data.Opcode;
switch(opcode)
{
case GatewayOpcode.Heartbeat:
{
// TODO: validate heartbeat sequence
await SendEntity(new GatewayEntity(GatewayOpcode.HeartbeatAck));
break;
}
case GatewayOpcode.Identify:
{
websocketLogger.LogInformation("Handling Identify");
GatewayIdentify loginInfo = JsonConvert.DeserializeObject<GatewayIdentify>(message);
if (string.IsNullOrWhiteSpace(loginInfo.ClientToken))
{
websocketLogger.LogWarning("Invalid client token was provided");
await SendClose(4004, "Invalid client token");
return;
}
else
{
websocketLogger.LogDebug("Client using token {0}", loginInfo.ClientToken);
}
var reconnectStatus = service.TryOverwrite(loginInfo.ClientToken, this);
if (reconnectStatus == ReconnectStatus.AlreadyConnected)
{
websocketLogger.LogWarning("A client already exists using the token {0}", loginInfo.ClientToken);
await SendClose(4005, "Already connected using given token");
return;
}
else if (reconnectStatus == ReconnectStatus.Reconnect)
{
websocketLogger.LogInformation("Handling Identify as reconnect: you should use Resume instead or mark a new connection");
}
if (loginInfo.ShardInfo != default(int[]))
{
// sharding: check two values were provided
if (loginInfo.ShardInfo.Length != 2)
{
websocketLogger.LogWarning("Invalid shard info (expected 2 values, got {0})", loginInfo.ShardInfo.Length);
await SendClose(4010, "Invalid shard info");
return;
}
else
{
var shardId = loginInfo.ShardInfo[0];
var shardCount = loginInfo.ShardInfo[1];
if (shardId < 0)
{
websocketLogger.LogWarning("Invalid shard info (shardId must be greater than or equal to 0)");
await SendClose(4010, "Invalid shard info");
return;
}
if (shardCount < 1)
{
websocketLogger.LogWarning("Invalid shard info (shardCount must be greater than 0)");
await SendClose(4010, "Invalid shard info");
return;
}
if (shardId >= shardCount)
{
websocketLogger.LogWarning("Invalid shard info (shardId {0} must be less than shardCount {1})", shardId, shardCount);
await SendClose(4010, "Invalid shard info");
return;
}
else
{
websocketLogger.LogDebug("Sharding information provided: id={0} count={1}", shardId, shardCount);
}
}
}
// if we go this far, the Identify packet was valid.
await SendIdentifyResponse();
break;
}
case GatewayOpcode.Resume:
{
websocketLogger.LogInformation("Handling Resume");
GatewayResume resumeInfo = JsonConvert.DeserializeObject<GatewayResume>(message);
bool resumeSuccess = true;
WebSocketController oldClient = null;
if (string.IsNullOrWhiteSpace(resumeInfo.ClientToken))
{
websocketLogger.LogWarning("Invalid client token was provided");
resumeSuccess = false;
}
else
{
websocketLogger.LogDebug("Client using token {0}", resumeInfo.ClientToken);
service.TryGet(resumeInfo.ClientToken, out oldClient);
var reconnectStatus = service.TryOverwrite(resumeInfo.ClientToken, this);
if (reconnectStatus == ReconnectStatus.AlreadyConnected)
{
websocketLogger.LogWarning("A client already exists using the token {0}", resumeInfo.ClientToken);
resumeSuccess = false;
}
else if (reconnectStatus == ReconnectStatus.InitialConnect)
{
websocketLogger.LogWarning("Client tried to resume a non-existant session");
resumeSuccess = false;
}
if (resumeInfo.SessionId != oldClient.SessionId)
{
websocketLogger.LogWarning("Client tried to use an invalid session id");
resumeSuccess = false;
}
if (resumeInfo.SequenceNumber > oldClient.Sequence)
{
websocketLogger.LogWarning("Client tried to use an invalid sequence number");
resumeSuccess = false;
}
}
await SendResumeResponse(resumeInfo, oldClient, resumeSuccess);
break;
}
default:
{
websocketLogger.LogWarning("Unknown opcode {0}", opcode);
await SendClose(4001);
break;
}
}
}
catch (JsonException e)
{
websocketLogger.LogTrace("Exception occured while deserializing JSON: {0}", e);
await SendClose(4002, $"JSON parsing error: {e.Message}");
}
}
private async Task SendIdentifyResponse()
{
await SendDispatch(new EventReady(SessionId));
}
private async Task SendResumeResponse(GatewayResume resumeInfo, WebSocketController previousSession, bool resumeSuccess)
{
if (!resumeSuccess)
{
await SendEntity(new GatewayEntity(GatewayOpcode.InvalidSession));
}
else
{
// TODO: replay events
int sequenceNumber = resumeInfo.SequenceNumber;
IEnumerable<GatewayDispatch> dispatches = previousSession.events.Where(x => x.Sequence > sequenceNumber && x.Sequence < Sequence);
foreach (GatewayDispatch dispatch in dispatches)
{
await SendEntity(dispatch);
}
}
}
public async Task SendHello()
{
await SendEntity(new GatewayHello()
{
HeartbeatInterval = HEARTBEAT_INTERVAL,
ConnectedServers = new string[]{"smallscord-gateway-dbg-1-0"}
});
}
}
} | 32.685065 | 145 | 0.688189 | [
"MIT"
] | FiniteReality/Smallcord | src/WebSockets/WebSocketController.cs | 10,067 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace XboxLoginTest
{
static class Program
{
/// <summary>
/// 해당 애플리케이션의 주 진입점입니다.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
| 21.478261 | 65 | 0.605263 | [
"MIT"
] | NamuTree0345/CmlLib.Core | XboxLoginTest/Program.cs | 528 | C# |
using Dapper.Contrib.Extensions;
using System;
using System.Collections.Generic;
using System.Text;
using WL.Core.DBModel;
namespace WL.Account.Core.DB
{
/// <summary>
/// 模块
/// </summary>
[Table("WL_SYSMODEL")]
public class SysModuleDBModel : BaseDBModel
{
/// <summary>
/// 模块编号
/// </summary>
public string ModuleID { get; set; } = string.Empty;
/// <summary>
/// 模块父级编号
/// </summary>
public string ModulePID { get; set; } = string.Empty;
/// <summary>
/// 模块id路径
/// </summary>
public string ModuleIDPath { get; set; } = string.Empty;
/// <summary>
/// 模块别名
/// </summary>
public string ModuleAlias { get; set; } = string.Empty;
/// <summary>
/// 模块别名路径
/// </summary>
public string ModulePath { get; set; } = string.Empty;
/// <summary>
/// 模块名
/// </summary>
public string ModuleName { get; set; } = string.Empty;
/// <summary>
/// 模块备注
/// </summary>
public string ModuleRemark { get; set; } = string.Empty;
/// <summary>
/// 模块AppKey
/// </summary>
public string ModuleAppKey { get; set; } = string.Empty;
/// <summary>
/// 模块接口 类名称 完整名称,待定
/// </summary>
public string ModuleInterface { get; set; } = string.Empty;
/// <summary>
///
/// </summary>
public string UrlPath { get; set; } = string.Empty;
}
}
| 27.473684 | 67 | 0.501277 | [
"MIT"
] | wlfsky/netcorewebapi | src/Account/WL.Account.Core/DB/SysModuleDBModel.cs | 1,666 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Netch.Properties {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Netch.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap CopyLink {
get {
object obj = ResourceManager.GetObject("CopyLink", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] defaultTUNTAP {
get {
object obj = ResourceManager.GetObject("defaultTUNTAP", resourceCulture);
return ((byte[])(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap delete {
get {
object obj = ResourceManager.GetObject("delete", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap edit {
get {
object obj = ResourceManager.GetObject("edit", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Netch {
get {
object obj = ResourceManager.GetObject("Netch", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap speed {
get {
object obj = ResourceManager.GetObject("speed", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Drawing.Bitmap.
/// </summary>
internal static System.Drawing.Bitmap Sponsor {
get {
object obj = ResourceManager.GetObject("Sponsor", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
/// <summary>
/// Looks up a localized resource of type System.Byte[].
/// </summary>
internal static byte[] zh_CN {
get {
object obj = ResourceManager.GetObject("zh_CN", resourceCulture);
return ((byte[])(obj));
}
}
}
}
| 39.020833 | 171 | 0.557395 | [
"MIT"
] | GuestKiller/Netch | Netch/Properties/Resources.Designer.cs | 5,621 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.