content
stringlengths
23
1.05M
using Orchard.Autoroute.Settings; namespace Orchard.Autoroute.ViewModels { public class AutoroutePartEditViewModel { public AutorouteSettings Settings { get; set; } public bool PromoteToHomePage { get; set; } public string CurrentUrl { get; set; } public string CustomPattern { get; set; } } }
using SEDC.Adv.Class01.Task01.Logic.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SEDC.Adv.Class01.Task01.Logic.Services { public class SearchService { public Dictionary<string, int> CountAppearancesInText(string text, List<string> searchStrings) { var searchResults = new Dictionary<string, int>(); var textArr = text.Split(" ", StringSplitOptions.RemoveEmptyEntries); foreach (var str in searchStrings) { var result = Array.FindAll(textArr, _word => _word.Equals(str, StringComparison.OrdinalIgnoreCase)); searchResults[str] = result.Length; } return searchResults; } public List<SearchResult> CountAppearancesInText2(string text, List<string> searchStrings) { var searchText = text .Split(" ", StringSplitOptions.RemoveEmptyEntries); return searchStrings .Select(_str => new SearchResult() { Name = _str, Appearance = searchText.Count(_word => _word.Equals(_str, StringComparison.OrdinalIgnoreCase)) }) .ToList(); } public void CountAppearancesInText3(string text, List<string> searchStrings) { var searchText = text.Split(" "); int counter = 0; foreach (var searchStr in searchStrings) { foreach (var word in searchText) { if(word.Trim().ToLower() == searchStr.Trim().ToLower()) { counter++; } } Console.WriteLine(string.Format("Name: {0} is contained {1}", searchStr, counter)); counter = 0; } } } }
using UnityEngine; using UnityEngine.UI; using System.Collections; public class WaveController : MonoBehaviour { public GameObject rhythmObj; public GameObject ritualObj; public GameObject waveInstances; public GameObject playerPart; public AudioClip audioLvlUp; public AudioClip audioCCosaDead; public Text uiLvlText; public Text uiWavesText; private float[] lvlTimes; private int currentLvl; private float cycleTime; private int randomSequence; private int wavesClear; private int totalWavesCleared; private bool isBoss; void Start () { lvlTimes = new float[]{0.5f, 0.5f, 0.45f, 0.4f, 0.35f, 0.3f, 0.3f, 0.2f}; currentLvl = -1; randomSequence = 0; wavesClear = 0; isBoss = false; StartCoroutine(initialWave()); } void Update () { } void lvlUp () { currentLvl += 1; uiLvlText.text = "Level: "+currentLvl; if (currentLvl==3) { uiLvlText.text = "MAX LEVEL!"; } transform.GetComponent<AudioSource> ().PlayOneShot (audioLvlUp); cycleTime = lvlTimes [currentLvl] + lvlTimes [currentLvl + 1]; rhythmObj.GetComponent<RhythmController> ().soundDuration = lvlTimes[currentLvl*2]; rhythmObj.GetComponent<RhythmController> ().soundDelay = lvlTimes[currentLvl*2 +1]; } public void ritualComplete() { Debug.Log("RITUAL COMPLETE!"); killWave (); wavesClear += 1; totalWavesCleared += 1; uiWavesText.text = "Waves Cleared: "+totalWavesCleared; if (isBoss) { wavesClear = 0; isBoss = false; if (currentLvl < 3) { lvlUp (); } else if (currentLvl ==1) { playerPart.transform.Find ("FirePower").GetComponent<ParticleSystem> ().Play(); } } if (wavesClear == 4) { spawnBoss (); } else { spawnChavicosas (); } } void spawnChavicosas() { //GetComponent<AudioSource>().Play(); randomSequence = Random.Range(currentLvl, (currentLvl+1)*3); ritualObj.GetComponent<RitualController> ().setCorrectSequence (randomSequence); transform.GetChild(currentLvl).GetComponent<SpawnController>().spawnChavicosas(2f*cycleTime*currentLvl+3); Debug.Log ("New Wave"); } void spawnBoss () { //GetComponent<AudioSource>().Play(); isBoss = true; randomSequence = Random.Range(12, 15); ritualObj.GetComponent<RitualController>().setCorrectSequence(randomSequence); transform.GetChild(currentLvl).GetComponent<SpawnController>().spawnBoss(1.5f*cycleTime*10); Debug.Log ("New BOSS!!"); } void killWave() { foreach (Transform child in waveInstances.transform) { foreach (Transform childAnim in child) { childAnim.GetChild (0).gameObject.SetActive (true); } child.GetComponent<Rigidbody> ().useGravity = true; } playerPart.transform.Find ("FireExp").GetComponent<ParticleSystem> ().Play(); transform.GetComponent<AudioSource> ().PlayOneShot (audioCCosaDead); } IEnumerator initialWave() { yield return new WaitForSeconds(3f); lvlUp (); spawnChavicosas (); } }
using System; using System.Windows.Input; using Jamiras.Commands; using NUnit.Framework; namespace Jamiras.Core.Tests.Commands { [TestFixture] class CommandBaseTests { private class TestCommand : CommandBase { public bool IsExecuted { get; set; } public override void Execute() { IsExecuted = true; } public void SetCanExecute(bool newValue) { CanExecute = newValue; } } [Test] public void TestInheritance() { var command = new TestCommand(); Assert.That(command, Is.InstanceOf<ICommand>()); } [Test] public void TestCanExecute() { var command = new TestCommand(); Assert.That(command.CanExecute, Is.True); Assert.That(((ICommand)command).CanExecute(null), Is.True); Assert.That(command.IsExecuted, Is.False); } [Test] public void TestExecute() { var command = new TestCommand(); Assert.That(command.IsExecuted, Is.False); command.Execute(); Assert.That(command.IsExecuted, Is.True); } [Test] [Apartment(System.Threading.ApartmentState.STA)] public void TestExecuteICommand() { var command = new TestCommand(); Assert.That(command.IsExecuted, Is.False); ((ICommand)command).Execute(null); Assert.That(command.IsExecuted, Is.True); } [Test] public void TestCanExecuteChanged() { var eventRaised = false; var command = new TestCommand(); command.CanExecuteChanged += (o, e) => eventRaised = true; command.SetCanExecute(true); Assert.That(eventRaised, Is.False); command.SetCanExecute(false); Assert.That(eventRaised, Is.True); } private class TestParameterizedCommand : CommandBase<int> { public int ExecuteParameter { get; private set; } public override bool CanExecute(int parameter) { return (parameter % 2) == 0; } public override void Execute(int parameter) { ExecuteParameter = parameter; } public void RaiseCanExecuteChanged() { OnCanExecuteChanged(EventArgs.Empty); } } [Test] public void TestParameterizedInheritance() { var command = new TestParameterizedCommand(); Assert.That(command, Is.InstanceOf<ICommand>()); } [Test] public void TestParameterizedCanExecute() { var command = new TestParameterizedCommand(); Assert.That(command.CanExecute(4), Is.True); Assert.That(command.CanExecute(7), Is.False); Assert.That(((ICommand)command).CanExecute(4), Is.True); Assert.That(((ICommand)command).CanExecute(7), Is.False); Assert.That(command.ExecuteParameter, Is.EqualTo(0)); } [Test] public void TestParameterizedCanExecuteInvalidParameter() { var command = new TestParameterizedCommand(); Assert.That(((ICommand)command).CanExecute(null), Is.False); Assert.That(((ICommand)command).CanExecute("happy"), Is.False); } [Test] public void TestParameterizedExecute() { var command = new TestParameterizedCommand(); Assert.That(command.ExecuteParameter, Is.EqualTo(0)); command.Execute(4); Assert.That(command.ExecuteParameter, Is.EqualTo(4)); } [Test] [Apartment(System.Threading.ApartmentState.STA)] public void TestParameterizedExecuteICommand() { var command = new TestParameterizedCommand(); Assert.That(command.ExecuteParameter, Is.EqualTo(0)); ((ICommand)command).Execute(4); Assert.That(command.ExecuteParameter, Is.EqualTo(4)); } [Test] public void TestParameterizedCanExecuteChanged() { var eventRaised = false; var command = new TestParameterizedCommand(); command.CanExecuteChanged += (o, e) => eventRaised = true; command.RaiseCanExecuteChanged(); Assert.That(eventRaised, Is.True); } } }
namespace Rebus.Routing.TransportMessages { enum ActionType { /// <summary> /// Doesn't do anything - dispatches the message as normally /// </summary> None, /// <summary> /// Forwards the message to one or more recipients /// </summary> Forward, /// <summary> /// Ignores the message (thus effectively losing it) /// </summary> Ignore, } }
namespace LogicMonitor.Api.LogicModules; /// <summary> /// A DataSource DataPoint /// </summary> [DataContract] public class DataSourceDataPoint : NamedItem { /// <summary> /// The alertExprNote /// </summary> [DataMember(Name = "alertExprNote")] public string AlertExpressionNote { get; set; } /// <summary> /// The DataPoint Id /// </summary> [DataMember(Name = "dataPointId")] public int DataPointId { get; set; } /// <summary> /// The DataSource Id /// </summary> [DataMember(Name = "dataSourceId")] public int DataSourceId { get; set; } /// <summary> /// alertTransitionInterval /// </summary> [DataMember(Name = "alertTransitionInterval")] public int AlertTransitionInterval { get; set; } /// <summary> /// alertClearTransitionInterval /// </summary> [DataMember(Name = "alertClearTransitionInterval")] public int AlertClearTransitionInterval { get; set; } /// <summary> /// The consolidation function /// </summary> [DataMember(Name = "consolidateFunc")] public string ConsolidationFunction { get; set; } /// <summary> /// type /// </summary> [DataMember(Name = "type")] public int Type { get; set; } /// <summary> /// dataType /// </summary> [DataMember(Name = "dataType")] public int DataType { get; set; } /// <summary> /// maxDigits /// </summary> [DataMember(Name = "maxDigits")] public int MaxDigits { get; set; } /// <summary> /// postProcessorMethod /// </summary> [DataMember(Name = "postProcessorMethod")] public string PostProcessorMethod { get; set; } /// <summary> /// postProcessorMethod /// </summary> [DataMember(Name = "postProcessorParam")] public string PostProcessorParam { get; set; } /// <summary> /// rawDataFieldName /// </summary> [DataMember(Name = "rawDataFieldName")] public string RawDataFieldName { get; set; } /// <summary> /// maxValue /// </summary> [DataMember(Name = "maxValue")] public string MaxValue { get; set; } /// <summary> /// minValue /// </summary> [DataMember(Name = "minValue")] public string MinValue { get; set; } /// <summary> /// userParam1 /// </summary> [DataMember(Name = "userParam1")] public string UserParam1 { get; set; } /// <summary> /// userParam2 /// </summary> [DataMember(Name = "userParam2")] public string UserParam2 { get; set; } /// <summary> /// userParam3 /// </summary> [DataMember(Name = "userParam3")] public string UserParam3 { get; set; } /// <summary> /// alertForNoData /// </summary> [DataMember(Name = "alertForNoData")] public int AlertForNoData { get; set; } /// <summary> /// The alert expression /// </summary> [DataMember(Name = "alertExpr")] public string AlertExpression { get; set; } /// <summary> /// alertSubject /// </summary> [DataMember(Name = "alertSubject")] public string AlertSubject { get; set; } /// <summary> /// alertBody /// </summary> [DataMember(Name = "alertBody")] public string AlertBody { get; set; } }
using System; using System.ComponentModel; namespace OpenRiaServices.Data.DomainServices { /// <summary> /// Abstract base class that is responsible for loading data for the source collection /// of the collection view. /// </summary> public abstract class CollectionViewLoader { #region Constructors /// <summary> /// Initializes a new instance of the <see cref="CollectionViewLoader"/> /// </summary> protected CollectionViewLoader() { } #endregion #region Events /// <summary> /// Event raised when the value of <see cref="CanLoad"/> changes /// </summary> public event EventHandler CanLoadChanged; /// <summary> /// Event raised when an asynchronous <see cref="Load"/> operation completes /// </summary> public event AsyncCompletedEventHandler LoadCompleted; #endregion #region Properties /// <summary> /// Gets or sets a value that indicates whether a <see cref="Load"/> can be successfully invoked /// </summary> public abstract bool CanLoad { get; } #endregion #region Methods /// <summary> /// Asynchronously loads data into the source collection of the collection view /// </summary> /// <remarks> /// The <see cref="LoadCompleted"/> event will be raised upon successful completion as well as /// when cancellation and exceptions occur. /// </remarks> /// <param name="userState">The user state will be returned in the <see cref="LoadCompleted"/> event /// args. This parameter is optional. /// </param> /// <exception cref="InvalidOperationException"> is thrown when <see cref="CanLoad"/> is false</exception> public abstract void Load(object userState); /// <summary> /// Raises a <see cref="CanLoadChanged"/> event /// </summary> protected virtual void OnCanLoadChanged() { EventHandler handler = this.CanLoadChanged; if (handler != null) { handler(this, EventArgs.Empty); } } /// <summary> /// Raises a <see cref="LoadCompleted"/> event /// </summary> /// <param name="e">The event to raise</param> protected virtual void OnLoadCompleted(AsyncCompletedEventArgs e) { AsyncCompletedEventHandler handler = this.LoadCompleted; if (handler != null) { handler(this, e); } } #endregion } }
using UnityEngine; using System.Collections; public class DayNightLightIntensity : MonoBehaviour { public Gradient lightColor; public float maxIntensity; public float minIntensity; public float minPoint; public float maxAmbient; public float minAmbient; public float minAmbientPoint; public Gradient fogColor; public AnimationCurve fogDensity; public float fogScale = 1f; public float atmosphere = 0.4f; Light light; Skybox sky; Material skyMaterial; // Use this for initialization void Start() { light = GetComponent<Light>(); skyMaterial = RenderSettings.skybox; } // Update is called once per frame void Update() { calcIntensity(); float dot = calcAmbience(); light.color = lightColor.Evaluate(dot); //RenderSettings.ambientLight = light.color; //RenderSettings.fogColor = lightColor.Evaluate(dot); //RenderSettings.fogDensity = fogDensity.Evaluate(dot) * fogScale; } private float calcAmbience() { float tRange = 1 - minAmbientPoint; float dot = Mathf.Clamp01((Vector3.Dot(light.transform.forward, Vector3.down) - minPoint) / tRange); //float i = ((maxAmbient - minAmbient) * dot) + minAmbient; //RenderSettings.ambientIntensity = i; return dot; } private void calcIntensity() { float tRange = 1 - minPoint; float dot = Mathf.Clamp01((Vector3.Dot(light.transform.forward, Vector3.down) - minPoint) / tRange); float i = ((maxIntensity - minIntensity) * dot) + minIntensity; light.intensity = i; } }
using System; using System.Collections.ObjectModel; using Avalonia.Controls.Platform; namespace Avalonia.Win32 { public class WindowsMountedVolumeInfoProvider : IMountedVolumeInfoProvider { public IDisposable Listen(ObservableCollection<MountedVolumeInfo> mountedDrives) { Contract.Requires<ArgumentNullException>(mountedDrives != null); return new WindowsMountedVolumeInfoListener(mountedDrives); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerMovement : MonoBehaviour{ public CharacterController2D controller; public float runSpeed = 40f; public Animator animator; public Rigidbody2D rb; GameManager gameManager; bool collision = false; float horizontalMove = 0; bool jump = false; bool crouch = false; // Start is called before the first frame update void Start(){ gameManager = FindObjectOfType<GameManager>(); } // Update is called once per frame void Update(){ horizontalMove = Input.GetAxisRaw("Horizontal") * runSpeed; animator.SetFloat("Speed", Mathf.Abs(horizontalMove)); if (Input.GetButtonDown("Jump")){ gameManager.sound_jump(); jump = true; } if (Input.GetButtonDown("Crouch")){ crouch = true; }else if(Input.GetButtonUp("Crouch")){ crouch = false; } if (rb.position.y < -9.0){ gameManager.GameOver(); } } void FixedUpdate(){ if (rb.velocity.y > 0.0 && !collision){ animator.SetBool("Up", true); animator.SetBool("Down", false); } if (rb.velocity.y < 0.0 && !collision){ animator.SetBool("Down", true); animator.SetBool("Up", false); } controller.Move(horizontalMove * Time.fixedDeltaTime, crouch, jump); jump = false; } private void OnCollisionEnter2D(Collision2D collision){ if (collision.collider.tag == "Ground"){ this.collision = true; animator.SetBool("Down", false); animator.SetBool("Up", false); } if (collision.collider.tag == "Enemy"){ gameManager.GameOver(); } } private void OnCollisionExit2D(Collision2D collision){ if (collision.collider.tag == "Ground"){ this.collision = false; } } private void OnTriggerStay2D(Collider2D collision){ if (Input.GetKey("e")){ GameObject.Find("Chest").GetComponent<Animator>().enabled = true; GameObject.Find("Chest").GetComponent<Animator>().Play("Chest"); gameManager.sound_chest(); gameManager.CheckpointSave(gameObject.GetComponent<Transform>().position); } } private void OnTriggerEnter2D(Collider2D collision){ if (collision.CompareTag("BossControl")){ gameManager.Set_bossZone(true); } } }
using System; using System.Collections.Generic; using System.Linq; using Amazon.S3; using Amazon.S3.IO; namespace Sync.Net.IO { public class S3DirectoryObject : IDirectoryObject { private readonly string _bucketName; private readonly IAmazonS3 _s3Client; private S3DirectoryInfo _s3DirectoryInfo; private string key; private string _key; public S3DirectoryObject(string bucketName) : this(new AmazonS3Client(), bucketName) { } public S3DirectoryObject(IAmazonS3 s3Client, string bucketName) : this(s3Client, new S3DirectoryInfo(s3Client, bucketName)) { _bucketName = bucketName; } private S3DirectoryObject(IAmazonS3 s3Client, S3DirectoryInfo directoryInfo) { _s3DirectoryInfo = directoryInfo; _bucketName = _s3DirectoryInfo.Bucket.Name; _s3Client = s3Client; } public S3DirectoryObject(IAmazonS3 s3Client, string bucketName, string key) : this(s3Client, new S3DirectoryInfo(s3Client, bucketName, key)) { _key = key; } public string Name => _s3DirectoryInfo.Name; public bool Exists => _s3DirectoryInfo.Exists; public string FullName => _s3DirectoryInfo.FullName; public IFileObject GetFile(string name) { return new S3FileObject(_s3Client, _bucketName, GetSubKey(name)); } public IEnumerable<IFileObject> GetFiles(bool recursive = false) { throw new NotImplementedException(); } public IEnumerable<IDirectoryObject> GetDirectories() { return _s3DirectoryInfo.GetDirectories().Select(x => new S3DirectoryObject(_s3Client, x)); } public void Create() { _s3DirectoryInfo.Create(); } public IDirectoryObject GetDirectory(string name) { return new S3DirectoryObject(_s3Client, _bucketName, GetSubKey(name)); } public void Rename(string newName) { var newKey = _key.Replace(Name, newName); var newDirectory = new S3DirectoryInfo(_s3Client, _bucketName, newKey); if(!newDirectory.Exists) newDirectory.Create(); foreach (var s3FileInfo in _s3DirectoryInfo.GetFiles()) { s3FileInfo.MoveTo(newDirectory); } _s3DirectoryInfo.Delete(); _s3DirectoryInfo = newDirectory; } private string GetSubKey(string key) { if (_s3DirectoryInfo.Bucket.Name == _s3DirectoryInfo.Name) return key; return _s3DirectoryInfo.Name + $"\\{key}"; } } }
// 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; namespace Microsoft.CodeAnalysis { internal abstract class SymbolFactory<ModuleSymbol, TypeSymbol> where TypeSymbol : class { internal abstract TypeSymbol GetUnsupportedMetadataTypeSymbol(ModuleSymbol moduleSymbol, BadImageFormatException exception); /// <summary> /// Produce unbound generic type symbol if the type is a generic type. /// </summary> internal abstract TypeSymbol MakeUnboundIfGeneric(ModuleSymbol moduleSymbol, TypeSymbol type); internal abstract TypeSymbol GetSZArrayTypeSymbol(ModuleSymbol moduleSymbol, TypeSymbol elementType, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers); internal abstract TypeSymbol GetMDArrayTypeSymbol(ModuleSymbol moduleSymbol, int rank, TypeSymbol elementType, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers, ImmutableArray<int> sizes, ImmutableArray<int> lowerBounds); /// <summary> /// Produce constructed type symbol. /// </summary> /// <param name="moduleSymbol"></param> /// <param name="generic"> /// Symbol for generic type. /// </param> /// <param name="arguments"> /// Generic type arguments, including those for containing types. /// </param> /// <param name="refersToNoPiaLocalType"> /// Flags for arguments. Each item indicates whether corresponding argument refers to NoPia local types. /// </param> internal abstract TypeSymbol SubstituteTypeParameters(ModuleSymbol moduleSymbol, TypeSymbol generic, ImmutableArray<KeyValuePair<TypeSymbol, ImmutableArray<ModifierInfo<TypeSymbol>>>> arguments, ImmutableArray<bool> refersToNoPiaLocalType); internal abstract TypeSymbol MakePointerTypeSymbol(ModuleSymbol moduleSymbol, TypeSymbol type, ImmutableArray<ModifierInfo<TypeSymbol>> customModifiers); internal abstract TypeSymbol GetSpecialType(ModuleSymbol moduleSymbol, SpecialType specialType); internal abstract TypeSymbol GetSystemTypeSymbol(ModuleSymbol moduleSymbol); internal abstract TypeSymbol GetEnumUnderlyingType(ModuleSymbol moduleSymbol, TypeSymbol type); internal abstract bool IsVolatileModifierType(ModuleSymbol moduleSymbol, TypeSymbol type); internal abstract Cci.PrimitiveTypeCode GetPrimitiveTypeCode(ModuleSymbol moduleSymbol, TypeSymbol type); } }
using System; using System.Collections.Generic; using System.Text; using Antlr.Runtime; using Haskell.CoreParser.AbstractSyntaxTree.AtomicExpressionTree; using Haskell.CoreParser.AbstractSyntaxTree.ArgumentTree; namespace Haskell.CoreParser.AbstractSyntaxTree.ExpressionTree { public class ApplicationExpression : Expression { public ApplicationExpression(IToken payload) : base(payload) { } public AtomicExpression Expression { get { return (AtomicExpression) Children[0]; } } public IList<Argument> Arguments { get { List<Argument> arguments = new List<Argument>(ChildCount - 1); for (int i = 1; i < ChildCount; i++) { arguments.Add((Argument)Children[i]); } return arguments; } } public override string Text { get { return String.Format("ApplicationExpression({0})", Expression.Text); } } public override object Accept(ICoreVisitor visitor, object o) { return visitor.Visit(this, o); } } }
using UnityEngine; using System.Collections; public class ColorRegistry { public static Color backgroundColor = new Color32(0,0,0,255); public static Color foregroundColor = new Color32(0, 0, 170, 255); public static Color textColor = new Color32(170, 170, 170, 255); }
using System.Diagnostics; namespace NppNetInf { public abstract class PluginMain { public abstract string PluginName { get; } public PluginMain() { #if RUN_DEBUGGER Debugger.Launch(); #endif } public abstract void CommandMenuInit(); public virtual void SetToolBarIcon() { } public virtual void OnNotification(ScNotification notification) { } public virtual void PluginCleanUp() { } } }
using IRunes.App.Controllers; using IRunes.App.Controllers.Contracts; using IRunes.Data; using IRunes.Services; using IRunes.Services.Contracts; using SIS.Framework.Api; using SIS.Services.Contracts; namespace IRunes.App { public class Startup : MvcApplication { public override void ConfigureServices(IServiceCollection services) { services.RegisterDbContext<IRunesDbContext>(); services.RegisterService<IHomeController, HomeController>(); services.RegisterService<IUserService, UserService>(); services.RegisterService<IUsersController, UsersController>(); services.RegisterService<IAlbumService, AlbumService>(); services.RegisterService<IAlbumsController, AlbumsController>(); services.RegisterService<IAlbumTrackService, AlbumTrackService>(); services.RegisterService<ITrackService, TrackService>(); services.RegisterService<ITracksController, TracksController>(); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml; namespace Engine.Saving.Json { class JsonGuid : JsonValue<Guid> { public JsonGuid(JsonSaver xmlWriter) : base(xmlWriter, "Guid") { } public override void writeValue(Guid value, JsonWriter writer) { writer.WriteValue(value.ToString()); } public override Guid parseValue(JsonReader xmlReader) { return new Guid(xmlReader.ReadAsString()); } } }
using System; using System.ComponentModel.Composition; using System.Windows; namespace ColorPicker.Helpers { [Export(typeof(AppStateHandler))] public class AppStateHandler { [ImportingConstructor] public AppStateHandler() { Application.Current.MainWindow.Closed += MainWindow_Closed; } public event EventHandler AppShown; public event EventHandler AppHidden; public event EventHandler AppClosed; public void ShowColorPicker() { AppShown?.Invoke(this, EventArgs.Empty); Application.Current.MainWindow.Opacity = 0; Application.Current.MainWindow.Visibility = Visibility.Visible; } public void HideColorPicker() { Application.Current.MainWindow.Opacity = 0; Application.Current.MainWindow.Visibility = Visibility.Collapsed; AppHidden?.Invoke(this, EventArgs.Empty); } public void SetTopMost() { Application.Current.MainWindow.Topmost = false; Application.Current.MainWindow.Topmost = true; } private void MainWindow_Closed(object sender, EventArgs e) { AppClosed?.Invoke(this, EventArgs.Empty); } } }
using System.IO; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading.Tasks; namespace OwnID.Extensibility.Json { public static class OwnIdSerializer { private static readonly JsonSerializerOptions DefaultOptions = GetDefaultProperties(); public static string Serialize(object data, JsonSerializerOptions options = null) { return JsonSerializer.Serialize(data, options ?? DefaultOptions); } public static T Deserialize<T>(string json, JsonSerializerOptions options = null) { return JsonSerializer.Deserialize<T>(json, options ?? DefaultOptions); } public static async Task<T> DeserializeAsync<T>(Stream jsonStream, JsonSerializerOptions options = null) { return await JsonSerializer.DeserializeAsync<T>(jsonStream, options ?? DefaultOptions); } public static JsonSerializerOptions GetDefaultProperties() { return new JsonSerializerOptions { Converters = {new JsonStringEnumConverter(JsonNamingPolicy.CamelCase), new AutoPrimitiveToStringConverter()}, IgnoreNullValues = true, PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; ; } } }
using RedditSharp; namespace SnooViewer { public static class DataContext { public static Reddit Reddit { get; set; } public static string Token { get; set; } public static string RefreshToken { get; set; } } }
using GenArt.Core.Classes; namespace GenArt.Core.AST.Mutation { public static class DnaPointMutateExtension { public static void Mutate(this DnaPoint dnaPoint, DnaDrawing dnaDrawing) { if (Tools.WillMutate(Settings.ActiveMovePointMaxMutationRate)) { dnaPoint.X = Tools.GetRandomNumber(0, dnaDrawing.Width); dnaPoint.Y = Tools.GetRandomNumber(0, dnaDrawing.Height); dnaDrawing.SetDirty(); } if (Tools.WillMutate(Settings.ActiveMovePointMidMutationRate)) { dnaPoint.X = MathUtils.Clamp( dnaPoint.X + Tools.GetRandomNumber(-Settings.ActiveMovePointRangeMid, Settings.ActiveMovePointRangeMid), 0, dnaDrawing.Width); dnaPoint.Y = MathUtils.Clamp( dnaPoint.Y + Tools.GetRandomNumber(-Settings.ActiveMovePointRangeMid, Settings.ActiveMovePointRangeMid), 0, dnaDrawing.Height); dnaDrawing.SetDirty(); } if (Tools.WillMutate(Settings.ActiveMovePointMinMutationRate)) { dnaPoint.X = MathUtils.Clamp( dnaPoint.X + Tools.GetRandomNumber(-Settings.ActiveMovePointRangeMin, Settings.ActiveMovePointRangeMin), 0, dnaDrawing.Width); dnaPoint.Y = MathUtils.Clamp( dnaPoint.Y + Tools.GetRandomNumber(-Settings.ActiveMovePointRangeMin, Settings.ActiveMovePointRangeMin), 0, dnaDrawing.Height); dnaDrawing.SetDirty(); } } } }
// Copyright 2021 Niantic, Inc. All Rights Reserved. using System.Collections.Generic; using Niantic.ARDK.AR; using Niantic.ARDK.AR.Anchors; using Niantic.ARDK.AR.ARSessionEventArgs; using Niantic.ARDK.AR.HitTest; using Niantic.ARDK.External; using Niantic.ARDK.Utilities; using Niantic.ARDK.Utilities.Logging; using UnityEngine; namespace Niantic.ARDKExamples.Helpers { //! A helper class that demonstrates hit tests based on user input /// <summary> /// A sample class that can be added to a scene and takes user input in the form of a screen touch. /// A hit test is run from that location. If a plane is found, spawn a game object at the /// hit location. /// </summary> public class ARHitTester: MonoBehaviour { /// The camera used to render the scene. Used to get the center of the screen. public Camera Camera; /// The types of hit test results to filter against when performing a hit test. [EnumFlagAttribute] public ARHitTestResultType HitTestType = ARHitTestResultType.ExistingPlane; /// The object we will place when we get a valid hit test result! public GameObject PlacementObjectPf; /// A list of placed game objects to be destroyed in the OnDestroy method. private List<GameObject> _placedObjects = new List<GameObject>(); /// Internal reference to the session, used to get the current frame to hit test against. private IARSession _session; private void Start() { ARSessionFactory.SessionInitialized += OnAnyARSessionDidInitialize; } private void OnAnyARSessionDidInitialize(AnyARSessionInitializedArgs args) { _session = args.Session; _session.Deinitialized += OnSessionDeinitialized; } private void OnSessionDeinitialized(ARSessionDeinitializedArgs args) { ClearObjects(); } private void OnDestroy() { ARSessionFactory.SessionInitialized -= OnAnyARSessionDidInitialize; _session = null; ClearObjects(); } private void ClearObjects() { foreach (var placedObject in _placedObjects) { Destroy(placedObject); } _placedObjects.Clear(); } private void Update() { if (_session == null) { return; } if (PlatformAgnosticInput.touchCount <= 0) { return; } var touch = PlatformAgnosticInput.GetTouch(0); if (touch.phase == TouchPhase.Began) { TouchBegan(touch); } } private void TouchBegan(Touch touch) { var currentFrame = _session.CurrentFrame; if (currentFrame == null) { return; } var results = currentFrame.HitTest ( Camera.pixelWidth, Camera.pixelHeight, touch.position, HitTestType ); int count = results.Count; Debug.Log("Hit test results: " + count); if (count <= 0) return; // Get the closest result var result = results[0]; var hitPosition = result.WorldTransform.ToPosition(); // Assumes that the prefab is one unit tall and getting scene height from local scale // Place the object on top of the surface rather than exactly on the hit point // Note (Kelly): Now that vertical planes are also supported in-editor, need to be // more elegant about how/if to handle instantiation of the cube hitPosition.y += PlacementObjectPf.transform.localScale.y / 2.0f; _placedObjects.Add(Instantiate(PlacementObjectPf, hitPosition, Quaternion.identity)); var anchor = result.Anchor; Debug.LogFormat ( "Spawning cube at {0} (anchor: {1})", hitPosition.ToString("F4"), anchor == null ? "none" : anchor.AnchorType + " " + anchor.Identifier ); } } }
using Prism; using Prism.DryIoc; using Prism.Ioc; using System; using Xamarin.Forms; using Xamarin.Forms.Xaml; using XLojaDemo.App.Interfaces; using XLojaDemo.App.Services; using XLojaDemo.App.ViewModels; using XLojaDemo.App.Views; namespace XLojaDemo.App { public partial class App : PrismApplication { public App() : this(null) { } public App(IPlatformInitializer initializer) : this(initializer, true) { } public App(IPlatformInitializer initializer, bool setFormsDependencyResolver) : base(initializer, setFormsDependencyResolver) { } protected override async void OnInitialized() { InitializeComponent(); await NavigationService.NavigateAsync("MainPage"); } protected override void RegisterTypes(IContainerRegistry containerRegistry) { containerRegistry.RegisterForNavigation<NavigationPage>(); containerRegistry.RegisterForNavigation<MainPage, MainViewModel>(); containerRegistry.RegisterForNavigation<MenuPage, MenuViewModel>(); containerRegistry.RegisterForNavigation<CadastroProdutoPage, CadastroProdutoViewModel>(); containerRegistry.RegisterForNavigation<ProdutosPage, ProdutosViewModel>(); containerRegistry.RegisterForNavigation<EditarProdutoPage, EditarProdutoViewModel>(); containerRegistry.RegisterSingleton<ILojaApiService, LojaApiService>(); } } }
using System; public class NugetVersionChecker { public NugetVersionChecker() { //this class should check the items found by the MarkdownHelper and compare them with what the nuget API returns } }
using Unity.Entities; namespace NSprites { public struct SpriteRenderID : ISharedComponentData { public int id; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ObjSpike : MonoBehaviour { // ======================================================================== // OBJECT AND COMPONENT REFERENCES // ======================================================================== CharacterGroundedDetector characterGroundedDetector; GameObject topPositionObj; void InitReferences() { characterGroundedDetector = GetComponent<CharacterGroundedDetector>(); topPositionObj = transform.Find("Top Position").gameObject; } // ======================================================================== float topAngle => transform.rotation.eulerAngles.z; // ======================================================================== public void TryAction(Character character, float collisionAngle) { if (Mathf.Abs(collisionAngle - topAngle) > 0.1) return; DoAction(character); } public void OnCollisionEnter(Collision collision) { if (topAngle == 0) return; GameObject other = collision.gameObject; Character[] characters = other.GetComponentsInParent<Character>(); if (characters.Length == 0) return; Character character = characters[0]; ContactPoint hit = collision.GetContact(0); float collisionAngle = ( Quaternion.FromToRotation(Vector3.up, hit.normal).eulerAngles.z + 180 ) % 360; TryAction(character, collisionAngle); } public void OnCollisionStay(Collision collision) { OnCollisionEnter(collision); } void Update() { foreach(Character character in characterGroundedDetector.characters) { TryAction(character, character.transform.eulerAngles.z); // Save script time by only processing one character // Triggering the action via the GroundedDetectors is a fallback anyways break; } } public void OnCollisionExit(Collision collision) {} public void OnTriggerEnter(Collider other) {} public void OnTriggerExit(Collider other) {} // ======================================================================== void Start() { InitReferences(); } public void DoAction(Character character) { character.Hurt(character.position.x <= transform.position.x, true); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace ObjectPools { public class PoolObject : MonoBehaviour { bool active; public static void AddToObject(GameObject g) { if (g.GetComponent<PoolObject>() == null) { g.AddComponent(typeof(PoolObject)); } } public void Deactivate() { active = false; ReturnToOriginalPos(); } public void Activate() { if (GetComponent<IPoolObject>() != null) { GetComponent<IPoolObject>().Activate(); } active = true; } void ReturnToOriginalPos() { transform.position = new Vector3(1000, -1000, 1000); print(transform.position); } public bool Active { get => active; set => active = value; } } }
using GMap.NET; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace dajiangspider { public static class GMapEx { public static PointLatLng ToLatLng(this double[] p) { if (p.Length < 2) return new PointLatLng(); return new PointLatLng(p[0],p[1]); } } }
using DragonSpark.Model.Selection; namespace DragonSpark.Application.Runtime.Operations; public interface IReporter<T> : IReporter<T, T> {} public interface IReporter<TIn, out TOut> : ISelect<Report<TIn>, TOut> {}
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab_05_FolderSize { class folderSize { static void Main(string[] args) { MeasureFolder(); } //Измерва размера на файловете в директорията. static void MeasureFolder() { var totalSize = 0.0; string[] filesInTheFolder = Directory.GetFiles("../../TestFolder"); foreach(var file in filesInTheFolder) { FileInfo size =new FileInfo(file); totalSize += size.Length; } totalSize = totalSize / 1024 / 1024; CreateOutput(totalSize); } //Създава файл, който да съдържа отговора. static void CreateOutput(double totalSize) { File.WriteAllText("output.txt", totalSize.ToString()); PrintOutput(); } //Принтира отговора от файл. static void PrintOutput() { Console.WriteLine(File.ReadAllText("output.txt")); } } }
using System.Threading.Tasks; using GreatWall.Service.Abstractions; using GreatWall.Service.Dtos; using GreatWall.Service.Dtos.Requests; using GreatWall.Service.Queries; using Microsoft.AspNetCore.Mvc; using Util.Ui.Controllers; namespace GreatWall.Apis.Systems { /// <summary> /// 模块控制器 /// </summary> public class ModuleController : TreeTableControllerBase<ModuleDto, ResourceQuery> { /// <summary> /// 初始化模块控制器 /// </summary> /// <param name="service">模块服务</param> /// <param name="queryService">模块查询服务</param> public ModuleController( IModuleService service, IQueryModuleService queryService ) : base( queryService ) { ModuleService = service; } /// <summary> /// 模块服务 /// </summary> public IModuleService ModuleService { get; } /// <summary> /// 创建模块 /// </summary> /// <param name="request">创建参数</param> [HttpPost] public async Task<IActionResult> CreateAsync( [FromBody] CreateModuleRequest request ) { var id = await ModuleService.CreateAsync( request ); return Success( id ); } /// <summary> /// 修改 /// </summary> /// <param name="request">修改参数</param> [HttpPut] public async Task<IActionResult> UpdateAsync( [FromBody] ModuleDto request ) { await ModuleService.UpdateAsync( request ); return Success(); } } }
 using Archimedes.Patterns.CommandLine; using NUnit.Framework; namespace Archimedes.Patterns.Test { [TestFixture] class CommandLineParserTest { [Test] public void ParseTest() { string[] args = {"/simple.prop", "hellowurld"}; var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual("hellowurld", options.GetParameterValue("simple.prop")); } [Test] public void ParseTestFlag2() { string[] args = { "-simple.prop", "hellowurld" }; var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual("hellowurld", options.GetParameterValue("simple.prop")); } /* [Test] public void ParseTestFlag3() { string[] args = { "--simple.prop", "hellowurld" }; var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual("hellowurld", options.GetParameterValue("simple.prop")); }*/ [Test] public void ParseTestfAIL() { string[] args = { "\\simple.prop", "hellowurld" }; // Not working, since flag is wrong way. var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual(null, options.GetParameterValue("simple.prop")); } [Test] public void ParseTestSpaces() { string[] args = { "/simple.filepath", @"C:\folder with spaces\and file with.txt" }; var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual(@"C:\folder with spaces\and file with.txt", options.GetParameterValue("simple.filepath")); } [Test] public void ParseBooleanFlag() { string[] args = { "/quiet", "True" }; var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual(true.ToString(), options.GetParameterValue("quiet")); } [Test] public void ParseBooleanFlagShorthand() { string[] args = { "/quiet" }; var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual(true.ToString(), options.GetParameterValue("quiet")); } [Test] public void ParseTestSpecail() { string[] args = { "/erp.connection", @"C:\Temp\Planung\DATA-007_Zu" }; var options = CommandLineParser.ParseCommandLineArgs(args); Assert.AreEqual(@"C:\Temp\Planung\DATA-007_Zu", options.GetParameterValue("erp.connection")); } } }
namespace HotChocolate.Types.Descriptors.Definitions { public interface IDefinitionFactory<out T> : IDefinitionFactory where T : DefinitionBase { new T CreateDefinition(); } }
using System; using System.Activities; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace InfPro.Dotiga.Activities { public class CreateTaskActivity : NativeActivity<string> { public InArgument<string> ResponsibleUser { get; set; } public InArgument<Dictionary<string, object>> ReadonlyTaskFields { get; set; } public InArgument<Dictionary<string, object>> EditableTaskFields { get; set; } public InArgument<List<string>> TaskCommands { get; set; } protected override void Execute(NativeActivityContext context) { } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; namespace XLabs.ContentProvider { public class Query<T> : IOrderedQueryable<T> { public Query(IQueryProvider provider) { this.provider = provider; this.expression = Expression.Constant(this); } public Query(IQueryProvider provider, Expression expression) { this.provider = provider; this.expression = expression; } public IEnumerator<T> GetEnumerator() { var enumerable = ((IEnumerable<T>)this.provider.Execute(this.expression)); return (enumerable ?? Enumerable.Empty<T>()).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } public Type ElementType { get { return typeof(T); } } public Expression Expression { get { return this.expression; } } public IQueryProvider Provider { get { return this.provider; } } private readonly Expression expression; private readonly IQueryProvider provider; } }
// This file is licensed to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; namespace Spines.Mahjong.Analysis.Classification { /// <summary> /// Parses the shorthand representation of a hand. /// </summary> public class ShorthandParser { /// <summary> /// Creates a new instance of ShorthandParser. /// </summary> /// <param name="hand">The string that represents the hand.</param> public ShorthandParser(string hand) { _hand = hand; } /// <summary> /// The concealed tiles in the hand. /// </summary> public IEnumerable<Tile> Tiles { get { var concealed = Concealed.ToList(); for (var i = 0; i < 34; ++i) { for (var c = 0; c < concealed[i]; ++c) { yield return new Tile {Suit = IdToSuit[i / 9], Index = i % 9, Location = TileLocation.Concealed}; } } } } /// <summary> /// The melds in the hand. /// </summary> public IEnumerable<Meld> Melds { get { var manzu = ManzuMeldIds.Select(meldId => new Meld(Suit.Manzu, meldId)); var pinzu = PinzuMeldIds.Select(meldId => new Meld(Suit.Pinzu, meldId)); var souzu = SouzuMeldIds.Select(meldId => new Meld(Suit.Souzu, meldId)); var jihai = JihaiMeldIds.Select(meldId => new Meld(Suit.Jihai, meldId)); return manzu.Concat(pinzu).Concat(souzu).Concat(jihai); } } private static readonly Suit[] IdToSuit = {Suit.Manzu, Suit.Pinzu, Suit.Souzu, Suit.Jihai}; private readonly string _hand; private IEnumerable<int> GetMelds(char tileGroupName, char[] forbidden) { var regex = new Regex(@"(\d*)" + tileGroupName); var groups = regex.Matches(_hand).OfType<Match>().SelectMany(m => m.Groups.OfType<Group>().Skip(1)); foreach (var captureGroup in groups) { if (forbidden.Intersect(captureGroup.Value).Any()) { throw GetForbiddenDigitsException(tileGroupName, forbidden); } var tiles = captureGroup.Value.Select(GetTileTypeIndex).OrderBy(x => x).ToList(); var i = tiles.Min(); if (tiles.SequenceEqual(Enumerable.Range(i, 3))) { yield return i; } else if (tiles.SequenceEqual(Enumerable.Repeat(i, 3))) { yield return 7 + i; } else if (tiles.SequenceEqual(Enumerable.Repeat(i, 4))) { yield return 7 + 9 + i; } else { throw new FormatException(captureGroup.Value + " is not a valid meld."); } } } private IEnumerable<int> GetTiles(char tileGroupName, int typesInSuit, char[] forbidden) { var regex = new Regex(@"(\d*)" + tileGroupName); var groups = regex.Matches(_hand).OfType<Match>().SelectMany(m => m.Groups.OfType<Group>().Skip(1)); var digits = groups.SelectMany(g => g.Value).ToList(); if (digits.Intersect(forbidden).Any()) { throw GetForbiddenDigitsException(tileGroupName, forbidden); } var tiles = digits.Select(GetTileTypeIndex); var idToCount = tiles.GroupBy(t => t).ToDictionary(g => g.Key, g => g.Count()); return Enumerable.Range(0, typesInSuit).Select(i => idToCount.ContainsKey(i) ? idToCount[i] : 0); } private static FormatException GetForbiddenDigitsException(char tileGroupName, char[] forbidden) { return new FormatException(string.Join(",", forbidden) + " are not allowed in group " + tileGroupName + "."); } /// <summary> /// Retruns the index of a tile type within a suit. /// </summary> /// <param name="digit">The digit that represents the tile in shorthand notation.</param> /// <returns>The index of the tile type.</returns> private static int GetTileTypeIndex(char digit) { var numericValue = (int) char.GetNumericValue(digit); if (numericValue == 0) { return 4; } return numericValue - 1; } /// <summary> /// The counts of the 34 tile types, in order manzu 1-9, pinzu 1-9, souzu 1-9, honors 1-7. /// </summary> internal IEnumerable<int> Concealed => Manzu.Concat(Pinzu).Concat(Souzu).Concat(Jihai); /// <summary> /// The counts of the 9 manzu types, in order 1-9. /// </summary> internal IEnumerable<int> Manzu => GetTiles('m', 9, new char[0]); /// <summary> /// The counts of the 9 pinzu types, in order 1-9. /// </summary> internal IEnumerable<int> Pinzu => GetTiles('p', 9, new char[0]); /// <summary> /// The counts of the 9 souzu types, in order 1-9. /// </summary> internal IEnumerable<int> Souzu => GetTiles('s', 9, new char[0]); /// <summary> /// The counts of the 7 honor types, in order 1-7. /// </summary> internal IEnumerable<int> Jihai => GetTiles('z', 7, new[] {'0', '8', '9'}); internal IEnumerable<int> ManzuMeldIds => GetMelds('M', new char[0]); internal IEnumerable<int> PinzuMeldIds => GetMelds('P', new char[0]); internal IEnumerable<int> SouzuMeldIds => GetMelds('S', new char[0]); internal IEnumerable<int> JihaiMeldIds => GetMelds('Z', new[] {'0', '8', '9'}); } }
namespace HardDev.Context { public enum ThreadContextType { UndefinedContext, ThreadContext, StaticThreadPool, DynamicThreadPool, UndefinedThreadPool } }
using Clinicas.ViewModels.EstadoConsulta; using FluentValidation; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Clinicas.Validations.EstadoConsulta { public class EstadoConsultaValidator: AbstractValidator<EstadoConsultaVM> { public EstadoConsultaValidator() { RuleFor(x => x.Estado).NotNull().NotEmpty().Length(5, 15); } } }
using System; using System.Collections.Generic; namespace ReduxSimple.Uwp.Samples.Pokedex { public class GetPokemonListAction { } public class GetPokemonListFullfilledAction { public List<PokemonGeneralInfo> Pokedex { get; set; } } public class GetPokemonListFailedAction { public Exception Exception { get; set; } } public class GetPokemonByIdAction { public int Id { get; set; } } public class GetPokemonByIdFullfilledAction { public Pokemon Pokemon { get; set; } } public class GetPokemonByIdFailedAction { public Exception Exception { get; set; } } public class UpdateSearchStringAction { public string Search { get; set; } } public class ResetPokemonAction { } }
using System.Collections.Generic; using Linux.FileSystem; using Linux.IO; namespace Linux.Configuration { public abstract class FileDatabase<T> { protected VirtualFileTree Fs { get; set; } public FileDatabase(VirtualFileTree fs) { Fs = fs; } public abstract void Add(T item); public int Count() { return LoadFromFs().Count; } public abstract File DataSource(); protected abstract T ItemFromTokens(string[] tokens); protected List<T> LoadFromFs() { string[] lines = ReadLines(); List<T> items = new List<T>(); foreach (string line in lines) { string[] tokens = line.Split(':'); T item = ItemFromTokens(tokens); if (item != null) { items.Add(item); } } return items; } public List<T> ToList() { return LoadFromFs(); } protected string[] ReadLines() { using (ITextIO stream = Fs.Open(DataSource().Path, AccessMode.O_RDONLY)) { return stream.ReadLines(); } } protected int AppendLine(string line) { using(ITextIO stream = Fs.Open(DataSource().Path, AccessMode.O_APONLY)) { return stream.WriteLine(line); } } } }
using Silverback.Integration.OpenTracing; using Silverback.Messaging.Configuration; namespace Microsoft.Extensions.DependencyInjection { public static class SilverbackBuilderExtensions { public static ISilverbackBuilder UseOpenTracing(this ISilverbackBuilder builder) { builder.Services .AddSingletonBrokerBehavior<ConsumerTracingBehavior>() .AddSingletonBrokerBehavior<ProducerTracingBehavior>(); return builder; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Maquina_de_Cafe_Virtual.Model { class Moedas { public enumMoedas valorMoeda; public Moedas(enumMoedas valorMoeda) { this.valorMoeda = valorMoeda; } } public enum enumMoedas : int { dezCentavos = 10, vinteCincoCentavos = 25, cinquinetaCentavos = 50, umReal = 100 } }
using SqlRepoEx.Core; namespace SqlRepoEx.MsSqlServer { public class FilterGroup : FilterGroupBase { } }
using System.Collections.Generic; using TRGE.Core; namespace TRGE.View.Model.Data { public class FlaggedLevelData : List<FlaggedLevel> { public FlaggedLevelData(List<MutableTuple<string, string, bool>> unarmedLevels) { foreach (MutableTuple<string, string, bool> data in unarmedLevels) { Add(new FlaggedLevel(data.Item1, data.Item2, data.Item3)); } } public List<MutableTuple<string, string, bool>> ToTupleList() { List<MutableTuple<string, string, bool>> result = new List<MutableTuple<string, string, bool>>(); foreach (FlaggedLevel level in this) { result.Add(level.ToTuple()); } return result; } } public class FlaggedLevel : BaseLevelData { public bool Flag { get; set; } public FlaggedLevel(string levelID, string levelName, bool flag) :base(levelID, levelName) { Flag = flag; } public MutableTuple<string, string, bool> ToTuple() { return new MutableTuple<string, string, bool>(LevelID, LevelName, Flag); } } }
// #region File Annotation // // Author:Zhiqiang Li // // FileName:AppCacheKey.cs // // Project:RedisLock.AspNetCore // // CreateDate:2018/04/27 // // Note: The reference to this document code must not delete this note, and indicate the source! // // #endregion namespace RedisLock.AspNetCore.Config { public static class AppCacheKey { public static string ProductLock = "xc.product.lock.{0}"; } }
using System.Diagnostics.CodeAnalysis; namespace TMFileParser.Models.tm7 { [ExcludeFromCodeCoverage] public class TM7Validations { } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace CaptainHook.Api.Controllers { /// <summary> /// Probe controller /// </summary> [Route("[controller]")] [AllowAnonymous] public class ProbeController : Controller { /// <summary> /// Returns a probe result /// </summary> /// <returns>Returns status code 200</returns> [HttpGet] [HttpHead] public IActionResult GetProbe() { return Ok("Healthy"); } } }
using System; using System.IO; using System.Linq; using kUMTE_2018.Models; using SQLite; using Xamarin.Forms; using Xamarin.Forms.Xaml; [assembly: XamlCompilation (XamlCompilationOptions.Compile)] namespace kUMTE_2018 { public partial class App : Application { public static string AppDataDir = string.Empty; public static string AppDataDbString = string.Empty; public App () { InitializeComponent(); MainPage = new MainPage(); } public App(string appDataDir) { InitializeComponent(); AppDataDir = appDataDir; AppDataDbString = Path.Combine(App.AppDataDir, AppSetting.DbFileName); InitializeDb(); MainPage = new NavigationPage(new MainPage()); } private void InitializeDb() { using (var conn = new SQLiteConnection(AppDataDbString)) { conn.CreateTable<AppSetting>(); var data = conn.Table<AppSetting>(); if (!data.Any()) { var d = new AppSetting() { AppName = "kUMTE_2018", Author = "Jaroslav Langer", AuthKey = "2f6421653f8eb04e42492f94615d6b32daf343bc" }; conn.Insert(d); } } } protected override void OnStart () { // Handle when your app starts } protected override void OnSleep () { // Handle when your app sleeps } protected override void OnResume () { // Handle when your app resumes } } }
using System; using JetBrains.Annotations; namespace UniFlow.Signal { [PublicAPI] public class HandleEventSignal : SignalBase<HandleEventSignal, HandleEventType> { public HandleEventType HandleEventType { get; private set; } public override HandleEventType ComparableValue { get => HandleEventType; set => HandleEventType = value; } } [PublicAPI] public enum HandleEventType { Activate, Deactivate, } [Serializable] public class HandleEventTypeCollector : ValueCollectorBase<HandleEventType> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using SF.Core.QueryExtensions.SearchExtensions.Levenshtein; using SF.Core.QueryExtensions.SearchExtensions.Soundex; namespace SF.Core.QueryExtensions.SearchExtensions.Helpers.ExpressionBuilders { internal static class ExpressionMethods { #region Contants public static readonly ConstantExpression EmptyStringExpression = Expression.Constant(string.Empty); public static readonly ConstantExpression NullExpression = Expression.Constant(null); public static readonly ConstantExpression ZeroConstantExpression = Expression.Constant(0); #endregion #region Properties public static readonly PropertyInfo StringLengthProperty = typeof(string).GetProperty("Length"); #endregion #region Methods public static readonly MethodInfo IndexOfMethod = typeof (string).GetMethod("IndexOf", new[] {typeof (string)}); public static readonly MethodInfo IndexOfMethodWithComparison = typeof(string).GetMethod("IndexOf", new[] { typeof(string), typeof(StringComparison) }); public static readonly MethodInfo ReplaceMethod = typeof(string).GetMethod("Replace", new[] { typeof(string), typeof(string) }); public static readonly MethodInfo EqualsMethod = typeof(string).GetMethod("Equals", new[] { typeof(string), typeof(StringComparison) }); public static readonly MethodInfo StartsWithMethod = typeof(string).GetMethod("StartsWith", new[] { typeof(string) }); public static readonly MethodInfo StartsWithMethodWithComparison = typeof(string).GetMethod("StartsWith", new[] { typeof(string), typeof(StringComparison) }); public static readonly MethodInfo EndsWithMethod = typeof(string).GetMethod("EndsWith", new[] { typeof(string) }); public static readonly MethodInfo EndsWithMethodWithComparison = typeof(string).GetMethod("EndsWith", new[] { typeof(string), typeof(StringComparison) }); public static readonly MethodInfo StringConcatMethod = typeof(string).GetMethod("Concat", new[] { typeof(string), typeof(string) }); public static readonly MethodInfo StringContainsMethod = typeof(string).GetMethod("Contains", new[] { typeof(string) }); public static readonly MethodInfo StringListContainsMethod = typeof(List<string>).GetMethod("Contains", new[] { typeof(string) }); public static readonly MethodInfo SoundexMethod = typeof(SoundexProcessor).GetMethod("ToSoundex"); public static readonly MethodInfo ReverseSoundexMethod = typeof(SoundexProcessor).GetMethod("ToReverseSoundex"); public static readonly MethodInfo LevensteinDistanceMethod = typeof(LevenshteinProcessor).GetMethod("LevenshteinDistance"); public static readonly MethodInfo CustomReplaceMethod = typeof(StringExtensionHelper).GetMethod("Replace"); public static readonly MethodInfo QuickReverseMethod = typeof(StringExtensionHelper).GetMethod("QuickReverse"); public static readonly MethodInfo AnyQueryableMethod = typeof(Enumerable).GetMethods() .Single(mi => mi.Name == "Any" && mi.GetParameters().Length == 2); #endregion } }
using System; using System.ComponentModel; using System.ComponentModel.DataAnnotations; namespace Models.DTOs { public class DataEntity : BaseEntity { [DisplayName("XML"), Required] public String Data { get; set; } public DataEntity() { base.Id = Guid.NewGuid(); } } }
namespace SSW.Ports.AzureStorage.Adapter.InMemory.PlatformTests.Blobs { public class BlobDirectoryTests : Definition.Tests.Blobs.BlobDirectoryTests { public BlobDirectoryTests() { BlobContainer = new StorageAccountFactory().GetStorageAccount("UseInMemoryDevelopmentStorage=true") .CreateBlobClient().GetBlobContainer("BlobContainerTestDirectory"); } } }
 namespace Nullspace { // 运行时间内 public class BTTimerLimitNode<Target> : BTDecoratorNode<Target> { private SequenceMultiple mTimerLimit; public BTTimerLimitNode(float interval) : base() { mTimerLimit = SequenceManager.CreateMultiple(); mTimerLimit.PrependInterval(interval); } public override BTNodeState Process(Target obj) { mNodeState = mChild.Process(obj); if (mNodeState == BTNodeState.Running) { if (mTimerLimit.IsFinished) { mNodeState = BTNodeState.Failure; } } else { mTimerLimit.Reset(); } return mNodeState; } public override void Clear() { base.Clear(); mTimerLimit.Clear(); } public override void Reset() { base.Reset(); mTimerLimit.Reset(); } } }
using MSCorp.FirstResponse.Client.Helpers; using MSCorp.FirstResponse.Client.Services.Cities; using MSCorp.FirstResponse.Client.ViewModels.Base; using System.Windows.Input; using System.Linq; using Xamarin.Forms; namespace MSCorp.FirstResponse.Client.ViewModels { public class ConfigViewModel : ViewModelBase { public bool UseMockService { get; set; } = ViewModelLocator.Instance.UseMockService; public string ServiceEndpoint { get; set; } = Settings.ServiceEndpoint; public double UserSpeed { get; set; } = Settings.UserSpeed; public ICommand SaveChangesCommand => new Command(SaveChanges); private async void SaveChanges() { ViewModelLocator.Instance.UseMockService = UseMockService; if (UseMockService) { // reset to mock values Settings.SelectedCity = GlobalSetting.DefaultMockCityId; Settings.UserLatitude = GlobalSetting.UserLatitude; Settings.UserLongitude = GlobalSetting.UserLongitude; Settings.AmbulanceLatitude = GlobalSetting.AmbulanceLatitude; Settings.AmbulanceLongitude = GlobalSetting.AmbulanceLongitude; } else { // load selected city from api ICitiesService citiesService = ViewModelLocator.Instance.Resolve<ICitiesService>(); Settings.SelectedCity = Settings.SelectedCity == 0 ? GlobalSetting.DefaultCityId : Settings.SelectedCity; var city = (await citiesService.GetEventsAsync()).FirstOrDefault(q => q.CityId == Settings.SelectedCity); Settings.UserLatitude = city.Latitude; Settings.UserLongitude = city.Longitude; Settings.AmbulanceLatitude = city.AmbulancePosition.Latitude; Settings.AmbulanceLongitude = city.AmbulancePosition.Longitude; } Settings.ServiceEndpoint = ServiceEndpoint; Settings.UserSpeed = UserSpeed; await NavigationService.NavigateToAsync<LoginViewModel>(); await NavigationService.RemoveBackStackAsync(); } } }
// This file is auto-generated, don't edit it. Thanks. using System; using System.Collections.Generic; using System.IO; using Tea; namespace AntChain.SDK.BLOCKCHAIN.Models { public class ReleaseBlockchainOrderPhysicalRequest : TeaModel { // OAuth模式下的授权token [NameInMap("auth_token")] [Validation(Required=false)] public string AuthToken { get; set; } [NameInMap("product_instance_id")] [Validation(Required=false)] public string ProductInstanceId { get; set; } // bid [NameInMap("bid")] [Validation(Required=true)] public string Bid { get; set; } // country [NameInMap("country")] [Validation(Required=false)] public string Country { get; set; } // gmt_wakeup [NameInMap("gmt_wakeup")] [Validation(Required=false)] public string GmtWakeup { get; set; } // hid [NameInMap("hid")] [Validation(Required=true)] public long? Hid { get; set; } // interrupt [NameInMap("interrupt")] [Validation(Required=false)] public bool? Interrupt { get; set; } // pk [NameInMap("pk")] [Validation(Required=true)] public string Pk { get; set; } // region_id [NameInMap("region_id")] [Validation(Required=false)] public string RegionId { get; set; } // request_id [NameInMap("request_id")] [Validation(Required=false)] public string RequestId { get; set; } // task_extra_data [NameInMap("task_extra_data")] [Validation(Required=false)] public string TaskExtraData { get; set; } // task_identifier [NameInMap("task_identifier")] [Validation(Required=false)] public string TaskIdentifier { get; set; } } }
using Moq; using Xunit; using Assert = Microsoft.TestCommon.AssertEx; namespace System.Web.Mvc.Test { public class ValidateInputAttributeTest { [Fact] public void EnableValidationProperty() { // Act ValidateInputAttribute attrTrue = new ValidateInputAttribute(true); ValidateInputAttribute attrFalse = new ValidateInputAttribute(false); // Assert Assert.True(attrTrue.EnableValidation); Assert.False(attrFalse.EnableValidation); } [Fact] public void OnAuthorizationSetsControllerValidateRequestToFalse() { // Arrange Controller controller = new EmptyController() { ValidateRequest = true }; ValidateInputAttribute attr = new ValidateInputAttribute(enableValidation: false); AuthorizationContext authContext = GetAuthorizationContext(controller); // Act attr.OnAuthorization(authContext); // Assert Assert.False(controller.ValidateRequest); } [Fact] public void OnAuthorizationSetsControllerValidateRequestToTrue() { // Arrange Controller controller = new EmptyController() { ValidateRequest = false }; ValidateInputAttribute attr = new ValidateInputAttribute(enableValidation: true); AuthorizationContext authContext = GetAuthorizationContext(controller); // Act attr.OnAuthorization(authContext); // Assert Assert.True(controller.ValidateRequest); } [Fact] public void OnAuthorizationThrowsIfFilterContextIsNull() { // Arrange ValidateInputAttribute attr = new ValidateInputAttribute(true); // Act & assert Assert.ThrowsArgumentNull( delegate { attr.OnAuthorization(null); }, "filterContext"); } private static AuthorizationContext GetAuthorizationContext(ControllerBase controller) { Mock<AuthorizationContext> mockAuthContext = new Mock<AuthorizationContext>(); mockAuthContext.Setup(c => c.Controller).Returns(controller); return mockAuthContext.Object; } private class EmptyController : Controller { } } }
namespace Autoccultist { using System; using System.IO; using System.Linq; using Autoccultist.Brain; using Autoccultist.Config; using Autoccultist.GameState; using Autoccultist.GUI; using HarmonyLib; using UnityEngine; /// <summary> /// The main entrypoint for Autoccultist, loaded by BenInEx. /// </summary> [BepInEx.BepInPlugin("net.robophreddev.CultistSimulator.Autoccultist", "Autoccultist", "0.0.1")] public class AutoccultistPlugin : BepInEx.BaseUnityPlugin { /// <summary> /// Gets the instance of the plugin. /// </summary> public static AutoccultistPlugin Instance { get; private set; } /// <summary> /// Gets the directory the mod dll is located in. /// </summary> public static string AssemblyDirectory { get { var assemblyLocation = typeof(AutoccultistPlugin).Assembly.Location; return Path.GetDirectoryName(assemblyLocation); } } /// <summary> /// Starts the mod. /// </summary> public void Start() { Instance = this; var harmony = new Harmony("net.robophreddev.CultistSimulator.Autoccultist"); harmony.PatchAll(); GameAPI.Initialize(); this.ReloadAll(); if (Library.ParseErrors.Count > 0) { ParseErrorsGUI.IsShowing = true; } GameEventSource.GameStarted += (_, __) => { var state = GameStateProvider.Current; var arc = Library.Arcs.FirstOrDefault(arc => arc.SelectionHint.IsConditionMet(state)); if (arc != null) { Superego.SetArc(arc); } }; GameEventSource.GameEnded += (_, __) => { this.StopAutoccultist(); Superego.SetArc(null); }; this.LogInfo("Autoccultist initialized."); } /// <summary> /// Reload all tasks in the TaskDriver. /// </summary> public void ReloadAll() { this.LogInfo("Reloading all configs"); Library.LoadAll(); Superego.Clear(); SituationOrchestrator.AbortAll(); } /// <summary> /// Renders the mod GUI. /// </summary> public void OnGUI() { // Allow ParseErrorsGUI to run when the core game is not in play. ParseErrorsGUI.OnGUI(); if (!GameAPI.IsRunning) { return; } DiagnosticGUI.OnGUI(); GoalsGUI.OnGUI(); ArcsGUI.OnGUI(); } /// <summary> /// Runs an update tick on the mod. /// </summary> public void Update() { GameStateProvider.Invalidate(); MechanicalHeart.Update(); this.HandleHotkeys(); } /// <summary> /// Log an info-level message. /// </summary> /// <param name="message">The message to log.</param> public void LogInfo(string message) { this.Logger.LogInfo(message); } /// <summary> /// Log a trace-level message. /// </summary> /// <param name="message">The message to log.</param> public void LogTrace(string message) { this.Logger.LogInfo(message); } /// <summary> /// Log a warning-level message. /// </summary> /// <param name="message">The message to log.</param> public void LogWarn(string message) { this.Logger.LogWarning(message); GameAPI.Notify("Autoccultist Warning", message); } /// <summary> /// Logs a warning-level message with an exception. /// </summary> /// <param name="ex">The exception to log.</param> /// <param name="message">The message.</param> public void LogWarn(Exception ex, string message) { this.Logger.LogWarning($"{message}\n{ex.Message}\n{ex.StackTrace}"); GameAPI.Notify("Autoccultist Warning", message); } /// <summary> /// Log and handle a fatal event. /// This will also stop the brain from running. /// </summary> /// <param name="message">The message to log.</param> public void Fatal(string message) { this.Logger.LogError("Fatal - " + message); GameAPI.Notify("Autoccultist Fatal", message); this.StopAutoccultist(); } private void HandleHotkeys() { if (Input.GetKeyDown(KeyCode.F11)) { if (MechanicalHeart.IsRunning) { this.LogInfo("Stopping Autoccultist"); this.StopAutoccultist(); } else { if (Input.GetKey(KeyCode.LeftShift)) { this.ReloadAll(); } else { this.LogInfo("Starting Autoccultist"); this.StartAutoccultist(); } } } else if (Input.GetKeyDown(KeyCode.F10)) { DiagnosticGUI.IsShowing = !DiagnosticGUI.IsShowing; } else if (Input.GetKeyDown(KeyCode.F9)) { this.LogInfo("Dumping status"); NucleusAccumbens.DumpStatus(); SituationOrchestrator.LogStatus(); } else if (Input.GetKeyDown(KeyCode.F8)) { this.LogInfo("Dumping situations"); SituationLogger.LogSituations(); } } private void StartAutoccultist() { Ego.Start(); MechanicalHeart.Start(); } private void StopAutoccultist() { MechanicalHeart.Stop(); Ego.Stop(); NucleusAccumbens.Reset(); } } }
using System.CommandLine.Parsing; using System.Linq; namespace DotNetBlog.Cli { public static class ParseResultExtensions { public static string GetRootCommand(this ParseResult parseResult) { var symbol = parseResult.RootCommandResult.Children?. Select(child => child.Symbol) .FirstOrDefault(); return symbol?.Name ?? string.Empty; } public static string[] GetCommandParameter(this string[] args) { var subargs = args.ToList(); subargs.RemoveAt(0); return args; } } }
// Copyright (c) Project Initium. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System; using Initium.Portal.Core.Database; using Initium.Portal.Core.MultiTenant; using Initium.Portal.Domain.AggregatesModel.RoleAggregate; using Microsoft.EntityFrameworkCore; namespace Initium.Portal.Infrastructure.EntityTypeConfigurationProviders { public class RoleEntityTypeConfigurationProvider : IEntityTypeConfigurationProvider { private readonly FeatureBasedTenantInfo _tenantInfo; public RoleEntityTypeConfigurationProvider(FeatureBasedTenantInfo tenantInfo) { this._tenantInfo = tenantInfo; } public void ApplyConfigurations(ModelBuilder modelBuilder) { var roles = modelBuilder.Entity<Role>(); roles.ToTable("Role", "AccessProtection"); roles.HasKey(role => role.Id); roles.Ignore(role => role.DomainEvents); roles.Ignore(role => role.IntegrationEvents); roles.Property(role => role.Id).ValueGeneratedNever(); roles.Metadata.AddAnnotation("MULTI_TENANT", null); roles.Property<Guid>("TenantId"); roles.HasQueryFilter(role => EF.Property<Guid>(role, "TenantId") == Guid.Parse(this._tenantInfo.Id)); roles.OwnsMany(role => role.RoleResources, roleResources => { roleResources.ToTable("RoleResource", "AccessProtection"); roleResources.HasKey(entity => entity.Id); roleResources.Property(roleResource => roleResource.Id).ValueGeneratedNever(); roleResources.Property(roleResource => roleResource.Id).HasColumnName("ResourceId"); roleResources.Ignore(roleResource => roleResource.DomainEvents); roleResources.Ignore(roleResource => roleResource.IntegrationEvents); roleResources.OwnedEntityType.AddAnnotation("MULTI_TENANT", null); roleResources.Property<Guid>("TenantId"); }).UsePropertyAccessMode(PropertyAccessMode.Field); } } }
//----------------------------------------------------------------------- // <copyright file="MurmurHash.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 System.Collections; using System.Collections.Generic; using System.Linq; namespace Akka.Util { /// <summary> /// Murmur3 Hash implementation /// </summary> public static class MurmurHash { // Magic values used for MurmurHash's 32 bit hash. // Don't change these without consulting a hashing expert! private const uint VisibleMagic = 0x971e137b; private const uint HiddenMagicA = 0x95543787; private const uint HiddenMagicB = 0x2ad7eb25; private const uint VisibleMixer = 0x52dce729; private const uint HiddenMixerA = 0x7b7d159c; private const uint HiddenMixerB = 0x6bce6396; private const uint FinalMixer1 = 0x85ebca6b; private const uint FinalMixer2 = 0xc2b2ae35; // Arbitrary values used for hashing certain classes private const uint StringSeed = 0x331df49; private const uint ArraySeed = 0x3c074a61; /** The first 23 magic integers from the first stream are stored here */ private static readonly uint[] StoredMagicA; /** The first 23 magic integers from the second stream are stored here */ private static readonly uint[] StoredMagicB; /// <summary> /// The initial magic integer in the first stream. /// </summary> public const uint StartMagicA = HiddenMagicA; /// <summary> /// The initial magic integer in the second stream. /// </summary> public const uint StartMagicB = HiddenMagicB; /// <summary> /// TBD /// </summary> static MurmurHash() { //compute range of values for StoredMagicA var storedMagicA = new List<uint>(); var nextMagicA = HiddenMagicA; foreach (var i in Enumerable.Repeat(0, 23)) { nextMagicA = NextMagicA(nextMagicA); storedMagicA.Add(nextMagicA); } StoredMagicA = storedMagicA.ToArray(); //compute range of values for StoredMagicB var storedMagicB = new List<uint>(); var nextMagicB = HiddenMagicB; foreach (var i in Enumerable.Repeat(0, 23)) { nextMagicB = NextMagicB(nextMagicB); storedMagicB.Add(nextMagicB); } StoredMagicB = storedMagicB.ToArray(); } /// <summary> /// Begin a new hash with a seed value. /// </summary> /// <param name="seed">TBD</param> /// <returns>TBD</returns> public static uint StartHash(uint seed) { return seed ^ VisibleMagic; } /// <summary> /// Given a magic integer from the first stream, compute the next /// </summary> /// <param name="magicA">TBD</param> /// <returns>TBD</returns> public static uint NextMagicA(uint magicA) { return magicA * 5 + HiddenMixerA; } /// <summary> /// Given a magic integer from the second stream, compute the next /// </summary> /// <param name="magicB">TBD</param> /// <returns>TBD</returns> public static uint NextMagicB(uint magicB) { return magicB * 5 + HiddenMixerB; } /// <summary> /// Incorporates a new value into an existing hash /// </summary> /// <param name="hash">The prior hash value</param> /// <param name="value">The new value to incorporate</param> /// <param name="magicA">A magic integer from the left of the stream</param> /// <param name="magicB">A magic integer from a different stream</param> /// <returns>The updated hash value</returns> public static uint ExtendHash(uint hash, uint value, uint magicA, uint magicB) { return (hash ^ RotateLeft32(value * magicA, 11) * magicB) * 3 + VisibleMixer; } /// <summary> /// Once all hashes have been incorporated, this performs a final mixing. /// </summary> /// <param name="hash">TBD</param> /// <returns>TBD</returns> public static uint FinalizeHash(uint hash) { var h = (hash ^ (hash >> 16)); h *= FinalMixer1; h ^= h >> 13; h *= FinalMixer2; h ^= h >> 16; return h; } #region Internal 32-bit hashing helpers /// <summary> /// Rotate a 32-bit unsigned integer to the left by <paramref name="shift"/> bits /// </summary> /// <param name="original">Original value</param> /// <param name="shift">The shift value</param> /// <returns>The rotated 32-bit integer</returns> private static uint RotateLeft32(uint original, int shift) { return (original << shift) | (original >> (32 - shift)); } /// <summary> /// Rotate a 64-bit unsigned integer to the left by <paramref name="shift"/> bits /// </summary> /// <param name="original">Original value</param> /// <param name="shift">The shift value</param> /// <returns>The rotated 64-bit integer</returns> private static ulong RotateLeft64(ulong original, int shift) { return (original << shift) | (original >> (64 - shift)); } #endregion /// <summary> /// Compute a high-quality hash of a byte array /// </summary> /// <param name="b">TBD</param> /// <returns>TBD</returns> public static int ByteHash(byte[] b) { return ArrayHash(b); } /// <summary> /// Compute a high-quality hash of an array /// </summary> /// <param name="a">TBD</param> /// <returns>TBD</returns> public static int ArrayHash<T>(T[] a) { unchecked { var h = StartHash((uint)a.Length * ArraySeed); var c = HiddenMagicA; var k = HiddenMagicB; var j = 0; while (j < a.Length) { h = ExtendHash(h, (uint)a[j].GetHashCode(), c, k); c = NextMagicA(c); k = NextMagicB(k); j += 1; } return (int)FinalizeHash(h); } } /// <summary> /// Compute high-quality hash of a string /// </summary> /// <param name="s">TBD</param> /// <returns>TBD</returns> public static int StringHash(string s) { unchecked { var sChar = s.ToCharArray(); var h = StartHash((uint)s.Length * StringSeed); var c = HiddenMagicA; var k = HiddenMagicB; var j = 0; while (j + 1 < s.Length) { var i = (uint)((sChar[j] << 16) + sChar[j + 1]); h = ExtendHash(h, i, c, k); c = NextMagicA(c); k = NextMagicB(k); j += 2; } if (j < s.Length) h = ExtendHash(h, sChar[j], c, k); return (int)FinalizeHash(h); } } /// <summary> /// Compute a hash that is symmetric in its arguments--that is, /// where the order of appearance of elements does not matter. /// This is useful for hashing sets, for example. /// </summary> /// <param name="xs">TBD</param> /// <param name="seed">TBD</param> /// <returns>TBD</returns> public static int SymmetricHash<T>(IEnumerable<T> xs, uint seed) { unchecked { uint a = 0, b = 0, n = 0; uint c = 1; foreach (var i in xs) { var u = (uint)i.GetHashCode(); a += u; b ^= u; if (u != 0) c *= u; n += 1; } var h = StartHash(seed*n); h = ExtendHash(h, a, StoredMagicA[0], StoredMagicB[0]); h = ExtendHash(h, b, StoredMagicA[1], StoredMagicB[1]); h = ExtendHash(h, c, StoredMagicA[2], StoredMagicB[2]); return (int)FinalizeHash(h); } } } /// <summary> /// Extension method class to make it easier to work with <see cref="BitArray"/> instances /// </summary> public static class BitArrayHelpers { /// <summary> /// Converts a <see cref="BitArray"/> into an array of <see cref="byte"/> /// </summary> /// <param name="arr">TBD</param> /// <exception cref="ArgumentException"> /// This exception is thrown if there aren't enough bits in the given <paramref name="arr"/> to make a byte. /// </exception> /// <returns>TBD</returns> public static byte[] ToBytes(this BitArray arr) { if (arr.Length != 8) { throw new ArgumentException("Not enough bits to make a byte!", nameof(arr)); } var bytes = new byte[(arr.Length - 1) / 8 + 1]; ((ICollection)arr).CopyTo(bytes, 0); return bytes; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using WorkRegistry.model; namespace WorkRegistry.viewmodel { public class CarsViewModel : INotifyPropertyChanged { public ObservableCollection<Car> Cars { get; set; } public event PropertyChangedEventHandler PropertyChanged; public CarsViewModel() { Cars = new ObservableCollection<Car>(DbOperations.GetAllCars()); } public void DeleteCar(Car car) { Cars.Remove(car); DbOperations.RemoveCar(car); if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Cars")); } public void AddOrEditCar(Car car) { Cars.Clear(); DbOperations.AddOrEditCar(car); foreach (Car CurrentCar in DbOperations.GetAllCars()) { Cars.Add(CurrentCar); } if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Cars")); } } }
using UnityEngine; using System.Collections; [ExecuteInEditMode] public class BackgroundCarDebugInfo : MonoBehaviour { #if UNITY_EDITOR public Material PeakHoursMaterial; public Material RegularHoursMaterial; public Material MostHoursMaterial; public Material AllHoursMaterial; void Update () { // Set material colour based on active hours. BackgroundCar backgroundCar = GetComponent<BackgroundCar>(); Renderer renderer = GetComponent<Renderer>(); switch (backgroundCar.ActivePeriod) { case BackgroundCar.ActivePeriods.PEAK_HOURS: renderer.material = PeakHoursMaterial; break; case BackgroundCar.ActivePeriods.REGULAR_HOURS: renderer.material = RegularHoursMaterial; break; case BackgroundCar.ActivePeriods.MOST_HOURS: renderer.material = MostHoursMaterial; break; case BackgroundCar.ActivePeriods.ALL_HOURS: renderer.material = AllHoursMaterial; break; } } #endif }
namespace Lime { internal interface IStockCursors { MouseCursor Default { get; } MouseCursor Empty { get; } MouseCursor Hand { get; } MouseCursor IBeam { get; } MouseCursor SizeNS { get; } MouseCursor SizeWE { get; } MouseCursor SizeAll { get; } MouseCursor SizeNWSE { get; } MouseCursor SizeNESW { get; } } }
using System; namespace SuccincT.Functional { /// <summary> /// Extension methods for partially applying C# functions (ie, methods that return a value) /// </summary> public static class PartialFunctionApplications { /// <summary> /// Partially applies f(p1,p2), via f.Apply(v1), into f'(p2) /// </summary> public static Func<T2, TResult> Apply<T1, T2, TResult>(this Func<T1, T2, TResult> functionToApply, T1 p1) => p2 => functionToApply(p1, p2); /// <summary> /// Partially applies f(p1,p2,p3), via f.Apply(v1), into f'(p2,p3) /// </summary> public static Func<T2, T3, TResult> Apply<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> functionToApply, T1 p1) => (p2, p3) => functionToApply(p1, p2, p3); /// <summary> /// Partially applies f(p1,p2,p3), via f.Apply(v1,v2), into f'(p3) /// </summary> public static Func<T3, TResult> Apply<T1, T2, T3, TResult>(this Func<T1, T2, T3, TResult> functionToApply, T1 p1, T2 p2) => p3 => functionToApply(p1, p2, p3); /// <summary> /// Partially applies f(p1,p2,p3,p4), via f.Apply(v1), into f'(p2,p3,p4) /// </summary> public static Func<T2, T3, T4, TResult> Apply<T1, T2, T3, T4, TResult>(this Func<T1, T2, T3, T4, TResult> functionToApply, T1 p1) => (p2, p3, p4) => functionToApply(p1, p2, p3, p4); /// <summary> /// Partially applies f(p1,p2,p3,p4), via f.Apply(v1,v2), into f'(p3,p4) /// </summary> public static Func<T3, T4, TResult> Apply<T1, T2, T3, T4, TResult>(this Func<T1, T2, T3, T4, TResult> functionToApply, T1 p1, T2 p2) => (p3, p4) => functionToApply(p1, p2, p3, p4); /// <summary> /// Partially applies f(p1,p2,p3,p4), via f.Apply(v1,v2,v3), into f'(p4) /// </summary> public static Func<T4, TResult> Apply<T1, T2, T3, T4, TResult>(this Func<T1, T2, T3, T4, TResult> functionToApply, T1 p1, T2 p2, T3 p3) => p4 => functionToApply(p1, p2, p3, p4); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5), via f.Apply(v1), into f'(p2,p3,p4,p5) /// </summary> public static Func<T2, T3, T4, T5, TResult> Apply<T1, T2, T3, T4, T5, TResult>(this Func<T1, T2, T3, T4, T5, TResult> functionToApply, T1 p1) => (p2, p3, p4, p5) => functionToApply(p1, p2, p3, p4, p5); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5), via f.Apply(v1,v2), into f'(p3,p4,p5) /// </summary> public static Func<T3, T4, T5, TResult> Apply<T1, T2, T3, T4, T5, TResult>(this Func<T1, T2, T3, T4, T5, TResult> functionToApply, T1 p1, T2 p2) => (p3, p4, p5) => functionToApply(p1, p2, p3, p4, p5); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5), via f.Apply(v1,v2,v3), into f'(p4,p5) /// </summary> public static Func<T4, T5, TResult> Apply<T1, T2, T3, T4, T5, TResult>(this Func<T1, T2, T3, T4, T5, TResult> functionToApply, T1 p1, T2 p2, T3 p3) => (p4, p5) => functionToApply(p1, p2, p3, p4, p5); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5), via f.Apply(v1,v2,v3,v4), into f'(p5) /// </summary> public static Func<T5, TResult> Apply<T1, T2, T3, T4, T5, TResult>(this Func<T1, T2, T3, T4, T5, TResult> functionToApply, T1 p1, T2 p2, T3 p3, T4 p4) => p5 => functionToApply(p1, p2, p3, p4, p5); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5,p6), via f.Apply(v1), into f'(p2,p3,p4,p5,p6) /// </summary> public static Func<T2, T3, T4, T5, T6, TResult> Apply<T1, T2, T3, T4, T5, T6, TResult>(this Func<T1, T2, T3, T4, T5, T6, TResult> functionToApply, T1 p1) => (p2, p3, p4, p5, p6) => functionToApply(p1, p2, p3, p4, p5, p6); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5,p6), via f.Apply(v1,v2), into f'(p3,p4,p5,p6) /// </summary> public static Func<T3, T4, T5, T6, TResult> Apply<T1, T2, T3, T4, T5, T6, TResult>(this Func<T1, T2, T3, T4, T5, T6, TResult> functionToApply, T1 p1, T2 p2) => (p3, p4, p5, p6) => functionToApply(p1, p2, p3, p4, p5, p6); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5,p6), via f.Apply(v1,v2,v3), into f'(p4,p5,p6) /// </summary> public static Func<T4, T5, T6, TResult> Apply<T1, T2, T3, T4, T5, T6, TResult>(this Func<T1, T2, T3, T4, T5, T6, TResult> functionToApply, T1 p1, T2 p2, T3 p3) => (p4, p5, p6) => functionToApply(p1, p2, p3, p4, p5, p6); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5,p6), via f.Apply(v1,v2,v3,v4), into f'(p5, p6) /// </summary> public static Func<T5, T6, TResult> Apply<T1, T2, T3, T4, T5, T6, TResult>(this Func<T1, T2, T3, T4, T5, T6, TResult> functionToApply, T1 p1, T2 p2, T3 p3, T4 p4) => (p5, p6) => functionToApply(p1, p2, p3, p4, p5, p6); /// <summary> /// Partially applies f(p1,p2,p3,p4,p5,p6), via f.Apply(v1,v2,v3,v4,v5), into f'(p6) /// </summary> public static Func<T6, TResult> Apply<T1, T2, T3, T4, T5, T6, TResult>(this Func<T1, T2, T3, T4, T5, T6, TResult> functionToApply, T1 p1, T2 p2, T3 p3, T4 p4, T5 p5) => p6 => functionToApply(p1, p2, p3, p4, p5, p6); } }
using AutoMapper; using TwitterBackup.Data.Models; using TwitterBackup.Data.Models.Identity; using TwitterBackup.Services.ViewModels; using TwitterBackup.TwitterApiClient.Models; namespace TwitterBackup.Services.Mapping { public class DomainToVMMappingProfile : Profile { public DomainToVMMappingProfile() { CreateMap<TwitterAccount, TwitterAccountViewModel>() .ForMember(d => d.ProfileImage, opt => opt.MapFrom(s => s.TwitterAccountImage.ProfileImage)); CreateMap<TwitterStatus, TwitterStatusViewModel>() .ForMember(d => d.CreatedAt, opt => opt.MapFrom(s => s.CreatedAtTwitter)); CreateMap<User, UserViewModel>(); //DTO mapping CreateMap<TwitterAccountDTO, TwitterAccountViewModel>(); CreateMap<TwitterStatusDTO, TwitterStatusPartialViewModel>() .ForMember(d => d.TwitterStatusId, opt => opt.MapFrom(s => s.IdString)); CreateMap<TwitterErrorDTO, TwitterErrorViewModel>(); } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace OMDB_API_Wrapper.Models.API_Responses { /// <summary> /// JSON-deserialized object received in response to a BySearchRequest. /// </summary> public class BySearchResponse : Response { [JsonProperty("Search")] public List<SearchResultItem> SearchResults; [JsonProperty("totalResults")] public uint TotalResults; public class SearchResultItem { [JsonProperty("Title")] public string Title; [JsonProperty("Year")] public string Year; [JsonProperty("imdbID")] public string IMDB_ID; [JsonProperty("Type")] public string Type; [JsonProperty("Poster")] public string Poster_URI; } } }
namespace Exrin.Abstraction { public interface IResult { /// <summary> /// The resulting action of the execute /// </summary> ResultType ResultAction { get; set; } /// <summary> /// Arguments that may be required to pass to the next operation /// Or for the final handling of the final rezult /// </summary> IResultArgs Arguments { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class LanternUI : MonoBehaviour { GameObject playerSpriteMask; float maxRadiusTransform; float curRadiusTransform; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (playerSpriteMask == null) { playerSpriteMask = GameObject.Find("PlayerSpriteMask"); maxRadiusTransform = playerSpriteMask.GetComponent<PlayerLightRadius>().maxLightSizeX - 6; } else { curRadiusTransform = playerSpriteMask.GetComponent<PlayerLightRadius>().curLightRadius - 6; //curRadiusTransform = curRadiusTransform / maxRadiusTransform; //Debug.Log (curRadiusTransform); GetComponent<Image>().fillAmount = Mathf.Round((curRadiusTransform / maxRadiusTransform) * 100) / 100; } } }
using System.Data.Entity; namespace ProjetoTCC.Models { public class UsuarioContext : DbContext { public UsuarioContext():base(Functions.Conexao()) { } public DbSet<Usuario> usuario { get; set; } } }
using BurningKnight.assets; using BurningKnight.assets.particle; using BurningKnight.assets.particle.controller; using BurningKnight.assets.particle.renderer; using BurningKnight.entity.component; using Lens.entity; using Lens.util.math; using Microsoft.Xna.Framework; namespace BurningKnight.entity.buff { public class PoisonBuff : Buff { public static Vector4 Color = new Vector4(0.1f, 0.5f, 0.1f, 1f); public const string Id = "bk:poison"; private const float Delay = 2f; private float tillDamage = Delay; private float lastParticle; public PoisonBuff() : base(Id) { Duration = 10; } public override void Update(float dt) { base.Update(dt); lastParticle += dt; if (lastParticle >= 0.5f) { lastParticle = 0; var part = new ParticleEntity(new Particle(Controllers.Float, new TexturedParticleRenderer(CommonAse.Particles.GetSlice($"poison_{Rnd.Int(1, 4)}")))); part.Position = Entity.Center; if (Entity.TryGetComponent<ZComponent>(out var z)) { part.Position -= new Vector2(0, z.Z); } Entity.Area.Add(part); part.Particle.Velocity = new Vector2(Rnd.Float(8, 16) * (Rnd.Chance() ? -1 : 1), -Rnd.Float(30, 56)); part.Particle.Angle = 0; part.Particle.Alpha = 0.8f; part.Depth = Layers.InGameUi; } tillDamage -= dt; if (tillDamage <= 0) { tillDamage = Delay; Entity.GetComponent<HealthComponent>().ModifyHealth(-2, Entity); } } public override string GetIcon() { return "poison"; } } }
namespace ARMeilleure.Decoders { class OpCodeSimdFcond : OpCodeSimdReg, IOpCodeCond { public int Nzcv { get; private set; } public Condition Cond { get; private set; } public OpCodeSimdFcond(InstDescriptor inst, ulong address, int opCode) : base(inst, address, opCode) { Nzcv = (opCode >> 0) & 0xf; Cond = (Condition)((opCode >> 12) & 0xf); } } }
 using NUnit.Framework; namespace HFM.Log { [TestFixture] public class LogLineDataParserErrorTests { [Test] public void LogLineDataParserError_CopyConstructor_Test() { // Arrange var data = new LogLineDataParserError { Message = "Foo" }; // Act var copy = new LogLineDataParserError(data); // Assert Assert.AreEqual(data.Message, copy.Message); } [Test] public void LogLineDataParserError_CopyConstructor_OtherIsNull_Test() { // Act var copy = new LogLineDataParserError(null); // Assert Assert.AreEqual(null, copy.Message); } } }
using OpenTemenos.Transacts.Reference.AccountOfficers; using OpenTemenos.Transacts.Reference.BalanceTypes; using OpenTemenos.Transacts.Reference.Beneficiaries; using OpenTemenos.Transacts.Reference.BICs; using OpenTemenos.Transacts.Reference.Brokers; using OpenTemenos.Transacts.Reference.BundleRates; using OpenTemenos.Transacts.Reference.Categories; using OpenTemenos.Transacts.Reference.ChequeTypes; using OpenTemenos.Transacts.Reference.CollateralClassifications; using OpenTemenos.Transacts.Reference.Companies; using OpenTemenos.Transacts.Reference.Countries; using OpenTemenos.Transacts.Reference.Currencies; using OpenTemenos.Transacts.Reference.Dates; using OpenTemenos.Transacts.Reference.Dealers; using OpenTemenos.Transacts.Reference.IBANs; using OpenTemenos.Transacts.Reference.InterestBases; using OpenTemenos.Transacts.Reference.InterestRates; using OpenTemenos.Transacts.Reference.Lookups; using OpenTemenos.Transacts.Reference.NationalIds; using OpenTemenos.Transacts.Reference.OrganizationStructures; using OpenTemenos.Transacts.Reference.PeriodDates; using OpenTemenos.Transacts.Reference.PortfolioAccounts; using OpenTemenos.Transacts.Reference.Products; using OpenTemenos.Transacts.Reference.RoundingRules; using OpenTemenos.Transacts.Reference.TransactionCodes; using OpenTemenos.Transacts.Reference.Treasuries; using OpenTemenos.Transacts.Reference.UsBenOwnerTypes; using OpenTemenos.Transacts.Reference.UsCounties; using OpenTemenos.Transacts.Reference.UsCovenants; using OpenTemenos.Transacts.Reference.UsCustomerRatings; using OpenTemenos.Transacts.Reference.UsCustomerSuffixs; using OpenTemenos.Transacts.Reference.UsCustomerTitles; using OpenTemenos.Transacts.Reference.UsFdicClassCodes; using OpenTemenos.Transacts.Reference.UsHoldTypes; using OpenTemenos.Transacts.Reference.UsIdDocuments; using OpenTemenos.Transacts.Reference.UsIndustries; using OpenTemenos.Transacts.Reference.UsSectors; using OpenTemenos.Transacts.Reference.UsSortCodes; using OpenTemenos.Transacts.Reference.UsStates; namespace OpenTemenos.Transacts; //TODO: Rename Transact.IReferenceClient methods public interface IReferenceClient { public IAccountOfficerService AccountOfficerService { get; } public IBalanceTypeService BalanceTypeService { get; } public IBeneficiaryService BeneficiaryService { get; } public IBICService BICService { get; } public IBrokerService BrokerService { get; } public IBundleRateService BundleRateService { get; } public ICategoryService CategoryService { get; } public IChequeTypeService ChequeTypeService { get; } public ICollateralClassificationService CollateralClassificationService { get; } public ICompanyService CompanyService { get; } public ICountryService CountryService { get; } public ICurrencyService CurrencyService { get; } public IDateService DateService { get; } public IDealerService DealerService { get; } public IIBANService IBANService { get; } public IInterestBaseService InterestBaseService { get; } public IInterestRateService InterestRateService { get; } public ILookupService LookupService { get; } public INationalIdService NationalIdService { get; } public IOrganizationStructureService OrganizationStructureService { get; } public IPeriodDateService PeriodDateService { get; } public IPortfolioAccountService PortfolioAccountService { get; } public IProductService ProductService { get; } public IRoundingRuleService RoundingRuleService { get; } public ITransactionCodeService TransactionCodeService { get; } public ITreasuryService TreasuryService { get; } public IUsBenOwnerTypeService UsBenOwnerTypeService { get; } public IUsCountyService UsCountyService { get; } public IUsCovenantService UsCovenantService { get; } public IUsCustomerRatingService UsCustomerRatingService { get; } public IUsCustomerSuffixService UsCustomerSuffixService { get; } public IUsCustomerTitleService UsCustomerTitleService { get; } public IUsFdicClassCodeService UsFdicClassCodeService { get; } public IUsHoldTypeService UsHoldTypeService { get; } public IUsIdDocumentService UsIdDocumentService { get; } public IUsIndustryService UsIndustryService { get; } public IUsSectorService UsSectorService { get; } public IUsSortCodeService UsSortCodeService { get; } public IUsStateService UsStateService { get; } }
using System; using System.IO; using System.Threading.Tasks; using Blaise.Api.Tests.Helpers.Case; using Blaise.Api.Tests.Helpers.Configuration; using Blaise.Api.Tests.Helpers.Extensions; using Blaise.Api.Tests.Helpers.Files; using Blaise.Api.Tests.Helpers.Instrument; using Blaise.Api.Tests.Helpers.RestApi; using NUnit.Framework; using TechTalk.SpecFlow; namespace Blaise.Api.Tests.Behaviour.Steps { [Binding] public sealed class GetQuestionnaireDataSteps { private const int ExpectedNumberOfCases = 10; private const string ApiResponse = "ApiResponse"; private readonly string _tempFilePath; private readonly ScenarioContext _scenarioContext; public GetQuestionnaireDataSteps(ScenarioContext scenarioContext) { _tempFilePath = Path.Combine(BlaiseConfigurationHelper.TempPath, "Tests", Guid.NewGuid().ToString()); _scenarioContext = scenarioContext; } [Then(@"the questionnaire does not contain any correspondent data")] public void ThenTheQuestionnaireDoesNotContainAnyCorrespondentData() { var numberOfCases = CaseHelper.GetInstance().NumberOfCasesInInstrument(); Assert.AreEqual(0, numberOfCases); } [Given(@"we have captured correspondent data for the questionnaire")] public void GivenWeHaveCapturedCorrespondentDataForTheQuestionnaire() { CaseHelper.GetInstance().CreateCasesInBlaise(ExpectedNumberOfCases); } [When(@"the API is called to retrieve the questionnaire with data")] public async Task WhenTheApiIsCalledToDeliverTheQuestionnaireWithData() { var instrumentFile = await RestApiHelper.GetInstance().GetInstrumentWithData( RestApiConfigurationHelper.InstrumentDataUrl, _tempFilePath); _scenarioContext.Set(instrumentFile, ApiResponse); } [Then(@"the questionnaire package contains the captured correspondent data")] public void ThenTheQuestionnairePackageContainsTheCapturedCorrespondentData() { var deliveredFile = _scenarioContext.Get<string>(ApiResponse); var extractedFilePath = Path.Combine( _tempFilePath, BlaiseConfigurationHelper.InstrumentName); deliveredFile.ExtractFiles(extractedFilePath); var dataInterfaceFile = $@"{extractedFilePath}\{BlaiseConfigurationHelper.InstrumentName}.bdix"; var numberOfCases = CaseHelper.GetInstance().NumberOfCasesInInstrument(dataInterfaceFile); Assert.AreEqual(ExpectedNumberOfCases, numberOfCases); } [AfterScenario("data")] public void CleanUpScenario() { CaseHelper.GetInstance().DeleteCases(); InstrumentHelper.GetInstance().UninstallSurvey(); FileSystemHelper.GetInstance().CleanUpTempFiles(_tempFilePath); } } }
using Definux.Emeraude.Domain.Entities; namespace Definux.Emeraude.Domain.Abstractions { /// <summary> /// Abstract class that represent helper for create object builder for creation domein entity with builder pattern. /// </summary> /// <typeparam name="TEntity">Target entity.</typeparam> /// <typeparam name="TEntityBuilder">Target entity builder.</typeparam> public abstract class ObjectBuilder<TEntity, TEntityBuilder> where TEntity : class, IEntity, new() where TEntityBuilder : ObjectBuilder<TEntity, TEntityBuilder>, new() { /// <summary> /// Initializes a new instance of the <see cref="ObjectBuilder{TEntity, TEntityBuilder}"/> class. /// </summary> protected ObjectBuilder() { this.Entity = new TEntity(); } /// <summary> /// Target entity. /// </summary> protected TEntity Entity { get; set; } /// <summary> /// Initialization step for the builder. /// </summary> /// <returns></returns> public static TEntityBuilder Init() { return new TEntityBuilder(); } /// <summary> /// Finalize method for the builder that build and return the target entity. /// </summary> /// <returns></returns> public virtual TEntity Build() { return this.Entity; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CreatePrefabOnHit : HitTarget { public Transform prefab; public int createOnlyOnHit = 0; int numHits = 0; void Start() { } bool ShouldCreate() { return createOnlyOnHit == 0 || numHits == createOnlyOnHit; } void Create() { Instantiate(prefab, transform.position, transform.rotation); } override public void Hit(TouchHitInfo hitInfo) { numHits++; if (prefab != null && ShouldCreate()) Create(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using Vta.Models; namespace Vta.RequestModels { public static class FilterCollection { public static IQueryable<T> FilterBy<T>(this IQueryable<T> queryable, string id, Expression<Func<T, bool>> predicate) { if (!string.IsNullOrWhiteSpace(id) && id != new Guid().ToString()) { queryable = queryable.Where(predicate); } return queryable; } // Level public static IQueryable<Level> ByCourse(this IQueryable<Level> queryable, string id) { return queryable.FilterBy(id, x => x.CourseId == id); } // Content public static IQueryable<Content> ByCourse(this IQueryable<Content> queryable, string id) { return queryable.FilterBy(id, x => x.Level.CourseId == id); } public static IQueryable<Content> ByLevel(this IQueryable<Content> queryable, string id) { return queryable.FilterBy(id, x => x.LevelId == id); } public static IQueryable<Content> ByPublic(this IQueryable<Content> queryable) { return queryable.FilterBy(null, x => x.IsPublic); } // Question public static IQueryable<Question> ByCourse(this IQueryable<Question> queryable, string id) { return queryable.FilterBy(id, x => x.Content.Level.CourseId == id); } public static IQueryable<Question> ByLevel(this IQueryable<Question> queryable, string id) { return queryable.FilterBy(id, x => x.Content.LevelId == id); } public static IQueryable<Question> ByContent(this IQueryable<Question> queryable, string id) { return queryable.FilterBy(id, x => x.ContentId == id); } // Option public static IQueryable<Option> ByCourse(this IQueryable<Option> queryable, string id) { return queryable.FilterBy(id, x => x.Question.Content.Level.CourseId == id); } public static IQueryable<Option> ByLevel(this IQueryable<Option> queryable, string id) { return queryable.FilterBy(id, x => x.Question.Content.LevelId == id); } public static IQueryable<Option> ByContent(this IQueryable<Option> queryable, string id) { return queryable.FilterBy(id, x => x.Question.ContentId == id); } public static IQueryable<Option> ByQuestion(this IQueryable<Option> queryable, string id) { return queryable.FilterBy(id, x => x.QuestionId == id); } // File public static IQueryable<File> ByCourse(this IQueryable<File> queryable, string id) { return queryable.FilterBy(id, x => x.Content.Level.CourseId == id); } public static IQueryable<File> ByLevel(this IQueryable<File> queryable, string id) { return queryable.FilterBy(id, x => x.Content.LevelId == id); } public static IQueryable<File> ByContent(this IQueryable<File> queryable, string id) { return queryable.FilterBy(id, x => x.ContentId == id); } // Website public static IQueryable<Website> ByCourse(this IQueryable<Website> queryable, string id) { return queryable.FilterBy(id, x => x.Content.Level.CourseId == id); } public static IQueryable<Website> ByLevel(this IQueryable<Website> queryable, string id) { return queryable.FilterBy(id, x => x.Content.LevelId == id); } public static IQueryable<Website> ByContent(this IQueryable<Website> queryable, string id) { return queryable.FilterBy(id, x => x.ContentId == id); } } }
using System.Windows.Forms; namespace Mike.Utilities.Desktop { public static class AdapterScreen { public static void Adaptar(Form form) { int x = Screen.PrimaryScreen.Bounds.Size.Width; int y = Screen.PrimaryScreen.Bounds.Size.Height; form.Size = new System.Drawing.Size(x, y); form.Location = new System.Drawing.Point(0, 0); } } }
using System; using System.Threading; using System.Threading.Tasks; using Windows.Devices.Gpio; namespace HelloWorldIoTCS_2019.GpioControl { public class LedBlinking { public bool IsActive { get; private set; } = false; public int GpioPinNumber { get; private set; } public int MsShineDuration { get; private set; } private Task blinkingTask; private CancellationTokenSource blinkingCancellationTokenSource; private GpioPin gpioPin; public LedBlinking(int gpioPinNumber, int msShineDuration) { GpioPinNumber = gpioPinNumber; MsShineDuration = msShineDuration; gpioPin = ConfigureGpioPin(GpioPinNumber); if(gpioPin == null) { throw new Exception("GPIO pin unavailable"); } } public void Start() { if (!IsActive) { InitializeBlinkingTask(); blinkingTask.Start(); IsActive = true; } } public void Stop() { if (IsActive) { blinkingCancellationTokenSource.Cancel(); IsActive = false; } } private void InitializeBlinkingTask() { blinkingCancellationTokenSource = new CancellationTokenSource(); blinkingTask = new Task(() => { while (!blinkingCancellationTokenSource.IsCancellationRequested) { if (IsActive) { SwitchGpioPin(gpioPin); Task.Delay(MsShineDuration).Wait(); } } }, blinkingCancellationTokenSource.Token); } private GpioPin ConfigureGpioPin(int pinNumber) { var gpioController = GpioController.GetDefault(); GpioPin pin = null; if (gpioController != null) { pin = gpioController.OpenPin(pinNumber); if (pin != null) { pin.SetDriveMode(GpioPinDriveMode.Output); } } return pin; } private void SwitchGpioPin(GpioPin gpioPin) { var currentPinValue = gpioPin.Read(); GpioPinValue newPinValue = InvertGpioPinValue(currentPinValue); gpioPin.Write(newPinValue); } private GpioPinValue InvertGpioPinValue(GpioPinValue currentPinValue) { GpioPinValue invertedGpioPinValue; if (currentPinValue == GpioPinValue.High) { invertedGpioPinValue = GpioPinValue.Low; } else { invertedGpioPinValue = GpioPinValue.High; } return invertedGpioPinValue; } } }
#region << 版 本 注 释 >> /* * 项目名称 :BerryCore.BLL.SystemManage * 项目描述 : * 类 名 称 :DataBaseLinkBLL * 类 描 述 : * 所在的域 :DASHIXIONG * 命名空间 :BerryCore.BLL.SystemManage * 机器名称 :DASHIXIONG * CLR 版本 :4.0.30319.42000 * 作 者 :赵轶 * 创建时间 :2019-12-17 18:33:34 * 更新时间 :2019-12-17 18:33:34 * 版 本 号 :V2.0.0.0 *********************************************************************** * Copyright © 大師兄丶 2019. All rights reserved. * *********************************************************************** */ #endregion using System; using System.Collections.Generic; using System.Data.Common; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; using BerryCore.Entity.SystemManage; using BerryCore.IBLL.SystemManage; using BerryCore.IService.SystemManage; using BerryCore.Service.SystemManage; namespace BerryCore.BLL.SystemManage { /// <summary> /// 功能描述 :DataBaseLinkBLL /// 创 建 者 :赵轶 /// 创建日期 :2019-12-17 18:33:34 /// 最后修改者 :赵轶 /// 最后修改日期:2019-12-17 18:33:34 /// </summary> public class DataBaseLinkBLL : IDataBaseLinkBLL { private readonly IDataBaseLinkService service = new DataBaseLinkService(); /// <summary> /// 库连接列表 /// </summary> /// <returns></returns> public IEnumerable<DataBaseLinkEntity> GetDataBaseLinkList() { return service.GetDataBaseLinkList(); } /// <summary> /// 库连接实体 /// </summary> /// <param name="keyValue">主键值</param> /// <returns></returns> public DataBaseLinkEntity GetDataBaseLinkEntity(string keyValue) { return service.GetDataBaseLinkEntity(keyValue); } /// <summary> /// 删除库连接 /// </summary> /// <param name="keyValue">主键</param> public void RemoveByKey(string keyValue) { service.RemoveByKey(keyValue); } /// <summary> /// 保存库连接表单(新增、修改) /// </summary> /// <param name="keyValue">主键值</param> /// <param name="databaseLinkEntity">库连接实体</param> /// <returns></returns> public void SaveForm(string keyValue, DataBaseLinkEntity databaseLinkEntity) { #region 测试连接数据库 DbConnection dbConnection = null; string serverAddress = ""; switch (databaseLinkEntity.DbType) { case "SqlServer": dbConnection = new SqlConnection(databaseLinkEntity.DbConnection); serverAddress = dbConnection.DataSource; break; default: break; } if (dbConnection != null) dbConnection.Close(); databaseLinkEntity.ServerAddress = serverAddress; #endregion 测试连接数据库 service.SaveForm(keyValue, databaseLinkEntity); } } }
using Elsa.Activities.Http.Middleware; using Elsa.Activities.Http.Options; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; // ReSharper disable once CheckNamespace namespace Microsoft.AspNetCore.Builder { public static class ApplicationBuilderExtensions { public static IApplicationBuilder UseHttpActivities(this IApplicationBuilder app) { var options = app.ApplicationServices.GetRequiredService<IOptions<HttpActivityOptions>>().Value; var basePath = options.BasePath; return basePath != null ? app.Map(basePath.Value, branch => branch.UseMiddleware<HttpEndpointMiddleware>()) : app.UseMiddleware<HttpEndpointMiddleware>(); } } }
using System; using System.Collections.Generic; using OpenTK; namespace VRLib { public interface IGameObj { // Attributes long Id { get; } // ID is guaranteed to be unique and not change over the object's lifetime. Vector3d OldLoc { get; set; } Vector3d Loc { get; set; } Quaterniond OldFacing { get; set; } Quaterniond Facing { get; set; } Vector3d Vel { get; set; } double RVel { get; set; } double Mass { get; set; } double Moment { get; set; } Collider Collider { get; set; } // True if colliding with it does something bool Collidable { get; set; } bool Alive { get; set; } // Operations void Push(Vector3d force); void Rotate(Vector3d axis, double torque); bool Colliding(IGameObj o); void OnCollide(IGameObj o, IPlace g); void Update(IPlace g, double dt); void Die(IPlace g); void FreezeCallback(double freezeTime); void UnfreezeCallback(double unfreezeTime); } /* public interface IControllable : IGameObj { double MaxVel { get; set; } IGameObj Target { get; set; } void Thrust(); void TurnLeft(); void TurnRight(); void Brake(); //void Fire(GameState g); //void Secondary(GameState g); //void Special(GameState g); //void SwitchMain(); //void SwitchSecondary(); //void SwitchSpecial(); }*/ /// <summary> /// Any kind of object in space that is affected by conventional physics and /// </summary> public class SpaceObj : IGameObj { // Attributes public long Id { get; set; } public Vector3d OldLoc { get; set; } public Vector3d Loc { get; set; } public Quaterniond OldFacing { get; set; } public Quaterniond Facing { get; set; } public Vector3d Vel { get; set; } public double RVel { get; set; } public double Mass { get; set; } public double Moment { get; set; } public Collider Collider { get; set; } // True if colliding with it does something public bool Collidable { get; set; } public bool Alive { get; set; } public SpaceObj(Vector3d loc) { Loc = loc; OldLoc = loc; Facing = Quaterniond.Identity; OldFacing = Quaterniond.Identity; Mass = 1.0; Moment = 1.0; Collider = null; Vel = Vector3d.Zero; RVel = 0; Collidable = false; } // Operations public virtual void Push(Vector3d force) { // Planets do not get pushed. } public virtual void Rotate(Vector3d axis, double torque) { // Planets do not have their rotation changed, either. } public bool Colliding(IGameObj o) { if (Collidable && o.Collidable) { return Collider.Colliding(o.Collider); } else { return false; } } public virtual void OnCollide(IGameObj o, IPlace g) { } public virtual void Die(IPlace g) { } public virtual void Update(IPlace g, double dt) { OldLoc = Loc; } public virtual void FreezeCallback(double freezeTime) { } public virtual void UnfreezeCallback(double unfreezeTime) { } } public class Ship : SpaceObj { public Ship(Vector3d loc) : base(loc) { } } /// <summary> /// An astronomical body in a star system... a star, planet, moon, whatever. /// As such, it moves on a fixed orbit and cannot be physically affected by player interactions. /// </summary> public class Body : IGameObj { public string Name { get; set; } // The parent and orbit can be null. public Body Parent { get; set; } public KeplerOrbit Orbit { get; set; } public double Radius { get; set; } double orbitTime = 0.0; // Attributes public long Id { get; set; } public Vector3d OldLoc { get; set; } public Vector3d Loc { get; set; } public Quaterniond OldFacing { get; set; } public Quaterniond Facing { get; set; } public Vector3d Vel { get; set; } public double RVel { get; set; } public double Mass { get; set; } public double Moment { get; set; } public Collider Collider { get; set; } // True if colliding with it does something public bool Collidable { get; set; } public bool Alive { get; set; } public Body(Vector3d loc, Quaterniond facing, double mass) { Loc = loc; OldLoc = loc; Facing = facing; OldFacing = facing; Mass = mass; Moment = 1.0; Collider = new SphereCollider(loc, 1.0); Vel = Vector3d.Zero; RVel = 0; Collidable = true; } public Body(Vector3d loc, Quaterniond facing, double mass, Body parent, KeplerOrbit orbit) : this(loc, facing, mass) { Parent = parent; Orbit = orbit; } public Body() : this(Vector3d.Zero, Quaterniond.Identity, 1.0) { } // Operations public virtual void Push(Vector3d force) { // Planets do not get pushed. } public virtual void Rotate(Vector3d axis, double torque) { // Planets do not have their rotation changed, either. } public bool Colliding(IGameObj o) { if (Collidable && o.Collidable) { return Collider.Colliding(o.Collider); } else { return false; } } public virtual void OnCollide(IGameObj o, IPlace g) { } public virtual void Die(IPlace g) { } Vector3d getLocation(double t) { if (Parent == null) { return Loc; } else { var ploc = Parent.getLocation(t); var offset = Orbit.offsetVector(t); return ploc + new Vector3d(offset); } } public virtual void Update(IPlace g, double dt) { OldLoc = Loc; //Console.WriteLine("Updated body, dt {0}", dt); orbitTime += dt; Loc = getLocation(orbitTime); } public virtual void FreezeCallback(double freezeTime) { orbitTime = freezeTime; } public virtual void UnfreezeCallback(double unfreezeTime) { orbitTime = unfreezeTime; } } }
// Copyright 2018 Grigoryan Artem // Licensed under the Apache License, Version 2.0 using System; using System.Runtime.Serialization; namespace Sockets.Chat.Model.Clients { public class ServerUnavailableException : Exception { public ServerUnavailableException() { } public ServerUnavailableException(string message) : base(message) { } public ServerUnavailableException(string message, Exception innerException) : base(message, innerException) { } protected ServerUnavailableException(SerializationInfo info, StreamingContext context) : base(info, context) { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Win32.SafeHandles; using System.Security; namespace System.IO.MemoryMappedFiles { internal partial class MemoryMappedView { [SecurityCritical] public unsafe static MemoryMappedView CreateView( SafeMemoryMappedFileHandle memMappedFileHandle, MemoryMappedFileAccess access, Int64 offset, Int64 size) { throw NotImplemented.ByDesign; // TODO: Implement this } [SecurityCritical] public void Flush(UIntPtr capacity) { throw NotImplemented.ByDesign; // TODO: Implement this } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public static class TurnManager { public static List<Enemy> Enemies = new List<Enemy>(); public static List<Enemy> PendingAdditions = new List<Enemy>(); public static List<Enemy> PendingRemovals = new List<Enemy>(); public static void EnemyTurn() { foreach (Enemy e in Enemies) if (!PendingRemovals.Contains(e)) e.Turn(); Enemies.AddRange(PendingAdditions); PendingAdditions.Clear(); foreach (Enemy e in PendingRemovals) { Enemies.Remove(e); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ETModel; using UnityEngine; using UnityEngine.UI; namespace ETHotfix { [ObjectSystem] public class GetGoodsOneItemAwakeSystem : AwakeSystem<GetGoodsOneItem, GameObject, GetGoodsOne> { public override void Awake(GetGoodsOneItem self, GameObject go, GetGoodsOne data) { self.Awake(go, data, UIType.GetGoodsHintPanel); } } public class GetGoodsOneItem:BaseItem<GetGoodsOne> { private Text mQuantityText; private Image mIconImage; public override void Awake(GameObject go, GetGoodsOne data, string uiType) { base.Awake(go, data, uiType); mQuantityText = rc.Get<GameObject>("QuantityText").GetComponent<Text>(); mIconImage = rc.Get<GameObject>("IconImage").GetComponent<Image>(); InitPanel(); } public void InitPanel() { mQuantityText.text = "x"+mData.GetAmount; mIconImage.sprite = GetResoure<Sprite>(GoodsInfoTool.GetGoodsIcon(mData.GoodsId)); mIconImage.SetNativeSize(); } } }
using System; namespace PushSharp.FirefoxOS { /// <summary> /// Fluent extension for configuring FirefoxOS notification. /// </summary> public static class FirefoxOSFluentNotification { /// <summary> /// Adds an endpoint url to the notification. /// </summary> /// /// <param name="n">Notification object.</param> /// <param name="endpoint">Endpoint url.</param> public static FirefoxOSNotification ForEndpointUrl(this FirefoxOSNotification n, Uri endpoint) { n.EndPointUrl = endpoint; return n; } /// <summary> /// Adds a version to the notification. /// </summary> /// /// <param name="n">Notification object.</param> /// <param name="version">Version to set.</param> public static FirefoxOSNotification WithVersion(this FirefoxOSNotification n, string version) { n.Version = version; return n; } } }
using System; class NonGeneratedCode { } // semmle-extractor-options: /r:System.Diagnostics.Tools.dll
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ZapLib { /// <summary> /// 自訂 SQL Param 處理方式的介面,可以實作這個介面來定義該如何處理 SQL Param /// </summary> public interface ISQLParam { /// <summary> /// 自定義處理 SQL Param 的方法 /// </summary> /// <param name="cmd">目前正在使用的資料庫指令物件</param> /// <param name="name">Param 的名稱</param> /// <param name="attr">使用者定義的要強制指定的 SQL 類型標籤</param> void CustomParamProcessing(SqlCommand cmd, string name, ISQLTypeAttribute attr); } }
using System; using ConsoleFramework.Native; using Xaml; namespace ConsoleFramework.Events { [TypeConverter( typeof ( KeyGestureConverter ) )] public class KeyGesture { private readonly string _displayString; private readonly VirtualKeys _key; private static readonly ITypeConverter _keyGestureConverter = new KeyGestureConverter( ); private readonly ModifierKeys _modifiers; public KeyGesture( VirtualKeys key ) : this( key, ModifierKeys.None ) { } public KeyGesture( VirtualKeys key, ModifierKeys modifiers ) : this( key, modifiers, string.Empty ) { } public KeyGesture( VirtualKeys key, ModifierKeys modifiers, string displayString ) { if ( displayString == null ) throw new ArgumentNullException( "displayString" ); if ( !IsValid( key, modifiers ) ) throw new InvalidOperationException( "KeyGesture is invalid" ); this._modifiers = modifiers; this._key = key; this._displayString = displayString; } public string GetDisplayString( ) { if ( !string.IsNullOrEmpty( this._displayString ) ) { return this._displayString; } return ( string ) _keyGestureConverter.ConvertTo( this, typeof ( string ) ); } // todo : check incompatible combinations internal static bool IsValid( VirtualKeys key, ModifierKeys modifiers ) { return true; } public bool Matches( KeyEventArgs args ) { VirtualKeys wVirtualKeyCode = args.wVirtualKeyCode; if ( this.Key != wVirtualKeyCode ) return false; ControlKeyState controlKeyState = args.dwControlKeyState; ModifierKeys modifierKeys = this.Modifiers; // Проверяем все возможные модификаторы по очереди if ( ( modifierKeys & ModifierKeys.Alt ) != 0 ) { if ( ( controlKeyState & ( ControlKeyState.LEFT_ALT_PRESSED | ControlKeyState.RIGHT_ALT_PRESSED ) ) == 0 ) { // Должен быть взведён один из флагов, показывающих нажатие Alt, а его нет return false; } } else { if ( ( controlKeyState & ( ControlKeyState.LEFT_ALT_PRESSED | ControlKeyState.RIGHT_ALT_PRESSED ) ) != 0 ) { // Не должно быть взведено ни одного флага, показывающего нажатие Alt, // а на самом деле - флаг стоит return false; } } if ( ( modifierKeys & ModifierKeys.Control ) != 0 ) { if ( ( controlKeyState & ( ControlKeyState.LEFT_CTRL_PRESSED | ControlKeyState.RIGHT_CTRL_PRESSED ) ) == 0 ) { return false; } } else { if ( ( controlKeyState & ( ControlKeyState.LEFT_CTRL_PRESSED | ControlKeyState.RIGHT_CTRL_PRESSED ) ) != 0 ) { return false; } } if ( ( modifierKeys & ModifierKeys.Shift ) != 0 ) { if ( ( controlKeyState & ( ControlKeyState.SHIFT_PRESSED ) ) == 0 ) { return false; } } else { if ( ( controlKeyState & ( ControlKeyState.SHIFT_PRESSED ) ) != 0 ) { return false; } } return true; } public string DisplayString { get { return this._displayString; } } public VirtualKeys Key { get { return this._key; } } public ModifierKeys Modifiers { get { return this._modifiers; } } } }
//=========================================== // MVC# Framework | www.MVCSharp.org | // ------------------------------------------ // Copyright (C) 2008 www.MVCSharp.org | // All rights reserved. | //=========================================== using System; using System.Text; namespace MVCSharp.Core.Configuration { #region Documentation /// <summary> /// Helper class for creating objects. /// </summary> #endregion public class CreateHelper { #region Documentation /// <summary> /// Creates an object of specified type. /// </summary> #endregion public static object Create(Type t) { return t.GetConstructor(new Type[] { }).Invoke(new object[] { }); } #region Documentation /// <summary> /// Creates an object of specified type with parameters passed to the constructor. /// </summary> #endregion public static object Create(Type t, params object[] parameters) { Type[] paramTypes = new Type[parameters.Length]; for (int i = 0; i < parameters.Length; i++) paramTypes[i] = parameters[i].GetType(); return t.GetConstructor(paramTypes).Invoke(parameters); } } }
using System.Web.Mvc; using BuildMonitor.Models; using BuildMonitor.Models.Repository; namespace BuildMonitor.Areas.Admin.Controllers { public class FeaturesController : Controller { private readonly IFeatureRepository _featureRepository; public FeaturesController(IFeatureRepository featureRepository) { _featureRepository = featureRepository; } public ActionResult Index() { var features = _featureRepository.GetAllFeatures(); return View(features); } public ActionResult Details(int id) { var feature = _featureRepository.GetFeature(id); return View(feature); } public ActionResult Create() { return View(); } [HttpPost] public ActionResult Create(Feature feature) { _featureRepository.Create(feature); return RedirectToAction("Index"); } public ActionResult Edit(int id) { var feature = _featureRepository.GetFeature(id); return View(feature); } [HttpPost] public ActionResult Edit(Feature feature) { _featureRepository.Update(feature); return RedirectToAction("Index"); } public ActionResult Delete(int id) { var feature = _featureRepository.GetFeature(id); return View(feature); } [HttpPost] public ActionResult Delete(Feature feature) { _featureRepository.Delete(feature); return RedirectToAction("Index"); } } }
using System.Collections.Generic; using UnityEngine; using WhoLivesInThisHouse; public class ClientStartup : MonoBehaviour { public int maxOwners; public GameObject cardCanvas; public GameObject ownerCard; private CharacterListApiCaller apiCaller; private void Awake() { apiCaller = new CharacterListApiCaller("http://192.168.1.95:9595"); List<Character> characters = apiCaller.GetCharacters(); foreach (Character character in characters) { Debug.Log(character); CreateCard(character.Name, character.LikeTags, character.DislikeTags, character.SafeCode); } } void CreateCard(string charName, List<Tag> likes, List<Tag> dislikes, string safe) { GameObject newCard = Instantiate(ownerCard, transform) as GameObject; var cardScript = newCard.GetComponent<InitialiseOwnerCard>(); string likesStr = ""; string dislikesStr = ""; foreach(Tag like in likes) { likesStr += like.Name + "\n"; } foreach (Tag dislike in dislikes) { dislikesStr += dislike.Name + "\n"; Debug.Log(dislikesStr); } cardScript.FillData(charName, likesStr, dislikesStr, safe); } }
namespace Terka.FontBuilder { using System; using NUnit.Framework; // ReSharper disable InconsistentNaming // ReSharper disable EqualExpressionComparison // ReSharper disable ObjectCreationAsStatement #pragma warning disable 252,253 // Possible reference comparison // ReSharper disable ReturnValueOfPureMethodIsNotUsed /// <summary> /// Tests for the <see cref="Tag"/> class. /// </summary> [TestFixture] public class TagTests { /// <summary> /// Tests that Ctor throws exception when called with label of different length than 4. /// </summary> [Test] [ExpectedException(typeof(ArgumentException))] public void Ctor_BadLengthLabel_ThrowsException() { new Tag("abcdefg"); } /// <summary> /// Tests that Ctor throws exception when called with null label. /// </summary> [Test] [ExpectedException(typeof(ArgumentNullException))] public void Ctor_NullLabel_ThrowsException() { new Tag(null); } /// <summary> /// Tests that == returns false when a tag is compared with tag with different label. /// </summary> [Test] public void EqualsOperator_DifferentLabelTag_ReturnFalse() { Assert.IsFalse(new Tag("abcd") == new Tag("defg")); } /// <summary> /// Tests that == returns true when a tag is compared with equal tag. /// </summary> [Test] public void EqualsOperator_EqualLabelTag_ReturnTrue() { Assert.IsTrue(new Tag("abcd") == new Tag("abcd")); } /// <summary> /// Tests that == returns false when a tag is compared with different type. /// </summary> [Test] public void EqualsOperator_NonTag_ReturnFalse() { Assert.IsFalse(new Tag("abcd") == new object()); } /// <summary> /// Tests that == returns false when a tag is compared with null. /// </summary> [Test] public void EqualsOperator_Null_ReturnFalse() { Assert.IsFalse(new Tag("abcd") == null); } /// <summary> /// Tests that Equals returns false when compared with tag with different label. /// </summary> [Test] public void Equals_DifferentLabelTag_ReturnsFalse() { Assert.IsFalse(new Tag("abcd").Equals(new Tag("defg"))); } /// <summary> /// Tests that Equals returns true when compared with null. /// </summary> [Test] public void Equals_EqualLabelTag_ReturnsTrue() { Assert.IsTrue(new Tag("abcd").Equals(new Tag("abcd"))); } /// <summary> /// Tests that Equals returns false when compared with non-tag. /// </summary> [Test] public void Equals_NonTag_ReturnsFalse() { Assert.IsFalse(new Tag("abcd").Equals(new object())); } /// <summary> /// Tests that Equals returns false when compared with null. /// </summary> [Test] public void Equals_Null_ReturnsFalse() { Assert.IsFalse(new Tag("abcd").Equals(null)); } /// <summary> /// Tests that GetHashCode returns hash of the label. /// </summary> [Test] public void GetHashCode_ValidLabel_ReturnsHashOfLabel() { Assert.AreEqual("abcd".GetHashCode(), new Tag("abcd").GetHashCode()); } /// <summary> /// Tests that != returns true when a tag is compared with tag with different label. /// </summary> [Test] public void NotEqualsOperator_DifferentLabelTag_ReturnFalse() { Assert.IsTrue(new Tag("abcd") != new Tag("defg")); } /// <summary> /// Tests that != returns false when a tag is compared with equal tag. /// </summary> [Test] public void NotEqualsOperator_EqualLabelTag_ReturnFalse() { Assert.IsFalse(new Tag("abcd") != new Tag("abcd")); } /// <summary> /// Tests that != returns true when a tag is compared with different type. /// </summary> [Test] public void NotEqualsOperator_NonTag_ReturnFalse() { Assert.IsTrue(new Tag("abcd") != new object()); } /// <summary> /// Tests that != returns true when a tag is compared with null. /// </summary> [Test] public void NotEqualsOperator_Null_ReturnFalse() { Assert.IsTrue(new Tag("abcd") != null); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using osu.Framework; using osu.Framework.Extensions.ObjectExtensions; using osu.Framework.Logging; using osu.Framework.Platform; namespace Aurora.Game.API { /// <summary> /// Instanced plugin loading class. /// </summary> public class PluginLoader : IDisposable { public const string PLUGIN_LIBRARY_PREFIX = "Aurora.Game.Plugins"; public readonly Dictionary<Assembly, Type> LoadedAssemblies = new(); public List<Plugin> LoadedPlugins = new(); private readonly Storage? storage; public PluginLoader(Storage? storage) { this.storage = storage; } public void LoadPlugins() { loadFromDisk(); AppDomain.CurrentDomain.AssemblyResolve += resolvePluginDependencyAssembly; Storage? pluginStorage = storage?.GetStorageForDirectory("plugins"); if (pluginStorage != null) loadUserPlugins(pluginStorage); LoadedPlugins.Clear(); LoadedPlugins.AddRange(LoadedAssemblies.Values .Select(x => Activator.CreateInstance(x) as Plugin) .Where(x => x is not null) .Select(x => x.AsNonNull()) .ToList()); } private void loadFromDisk() { try { string[] files = Directory.GetFiles(RuntimeInfo.StartupDirectory, $"{PLUGIN_LIBRARY_PREFIX}.*.dll"); foreach (string file in files.Where(x => !Path.GetFileName(x).Contains("Tests"))) loadPluginFromFile(file); } catch (Exception e) { Logger.Error(e, $"Could not load plug-in from directory {RuntimeInfo.StartupDirectory}"); } } private void loadPluginFromFile(string file) { string fileName = Path.GetFileNameWithoutExtension(file); if (LoadedAssemblies.Values.Any(x => Path.GetFileNameWithoutExtension(x.Assembly.Location) == fileName)) return; try { addPlugin(Assembly.LoadFrom(file)); } catch (Exception e) { Logger.Error(e, $"Failed to load plug-in {fileName}"); } } private void addPlugin(Assembly assembly) { if (LoadedAssemblies.ContainsKey(assembly)) return; if (LoadedAssemblies.Any(x => x.Key.FullName == assembly.FullName)) return; try { LoadedAssemblies[assembly] = assembly.GetTypes().First(x => x.IsPublic && x.IsSubclassOf(typeof(Plugin)) && !x.IsAbstract && x.GetConstructor(Array.Empty<Type>()) != null ); } catch (Exception e) { Logger.Error(e, $"Failed to add plug-in {assembly}"); } } private Assembly? resolvePluginDependencyAssembly(object? sender, ResolveEventArgs args) { AssemblyName asm = new(args.Name); Assembly? domainAssembly = AppDomain.CurrentDomain.GetAssemblies() .Where(x => { string? name = x.GetName().Name; if (name is null) return false; return args.Name.Contains(name, StringComparison.Ordinal); }) .OrderByDescending(x => x.GetName().Version) .FirstOrDefault(); return domainAssembly ?? LoadedAssemblies.Keys.FirstOrDefault(x => x.FullName == asm.FullName); } private void loadUserPlugins(Storage pluginStorage) { IEnumerable<string>? plugins = pluginStorage.GetFiles(".", $"{PLUGIN_LIBRARY_PREFIX}.*.dll"); foreach (string? plugin in plugins.Where(x => !x.Contains("Tests"))) loadPluginFromFile(pluginStorage.GetFullPath(plugin)); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { AppDomain.CurrentDomain.AssemblyResolve -= resolvePluginDependencyAssembly; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.Kusto.ServiceLayer.Connection.Contracts; namespace Microsoft.Kusto.ServiceLayer.Connection { /// <summary> /// Used to uniquely identify a CancellationTokenSource associated with both /// a string URI and a string connection type. /// </summary> public class CancelTokenKey : CancelConnectParams, IEquatable<CancelTokenKey> { public override bool Equals(object obj) { CancelTokenKey other = obj as CancelTokenKey; if (other == null) { return false; } return other.OwnerUri == OwnerUri && other.Type == Type; } public bool Equals(CancelTokenKey obj) { return obj.OwnerUri == OwnerUri && obj.Type == Type; } public override int GetHashCode() { return OwnerUri.GetHashCode() ^ Type.GetHashCode(); } } }
namespace NuPattern.Runtime { /// <summary> /// Definitions for URI's for solution items /// </summary> public static class SolutionUri { /// <summary> /// The scheme of the URI /// </summary> public const string UriScheme = "solution"; } }
using CodeWars; using NUnit.Framework; namespace CodeWarsTests { [TestFixture] public class TemperatureAnalysisITests { [Test] public void MyTest() { Assert.AreEqual(-8, TemperatureAnalysisI.LowestTemperature("-1 50 -4 20 22 -7 0 10 -8")); Assert.AreEqual(10, TemperatureAnalysisI.LowestTemperature("10 50 12 20 22 13 20 100 18")); Assert.AreEqual(-1, TemperatureAnalysisI.LowestTemperature("-1 50 16 20 22 1 0 10 34")); Assert.AreEqual(-2, TemperatureAnalysisI.LowestTemperature("-2 3 -1 12 45 14")); Assert.AreEqual(null, TemperatureAnalysisI.LowestTemperature("")); } } }
using System; using System.Collections.Generic; using System.ComponentModel; namespace Plugin.Beahat.Abstractions { /// <summary> /// Interface for Beahat /// </summary> public interface IBeahat : INotifyPropertyChanged { /// <summary> /// BeahatがiBeaconをスキャンしているかどうかを取得します。 /// </summary> /// <value><c>true</c>スキャン実行中<c>false</c>スキャン停止中</value> bool IsScanning { get; } /// <summary> /// スキャンで検出されたiBeaconの一覧を取得します。 /// 検出された各iBeaconについて、最も近接したときの情報を保持します。 /// </summary> List<iBeacon> BeaconListFromClosestApproachedEvent { get; } /// <summary> /// スキャンで検出されたiBeaconの一覧を取得します。 /// 検出された各iBeaconについて、最も直近に検出したときの情報を保持します。 /// </summary> List<iBeacon> BeaconListFromLastApproachedEvent { get; } /// <summary> /// 端末がBluetoothに対応しているかどうかを取得します。 /// </summary> /// <returns><c>true</c>対応<c>false</c>非対応</returns> bool SupportsBluetooth(); /// <summary> /// 端末のBluetooth機能がオンにされているかどうかを取得します。 /// 端末がBluetooth機能をオンにしていない場合、falseを返します。 /// また、端末がBluetoothをサポートしていない場合もfalseを返します。 /// </summary> /// <returns><c>true</c>オン<c>false</c>オフ</returns> bool IsReadyToUseBluetooth(); /// <summary> /// iBeacon検知のために必要な位置情報の使用が許可されているかどうかを取得します。 /// AndroidとUWPではiBeaconを検知するために位置情報利用の許可が必要ないため、常にtrueが返されます。 /// </summary> /// <returns><c>true</c>許可されている<c>false</c>許可されていない</returns> bool CanUseLocationForDetectBeacons(); /// <summary> /// 端末のBluetooth機能がオフにされている場合に、Bluetooth機能をオンにするためのダイアログを表示します。 /// UWPには対応する機能がないため、何もしません。 /// 端末がBluetoothに対応していない場合、例外BluetoothUnsupportedExceptionをthrowします。 /// </summary> void RequestToTurnOnBluetooth(); /// <summary> /// 位置情報機能がオフにされている、あるいは許可されていない場合に、iBeaconを検知可能にするための位置情報の使用許可をユーザーに求めるダイアログを表示します。 /// AndroidとUWPではiBeaconを検知するために位置情報利用の許可が必要ないため、何もしません。 /// </summary> void RequestToAllowUsingLocationForDetectBeacons(); /// <summary> /// 検知対象とするiBeaconと、そのiBeaconを検知したときに実行させる処理を追加します。 /// 同じiBeaconに対してこのメソッドを続けて実行することで、同じiBeaconを検知したときの処理を複数設定することが可能です。 /// </summary> /// <param name="uuid">検知対象とするiBeaconのUUID</param> /// <param name="major">検知対象とするiBeaconのMajor</param> /// <param name="minor">検知対象とするiBeaconのMinor</param> /// <param name="thresholdRssi">検知扱いとする下限RSSI</param> /// <param name="intervalMilliSec">次回の処理実行を待機させる時間(単位はミリ秒)</param> /// <param name="callback">iBeaconを検知したときに実行させる処理</param> void AddObservableBeaconWithCallback(Guid uuid, ushort major, ushort minor, short thresholdRssi, int intervalMilliSec, Action callback); /// <summary> /// 検知対象とするiBeaconと、そのiBeaconを検知したときに実行させる処理を追加します。 /// 同じiBeaconに対してこのメソッドを続けて実行することで、同じiBeaconを検知したときの処理を複数設定することが可能です。 /// </summary> /// <param name="uuid">検知対象とするiBeaconのUUID</param> /// <param name="major">検知対象とするiBeaconのMajor</param> /// <param name="thresholdRssi">検知扱いとする下限RSSI</param> /// <param name="intervalMilliSec">次回の処理実行を待機させる時間(単位はミリ秒)</param> /// <param name="callback">iBeaconを検知したときに実行させる処理</param> void AddObservableBeaconWithCallback(Guid uuid, ushort major, short thresholdRssi, int intervalMilliSec, Action callback); /// <summary> /// 検知対象とするiBeaconと、そのiBeaconを検知したときに実行させる処理を追加します。 /// 同じiBeaconに対してこのメソッドを続けて実行することで、同じiBeaconを検知したときの処理を複数設定することが可能です。 /// </summary> /// <param name="uuid">検知対象とするiBeaconのUUID</param> /// <param name="thresholdRssi">検知扱いとする下限RSSI</param> /// <param name="intervalMilliSec">次回の処理実行を待機させる時間(単位はミリ秒)</param> /// <param name="callback">iBeaconを検知したときに実行させる処理</param> void AddObservableBeaconWithCallback(Guid uuid, short thresholdRssi, int intervalMilliSec, Action callback); /// <summary> /// 検知対象とするiBeaconを追加します。 /// 同じiBeaconに対してAddObservableBeaconWithCallbackメソッドを実行することで、 /// 検出時に実行する処理を後から追加することが可能です。 /// </summary> /// <param name="uuid">UUID.</param> /// <param name="major">Major.</param> /// <param name="minor">Minor.</param> void AddObservableBeacon(Guid uuid, ushort major, ushort minor); /// <summary> /// 検知対象とするiBeaconを追加します。 /// 同じiBeaconに対してAddObservableBeaconWithCallbackメソッドを実行することで、 /// 検出時に実行する処理を後から追加することが可能です。 /// </summary> /// <param name="uuid">UUID.</param> /// <param name="major">Major.</param> void AddObservableBeacon(Guid uuid, ushort major); /// <summary> /// 検知対象とするiBeaconを追加します。 /// 同じiBeaconに対してAddObservableBeaconWithCallbackメソッドを実行することで、 /// 検出時に実行する処理を後から追加することが可能です。 /// </summary> /// <param name="uuid">UUID.</param> void AddObservableBeacon(Guid uuid); /// <summary> /// AddEventで設定された検出対象iBeaconと実行処理を全て消去します。 /// </summary> void ClearAllObservableBeacons(); /// <summary> /// 検出されたiBeaconの一覧を初期化します。 /// </summary> void InitializeDetectedBeaconList(); /// <summary> /// iBeaconのスキャンを開始します。 /// 端末がBluetoothに対応していない場合、例外BluetoothUnsupportedExceptionをthrowします。 /// 端末のBluetooth機能がオフにされている場合、例外BluetoothTurnedOffExceptionをthrowします。 /// iOSのみ、位置情報サービスの使用が許可されていない場合、例外LocationServiceNotAllowedExceptionをthrowします。 /// </summary> void StartScan(); /// <summary> /// iBeaconのスキャンを停止します。 /// </summary> void StopScan(); } }
using System.Collections.Generic; using System.Threading.Tasks; using AElf.Contracts.Configuration; using AElf.CSharp.Core.Extension; using AElf.Kernel.Blockchain.Application; using AElf.Kernel.SmartContract.Application; using AElf.Types; using Google.Protobuf; using Google.Protobuf.WellKnownTypes; using Shouldly; using Xunit; namespace AElf.Kernel.Configuration.Tests { public partial class ConfigurationServiceTest { [Fact] public async Task GetInterestedEventAsync_Without_DeployContract_Test() { var chain = await _blockchainService.GetChainAsync(); var chainContext = new ChainContext { BlockHash = chain.BestChainHash, BlockHeight = chain.BestChainHeight }; var configurationSetLogEventProcessor = GetRequiredService<IBlockAcceptedLogEventProcessor>(); var eventData = await configurationSetLogEventProcessor.GetInterestedEventAsync(chainContext); eventData.ShouldBeNull(); } [Fact] public async Task GetInterestedEventAsync_Repeat_Get_Test() { await InitializeContractsAndSetLib(); var chain = await _blockchainService.GetChainAsync(); var chainContext = new ChainContext { BlockHash = chain.BestChainHash, BlockHeight = chain.BestChainHeight }; var configurationSetLogEventProcessor = GetRequiredService<IBlockAcceptedLogEventProcessor>(); await configurationSetLogEventProcessor.GetInterestedEventAsync(chainContext); var eventData = await configurationSetLogEventProcessor.GetInterestedEventAsync(null); eventData.ShouldNotBeNull(); } [Fact] public async Task GetInterestedEventAsync_Test() { await InitializeContractsAndSetLib(); var chain = await _blockchainService.GetChainAsync(); var chainContext = new ChainContext { BlockHash = chain.BestChainHash, BlockHeight = chain.BestChainHeight }; var configurationSetLogEventProcessor = GetRequiredService<IBlockAcceptedLogEventProcessor>(); var eventData = await configurationSetLogEventProcessor.GetInterestedEventAsync(chainContext); eventData.LogEvent.Address.ShouldBe(ConfigurationContractAddress); } [Fact] public async Task ProcessLogEventAsync_Test() { var blockTransactionLimitConfigurationProcessor = GetRequiredService<IConfigurationProcessor>(); var configurationName = blockTransactionLimitConfigurationProcessor.ConfigurationName; var key = configurationName; var value = new Int32Value { Value = 100 }; var setting = new ConfigurationSet { Key = key, Value = value.ToByteString() }; var logEvent = setting.ToLogEvent(); var chain = await _blockchainService.GetChainAsync(); var block = await _blockchainService.GetBlockByHeightInBestChainBranchAsync(chain.BestChainHeight); var configurationSetLogEventProcessor = GetRequiredService<IBlockAcceptedLogEventProcessor>(); var logEventDic = new Dictionary<TransactionResult,List<LogEvent>>(); var transactionRet = new TransactionResult { BlockHash = block.GetHash() }; logEventDic[transactionRet] = new List<LogEvent>{logEvent}; await configurationSetLogEventProcessor.ProcessAsync(block, logEventDic); await _blockchainService.SetIrreversibleBlockAsync(chain, chain.BestChainHeight, chain.BestChainHash); var getValue = await _blockTransactionLimitProvider.GetLimitAsync(new BlockIndex { BlockHeight = chain.BestChainHeight, BlockHash = chain.BestChainHash }); getValue.ShouldBe(value.Value); } } }