content
stringlengths
23
1.05M
using Citolab.QTI.ScoringEngine.Interfaces; using System; using System.Collections.Generic; using System.Drawing; using System.Text; namespace Citolab.QTI.ScoringEngine.Model { internal class Circle : IShape { private readonly IProcessingContext _logContext; private float _cx = 0.0f; private float _cy = 0.0f; private float _r = 0.0f; public Circle(string coords, IProcessingContext logContext) { var splittedCoords = coords.Split(','); if (splittedCoords.Length == 3) { _cx = coords[0]; _cy = coords[1]; _r = coords[2]; } else { logContext.LogError("Unexpect number of point in coords"); } _logContext = logContext; } public PointF GetCenterPoint() => new PointF { X = _cx, Y = _cy }; public bool IsInside(string response) { var pointerInfo = Helpers.Helper.GetPointsFromResponse(response, _logContext); if (pointerInfo.HasValue) { var pointer = pointerInfo.Value; return ((_cx - pointer.X) * (_cx - pointer.X) + (_cy - pointer.Y) * (_cy - pointer.Y)) < _r * _r; } return false; } } }
using SharpDX.Direct3D11; using Molten.Collections; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Molten.Graphics { public abstract class PipelineShaderObject : PipelineObject<DeviceDX11, PipeDX11> { internal PipelineShaderObject(DeviceDX11 device) : base(device) { } private protected override void OnPipelineDispose() { UAV?.Dispose(); SRV?.Dispose(); UAV = null; SRV = null; } /// <summary>Gets or sets the <see cref="UnorderedAccessView"/> attached to the object.</summary> internal UnorderedAccessView UAV { get; set; } /// <summary>Gets the <see cref="ShaderResourceView"/> attached to the object.</summary> internal ShaderResourceView SRV { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace IoCContainerLibrary { internal class RegistryItem { internal Type Source { get; } internal Type Destination { get; } internal bool IsSingleton { get; } internal RegistryItem(Type source, Type destination, bool isSingleton) { Source = source; Destination = destination; IsSingleton = isSingleton; } } }
namespace GPAppointment.ViewModels.UserVMs { using DataAccess.Entities; using Models; using Tools; using System; using System.Linq.Expressions; public class UsersFilterVM : BaseFilterVM<User> { [FilterProperty(DisplayName = "Username")] public string Username { get; set; } [FilterProperty(DisplayName = "FirstName")] public string FirstName { get; set; } [FilterProperty(DisplayName = "LastName")] public string LastName { get; set; } [FilterProperty(DisplayName = "Email")] public string Email { get; set; } public override Expression<Func<User, Boolean>> BuildFilter() { return (u => (String.IsNullOrEmpty(Username) || u.Username.Contains(Username)) && (String.IsNullOrEmpty(FirstName) || u.FirstName.Contains(FirstName)) && (String.IsNullOrEmpty(LastName) || u.LastName.Contains(LastName)) && (String.IsNullOrEmpty(Email) || u.Email.Contains(Email)) && u.Id != AuthenticationManager.LoggedUser.Id); } } }
using System; using System.Collections.Generic; using UnityEngine; using UnityEngine.Experimental.U2D; namespace UnityEditor.Experimental.U2D.Animation { internal static class BoneCacheExtensions { public static BoneCache[] ToCharacterIfNeeded(this BoneCache[] bones) { return Array.ConvertAll(bones, b => ToCharacterIfNeeded(b)); } public static BoneCache[] ToSpriteSheetIfNeeded(this BoneCache[] bones) { return Array.ConvertAll(bones, b => ToSpriteSheetIfNeeded(b)); } public static BoneCache ToCharacterIfNeeded(this BoneCache bone) { if (bone == null) return null; var skinningCache = bone.skinningCache; if (skinningCache.hasCharacter) { if (bone.skeleton != skinningCache.character.skeleton) { var selectedSprite = skinningCache.selectedSprite; if (selectedSprite == null) return null; var skeleton = selectedSprite.GetSkeleton(); var characterPart = selectedSprite.GetCharacterPart(); Debug.Assert(skeleton != null); Debug.Assert(characterPart != null); Debug.Assert(bone.skeleton == skeleton); Debug.Assert(skeleton.BoneCount == characterPart.BoneCount); var index = skeleton.IndexOf(bone); if (index == -1) bone = null; else bone = characterPart.GetBone(index); } } return bone; } public static BoneCache ToSpriteSheetIfNeeded(this BoneCache bone) { if (bone == null) return null; var skinningCache = bone.skinningCache; if (skinningCache.hasCharacter && skinningCache.mode == SkinningMode.SpriteSheet) { var selectedSprite = skinningCache.selectedSprite; if (selectedSprite == null) return null; var characterSkeleton = skinningCache.character.skeleton; Debug.Assert(bone.skeleton == characterSkeleton); var skeleton = selectedSprite.GetSkeleton(); var characterPart = selectedSprite.GetCharacterPart(); Debug.Assert(skeleton != null); Debug.Assert(characterPart != null); Debug.Assert(skeleton.BoneCount == characterPart.BoneCount); var index = characterPart.IndexOf(bone); if (index == -1) bone = null; else bone = skeleton.GetBone(index); } return bone; } public static SpriteBone ToSpriteBone(this BoneCache bone, Matrix4x4 rootTransform, int parentId) { var position = bone.localPosition; var rotation = bone.localRotation; if (parentId == -1) { rotation = bone.rotation; position = rootTransform.inverse.MultiplyPoint3x4(bone.position); } return new SpriteBone() { name = bone.name, position = new Vector3(position.x, position.y, bone.depth), rotation = rotation, length = bone.localLength, parentId = parentId }; } public static SpriteBone[] ToSpriteBone(this BoneCache[] bones, Matrix4x4 rootTransform) { var spriteBones = new List<SpriteBone>(); foreach (var bone in bones) { var parentId = -1; if (ArrayUtility.Contains(bones, bone.parentBone)) parentId = Array.IndexOf(bones, bone.parentBone); spriteBones.Add(bone.ToSpriteBone(rootTransform, parentId)); } return spriteBones.ToArray(); } } }
using OpenTK.Mathematics; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cornerstone.Components { public enum Team : byte { Player, Enemy } [Flags] public enum BulletType : byte { Normal = 1, Explosive = 2, Penetrating = 4 } public struct Bullet { public Vector2 Position; public Vector2 PrevPosition; public Vector2 Velocity; public float LifeTime; public bool HasGravity; public float Damage; public BulletType BulletType; public Team Team; public Color4 Color; } }
using System; using System.Collections.Generic; using CBZ.ContactApp.Data.Model; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; namespace CBZ.ContactApp.Data.Configuration { public class ReportEntityTypeConfiguration:IEntityTypeConfiguration<Report> { public static IEnumerable<Report> ReportSeed => new List<Report> { new Report{Id = 1,Location = "Ankara",ContactCount = 3,PhoneNumberCount = 3}, new Report{Id = 2,Location = "Bursa",ContactCount = 2,PhoneNumberCount = 2}, }; public void Configure(EntityTypeBuilder<Report> builder) { //Shadow properties builder.Property<DateTime>("Inserted").HasDefaultValueSql("NOW()").ValueGeneratedOnAdd(); builder.Property<DateTime>("Updated").HasDefaultValueSql("NOW()").ValueGeneratedOnAddOrUpdate(); builder.Property(r => r.Location).IsRequired(); builder.Property(r => r.Id).HasIdentityOptions(startValue: 100); //Indexes builder.HasKey(r => r.Id); //Seed builder.HasData(ReportSeed); } } }
using System.Threading; using System.Threading.Tasks; using Qsi.Data; using Qsi.Tree; namespace Qsi.Analyzers { public interface IQsiAnalyzer { bool CanExecute(QsiScript script, IQsiTreeNode tree); ValueTask<IQsiAnalysisResult[]> Execute( QsiScript script, QsiParameter[] parameters, IQsiTreeNode tree, QsiAnalyzerOptions options, CancellationToken cancellationToken = default ); } }
using MZZT.DataBinding; namespace MZZT.DarkForces.Showcase { public class LayerListItem : Databound<int> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using ChristmasPi.Operations.Interfaces; using ChristmasPi.Operations.Utils; using ChristmasPi.Hardware.Interfaces; using ChristmasPi.Hardware.Factories; using ChristmasPi.Data.Exceptions; using ChristmasPi.Data; using Serilog; namespace ChristmasPi.Operations.Modes { public class OffMode : IOperationMode, IOffMode { #region Properties public string Name => "OffMode"; public bool CanBeDefault => false; public bool TurnedOff => _active; #endregion #region Fields private IRenderer renderer; private bool _active; // Whether or not off mode is currently active #endregion public OffMode() { _active = false; } #region IOperationMode Methods public void Activate(bool defaultmode) { renderer = RenderFactory.GetRenderer(); renderer.Start(); TurnOff(); _active = true; Log.ForContext<OffMode>().Information("Activated Off Mode"); } public void Deactivate() { renderer.Stop(); _active = false; Log.ForContext<OffMode>().Information("Deactivated Off Mode"); renderer = null; } public object Info() { return new { TurnedOff = _active }; } public object GetProperty(string property) { return PropertyHelper.ResolveProperty(property, this, typeof(OffMode)); } #endregion #region Methods public void TurnOff() { _active = true; renderer.SetAllLEDColors(Constants.COLOR_OFF); if (!renderer.AutoRender) renderer.Render(renderer); } #endregion } }
using System; using System.Collections.Generic; using System.Text; namespace DesignPattern.Decorator { public sealed class PatrickLiuHouse : House { public override void Renovation() { Console.WriteLine("装修PatrickLiu的房子"); } } }
using System; namespace Wallet.Api.Domain { public class GiftCard : Amount { public Date ValidBefore { get; } public GiftCard(Currency currency, decimal amount, Date validBefore) : base(currency, amount) { if (validBefore == null) throw new ArgumentNullException(nameof(validBefore)); ValidBefore = validBefore; } public override Money On(Timestamp time) => time.CompareTo(ValidBefore) >= 0 ? Zero(Currency) : this; } }
using WebApi.DataModel; using WebApi.Models; namespace WebApi.Services { public interface IMemberService { /// <summary> /// 取得會員 /// </summary> /// <param name="id">會員代碼</param> /// <returns></returns> Member? GetMember(int id); /// <summary> /// 新增會員 /// </summary> /// <param name="member">會員資料</param> /// <returns></returns> Task InsertMember(MemberModel member); /// <summary> /// 更新會員 /// </summary> /// <param name="member">會員資料</param> /// <returns></returns> void UpdateMember(MemberModel member); /// <summary> /// 取得會員列表 /// </summary> /// <param name="page">頁數</param> /// <param name="quantity">數量</param> /// <returns></returns> IEnumerable<Member> GetMembers(int page, int quantity); } }
using System.Threading.Tasks; namespace TakTikan.Tailor.Core.DataStorage { public interface IDataStorageManager { bool HasKey(string key); T Retrieve<T>(string key, T defaultValue = default(T), bool shouldDecrpyt = false); Task StoreAsync<T>(string key, T value, bool shouldEncrypt = false); void RemoveIfExists(string key); } }
// Copyright (c) The Vignette Authors // Licensed under BSD 3-Clause License. See LICENSE for details. using System; using System.Numerics; namespace Oxide.Apps { public class Monitor : DisposableObject { /// <summary> /// The app it owns. /// </summary> public readonly App App; /// <summary> /// Get the monitor's DPI scale (1.0 = 100%). /// </summary> public double Scale => AppCore.ulMonitorGetScale(Handle); /// <summary> /// Get the resolution of the monitor (in pixels). /// </summary> public Vector2 Resolution => new Vector2(Width, Height); /// <summary> /// Get the width of the monitor (in pixels). /// </summary> public int Width => (int)AppCore.ulMonitorGetWidth(Handle); /// <summary> /// Get the height of the monitor (in pixels). /// </summary> public int Height => (int)AppCore.ulMonitorGetHeight(Handle); internal Monitor(IntPtr handle, App app) : base(handle, false) { App = app; } /// <summary> /// Creates a new window from this monitor. /// </summary> public Window CreateWindow(int width, int height, bool isFullScreen, WindowFlags flags) => new Window(this, width, height, isFullScreen, flags); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Collections; using System.Collections.Generic; public class bullet : MonoBehaviour { public Rigidbody2D rb; public float speed=20f; public float damage = 40f; public bool canHit=false; // Start is called before the first frame update void Start() { rb.velocity= transform.right * speed; StartCoroutine(wait()); } private IEnumerator wait(){ yield return new WaitForSeconds(0.2f); canHit=true; } void OnTriggerEnter2D(Collider2D h){ Debug.Log("hit something"); Player player = h.gameObject.GetComponent<Player>(); if (player != null && canHit) { player.TakeDamage(damage); Destroy(gameObject); } } }
using System.Collections.Generic; namespace Monaco.Tests.Messages { public class FatTestMessage : IMessage { public ICollection<IMessage> Messages { get; set; } } }
//创建者:Icarus //手动滑稽,滑稽脸 //ヾ(•ω•`)o //https://www.ykls.app //2019年09月28日-15:11 //Assembly-CSharp using System.Collections.Generic; using CabinIcarus.IcSkillSystem.Expansion.Runtime.Buffs.Components; using CabinIcarus.IcSkillSystem.Expansion.Runtime.Builtin.Buffs; using CabinIcarus.IcSkillSystem.Runtime.Buffs; using CabinIcarus.IcSkillSystem.Runtime.Buffs.Components; using CabinIcarus.IcSkillSystem.Runtime.Buffs.Entitys; using CabinIcarus.IcSkillSystem.Runtime.Buffs.Systems; using CabinIcarus.IcSkillSystem.Runtime.Buffs.Systems.Interfaces; namespace Scripts.Buff.System { public class DeathSystem:ABuffUpdateSystem<IBuffDataComponent>,IBuffCreateSystem<IBuffDataComponent> { private List<IMechanicBuff> _buffs; public DeathSystem(IBuffManager<IBuffDataComponent> buffManager) : base(buffManager) { _buffs = new List<IMechanicBuff>(); } public override bool Filter(IEntity entity) { return BuffManager.HasBuff<IMechanicBuff>(entity,x=>x.MechanicsType == MechanicsType.Health) && !BuffManager.HasBuff<Death>(entity); } public override void Execute(IEntity entity) { BuffManager.GetBuffs(entity,x=>x.MechanicsType == MechanicsType.Health,_buffs); var buff = _buffs[0]; if (buff.Value <= 0) { BuffManager.CreateAndAddBuff<Death>(entity,null); } } public bool Filter(IEntity entity, IBuffDataComponent buff) { return buff is Death; } public void Create(IEntity entity, IBuffDataComponent buff) { BuffManager.DestroyEntityEx(entity); } } }
namespace Wellcome.Dds.AssetDomain.Mets { public interface IAssetMetadata { string GetFileName(); string GetFolder(); string GetFileSize(); string GetFormatName(); string GetAssetId(); string GetLengthInSeconds(); double GetDuration(); string GetBitrateKbps(); int GetNumberOfPages(); int GetNumberOfImages(); int GetImageWidth(); int GetImageHeight(); } }
namespace PexCard.Api.Client.Core.Models { public class BusinessBalanceModel { public int BusinessAccountId { get; set; } public decimal BusinessAccountBalance { get; set; } } }
namespace Infrastructure.Core.Security { public enum GatewayType { BackOffice = 1, WebSite = 2, Android = 4, Ios = 8, Unknown = -1 } }
using System; using System.Collections.Generic; using System.Text; namespace HideAndSeek { class SavedGame { public string PlayerLocation { get; set; } public Dictionary<string, string> OpponentLocations { get; set; } public List<string> FoundOpponents { get; set; } public int MoveNumber { get; set; } } }
namespace SimpleAggregate { using System.Threading; using System.Threading.Tasks; public interface IAggregateRepository<TAggregate> { Task<TAggregate> GetAsync(string aggregateId, CancellationToken cancellationToken = default); Task SaveAsync(TAggregate aggregate, CancellationToken cancellationToken = default); } }
using System; using System.Net; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Filters; using System.Web.Security; namespace ShadowEditor.Server.Base { /// <summary> /// ApiController权限验证属性 /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)] public class ApiAuth : ActionFilterAttribute { /// <summary> /// 权限验证 /// </summary> /// <param name="actionContext"></param> public override void OnActionExecuting(HttpActionContext actionContext) { try { // 允许匿名访问 if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Count > 0) { base.OnActionExecuting(actionContext); return; } // 获取cookie var cookie = actionContext.Request.Headers.GetCookies(); if (cookie == null || cookie.Count < 1) { DenyAction(actionContext, 301, "登录超时!"); return; } // 获取票据 FormsAuthenticationTicket ticket = null; foreach (var perCookie in cookie[0].Cookies) { if (perCookie.Name == FormsAuthentication.FormsCookieName) { ticket = FormsAuthentication.Decrypt(perCookie.Value); break; } } // 验证票据 if (ticket == null) { DenyAction(actionContext, 300, "无权限!"); return; } // 验证权限后将获得的用户信息写入Session HttpContext.Current.Items.Add("__userID", ticket.UserData); // 获取登陆时写入cookie的用户ID base.OnActionExecuting(actionContext); } catch { DenyAction(actionContext, 300, "权限验证出错!"); } } /// <summary> /// 处理拒绝访问 /// </summary> /// <param name="context">上下文环境</param> /// <param name="code">状态码(300-执行出错,301-登录超时)</param> /// <param name="msg">说明</param> private void DenyAction(HttpActionContext context, int code, string msg) { //context.Response.StatusCode = HttpStatusCode.OK; //var content = JsonHelper.ToJson(new Model.Result //{ // Code = code, // Msg = msg //}); //context.Response.Content = new StringContent(content, Encoding.UTF8, "application/json"); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; namespace LudumDare50 { public class Endurance : MonoBehaviour { public Image fillImage; public float maxEndurance = 100f; public float currentEndurance; public Action onExhaust; private void Awake() { currentEndurance = maxEndurance; } public void SetMaxEndurance(float max) { maxEndurance = max; currentEndurance = max; } public void ChangeEndurance(float amount) { currentEndurance += amount; if (currentEndurance > maxEndurance) currentEndurance = maxEndurance; else if (currentEndurance <= 0f) { currentEndurance = 0f; onExhaust?.Invoke(); } UpdateEnduranceUI(); } public void UpdateEnduranceUI() { fillImage.fillAmount = currentEndurance / maxEndurance; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Xml.Linq; namespace SpriteEditor.Models { /// <summary> /// A single pose in a sprite. /// </summary> public class Pose : IDisposable { /// <summary> /// Default constructor. /// </summary> public Pose() { BoundingBox = new Rect(-1, -1, -1, -1); DefaultDuration = 100; Repeats = -1; RequireCompletion = false; Origin = new Vec2(0.0f, 0.0f); Tags = new Dictionary<string, string>(); Frames = new List<Frame>(); } public Pose(Pose other) { BoundingBox = new Rect(other.BoundingBox); DefaultDuration = other.DefaultDuration; Repeats = other.Repeats; RequireCompletion = other.RequireCompletion; Origin = new Vec2(other.Origin); Image = other.Image; TransparentColor = other.TransparentColor; Tags = new Dictionary<string, string>(); foreach (var (key, value) in other.Tags) { Tags[key] = value; } Frames = other.Frames.Select(x => new Frame(x)).ToList(); } /// <summary> /// Collision bounding box. /// </summary> public Rect BoundingBox { get; set; } /// <summary> /// Total duration of one pose cycle in milliseconds. /// </summary> public int DefaultDuration { get; set; } /// <summary> /// Number of times pose is repeated (-1 = forever). /// </summary> public int Repeats { get; set; } /// <summary> /// Should all never-ending pose frames be finished before /// it can be marked as completed? /// </summary> public bool RequireCompletion { get; set; } /// <summary> /// Image origin. /// </summary> public Vec2 Origin { get; set; } /// <summary> /// Name of the pose's image. /// </summary> public string Image { get; set; } /// <summary> /// Transparent color as hex string /// </summary> public string TransparentColor { get; set; } /// <summary> /// Tags associated with pose /// </summary> public Dictionary<string, string> Tags { get; set; } /// <summary> /// List of frames. /// </summary> public List<Frame> Frames { get; set; } public string GetName() { return Tags.ContainsKey("Name") ? Tags["Name"] : ""; } public string NameWithTags() { var name = GetName(); if (Tags.ContainsKey("Direction")) { name += " [" + Tags["Direction"] + "]"; } if (Tags.ContainsKey("State")) { name += " [" + Tags["State"] + "]"; } return name; } public XElement ToXml() { var children = new List<object>(); if (!BoundingBox.Equals(-1, -1, -1, -1)) { children.Add(BoundingBox.ToXml("Bounding-Box")); } children.Add(new XAttribute("Duration", DefaultDuration)); if (Repeats != -1) { children.Add(new XAttribute("Repeats", Repeats)); } else if (RequireCompletion) { children.Add(new XAttribute("Require-Completion", RequireCompletion)); } if (!Utilities.CheckClose(Origin.X, 0.0f)) { children.Add(new XAttribute("X-Origin", Origin.X)); } if (!Utilities.CheckClose(Origin.Y, 0.0f)) { children.Add(new XAttribute("Y-Origin", Origin.Y)); } if (!string.IsNullOrEmpty(Image)) { children.Add(new XAttribute("Image", Image.Replace("\\", "/"))); } if (!string.IsNullOrEmpty(TransparentColor)) { children.Add(new XAttribute("Transparent-Color", TransparentColor)); } foreach (var pair in Tags) { var tagElement = new XElement( "Tag", new XAttribute("Key", pair.Key), new XAttribute("Value", pair.Value)); children.Add(tagElement); } foreach (var frame in Frames) { children.Add(frame.ToXml()); } return new XElement("Pose", children.ToArray()); } protected virtual void Dispose(bool disposing) { if (!disposing) return; foreach (var frame in Frames) { frame.Dispose(); } } public void Dispose() { Dispose(disposing: true); GC.SuppressFinalize(this); } } }
namespace MJPEG { public interface IStreamDecoder { event StreamDecoder.FrameHandler OnFrameReceived; void StartDecodingAsync(string uri); } }
using System; using System.Collections.Generic; using MelonLoader; using UnityEngine; using Harmony; using System.IO; namespace AudicaModding { public class AudicaMod : MelonMod { public static bool playPsychadelia = false; public static bool menuSpawned = false; public static OptionsMenuButton toggleButton = null; public static OptionsMenuSlider speedSlider = null; public static float timer = 0.0f; public static float defaultPhaseSeconds = 14.28f; public static Config config = new Config(); public static string path = Application.dataPath + "/../Mods/Config/TrippyMenu.json"; public static class BuildInfo { public const string Name = "TrippyMenus"; // Name of the Mod. (MUST BE SET) public const string Author = "Continuum"; // Author of the Mod. (Set as null if none) public const string Company = null; // Company that made the Mod. (Set as null if none) public const string Version = "0.1.0"; // Version of the Mod. (MUST BE SET) public const string DownloadLink = null; // Download Link for the Mod. (Set as null if none) } public override void OnApplicationStart() { HarmonyInstance instance = HarmonyInstance.Create("AudicaMod"); Hooks.ApplyHooks(instance); LoadConfig(); } public static void SaveConfig() { Directory.CreateDirectory(Application.dataPath + "/../Mods/Config"); string contents = Encoder.GetConfig(config); File.WriteAllText(path, contents); MelonModLogger.Log("Config saved"); } public static void LoadConfig() { if (!File.Exists(path)) { SaveConfig(); } Encoder.SetConfig(config, File.ReadAllText(path)); MelonModLogger.Log("Config loaded"); } public static void UpdateSlider(OptionsMenuSlider slider, string text) { if (slider == null) { return; } else { slider.label.text = text; SaveConfig(); } } public static void CreateSettingsButton(OptionsMenu optionsMenu) { string toggleText = "OFF"; if (config.activated) { toggleText = "ON"; } optionsMenu.AddHeader(0, "Trippy Menu"); toggleButton = optionsMenu.AddButton (0, toggleText, new Action(() => { if (config.activated) { config.activated = false; playPsychadelia = false; toggleButton.label.text = "OFF"; SaveConfig(); GameplayModifiers.I.mPsychedeliaPhase = 0; timer = 0; } else { config.activated = true; playPsychadelia = true; toggleButton.label.text = "ON"; SaveConfig(); } }), null, "Turns Trippy Menu on or off"); speedSlider = optionsMenu.AddSlider ( 0, "Trippy Menu Cycle Speed", "P", new Action<float>((float n) => { config.speed = Mathf.Round((config.speed + n) * 1000.0f) / 1000.0f; UpdateSlider(speedSlider, "Speed : " + config.speed.ToString()); }), null, null, "Changes color cycle speed" ); speedSlider.label.text = "Speed : " + config.speed.ToString(); //MelonModLogger.Log("Buttons created"); menuSpawned = true; } public override void OnUpdate() { if (!playPsychadelia) return; float phaseTime = defaultPhaseSeconds / config.speed; if (timer <= phaseTime) { timer += Time.deltaTime; float forcedPsychedeliaPhase = timer / (phaseTime); GameplayModifiers.I.mPsychedeliaPhase = forcedPsychedeliaPhase; } else timer = 0; } } }
using Libmirobot.Core; using System; using System.Collections.Generic; using System.IO.Ports; using System.Linq; namespace Libmirobot.IO { /// <summary> /// Represents a serial connection to the hardware. /// </summary> public class SerialConnection : ISerialConnection { /// <inheritdoc/> public event EventHandler<RobotTelegram>? TelegramReceived; /// <inheritdoc/> public event EventHandler<RobotTelegram>? TelegramSent; private readonly SerialPort serialPort = new SerialPort(); bool isConnecting = false; bool isConnected = false; string lastSentInstructionIdentifier = string.Empty; /// <summary> /// Instances a new serial connection using the given port name. /// </summary> /// <param name="portName">Port name, which shall be used to connect to the hardware.</param> public SerialConnection(string portName) { this.serialPort.PortName = portName; this.serialPort.BaudRate = 115200; this.serialPort.DataBits = 8; this.serialPort.StopBits = StopBits.One; } /// <inheritdoc/> public void AttachRobot(ISixAxisRobot robot) { robot.InstructionSent -= this.Robot_InstructionSent; robot.InstructionSent += this.Robot_InstructionSent; } private void Robot_InstructionSent(object sender, RobotTelegram e) { if (!this.isConnected) return; this.SendTelegram(e); } private void SendTelegram(RobotTelegram robotTelegram) { this.lastSentInstructionIdentifier = robotTelegram.InstructionIdentifier; this.serialPort.WriteLine(robotTelegram.Data); this.TelegramSent?.Invoke(this, robotTelegram); } /// <inheritdoc/> public void Connect() { if (!this.isConnecting) { this.isConnecting = true; this.serialPort.Open(); this.serialPort.DataReceived -= this.SerialPort_DataReceived; this.serialPort.DataReceived += this.SerialPort_DataReceived; this.isConnected = true; } } private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { var responseLine = serialPort.ReadLine(); //https://stackoverflow.com/a/12675073 this.TelegramReceived?.Invoke(this, new RobotTelegram(lastSentInstructionIdentifier, responseLine)); } /// <inheritdoc/> public void Disconnect() { if (this.isConnected) { this.serialPort.Close(); this.isConnected = false; this.isConnecting = false; } } /// <summary> /// Lists all serial ports, which can be used for communication with the hardware. /// </summary> /// <returns>List of all serial port names.</returns> public static IList<string> GetAvailablePortNames() { return SerialPort.GetPortNames().ToList(); } /// <summary> /// Disposes the serial connection. /// </summary> public void Dispose() { this.serialPort.Close(); this.serialPort.Dispose(); } } }
namespace Cavity.Caching { using System; using System.Collections.Generic; using System.Net; using Moq; using Xunit; public sealed class ICacheCollectionFacts { [Fact] public void a_definition() { Assert.True(new TypeExpectations<ICacheCollection>() .IsInterface() .IsNotDecorated() .Implements<IEnumerable<object>>() .Result); } [Fact] public void index_string_get() { const string key = "example"; var expected = new object(); var mock = new Mock<ICacheCollection>(); mock .SetupGet(x => x[key]) .Returns(expected) .Verifiable(); var actual = mock.Object[key]; Assert.Equal(expected, actual); mock.VerifyAll(); } [Fact] public void index_string_set() { const string key = "example"; var value = new object(); var mock = new Mock<ICacheCollection>(); mock .SetupSet(x => x[key] = value) .Verifiable(); mock.Object[key] = value; mock.VerifyAll(); } [Fact] public void op_Add_string_object() { const string key = "example"; var value = new object(); var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Add(key, value)) .Verifiable(); mock.Object.Add(key, value); mock.VerifyAll(); } [Fact] public void op_Add_string_object_DateTime() { const string key = "example"; var value = new object(); var absoluteExpiration = DateTime.UtcNow; var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Add(key, value, absoluteExpiration)) .Verifiable(); mock.Object.Add(key, value, absoluteExpiration); mock.VerifyAll(); } [Fact] public void op_Add_string_object_TimeSpan() { const string key = "example"; var value = new object(); var slidingExpiration = TimeSpan.Zero; var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Add(key, value, slidingExpiration)) .Verifiable(); mock.Object.Add(key, value, slidingExpiration); mock.VerifyAll(); } [Fact] public void op_Clear() { var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Clear()) .Verifiable(); mock.Object.Clear(); mock.VerifyAll(); } [Fact] public void op_ContainsKey_string() { const string key = "example"; var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.ContainsKey(key)) .Returns(true) .Verifiable(); Assert.True(mock.Object.ContainsKey(key)); mock.VerifyAll(); } [Fact] public void op_GetOfT_string() { const string key = "example"; var expected = new NetworkCredential(); var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Get<NetworkCredential>(key)) .Returns(expected) .Verifiable(); var actual = mock.Object.Get<NetworkCredential>(key); Assert.Equal(expected, actual); mock.VerifyAll(); } [Fact] public void op_Get_string() { const string key = "example"; var expected = new object(); var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Get(key)) .Returns(expected) .Verifiable(); var actual = mock.Object.Get(key); Assert.Equal(expected, actual); mock.VerifyAll(); } [Fact] public void op_RemoveOfT_string() { const string key = "example"; var expected = new NetworkCredential(); var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Remove<NetworkCredential>(key)) .Returns(expected) .Verifiable(); var actual = mock.Object.Remove<NetworkCredential>(key); Assert.Equal(expected, actual); mock.VerifyAll(); } [Fact] public void op_Remove_string() { const string key = "example"; var expected = new object(); var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Remove(key)) .Returns(expected) .Verifiable(); var actual = mock.Object.Remove(key); Assert.Equal(expected, actual); mock.VerifyAll(); } [Fact] public void op_Set_string_object() { const string key = "example"; var value = new object(); var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Set(key, value)) .Verifiable(); mock.Object.Set(key, value); mock.VerifyAll(); } [Fact] public void op_Set_string_object_DateTime() { const string key = "example"; var value = new object(); var absoluteExpiration = DateTime.UtcNow; var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Set(key, value, absoluteExpiration)) .Verifiable(); mock.Object.Set(key, value, absoluteExpiration); mock.VerifyAll(); } [Fact] public void op_Set_string_object_TimeSpan() { const string key = "example"; var value = new object(); var slidingExpiration = TimeSpan.Zero; var mock = new Mock<ICacheCollection>(); mock .Setup(x => x.Set(key, value, slidingExpiration)) .Verifiable(); mock.Object.Set(key, value, slidingExpiration); mock.VerifyAll(); } [Fact] public void prop_Count_get() { const int expected = 123; var mock = new Mock<ICacheCollection>(); mock .SetupGet(x => x.Count) .Returns(expected) .Verifiable(); var actual = mock.Object.Count; Assert.Equal(expected, actual); mock.VerifyAll(); } } }
using System; using System.Collections.Generic; using System.Xml.Serialization; using Bitsmith.BusinessProcess; using Bitsmith.Models; namespace Bitsmith.ProjectManagement { public class TaskManager { [XmlAttribute("id")] public string Id { get; set; } [XmlAttribute("createdAt")] public DateTime CreatedAt { get; set; } //[XmlElement("Domain")] //public List<Domain> Domains { get; set; } = new List<Domain>(); [XmlElement("Workflow")] public List<Workflow> Workflows { get; set; } = new List<Workflow>(); [XmlElement("Task")] public List<TaskItem> Items { get; set; } = new List<TaskItem>(); } }
using System.Threading.Tasks; using MultiPlug.Base.Attribute; using MultiPlug.Base.Http; using MultiPlug.Ext.RasPi.Config.Components.Home; using MultiPlug.Ext.RasPi.Config.Models.Components.Home.API; using MultiPlug.Ext.RasPi.Config.Utils.Swan; namespace MultiPlug.Ext.RasPi.Config.Controllers.API.Environment { [Route("environment/temperatures/")] public class TemperatureController : APIEndpoint { public Response Get() { Task<ProcessResult>[] Tasks = new Task<ProcessResult>[2]; Tasks[0] = HomeComponent.GetGPUTemperature(); Tasks[1] = HomeComponent.GetCPUTemperature(); Task.WaitAll(Tasks); return new Response { MediaType = "application/json", Model = new Temperatures { GPU = HomeComponent.ProcessGPUTemperature(Tasks[0]), CPU = HomeComponent.ProcessCPUTemperature(Tasks[1]) } }; } } }
using Microservice.Library.NLogger.Application; using Microservice.Library.NLogger.Extention; namespace Microservice.Library.NLogger.Gen { /// <summary> /// 日志组件生成器 /// </summary> public class NLoggerGenerator : INLoggerProvider { public NLoggerGenerator(NLoggerGenOptions options) { Options = options ?? new NLoggerGenOptions(); Init(); } readonly NLoggerGenOptions Options; void Init() { var config = new NLog.Config.LoggingConfiguration(); Options.TargetGeneratorOptions.ForEach(o => { config.AddTarget(o.Target); config.AddRule(o.MinLevel, o.MaxLevel, o.Target); }); NLog.LogManager.Configuration = config; } public NLog.ILogger GetNLogger(string name) { return NLog.LogManager.GetLogger(name); } } }
using System; using System.IO; using Sitecore.DataExchange.Attributes; using Sitecore.DataExchange.Contexts; using Sitecore.DataExchange.Models; using Sitecore.DataExchange.Processors.PipelineSteps; using Sitecore.DataExchange.Providers.Dropbox.Endpoints.Extensions; using Sitecore.DataExchange.Providers.Dropbox.Helpers; using Sitecore.DataExchange.Providers.Dropbox.Plugins; using Sitecore.Resources.Media; namespace Sitecore.DataExchange.Providers.Dropbox.Processors.PipelineSteps { [RequiredEndpointPlugins(typeof (DropboxSettings))] public class ReadFromDropboxAndUnzipAndIterateFilesStepProcessor : BaseReadDataStepProcessor { protected override void ReadData( Endpoint endpoint, PipelineStep pipelineStep, PipelineContext pipelineContext) { if (endpoint == null) { throw new ArgumentNullException(nameof(endpoint)); } if (pipelineStep == null) { throw new ArgumentNullException(nameof(pipelineStep)); } if (pipelineContext == null) { throw new ArgumentNullException(nameof(pipelineContext)); } var logger = pipelineContext.PipelineBatchContext.Logger; // //get the file path from the plugin on the endpoint var settings = endpoint.GetDropboxSettings(); if (settings == null) { return; } if (string.IsNullOrWhiteSpace(settings.DropboxUrl)) { logger.Error( "No Dropbox Url or Files Directory is specified on the endpoint. " + "(pipeline step: {0}, endpoint: {1})", pipelineStep.Name, endpoint.Name); return; } DownloadAndUnzipHelper.Run(settings.DropboxUrl); logger.Info("All files updated successfully"); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using System.Web.Http; using Microsoft.OData; namespace System.Web.OData.Formatter.Serialization { internal static class ODataPayloadKindHelper { public static bool IsDefined(ODataPayloadKind payloadKind) { return payloadKind == ODataPayloadKind.Batch || payloadKind == ODataPayloadKind.BinaryValue || payloadKind == ODataPayloadKind.Collection || payloadKind == ODataPayloadKind.EntityReferenceLink || payloadKind == ODataPayloadKind.EntityReferenceLinks || payloadKind == ODataPayloadKind.Resource || payloadKind == ODataPayloadKind.Error || payloadKind == ODataPayloadKind.ResourceSet || payloadKind == ODataPayloadKind.MetadataDocument || payloadKind == ODataPayloadKind.Parameter || payloadKind == ODataPayloadKind.Property || payloadKind == ODataPayloadKind.ServiceDocument || payloadKind == ODataPayloadKind.Value || payloadKind == ODataPayloadKind.IndividualProperty || payloadKind == ODataPayloadKind.Delta || payloadKind == ODataPayloadKind.Asynchronous || payloadKind == ODataPayloadKind.Unsupported; } public static void Validate(ODataPayloadKind payloadKind, string parameterName) { if (!IsDefined(payloadKind)) { throw Error.InvalidEnumArgument(parameterName, (int)payloadKind, typeof(ODataPayloadKind)); } } } }
using System; using System.ComponentModel.DataAnnotations; using GR.Crm.Organizations.Abstractions.Enums; namespace GR.Crm.Organizations.Abstractions.ViewModels.OrganizationsViewModels { public class OrganizationViewModel { public virtual Guid? Id { get; set; } /// <summary> /// Client Name /// </summary> [Required] [MinLength(2)] [MaxLength(128)] public virtual string Name { get; set; } /// <summary> /// Brand /// </summary> [MinLength(2)] [MaxLength(128)] public virtual string Brand { get; set; } /// <summary> /// Client type /// </summary> public virtual OrganizationType ClientType { get; set; } = OrganizationType.Prospect; /// <summary> /// Bank /// </summary> public virtual string Bank { get; set; } /// <summary> /// Email /// </summary> [Required] [MaxLength(50)] [DataType(DataType.EmailAddress)] [EmailAddress] public virtual string Email { get; set; } /// <summary> /// Phone /// </summary> [Required] [MaxLength(8)] [MinLength(8)] public virtual string Phone { get; set; } /// <summary> /// Web site /// </summary> [MaxLength(50)] public virtual string WebSite { get; set; } /// <summary> /// Fiscal code /// </summary> [MaxLength(15)] [MinLength(6)] public virtual string FiscalCode { get; set; } /// <summary> /// IBAN code /// </summary> [MaxLength(128)] public virtual string IBANCode { get; set; } /// <summary> /// cod swift /// </summary> public virtual string CodSwift { get; set; } /// <summary> /// cod TVA /// </summary> public virtual string VitCode { get; set; } /// <summary> /// Description /// </summary> public virtual string Description { get; set; } /// <summary> /// Industry Id /// </summary> public virtual Guid? IndustryId { get; set; } /// <summary> /// Employee id /// </summary> public virtual Guid? EmployeeId { get; set; } } }
using GizmoFort.Connector.ERPNext.PublicTypes; using GizmoFort.Connector.ERPNext.WrapperTypes; using System.ComponentModel; namespace GizmoFort.Connector.ERPNext.ERPTypes.Daily_work_summary { public class ERPDaily_work_summary : ERPNextObjectBase { public ERPDaily_work_summary() : this(new ERPObject(DocType.Daily_work_summary)) { } public ERPDaily_work_summary(ERPObject obj) : base(obj) { } public static ERPDaily_work_summary Create(string dailyworksummarygroup, Status status, string emailsentto) { ERPDaily_work_summary obj = new ERPDaily_work_summary(); obj.daily_work_summary_group = dailyworksummarygroup; obj.status = status; obj.email_sent_to = emailsentto; return obj; } public string daily_work_summary_group { get { return data.daily_work_summary_group; } set { data.daily_work_summary_group = value; data.name = value; } } public Status status { get { return parseEnum<Status>(data.status); } set { data.status = value.ToString(); } } public string email_sent_to { get { return data.email_sent_to; } set { data.email_sent_to = value; } } } //Enums go here public enum Status { [Description("Open")] Open, [Description("Sent")] Sent, } }
using System; using System.Diagnostics.CodeAnalysis; using AddonCraft.Domain.Entities; using AddonCraft.Domain.Enums; using AddonCraft.Infrastructure.Persistence.Names; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.ValueGeneration; namespace AddonCraft.Infrastructure.Persistence.Configurations { /// <inheritdoc/> /// <summary> /// Provides configuration for the persistence of <see cref="Addon"/>. /// </summary> // ExcludeFromCodeCoverage: There is no value in testing this and it is extremely hard to test. [ExcludeFromCodeCoverage] public class AddonConfiguration : IEntityTypeConfiguration<Addon> { public void Configure(EntityTypeBuilder<Addon> builder) { builder .Ignore(a => a.DomainEvents); builder .Property(a => a.Name) .IsRequired(); builder .Property(a => a.Version) .IsRequired(); builder .Property(a => a.GameFlavor) .HasConversion(t => (GameFlavor.GameFlavorEnum) t, f => GameFlavor.FromEnum(f)) .IsRequired(); builder .Property(a => a.ReleaseType) .HasConversion( t => (ReleaseType.ReleaseTypeEnum) t, f => ReleaseType.FromEnum(f)) .IsRequired(); builder .HasIndex(ColumnName.Id, ColumnName.GameFlavor, ColumnName.ReleaseType) .IsUnique(); builder .HasIndex(ColumnName.Name, ColumnName.GameFlavor, ColumnName.ReleaseType) .IsUnique(); builder .HasOne(a => a.Metadata) .WithMany(); builder .OwnsMany(a => a.Modules, m => { m.WithOwner().HasForeignKey(ColumnName.AddonId); m.Property<Guid>(ColumnName.Id).HasValueGenerator<GuidValueGenerator>(); m.HasKey(ColumnName.Id); m.ToTable(TableName.Modules); }); } } }
using PieEatingNinjas.EIdReader.Shared; using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Text; using System.Threading.Tasks; using Windows.Devices.SmartCards; using Windows.Security.Cryptography; namespace PieEatingNinjas.EIdReader.UWP { internal class EIdReader : IDisposable { private bool disposed = false; readonly SmartCardConnection connection; internal EIdReader(SmartCardConnection connection) { this.connection = connection; } internal Task<Dictionary<byte, string>> ReadAddress() => ReadFile(Command.ADDRESS_FILE_LOCATION, Tags.ADDRESS_TAGS); internal Task<Dictionary<byte, string>> ReadIdentity() => ReadFile(Command.IDENTITY_FILE_LOCATION, Tags.IDENTITY_TAGS); private async Task<Dictionary<byte, string>> ReadFile(byte[] fileLocation, IEnumerable<byte> tags) { await SelectFile(fileLocation); var data = await ReadFile(0); return ReadData(data, tags); } private Dictionary<byte, string> ReadData(byte[] rawData, IEnumerable<byte> tags) { var data = tags.ToDictionary(k => k, v => ""); int idx = 0; //we start at 0 :-) while (idx < rawData.Length) { byte tag = rawData[idx]; //at this location we have a Tag idx++; var length = rawData[idx]; //the next position holds the lenght of the data idx++; //start of the data if (tags.Contains(tag)) //this is a tag we are interested in { var res = new byte[length]; //create array to put data of this tag in. We know the length Array.Copy(rawData, idx, res, 0, length); //fill var value = Encoding.UTF8.GetString(res); //convert to string data[tag] = value; //put the string value we read in the data dictionary } idx += length; //moving on, skipping the length of data we just read } return data; } private async Task<byte[]> ReadFile(byte lenght) { var result = await connection.TransmitAsync(Command.GetReadFileCommand(lenght).AsBuffer()); CryptographicBuffer.CopyToByteArray(result, out byte[] readResponse); if (readResponse?.Length == 2 && readResponse[0] == StatusCode.READ_FILE_LE_INCORRECT) { //Getting back 0x6C, Length is in second byte return await ReadFile(readResponse[1]); } else { return readResponse; } } private async Task SelectFile(byte[] location) { var command = Command.GetSelectFileCommand(location); var result = await connection.TransmitAsync(command.AsBuffer()); CryptographicBuffer.CopyToByteArray(result, out byte[] response); if (response?.Length == 2 && (ushort)((response[0] << 8) + response[1]) == StatusCode.SELECT_FILE_OK) { //We're good! } else { //We didn't get a OK status when selecting the file //We are unable to read the card throw new ReadCardException(); } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (disposed) return; if (disposing) connection.Dispose(); disposed = true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Sharktooth.Mub; namespace Mub2Mid { class Program { static void Main(string[] args) { string inputPath, outputPath; if (args.Length < 1) { // Display usage Console.WriteLine("Usage: song.fsgmub output.mid"); return; } else if (args.Length == 1) { // Copies arguments inputPath = args[0]; outputPath = ReplaceExtension(inputPath, ".mid"); } else { inputPath = args[0]; outputPath = args[1]; } Mub mub = Mub.FromFile(inputPath); MubExport mid = new MubExport(mub); mid.Export(outputPath); } static string ReplaceExtension(string path, string extension) { if (!path.Contains('.')) return path + extension; int lastIdx = path.LastIndexOf('.'); return path.Substring(0, lastIdx) + extension; } } }
using Game.Characters.Stats.Commons; using Game.Characters.Stats.Utils; using System; namespace Game.Characters.Stats.Factories { //Not using IFactory interface cause I don't want to heavily depend on Zenject public class StatsFactory : IStatsFactory { readonly StatCalculator _statCalculator; public StatsFactory(StatCalculator statCalculator) { _statCalculator = statCalculator; } public Stat[] Create() { var statTypesInGame = Enum.GetValues(typeof(EStat)) as EStat[]; var stats = new Stat[statTypesInGame.Length]; for (int i = 0; i < stats.Length; i++) { var type = statTypesInGame[i]; stats[i] = new Stat(_statCalculator, type); } return stats; } } }
 namespace GeneXusCryptography.Commons { /// <summary> /// ISymmectricStreamCipherObject interface for EO /// </summary> public interface ISymmectricStreamCipherObject { /// <summary> /// Encrypts the given text with a stream encryption algorithm /// </summary> /// <param name="symmetricStreamAlgorithm">String SymmetrcStreamAlgorithm enum, algorithm name</param> /// <param name="key">String Hexa key for the algorithm excecution</param> /// <param name="IV">String Hexa IV (nonce) for those algorithms that uses, ignored if not</param> /// <param name="plainText">String UTF-8 plain text to encrypt</param> /// <returns>String Base64 encrypted text with the given algorithm and parameters</returns> string DoEncrypt(string symmetricStreamAlgorithm, string key, string IV, string plainText); /// <summary> /// Decrypts the given encrypted text with a stream encryption algorithm /// </summary> /// <param name="symmetricStreamAlgorithm">String SymmetrcStreamAlgorithm enum, algorithm name</param> /// <param name="key">String Hexa key for the algorithm excecution</param> /// <param name="IV">String Hexa IV (nonce) for those algorithms that uses, ignored if not</param> /// <param name="encryptedInput">String Base64 encrypted text with the given algorithm and parameters</param> /// <returns>plain text UTF-8</returns> string DoDecrypt(string symmetricStreamAlgorithm, string key, string IV, string encryptedInput); } }
using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; namespace Crash.Editor.Engine.Model.Common.UndoRedo { /// <summary> /// /// </summary> public sealed class UndoRedoHistory<TCommand> where TCommand : class, IUndoRedoCommand { private readonly Stack<TCommand> _undoStack = new Stack<TCommand>(); private readonly Stack<TCommand> _redoStack = new Stack<TCommand>(); public bool CanUndo => _undoStack.Any(); public bool CanRedo => _redoStack.Any(); public void Clear() { _undoStack.Clear(); _redoStack.Clear(); } /// <summary> /// /// </summary> public void TrimExcess() { _undoStack.TrimExcess(); _redoStack.TrimExcess(); } public void Execute(TCommand command) { command.Execute(); _undoStack.Push(command); _redoStack.Clear(); } public bool TryUndo([MaybeNullWhen(false)] out TCommand outCommand) { outCommand = null!; if (CanUndo) { outCommand = _undoStack.Pop(); outCommand.Undo(); _redoStack.Push(outCommand); return true; } return false; } public bool TryRedo([MaybeNullWhen(false)] out TCommand outCommand) { outCommand = null!; if (CanRedo) { outCommand = _redoStack.Pop(); outCommand.Execute(); _undoStack.Push(outCommand); return true; } return false; } } }
namespace GameLogic.Disasters { using System.ComponentModel; public class DisasterConditions : INotifyPropertyChanged { private int chanceForAssault; private int chanceForVirus; private int chanceForEarthquake; internal DisasterConditions() { this.ChanceForAssault = 0; this.ChanceForVirus = 0; this.ChanceForEarthquake = 0; } public event PropertyChangedEventHandler PropertyChanged; public int ChanceForAssault { get { return this.chanceForAssault; } internal set { this.chanceForAssault = value; this.OnPropertyChanged(null); } } public int ChanceForVirus { get { return this.chanceForVirus; } internal set { this.chanceForVirus = value; this.OnPropertyChanged(null); } } public int ChanceForEarthquake { get { return this.chanceForEarthquake; } internal set { this.chanceForEarthquake = value; this.OnPropertyChanged(null); } } protected void OnPropertyChanged(string name) { PropertyChangedEventHandler handler = this.PropertyChanged; if (handler != null) { handler(this, new PropertyChangedEventArgs(name)); } } } }
using System.ComponentModel.Composition; using DryIocAttributes; namespace DryIoc.MefAttributedModel.UnitTests.CUT { [Export, ExportMany, Export] public class WithBothTheSameExports { } public interface IOne { } public interface INamed { } [ExportMany(ContractName = "blah", IfAlreadyExported = IfAlreadyExported.Keep)] public class NamedOne : INamed, IOne { } [Export("named", typeof(INamed)), ExportMany, Export("named", typeof(INamed))] public class BothExportManyAndExport : INamed, IOne {} }
using DataStructures.Queue; using Xunit; namespace DataStructures.Tests.Queue.Tests { public class QueueTests { [Fact] public void Peek_throws_empty_exception() { // Arrange Queue<int> testQueue = new Queue<int>(); // Assert Assert.Throws<QueueEmptyException>(() => { // Act testQueue.Peek(); }); } [Fact] public void Enqueue_instantiates_new_queue_from_empty() { // Arrange Queue<int> testQueue = new Queue<int>(); // Act int result = testQueue.Enqueue(1); // Assert Assert.Equal(1, result); } [Fact] public void Enqueue_adds_multiple_items_to_rear() { // Arrange Queue<int> testQueue = new Queue<int>(); testQueue.Enqueue(1); // Act int result = testQueue.Enqueue(2); // Assert Assert.Equal(2, result); } [Fact] public void Peek_at_front_value_of_queue() { // Arrange Queue<int> testQueue = new Queue<int>(); testQueue.Enqueue(1); testQueue.Enqueue(2); // Act int result = testQueue.Peek(); // Assert Assert.Equal(1, result); } [Fact] public void Dequeue_throws_empty_exception() { // Arrange Queue<int> testQueue = new Queue<int>(); // Assert Assert.Throws<QueueEmptyException>(() => { // Act testQueue.Dequeue(); }); } [Fact] public void Dequeue_returns_value_of_dequeued_front_node() { // Arrange Queue<int> testQueue = new Queue<int>(); testQueue.Enqueue(3); testQueue.Enqueue(2); testQueue.Enqueue(1); // Act int result = testQueue.Dequeue(); // Assert Assert.Equal(3, result); } [Fact] public void Dequeue_returns_value_of_dequeued_front_node_on_queue_with_1_item() { // Arrange Queue<int> testQueue = new Queue<int>(); testQueue.Enqueue(1); // Act int result = testQueue.Dequeue(); // Assert Assert.Equal(1, result); } [Fact] public void Is_empty_true_if_empty_queue() { // Arrange Queue<int> testQueue = new Queue<int>(); // Act bool result = testQueue.IsEmpty(); // Assert Assert.True(result); } [Fact] public void Is_empty_false_if_not_empty_queue() { // Arrange Queue<int> testQueue = new Queue<int>(); testQueue.Enqueue(1); // Act bool result = testQueue.IsEmpty(); // Assert Assert.False(result); } [Fact] public void Dequeue_multiple_nodes_out_of_queue() { // Arrange Queue<int> testQueue = new Queue<int>(); testQueue.Enqueue(3); testQueue.Enqueue(2); testQueue.Enqueue(1); testQueue.Dequeue(); testQueue.Dequeue(); testQueue.Dequeue(); // Act bool result = testQueue.IsEmpty(); // Assert Assert.True(result); } [Fact] public void Dequeue_throws_after_emptied() { // Arrange Queue<int> testQueue = new Queue<int>(); testQueue.Enqueue(3); testQueue.Enqueue(2); testQueue.Enqueue(1); testQueue.Dequeue(); testQueue.Dequeue(); testQueue.Dequeue(); // Assert Assert.Throws<QueueEmptyException>(() => { // Act testQueue.Dequeue(); }); } } }
using System; using System.Collections.Generic; using System.Text; namespace SGE.Domain.Entities { public class TurmaEscola { public int IdTurma { get; set; } public int IdEscola { get; set; } public virtual Escola Escola { get; set; } public virtual Turma Turma { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.Common; using System.Data.Entity; using SehrimiTani.Entities; using System.Data.Entity.Validation; using CaracalSoft.Data; namespace SehrimiTani.DataAccessLayer { public class MyInitializer : CreateDatabaseIfNotExists<DatabaseContext> { //protected override void Seed(DatabaseContext context) //{ // List<Sehirler> sehirList = new List<Sehirler>(); // for (int i = 0; i < 10; i++) // { // //Şehir Ekleme // Sehirler sehir = new Sehirler() // { // Sehiradi = FakeData.PlaceData.GetCity(), // CreatedOn = DateTime.Now, // ModifiedOn = DateTime.Now, // ModifiedUsername = "ondersahin", // }; // sehirList.Add(sehir); // //context.Sehir.Add(sehir); // } // //context.SaveChanges(); // Repository<Sehirler>.CreateList(sehirList); // Yorumlar yorum = new Yorumlar(); // //Admin Ekleme // List<Kullanicilar> kullaniciListesi = new List<Kullanicilar>(); // Kullanicilar admin = new Kullanicilar() // { // Adi = "önder", // Soyadi = "Şahin", // Email = "ondershin@gmail.com", // ActivateGuid = Guid.NewGuid(), // isActive = true, // isAdmin = true, // CreatedOn = DateTime.Now, // ModifiedOn = DateTime.Now.AddMinutes(5), // ModifiedUsername = "ondersahin", // Kuladi = "Onder358", // Sifre = "123456", // Telefon = "5548384350", // }; // kullaniciListesi.Add(admin); // //Kullanıcı oluşturma // Kullanicilar standartUser = new Kullanicilar() // { // Adi = "Ahmet", // Soyadi = "Şahin", // Email = "ahmet@gmail.com", // ActivateGuid = Guid.NewGuid(), // isActive = true, // isAdmin = false, // CreatedOn = DateTime.Now, // ModifiedOn = DateTime.Now.AddMinutes(5), // ModifiedUsername = "ondersahin", // Kuladi = "Onder358", // Sifre = "123456", // Telefon = "05548384350", // }; // kullaniciListesi.Add(standartUser); // //Kullanıcılar oluşturma // for (int i = 0; i < 8; i++) // { // Kullanicilar user = new Kullanicilar() // { // Adi = FakeData.NameData.GetFirstName(), // Soyadi = FakeData.NameData.GetSurname(), // Email = FakeData.NetworkData.GetEmail(), // ActivateGuid = Guid.NewGuid(), // isActive = true, // isAdmin = false, // CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedUsername = $"user{i}", // Kuladi = $"user{i}", // Sifre = "123", // Telefon = "5548384350", // }; // kullaniciListesi.Add(user); // } // Repository<Kullanicilar>.CreateList(kullaniciListesi); // //try // //{ // // // Your code... // // //context.SaveChanges(); // //} // //catch (DbEntityValidationException e) // //{ // // foreach (var eve in e.EntityValidationErrors) // // { // // foreach (var ve in eve.ValidationErrors) // // { // // /*Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", // // ve.PropertyName, ve.ErrorMessage);*/ // // string a = ve.PropertyName; // // string b = ve.ErrorMessage; // // } // // } // // throw; // //} // List<Universite> universiteListesi = new List<Universite>(); // Sehirler gSehir = Repository<Sehirler>.Read(x => x.Id == 1); // //Fake dabase universite ekleme // for (int i = 0; i < 10; i++) // { // //Üniversite Ekleme // Universite uni = new Universite() // { // adi = FakeData.PlaceData.GetCity(), // Icerik = FakeData.PlaceData.GetAddress(), // CreatedOn = DateTime.Now, // ModifiedOn = DateTime.Now, // ModifiedUsername = "ondersahin", // SehirID = gSehir // }; // universiteListesi.Add(uni); // } // Repository<Universite>.CreateList(universiteListesi); // //context.Universiteler.Add(uni); // //context.SaveChanges(); // Barinma barinma = new Barinma() // { // Adres = FakeData.PlaceData.GetAddress(), // CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // Icerik = FakeData.TextData.GetSentence(), // ModifiedUsername = "ondersahin", // Tipi = "Yurt", // SehirID = gSehir // }; // Repository<Barinma>.Create(barinma); // //Yorumlar // List<Yorumlar> yorumListesi = new List<Yorumlar>(); // for (int k = 0; k < FakeData.NumberData.GetNumber(5, 9); k++) // { // yorum = new Yorumlar() // { // Icerik = FakeData.TextData.GetSentence(), // LikeCount = FakeData.NumberData.GetNumber(1, 9), // Owner = (k % 2 == 0) ? admin : standartUser, // CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedUsername = (k % 2 == 0) ? admin.Kuladi : standartUser.Kuladi, // SehirlerID = gSehir // }; // yorumListesi.Add(yorum); // } // Repository<Yorumlar>.CreateList(yorumListesi); // List<Kullanicilar> userlist = Repository<Kullanicilar>.ReadList(); // //Liked adding.. // List<Liked> likesList = Repository<Liked>.ReadList(); // for (int j = 0; j < yorum.LikeCount; j++) // { // Liked liked = new Liked() // { // LikedUser = userlist[j], // }; // likesList.Add(liked); // } // Repository<Liked>.CreateList(likesList); // //Gezilecek yer ekleme // List<Gezilecekyer> geziList = Repository<Gezilecekyer>.ReadList(); // for (int m = 0; m < FakeData.NumberData.GetNumber(5, 9); m++) // { // Gezilecekyer gezilecekyer = new Gezilecekyer() // { // Baslik = "Vizelerden Sonra Güzel Bir Sessizlik", // CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // Icerik = FakeData.TextData.GetSentence(), // ModifiedUsername = "ondersahin", // Resim = "image/man.jpg", // SehirlerID = gSehir // }; // //context.Gezilecekyerler.Add(gezilecekyer); // geziList.Add(gezilecekyer); // } // Repository<Gezilecekyer>.CreateList(geziList); // //Puan ekleme // List<Puan> puanList = Repository<Puan>.ReadList(); // for (int m = 0; m < FakeData.NumberData.GetNumber(5, 9); m++) // { // Puan puan = new Puan() // { // degerler = FakeData.NumberData.GetNumber(1, 10), // CreatedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedOn = FakeData.DateTimeData.GetDatetime(DateTime.Now.AddYears(-1), DateTime.Now), // ModifiedUsername = "ondersahin", // UniversiteID = Repository<Universite>.Read(x => x.Id == 1) // }; // // context.puanlar.Add(puan); // puanList.Add(puan); // } // Repository<Puan>.CreateList(puanList); // //Yemekler EKleme // List<Yemekler> yemeklerList = Repository<Yemekler>.ReadList(); // for (int m = 0; m < FakeData.NumberData.GetNumber(5, 9); m++) // { // Yemekler yemekler = new Yemekler() // { // Icerik = FakeData.TextData.GetSentence(), // SehirID = gSehir, // }; // //context.Yemek.Add(yemekler); // yemeklerList.Add(yemekler); // } // Repository<Yemekler>.CreateList(yemeklerList); //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using System.Threading.Tasks; namespace WebPlayer { internal class DebugFileManager : IFileManager { #pragma warning disable CS1998 // Async method lacks 'await' operators and will run synchronously public async Task<SourceFileData> GetFileForID(string id) #pragma warning restore CS1998 // Async method lacks 'await' operators and will run synchronously { return new SourceFileData { Filename = ConfigurationManager.AppSettings["DebugFileManagerFile"] }; } } }
public class PropertyAttributesWithNoEquals { [IgnoreDuringEquals] public int Property { get; set; } [CustomEqualsInternal] [CustomGetHashCode] public void Method() { } }
/**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using ScriptRuntime; namespace ScriptRuntime { public static class FlagUtil { public const uint BIT_FLAG_NONE = 0; public const uint BIT_FLAG_0 = (uint)1; public const uint BIT_FLAG_1 = (uint)1 << 1; public const uint BIT_FLAG_2 = (uint)1 << 2; public const uint BIT_FLAG_3 = (uint)1 << 3; public const uint BIT_FLAG_4 = (uint)1 << 4; public const uint BIT_FLAG_5 = (uint)1 << 5; public const uint BIT_FLAG_6 = (uint)1 << 6; public const uint BIT_FLAG_7 = (uint)1 << 7; public const uint BIT_FLAG_8 = (uint)1 << 8; public const uint BIT_FLAG_9 = (uint)1 << 9; public const uint BIT_FLAG_10 = (uint)1 << 10; public const uint BIT_FLAG_11 = (uint)1 << 11; public const uint BIT_FLAG_12 = (uint)1 << 12; public const uint BIT_FLAG_13 = (uint)1 << 13; public const uint BIT_FLAG_14 = (uint)1 << 14; public const uint BIT_FLAG_15 = (uint)1 << 15; public const uint BIT_FLAG_16 = (uint)1 << 16; public const uint BIT_FLAG_17 = (uint)1 << 17; public const uint BIT_FLAG_18 = (uint)1 << 18; public const uint BIT_FLAG_19 = (uint)1 << 19; public const uint BIT_FLAG_20 = (uint)1 << 20; public const uint BIT_FLAG_21 = (uint)1 << 21; public const uint BIT_FLAG_22 = (uint)1 << 22; public const uint BIT_FLAG_23 = (uint)1 << 23; public const uint BIT_FLAG_24 = (uint)1 << 24; public const uint BIT_FLAG_25 = (uint)1 << 25; public const uint BIT_FLAG_26 = (uint)1 << 26; public const uint BIT_FLAG_27 = (uint)1 << 27; public const uint BIT_FLAG_28 = (uint)1 << 28; public const uint BIT_FLAG_29 = (uint)1 << 29; public const uint BIT_FLAG_30 = (uint)1 << 30; public const uint BIT_FLAG_31 = (uint)1 << 31; public const byte BIT_FLAG_8BIT_MAX = 0xff; public const ushort BIT_FLAG_16BIT_MAX = 0xffff; public const uint BIT_FLAG_32BIT_MAX = 0xffffffff; public const int UNVALID_COUNT = -1; public static uint BIT_FLAG(int num) { return ((uint)1 << (num)); } } /// <summary> /// 场景中的基本方法,此类的方法都为静态方法。 /// </summary> public class Util : Base { static internal Guid CreateFromCPPByteArray(IntPtr arrayBegin) { Byte[] array = new Byte[16]; Marshal.Copy(arrayBegin, array, 0, 16); return new Guid(array); } /// <summary> /// 获取当前帧的时间. /// </summary> /// <returns>当前帧的时间.</returns> /**@brief<b>示例</b> *@code{.cpp} float fDeltaTime = Util.GetDeltaTime(); @endcode */ static public float GetDeltaTime() { return ICall_Util_GetDeltaTime(); } /// <summary> /// 保存场景 /// </summary> /// <param name="sceneName">要保存的场景的名字</param> /// <returns>是否保存成功</returns> static public bool SaveScene(String sceneName) { return ICall_Util_SaveScene(sceneName); } /// <summary> /// 获取脚本根节点. /// </summary> /// <returns>脚本根节点.</returns> static public RuntimeScriptRoot GetRootScript() { return ICall_Util_GetRootScript(); } [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static float ICall_Util_GetDeltaTime(); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static bool ICall_Util_SaveScene(String sceneName); [MethodImplAttribute(MethodImplOptions.InternalCall)] extern private static RuntimeScriptRoot ICall_Util_GetRootScript(); } }
@model IEnumerable<CosmoTrack.Models.UserJournal> @{ Layout = "_Layout"; } <br /> <br /> <br /> <br /> <p> <a asp-action="Create" class="btn btn-outline-secondary">Add a Journal Entry</a> </p> <div class="container mt-5 row"> @foreach (var item in Model) { <div class="card-deck col"> <div class="card text-center mr-5 mb-5" style="width: 18rem;"> <div class="card-body text-center"> <h6>@item.DateCreated</h6> <h3 class="card-header" style="background-color: #E6E6FA;"> <a asp-action="Edit" asp-route-id="@item.ID">Edit</a> <a asp-action="Delete" asp-route-id="@item.ID">Delete</a> </h3> <br /> <div class="journalTxt"> <h5>@item.JournalEntry</h5> </div> </div> </div> </div> } </div>
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Threading.Tasks; namespace InterpretGO.Models { public class Assignment { //How to assign client and interpreter to this assignment from id? [Key] public int AssignmentId { get; set; } public string Title { get; set; } public string Type { get; set; } public bool Claimed { get; set; } [DataType(DataType.Date)] public DateTime? Date { get; set; } public string Time { get; set; } public int Duration { get; set; } public string Language { get; set; } public string Location { get; set; } public int InterpreterId { get; set; } public virtual Interpreter Interpreter { get; set; } public int ClientId { get; set; } public virtual Client Client { get; set; } public Client FindClient(int ClientId) { Client thisClient = new InterpretGODbContext().Clients.FirstOrDefault(i => i.ClientId == ClientId); return thisClient; } } }
using ConsultaH.Domain.Entities; using System.Data.Entity.ModelConfiguration; namespace ConsultaH.Infra.EntityConfig { public class ConsultaConfiguration : EntityTypeConfiguration<Consulta> { public ConsultaConfiguration() { HasKey(c => c.ID); Property(c => c.Horario) .IsRequired(); Property(c => c.NumeroProtocolo) .IsRequired() .HasMaxLength(20); HasRequired(c => c.Paciente) .WithMany() .HasForeignKey(c => c.PacienteID); HasRequired(c => c.TipoExame) .WithMany() .HasForeignKey(c => c.TipoExameID); HasRequired(c => c.Exame) .WithMany() .HasForeignKey(c => c.ExameID); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ipfs.Hypermedia.Tools { internal static class EncodingTools { public static string EncodeString(string input, Encoding encoding) { var bytes = encoding.GetBytes(input); StringBuilder builder = new StringBuilder(); foreach (var b in bytes) { builder.Append(b); builder.Append(' '); } builder.Remove(builder.Length - 1, 1); return builder.ToString(); } public static string DecodeString(string input, Encoding encoding) { List<byte> buffer = new List<byte>(); string tmp = input + ' '; while(tmp != String.Empty) { string s = new string(tmp.TakeWhile(x => x != ' ').ToArray()); tmp = tmp.Remove(0, s.Length + 1); buffer.Add(byte.Parse(s)); } return encoding.GetString(buffer.ToArray()); } } }
using System; using Microsoft.Extensions.Configuration; using MongoDB.Driver; using MongoDB.Bson; namespace adb_dotnet_mongoapi { class Program { public static string ConnectString; public static MongoClient Client; public static string DBName; static void Main(string[] args) { // build the mongo config Program.createConfig(); Client = new MongoClient(ConnectString); // clean the cars collection to make the demo idempotent Client.GetDatabase(DBName).DropCollection(nameof(Car).ToLower()); // create cars repository and drop the existing collection CarRepository carRepo = new CarRepository(Client, DBName); // create the repo and add some cars to it Car mazda3 = new Car {Make="Mazda", Model="3", Cylinders=4}; Car hondaCrv = new Car {Make="Honda", Model="CRV", Cylinders=4}; Car hondaAccord = new Car {Make="Honda", Model="Accord", Cylinders=6}; Car fordF150 = new Car {Make="Ford", Model="F150", Cylinders=6}; Car nissanAltima = new Car {Make="Nissan", Model="Altima", Cylinders=4}; var m3id = carRepo.Create(mazda3); var hcrvid = carRepo.Create(hondaCrv); var haccid = carRepo.Create(hondaAccord); var f150id = carRepo.Create(fordF150); var naltid = carRepo.Create(nissanAltima); Console.WriteLine("Inserted 5 vehicles into DB..."); // get cars from DB and print printAllCars(carRepo); // update cylinders in altima from 4 -> 6 and show all cars Console.WriteLine("Updating Altima cylinders from 4 -> 6..."); nissanAltima.Cylinders=6; carRepo.Update(naltid, nissanAltima); printAllCars(carRepo); // show all Hondas (filter by make) Console.WriteLine("Retrieving all Hondas..."); foreach (var car in carRepo.GetByMake("Honda")) { Console.Write(car.Make + "-" + car.Model + "("+ car.Cylinders + ") "); } Console.WriteLine(); // delete Mazda 3 Console.WriteLine("Removing Mazda3 from DB..."); carRepo.Delete(ObjectId.Parse(m3id.ToString())); printAllCars(carRepo); } public static void printAllCars(CarRepository carRepo) { Console.Write("Read all from DB -> Make-Model(Cylinders): "); foreach (var car in carRepo.Get()) { Console.Write(car.Make + "-" + car.Model + "("+ car.Cylinders + ") "); } Console.WriteLine(); } public static void createConfig() { // connection settings var config = new ConfigurationBuilder() .SetBasePath(AppDomain.CurrentDomain.BaseDirectory) .AddJsonFile("appsettings.json", optional: true) .AddEnvironmentVariables().Build(); ConnectString = config.GetValue<string>("ConnectString"); DBName = config.GetValue<string>("DBName"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class All_range_generator : Barrage_generator { protected float default_dir; void Start(){ default_dir = direction; } protected override void Bullet_init(GameObject obj){ obj.GetComponent<Bullet>().Set_property(position, direction, speed); } public void SetStatus(float angle_gap, int i){ direction = default_dir + angle_gap * i; } }
using System; using System.Linq; namespace SumReversedNumbers { public class StartUp { public static void Main() { var arr = Console.ReadLine() .Split(new char[] {' '}, StringSplitOptions.RemoveEmptyEntries) .ToList(); int sum = 0; for (int i = 0; i < arr.Count; i++) { string input = arr[i]; char[] inputarray = input.ToCharArray(); Array.Reverse(inputarray); string output = new string(inputarray); sum += int.Parse(output); } Console.WriteLine(sum); } } }
using System; using System.Collections.Generic; using System.Text; namespace CommandDesignPattern { public interface Order { void execute(); } }
 using System.Collections.Generic; public class LinearJoint_Base : SkeletalJoint_Base { #region LinearDOF_Impl private class LinearDOF_Impl : LinearDOF { private readonly LinearJoint_Base ljb; public LinearDOF_Impl(LinearJoint_Base ljb) { this.ljb = ljb; } public float currentPosition { get { return ljb.currentLinearPosition; } } public float upperLimit { get { ljb.EnforceOrder(); return ljb.hasUpperLimit ? ljb.linearLimitHigh : float.PositiveInfinity; } set { ljb.linearLimitHigh = value; ljb.hasUpperLimit = !float.IsInfinity(ljb.linearLimitHigh); } } public float lowerLimit { get { ljb.EnforceOrder(); return ljb.hasLowerLimit ? ljb.linearLimitLow : float.NegativeInfinity; } set { ljb.linearLimitLow = value; ljb.hasLowerLimit = !float.IsInfinity(ljb.linearLimitLow); } } public BXDVector3 translationalAxis { get { return ljb.axis; } set { ljb.axis = value; } } public BXDVector3 basePoint { get { return ljb.basePoint; } set { ljb.basePoint = value; } } } #endregion public BXDVector3 axis; public BXDVector3 basePoint; public float currentLinearPosition; public bool hasUpperLimit, hasLowerLimit; public float linearLimitLow, linearLimitHigh; private readonly LinearDOF[] linearDOF; public LinearJoint_Base() { linearDOF = new LinearDOF[]{ new LinearDOF_Impl(this) }; } public override SkeletalJointType GetJointType() { return SkeletalJointType.LINEAR; } protected override void WriteBinaryJointInternal(System.IO.BinaryWriter writer) { EnforceOrder(); writer.Write(basePoint); writer.Write(axis); writer.Write((byte) ((hasLowerLimit ? 1 : 0) | (hasUpperLimit ? 2 : 0))); if (hasLowerLimit) { writer.Write(linearLimitLow); } if (hasUpperLimit) { writer.Write(linearLimitHigh); } writer.Write(currentLinearPosition); } protected override void ReadBinaryJointInternal(System.IO.BinaryReader reader) { basePoint = reader.ReadRWObject<BXDVector3>(); axis = reader.ReadRWObject<BXDVector3>(); byte limitFlags = reader.ReadByte(); hasLowerLimit = (limitFlags & 1) == 1; hasUpperLimit = (limitFlags & 2) == 2; if (hasLowerLimit) { linearLimitLow = reader.ReadSingle(); } if (hasUpperLimit) { linearLimitHigh = reader.ReadSingle(); } currentLinearPosition = reader.ReadSingle(); EnforceOrder(); } public void EnforceOrder() { if (hasLowerLimit && hasUpperLimit && linearLimitLow > linearLimitHigh) { float temp = linearLimitHigh; linearLimitHigh = linearLimitLow; linearLimitLow = temp; } } public override IEnumerable<AngularDOF> GetAngularDOF() { return new AngularDOF[0]; } public override IEnumerable<LinearDOF> GetLinearDOF() { return linearDOF; } }
/** * This file is part of OmniAPI, licensed under the MIT License (MIT). * * Copyright (c) 2017 Helion3 http://helion3.com/ * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ using OmniAPI.Components; using System; using UnityEngine; namespace OmniAPI.Rendering { /// <summary> /// Inventory renderer builder. /// </summary> public interface IInventoryRendererBuilder { /// <summary> /// Build this instance. /// </summary> /// <returns>The inventory renderer.</returns> IInventoryRenderer Build(); /// <summary> /// Allow or disallow item hover menus. /// </summary> /// <returns>The builder.</returns> /// <param name="allow">If set to <c>true</c> allow.</param> IInventoryRendererBuilder SetAllowHoverMenu(bool allow); /// <summary> /// Sets the allow slot execution. /// </summary> /// <returns>The allow slot execution.</returns> /// <param name="allow">If set to <c>true</c> allow.</param> IInventoryRendererBuilder SetAllowSlotExecution(bool allow); /// <summary> /// Sets the allow resize. /// </summary> /// <returns>The allow resize.</returns> /// <param name="allow">If set to <c>true</c> allow.</param> IInventoryRendererBuilder SetAllowResize(bool allow); /// <summary> /// Sets the source container. /// </summary> /// <returns>The builder.</returns> /// <param name="container">Container.</param> IInventoryRendererBuilder SetContainer(IContainerComponent container); /// <summary> /// Sets a callback which determines if a given slow is interactable. /// </summary> /// <returns>The builder.</returns> /// <param name="cb">Callback</param> IInventoryRendererBuilder SetIsSlotInteractable(Func<int, bool> cb); /// <summary> /// Sets the button press handler. /// </summary> /// <returns>Sets the button press handler.</returns> /// <param name="cb">Cb.</param> IInventoryRendererBuilder SetOnButtonPress(Func<int, bool> cb); /// <summary> /// Add a custom slot execution handler. /// </summary> /// <returns>The builder.</returns> /// <param name="cb">Execution interaction handler.</param> IInventoryRendererBuilder SetOnSlotExecute(Action<int> cb); /// <summary> /// Sets the on slot selection change callback. /// </summary> /// <returns>The builder.</returns> /// <param name="cb">Cb.</param> IInventoryRendererBuilder SetOnSlotSelectionChange(Action<int> cb); /// <summary> /// Sets the padding. /// </summary> /// <returns>The padding.</returns> /// <param name="padding">Padding.</param> IInventoryRendererBuilder SetPadding(Vector4 padding); /// <summary> /// Set whether to render the slot background sprites. /// </summary> /// <returns>The builder.</returns> /// <param name="render">If set to <c>true</c> render.</param> IInventoryRendererBuilder SetRenderSlotBackgrounds(bool render); /// <summary> /// Sets the length of the row. /// </summary> /// <returns>The builder.</returns> /// <param name="rowLength">Row length.</param> IInventoryRendererBuilder SetRowLength(int rowLength); /// <summary> /// Set whether to show the modal header. This will likely be replaced. /// </summary> /// <returns>The show modal header.</returns> /// <param name="show">If set to <c>true</c> show.</param> IInventoryRendererBuilder SetShowModalHeader(bool show); /// <summary> /// Sets the slot limit. Defaults to -1, which shows all container slots. /// </summary> /// <returns>The builder.</returns> /// <param name="limit">Limit.</param> IInventoryRendererBuilder SetSlotLimit(int limit); /// <summary> /// Sets custom slot positions. /// </summary> /// <returns>The slot positions.</returns> /// <param name="positions">Positions.</param> IInventoryRendererBuilder SetSlotPositions(Vector2[] positions); } }
using System; using System.Text; using System.Collections.Generic; namespace JsonOrg { internal class JsonStringer { /** The output data, containing at most one top-level array or object. */ internal StringBuilder output = new StringBuilder(); /** * Lexical scoping elements within this stringer, necessary to insert the * appropriate separator characters (ie. commas and colons) and to detect * nesting errors. */ internal enum Scope { /** * An array with no elements requires no separators or newlines before * it is closed. */ EMPTY_ARRAY, /** * A array with at least one value requires a comma and newline before * the next element. */ NONEMPTY_ARRAY, /** * An object with no keys or values requires no separators or newlines * before it is closed. */ EMPTY_OBJECT, /** * An object whose most recent element is a key. The next element must * be a value. */ DANGLING_KEY, /** * An object with at least one name/value pair requires a comma and * newline before the next element. */ NONEMPTY_OBJECT, /** * A special bracketless array needed by JSONStringer.join() and * JSONObject.quote() only. Not used for JSON encoding. */ NULL, } /** * Unlike the original implementation, this stack isn't limited to 20 * levels of nesting. */ private List<Scope> stack = new List<Scope>(); /** * A string containing a full set of spaces for a single level of * indentation, or null for no pretty printing. */ private string indent; public JsonStringer() { indent = null; } internal JsonStringer(int indentSpaces) { char[] indentChars = new char[indentSpaces]; for (int i = 0 ; i < indentChars.Length ; ++i) { indentChars[i] = ' '; } indent = new String(indentChars); } /** * Begins encoding a new array. Each call to this method must be paired with * a call to {@link #endArray}. * * @return this stringer. */ public JsonStringer Array() { return Open(Scope.EMPTY_ARRAY, "["); } /** * Ends encoding the current array. * * @return this stringer. */ public JsonStringer EndArray() { return Close(Scope.EMPTY_ARRAY, Scope.NONEMPTY_ARRAY, "]"); } /** * Begins encoding a new object. Each call to this method must be paired * with a call to {@link #endObject}. * * @return this stringer. */ public JsonStringer Obj() { return Open(Scope.EMPTY_OBJECT, "{"); } /** * Ends encoding the current object. * * @return this stringer. */ public JsonStringer EndObject() { return Close(Scope.EMPTY_OBJECT, Scope.NONEMPTY_OBJECT, "}"); } /** * Enters a new scope by appending any necessary whitespace and the given * bracket. */ internal JsonStringer Open(Scope empty, String openBracket) { if (stack.Count == 0 && output.Length > 0) { throw new JsonException("Nesting problem: multiple top-level roots"); } BeforeValue(); stack.Add(empty); output.Append(openBracket); return this; } /** * Closes the current scope by appending any necessary whitespace and the * given bracket. */ internal JsonStringer Close(Scope empty, Scope nonempty, String closeBracket) { Scope context = Peek(); if (context != nonempty && context != empty) { throw new JsonException("Nesting problem"); } stack.RemoveAt(stack.Count - 1); if (context == nonempty) { Newline(); } output.Append(closeBracket); return this; } /** * Returns the value on the top of the stack. */ private Scope Peek() { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } return stack[stack.Count - 1]; } /** * Replace the value on the top of the stack with the given value. */ private void ReplaceTop(Scope topOfStack) { stack[stack.Count - 1] = topOfStack; } /** * Encodes {@code value}. * * @param value a {@link JSONObject}, {@link JSONArray}, String, Boolean, * Integer, Long, Double or null. May not be {@link Double#isNaN() NaNs} * or {@link Double#isInfinite() infinities}. * @return this stringer. */ public JsonStringer Value(Object value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } if (value is JsonArray) { ((JsonArray) value).WriteTo(this); return this; } else if (value is JsonObject) { ((JsonObject) value).WriteTo(this); return this; } BeforeValue(); if (value == null || value == JsonObject.NULL) { output.Append(value); } else if (value is bool) { output.Append(value.ToString().ToLower()); } else if (Json.IsNumber(value)) { output.Append(JsonObject.NumberToString(value)); } else { Str(value.ToString()); } return this; } /** * Encodes {@code value} to this stringer. * * @return this stringer. */ public JsonStringer Value(bool value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } BeforeValue(); output.Append(value); return this; } /** * Encodes {@code value} to this stringer. * * @param value a finite value. May not be {@link Double#isNaN() NaNs} or * {@link Double#isInfinite() infinities}. * @return this stringer. */ public JsonStringer Value(double value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } BeforeValue(); output.Append(JsonObject.NumberToString(value)); return this; } /** * Encodes {@code value} to this stringer. * * @return this stringer. */ public JsonStringer Value(long value) { if (stack.Count == 0) { throw new JsonException("Nesting problem"); } BeforeValue(); output.Append(value); return this; } private void Str(string value) { output.Append("\""); for (int i = 0, length = value.Length ; i < length; i++) { char c = value[i]; /* * From RFC 4627, "All Unicode characters may be placed within the * quotation marks except for the characters that must be escaped: * quotation mark, reverse solidus, and the control characters * (U+0000 through U+001F)." */ switch (c) { case '"': case '\\': case '/': output.Append('\\').Append(c); break; case '\t': output.Append("\\t"); break; case '\b': output.Append("\\b"); break; case '\n': output.Append("\\n"); break; case '\r': output.Append("\\r"); break; case '\f': output.Append("\\f"); break; default: if (c <= 0x1F) { output.Append(string.Format("\\u{0:0000X}", (int) c)); } else { output.Append(c); } break; } } output.Append("\""); } private void Newline() { if (indent == null) { return; } output.Append("\n"); for (int i = 0; i < stack.Count; i++) { output.Append(indent); } } /** * Encodes the key (property name) to this stringer. * * @param name the name of the forthcoming value. May not be null. * @return this stringer. */ public JsonStringer Key(string name) { if (name == null) { throw new JsonException("Names must be non-null"); } BeforeKey(); Str(name); return this; } /** * Inserts any necessary separators and whitespace before a name. Also * adjusts the stack to expect the Key's value. */ private void BeforeKey() { Scope context = Peek(); if (context == Scope.NONEMPTY_OBJECT) { // first in object output.Append(','); } else if (context != Scope.EMPTY_OBJECT) { // not in an object! throw new JsonException("Nesting problem"); } Newline(); ReplaceTop(Scope.DANGLING_KEY); } /** * Inserts any necessary separators and whitespace before a literal value, * inline array, or inline object. Also adjusts the stack to expect either a * closing bracket or another element. */ private void BeforeValue() { if (stack.Count == 0) { return; } Scope context = Peek(); if (context == Scope.EMPTY_ARRAY) { // first in array ReplaceTop(Scope.NONEMPTY_ARRAY); Newline(); } else if (context == Scope.NONEMPTY_ARRAY) { // another in array output.Append(','); Newline(); } else if (context == Scope.DANGLING_KEY) { // value for key output.Append(indent == null ? ":" : ": "); ReplaceTop(Scope.NONEMPTY_OBJECT); } else if (context != Scope.NULL) { throw new JsonException("Nesting problem"); } } /** * Returns the encoded JSON string. * * <p>If invoked with unterminated arrays or unclosed objects, this method's * return value is undefined. * * <p><strong>Warning:</strong> although it contradicts the general contract * of {@link Object#toString}, this method returns null if the stringer * contains no data. */ public override string ToString() { return output.Length == 0 ? null : output.ToString(); } } }
using System; namespace minmpc.Core { internal class ConnectionEventArgs : EventArgs { public bool IsConnecting { get; private set; } public string ServerMessage { get; private set; } public ConnectionEventArgs(bool isConnecting, string serverMessage = null) { IsConnecting = isConnecting; ServerMessage = serverMessage; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TriggerBorder : MonoBehaviour { private void OnCollisionEnter2D(Collision2D collision) { if (collision.gameObject.GetComponent<Enemy>() != null) { DisableEnemyIfExiting(collision.gameObject.GetComponent<Enemy>()); } } private void OnTriggerEnter2D(Collider2D collision) { if (collision.gameObject.GetComponent<Enemy>() != null) { DisableEnemyIfExiting(collision.gameObject.GetComponent<Enemy>()); } } private void OnTriggerExit2D(Collider2D collision) { if (collision.gameObject.GetComponent<Enemy>() != null) { HandleEnemyEnteringField(collision.gameObject.GetComponent<Enemy>()); } } private void OnCollisionExit2D(Collision2D collision) { if (collision.gameObject.GetComponent<Enemy>() != null) { HandleEnemyEnteringField(collision.gameObject.GetComponent<Enemy>()); } } private void HandleEnemyEnteringField(Enemy enemy) { if (!enemy.JustSpawned) { return; } enemy.JustSpawned = false; enemy.Invulnerable = false; } private void DisableEnemyIfExiting(Enemy enemy) { if (enemy.JustSpawned) { return; } enemy.CanAct = false; if (enemy.ControllingAI.TypeOfAI == AIType.TeleportingAI) { enemy.gameObject.SetActive(false); } } }
using System; using System.Collections.Generic; using System.Text; namespace S7evemetry.F1_2020.Packets { public class FinalClassificationData { public static int Size { get; } = 1; public byte NumberOfCars { get; set; } public static FinalClassificationData Read(Span<byte> input) { return new FinalClassificationData { NumberOfCars = input[0] }; } } }
namespace ConsoleApp1.Domain; public class InventoryLine { public Soda Soda { get; set; } public int Quantity { get; set; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class InputManager : MonoBehaviour { private Dictionary<string, Dictionary<string, Action>> listeners; private Dictionary<string, Dictionary<string, Action>> buttonListeners; private Dictionary<string, bool> active; [SerializeField] private GameObject _toolGizmo; [SerializeField] private GameObject _playerPosition; public List<GameObject> handObjects; void Awake() { listeners = new Dictionary<string, Dictionary<string, Action>>(); buttonListeners = new Dictionary<string, Dictionary<string, Action>>(); active = new Dictionary<string, bool>(); } // Update is called once per frame void Update() { foreach(KeyValuePair<string, Dictionary<string, Action>> axis in listeners){ process(axis.Key, Input.GetAxis(axis.Key) > 0); } foreach(KeyValuePair<string, Dictionary<string, Action>> axis in buttonListeners){ processButton(axis.Key, Input.GetButton(axis.Key)); } } public void RightSqueezeFired() { InstantiateGizmo(); } public void LeftSqueezeFired() { InstantiateGizmo(); } public void RightTriggerFired() { InstantiateGizmo(); } public void LeftTriggerFired() { InstantiateGizmo(); } public void ControllerSqueezed() { InstantiateGizmo(); } private void InstantiateGizmo() { // if(_currentGizmo == null) // _currentGizmo = Instantiate(_toolGizmo, new Vector3(0,0,0), Quaternion.identity); // else // _currentGizmo.GetComponent<Transform>().position = hs.GetComponent<Transform>().position; _toolGizmo.transform.position = _playerPosition.transform.position; } public void registerListener(string axis, string action, Action callback){ if(!listeners.ContainsKey(axis)) listeners.Add(axis, new Dictionary<string, Action>()); if(!active.ContainsKey(axis)) active.Add(axis, false); if(!listeners[axis].ContainsKey(action)) listeners[axis].Add(action, callback); listeners[axis][action] = callback; } public void registerButton(string axis, Action callback){ registerButton(axis, "up", callback); } public void registerButton(string axis, string action, Action callback){ if(!buttonListeners.ContainsKey(axis)) buttonListeners.Add(axis, new Dictionary<string, Action>()); if(!active.ContainsKey(axis)) active.Add(axis, false); if(!buttonListeners[axis].ContainsKey(action)) buttonListeners[axis].Add(action, callback); buttonListeners[axis][action] = callback; } public void CursorMoved(){ foreach(KeyValuePair<string, Dictionary<string, Action>> axis in listeners){ if(active[axis.Key] && axis.Value.ContainsKey("drag")) axis.Value["drag"](); } } void process(string axis, bool down){ if(active[axis]){ if(down){ continueAxis(axis); } else{ stopAxis(axis); } } else{ if(down){ startAxis(axis); } } active[axis] = down; } void processButton(string axis, bool down){ if(active[axis]){ if(down){ continueButtonAxis(axis); } else{ stopButtonAxis(axis); } } else{ if(down){ startButtonAxis(axis); } } active[axis] = down; } void startAxis(string axis){ if(listeners[axis].ContainsKey("start")) listeners[axis]["start"](); } void continueAxis(string axis){ if(listeners[axis].ContainsKey("continue")) listeners[axis]["continue"](); } void stopAxis(string axis){ if(listeners[axis].ContainsKey("stop")) listeners[axis]["stop"](); } void startButtonAxis(string axis){ if(buttonListeners[axis].ContainsKey("down")) buttonListeners[axis]["down"](); } void continueButtonAxis(string axis){ if(buttonListeners[axis].ContainsKey("continue")) buttonListeners[axis]["continue"](); } void stopButtonAxis(string axis){ if(buttonListeners[axis].ContainsKey("up")) buttonListeners[axis]["up"](); } }
using UnityEngine; namespace AVRToolkit.EnemySpawner { public class EnemySpawnZone : MonoBehaviour { [SerializeField] protected int zone = 0; } }
using System.Linq; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.OData; using Microsoft.Azure.Mobile.Server; using ghostshockey.it.api.Models; using System; using System.Collections.Generic; using Microsoft.Azure.Mobile.Server.Config; using System.Web.Http.Results; using System.Web.OData.Routing; using System.Net; using System.Web.Http.Cors; namespace ghostshockey.it.api.Controllers { //[MobileAppController] //[Authorize] [EnableCors(origins: "*", headers: "*", methods: "*")] public class PlayerDatasController : ODataController { GhostsDbContext _ctx = new GhostsDbContext(); [EnableQuery] public IHttpActionResult GetPlayerDatas() { return Ok(_ctx.PlayerDatas); } public IHttpActionResult GetPlayerData([FromODataUri]int key) { var model = _ctx.PlayerDatas.FirstOrDefault(p => p.PlayerDataID == key); if (model != null) return Ok(model); else return NotFound(); } public IHttpActionResult Post(PlayerData model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } _ctx.PlayerDatas.Add(model); _ctx.SaveChanges(); return Created(model); } public IHttpActionResult Put([FromODataUri] int key, PlayerData model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var current = _ctx.PlayerDatas.FirstOrDefault(p => p.PlayerDataID == key); if (current == null) { return NotFound(); } model.PlayerDataID = current.PlayerDataID; _ctx.Entry(current).CurrentValues.SetValues(model); _ctx.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } public IHttpActionResult Patch([FromODataUri] int key, Delta<PlayerData> patch) { if (!ModelState.IsValid) { return BadRequest(ModelState); } var current = _ctx.PlayerDatas.FirstOrDefault(p => p.PlayerDataID== key); if (current == null) { return NotFound(); } patch.Patch(current); _ctx.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } public IHttpActionResult Delete([FromODataUri] int key) { var current = _ctx.PlayerDatas.FirstOrDefault(p => p.PlayerDataID == key); if (current == null) { return NotFound(); } _ctx.PlayerDatas.Remove(current); _ctx.SaveChanges(); return StatusCode(HttpStatusCode.NoContent); } protected override void Dispose(bool disposing) { _ctx.Dispose(); base.Dispose(disposing); } } }
using Lightning.Core.Media; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lightning.Node.Media { public class NodeMediaResolver : IMediaResolver { private readonly NodeConfiguration _options; public NodeMediaResolver(IOptions<NodeConfiguration> options) { _options = options.Value; } public string? GetFilePath(string filename) { //TODO: check if the file exists //TODO: add logging return Path.Combine(_options.Media.StoragePath, filename); } } }
using System; using System.Collections.Generic; using System.Text; namespace Poc.DemoNetCore.Domain.Core.Dto { public class Tracking { public int PessoaId { get; set; } public string Nome { get; set; } public double Distancia { get; set; } } public class Localizacao { public double Latitude { get; set; } public double Longitude { get; set; } } public class LocalizacaoAmigos { public PessoaOrigem Amigo { get; set; } public List<Tracking> ListaAmigosProximos { get; set; } } public class PessoaOrigem { public int PessoaId { get; set; } public string Nome { get; set; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using Shadowsocks.Encryption; using System.Threading; using System.Collections.Generic; using Shadowsocks.Encryption.Stream; using System.Diagnostics; namespace Shadowsocks.Test { [TestClass] public class CryptographyTest { [TestMethod] public void TestMD5() { for (int len = 1; len < 64; len++) { System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create(); byte[] bytes = new byte[len]; var random = new Random(); random.NextBytes(bytes); string md5str = Convert.ToBase64String(md5.ComputeHash(bytes)); string md5str2 = Convert.ToBase64String(MbedTLS.MD5(bytes)); Assert.IsTrue(md5str == md5str2); } } private void RunEncryptionRound(IEncryptor encryptor, IEncryptor decryptor) { RNG.Reload(); byte[] plain = new byte[16384]; byte[] cipher = new byte[plain.Length + 16]; byte[] plain2 = new byte[plain.Length + 16]; int outLen = 0; int outLen2 = 0; var random = new Random(); random.NextBytes(plain); encryptor.Encrypt(plain, plain.Length, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(plain.Length, outLen2); for (int j = 0; j < plain.Length; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 1000, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(1000, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } encryptor.Encrypt(plain, 12333, cipher, out outLen); decryptor.Decrypt(cipher, outLen, plain2, out outLen2); Assert.AreEqual(12333, outLen2); for (int j = 0; j < outLen2; j++) { Assert.AreEqual(plain[j], plain2[j]); } } private static bool encryptionFailed = false; private static object locker = new object(); [TestMethod] public void TestMbedTLSEncryption() { encryptionFailed = false; // run it once before the multi-threading test to initialize global tables RunSingleMbedTLSEncryptionThread(); List<Thread> threads = new List<Thread>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(RunSingleMbedTLSEncryptionThread)); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } RNG.Close(); Assert.IsFalse(encryptionFailed); } private void RunSingleMbedTLSEncryptionThread() { try { for (int i = 0; i < 100; i++) { IEncryptor encryptor; IEncryptor decryptor; encryptor = new StreamMbedTLSEncryptor("aes-256-cfb", "barfoo!"); decryptor = new StreamMbedTLSEncryptor("aes-256-cfb", "barfoo!"); RunEncryptionRound(encryptor, decryptor); } } catch { encryptionFailed = true; throw; } } [TestMethod] public void TestRC4Encryption() { encryptionFailed = false; // run it once before the multi-threading test to initialize global tables RunSingleRC4EncryptionThread(); List<Thread> threads = new List<Thread>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(RunSingleRC4EncryptionThread)); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } RNG.Close(); Assert.IsFalse(encryptionFailed); } private void RunSingleRC4EncryptionThread() { try { for (int i = 0; i < 100; i++) { var random = new Random(); IEncryptor encryptor; IEncryptor decryptor; encryptor = new StreamMbedTLSEncryptor("rc4-md5", "barfoo!"); decryptor = new StreamMbedTLSEncryptor("rc4-md5", "barfoo!"); RunEncryptionRound(encryptor, decryptor); } } catch { encryptionFailed = true; throw; } } [TestMethod] public void TestSodiumEncryption() { encryptionFailed = false; // run it once before the multi-threading test to initialize global tables RunSingleSodiumEncryptionThread(); List<Thread> threads = new List<Thread>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(RunSingleSodiumEncryptionThread)); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } RNG.Close(); Assert.IsFalse(encryptionFailed); } private void RunSingleSodiumEncryptionThread() { try { for (int i = 0; i < 100; i++) { var random = new Random(); IEncryptor encryptor; IEncryptor decryptor; encryptor = new StreamSodiumEncryptor("salsa20", "barfoo!"); decryptor = new StreamSodiumEncryptor("salsa20", "barfoo!"); RunEncryptionRound(encryptor, decryptor); } } catch { encryptionFailed = true; throw; } } [TestMethod] public void TestOpenSSLEncryption() { encryptionFailed = false; // run it once before the multi-threading test to initialize global tables RunSingleOpenSSLEncryptionThread(); List<Thread> threads = new List<Thread>(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new ThreadStart(RunSingleOpenSSLEncryptionThread)); threads.Add(t); t.Start(); } foreach (Thread t in threads) { t.Join(); } RNG.Close(); Assert.IsFalse(encryptionFailed); } private void RunSingleOpenSSLEncryptionThread() { try { for (int i = 0; i < 100; i++) { var random = new Random(); IEncryptor encryptor; IEncryptor decryptor; encryptor = new StreamOpenSSLEncryptor("aes-256-cfb", "barfoo!"); decryptor = new StreamOpenSSLEncryptor("aes-256-cfb", "barfoo!"); RunEncryptionRound(encryptor, decryptor); } } catch { encryptionFailed = true; throw; } } } }
namespace Merchello.Core.Models { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using Merchello.Core.Models.EntityBase; /// <summary> /// Represents a country associated with a warehouse /// </summary> public class ShipCountry : Entity, IShipCountry { /// <summary> /// The property selectors. /// </summary> private static readonly Lazy<PropertySelectors> _ps = new Lazy<PropertySelectors>(); /// <summary> /// The <see cref="ICountry"/>. /// </summary> private readonly ICountry _country; /// <summary> /// The warehouse catalog key. /// </summary> private Guid _catalogKey; /// <summary> /// Initializes a new instance of the <see cref="ShipCountry"/> class. /// </summary> /// <param name="catalogKey"> /// The catalog key. /// </param> /// <param name="country"> /// The country. /// </param> public ShipCountry(Guid catalogKey, ICountry country) { Ensure.ParameterCondition(catalogKey != Guid.Empty, "catalogKey"); Ensure.ParameterNotNull(country, "country"); _country = country; _catalogKey = catalogKey; } /// <inheritdoc/> [DataMember] public Guid CatalogKey { get { return _catalogKey; } internal set { SetPropertyValueAndDetectChanges(value, ref _catalogKey, _ps.Value.CatalogKeySelector); } } /// <summary> /// Gets the country code. /// </summary> public string CountryCode { get { return _country.CountryCode; } } /// <summary> /// Gets the name. /// </summary> public string Name { get { return _country.Name; } } /// <summary> /// Gets the ISO. /// </summary> public int Iso { get { return _country.Iso; } } /// <summary> /// Gets the province label. /// </summary> public string ProvinceLabel { get { return _country.ProvinceLabel; } } /// <summary> /// Gets the provinces. /// </summary> public IEnumerable<IProvince> Provinces { get { return _country.Provinces; } } /// <inheritdoc/> [DataMember] public bool HasProvinces { get { return Provinces.Any(); } } /// <summary> /// The property selectors. /// </summary> private class PropertySelectors { /// <summary> /// The catalog key selector. /// </summary> public readonly PropertyInfo CatalogKeySelector = ExpressionHelper.GetPropertyInfo<ShipCountry, Guid>(x => x.CatalogKey); } } }
using System; using UnityEngine; namespace NodeCanvas.Framework.Internal { [Serializable] public class BBObjectParameter : BBParameter<object> { [SerializeField] private Type _type; public override Type varType { get { return this._type; } } public BBObjectParameter() { this.SetType(typeof(object)); } public BBObjectParameter(Type t) { this.SetType(t); } public void SetType(Type t) { if (t == null) { t = typeof(object); } if (t != this._type) { this._value = null; } this._type = t; } } }
namespace BattleCalculator.Model.Enums { public enum LevelType { Débutant = 1, Intermédiaire = 2, Expert = 3 } }
namespace SKAutoNew.Services.Data { using Microsoft.EntityFrameworkCore; using SKAutoNew.Common.DtoModels.TownDtos; using SKAutoNew.Data.Models; using SKAutoNew.Data.Repositories; using SKAutoNew.Services.Data.Contractcs; using SKAutoNew.Services.Mappers.TownServiceMappers; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; /// <summary> /// business logic for Town /// </summary> public class TownService : ITownService { private readonly IRepository<Town> towns; private readonly IRepository<TownUseFullCategory> townUseFullCategories; private readonly IUseFullCategoryService useFullCategoryService; private readonly IRepository<Company> companyRepo; /// <summary> /// constructor /// </summary> /// <param name="towns"></param> /// <param name="townUseFullCategories"></param> /// <param name="useFullCategoryService"></param> /// <param name="companyRepo"></param> public TownService( IRepository<Town> towns, IRepository<TownUseFullCategory> townUseFullCategories, IUseFullCategoryService useFullCategoryService, IRepository<Company> companyRepo) { this.towns = towns; this.townUseFullCategories = townUseFullCategories; this.useFullCategoryService = useFullCategoryService; this.companyRepo = companyRepo; } /// <summary> /// check in database if there is same recipient /// </summary> /// <param name="name"></param> /// <returns></returns> public async Task<bool> CheckIfExistsAsync(string name) { bool checkTown = await this.towns.All().AnyAsync(x => x.Name.ToUpper() == name.ToUpper()); return checkTown; } /// <summary> /// create new town, create townusefullcategories and add them all to database /// </summary> /// <param name="name"></param> /// <returns></returns> public async Task CreateTownByNameAsync(string name) { var allUseFullCategories = await this.useFullCategoryService.GetAlluseFullCategoriesAsync(); Town town = new Town { Name = name, }; foreach (var useFullCategory in allUseFullCategories) { TownUseFullCategory townUseFullCategory = new TownUseFullCategory() { UseFullCategory = useFullCategory, Town = town, }; await this.townUseFullCategories.InsertAsync(townUseFullCategory); } await this.towns.InsertAsync(town); await this.towns.SaveAsync(); } /// <summary> /// delete town from database /// </summary> /// <param name="deleteDtoModel"></param> /// <returns></returns> public async Task<bool> DeleteTownAsync(TownDeleteDtoModel deleteDtoModel) { var neededTown = await this.towns.All() .Include(x => x.UseFullCategories) .Include(x => x.Companies) .FirstOrDefaultAsync(x => x.Id == deleteDtoModel.TownId); if (neededTown == null) { return false; } foreach (var item in neededTown.Companies.ToList()) { this.companyRepo.Delete(item); } foreach (var item in neededTown.UseFullCategories.ToList()) { this.townUseFullCategories.Delete(item); } this.towns.Delete(neededTown); await this.towns.SaveAsync(); return true; } /// <summary> /// get all towns from database /// </summary> /// <returns></returns> public async Task<IList<Town>> GetAllTownsAsync() { var allTowns = await this.towns.All().ToListAsync(); return allTowns; } /// <summary> /// find town by id and get it from database /// </summary> /// <param name="inputModel"></param> /// <returns></returns> public async Task<TownUpdateGetOutPutDto> GetTownById(TownUpdateGetInputDtoModel inputModel) { var neededTown = await this.towns.All().FirstOrDefaultAsync(x => x.Id == inputModel.TownId); var dtoModel = TownUpdateGetOutputServiceMapper.Map(neededTown); return dtoModel; } /// <summary> /// get all towns from database and return model that contains property for town names /// </summary> /// <returns></returns> public async Task<AllTownsViewDtoModel> GetTownNamesAsync() { var allTowns = await this.towns.All().ToListAsync(); var all = GetTownNamesMapper.Map(allTowns); return all; } /// <summary> /// get all towns by usefullcategory name from database /// </summary> /// <param name="name"></param> /// <returns></returns> public async Task<TownWithCategoryNameViewDtoModel> GetTownsByCategoryNameAsync(string name) { var allTowns = await this.towns.All() .Include(x => x.UseFullCategories) .SelectMany(x => x.UseFullCategories .Where(y => y.UseFullCategory.Name == name)) .Select(x => x.Town.Name) .OrderBy(x => x) .ToListAsync(); var viewModel = TownWithCategoryNameMapper.Map(name, allTowns); return viewModel; } /// <summary> /// get all towns from database /// </summary> /// <returns></returns> public async Task<IList<TownIndexDtoModel>> GetTownsForIndexAsync() { var allTowns = await this.towns.All().ToListAsync(); var townsDto = GetTownsForIndexMapper.Map(allTowns); return townsDto; } /// <summary> /// change town and update it in database /// </summary> /// <param name="inputModel"></param> /// <returns></returns> public async Task<bool> UpdateTownAsync(TownUpdatePostInputDtoModel inputModel) { var alltowns = await this.towns.All().ToListAsync(); if (alltowns.Any(x => x.Name == inputModel.TownName)) { return false; } var neededTown = alltowns.FirstOrDefault(x => x.Id == inputModel.TownId); if (neededTown == null) { return false; } neededTown.Name = inputModel.TownName; this.towns.Update(neededTown); await this.towns.SaveAsync(); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using System.ComponentModel.DataAnnotations; using System.Data.Entity; using System.Data.Entity.Infrastructure; using AutoMapper; using AutoMapper.QueryableExtensions; using PagedList; using CarService.Data; using CarService.Models; using CarService.Common; using CarService.Web.ViewModels; namespace CarService.Web.Controllers { public class PartsController : BaseController { public PartsController(ICarServiceData data) : base(data) { } [HttpGet] [Authorize(Roles=GlobalConstants.AdminRole)] public ActionResult Edit(int? id) { if (!id.HasValue) { return new HttpStatusCodeResult(HttpStatusCode.BadRequest); } var part = Data.ReplacementParts.GetById(id.Value); if (part == null) { return HttpNotFound(); } var model = Mapper.Map<PartEdit>(part); ViewBag.Categories = GetCategories(model.CategoryId); return View(model); } [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = GlobalConstants.AdminRole)] public ActionResult Edit(PartEdit edited) { if (ModelState.IsValid) { var url = TempData["Url"] as string; var part = Mapper.Map<ReplacementPart>(edited); try { Data.ReplacementParts.Update(part); Data.SaveChanges(); return Redirect(url); } catch (DbUpdateException ex) { HandleDbUpdateException(ex); } } ViewBag.Categories = GetCategories(edited.CategoryId); return View(edited); } [HttpGet] [Authorize(Roles = GlobalConstants.AdminRole)] public ActionResult Create() { ViewBag.Categories = GetCategories(); return View(new PartBase() { IsActive = true }); } [HttpPost] [ValidateAntiForgeryToken] [Authorize(Roles = GlobalConstants.AdminRole)] public ActionResult Create(PartBase created) { if (ModelState.IsValid) { var url = TempData["Url"] as string; var part = Mapper.Map<ReplacementPart>(created); try { Data.ReplacementParts.Add(part); Data.SaveChanges(); return Redirect(url); } catch (DbUpdateException ex) { HandleDbUpdateException(ex); } } ViewBag.Categories = GetCategories(); return View(created); } public ActionResult Search(int? page, string search, string sort, string stock, int catId = 0, int count = 10) { ViewBag.Name = string.IsNullOrEmpty(sort) ? "name_desc" : ""; ViewBag.Number = sort == "number" ? "number_desc" : "number"; ViewBag.Category = sort == "category" ? "category_desc" : "category"; ViewBag.Price = sort == "price" ? "price_desc" : "price"; ViewBag.Used = sort == "used" ? "used_desc" : "used"; ViewBag.TotalPrice = sort == "total_price" ? "total_price_desc" : "total_price"; var parts = Data .ReplacementParts .All(); if (catId > 0) { parts = parts.Where(p => p.CategoryId == catId); } if (!string.IsNullOrEmpty(search)) { parts = parts.Where(p => p.Name.Contains(search) || p.CatalogNumber.Contains(search)); } if (!string.IsNullOrEmpty(stock)) { parts = parts.Where(p => stock == "IN" ? p.IsActive : !p.IsActive); } var partsModel = parts .Project() .To<PartSearch>(); switch (sort) { case "name_desc": partsModel = partsModel.OrderByDescending(p => p.Name); break; case "category": partsModel = partsModel.OrderBy(p => p.Category); break; case "category_desc": partsModel = partsModel.OrderByDescending(p => p.Category); break; case "number": partsModel = partsModel.OrderBy(p => p.CatalogNumber); break; case "number_desc": partsModel = partsModel.OrderByDescending(p => p.CatalogNumber); break; case "price": partsModel = partsModel.OrderBy(p => p.CurrentPrice); break; case "price_desc": partsModel = partsModel.OrderByDescending(p => p.CurrentPrice); break; case "used": partsModel = partsModel.OrderBy(p => p.TotalUsedNumber); break; case "used_desc": partsModel = partsModel.OrderByDescending(p => p.TotalUsedNumber); break; case "total_price": partsModel = partsModel.OrderBy(p => p.TotalAmount); break; case "total_price_desc": partsModel = partsModel.OrderByDescending(p => p.TotalAmount); break; default: partsModel = partsModel.OrderBy(p => p.Name); break; } ViewBag.Categories = GetCategories(catId); var list = GetResultsPerPage(); ViewBag.Results = list; ViewBag.Stock = new List<SelectListItem>() { new SelectListItem { Text = "IN", Value = "IN", Selected = stock == "IN" }, new SelectListItem { Text = "OUT", Value = "OUT", Selected = stock == "OUT" } }; return View(partsModel.ToPagedList(page ?? 1, count)); } private IEnumerable<SelectListItem> GetCategories(int selected = 0) { var categories = Data .Categories .All() .OrderBy(c => c.Name) .ToList() .Select(c => new SelectListItem { Text = c.Name, Value = c.Id.ToString(), Selected = c.Id == selected }); return categories; } private IEnumerable<SelectListItem> GetResultsPerPage() { return new List<SelectListItem>() { new SelectListItem { Text = "5", Value = "5", }, new SelectListItem { Text = "10", Value = "10", }, new SelectListItem { Text = "20", Value = "20", }, new SelectListItem { Text = "50", Value = "50", }, }; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; namespace Comp3020A3 { public partial class ListForm : Comp3020A3.MainForm { bool editable; int selected1, selected2; public ListForm() { InitializeComponent(); } private void ListForm_Load(object sender, EventArgs e) { } protected override void fillInForm(Object element) { editable = false; reorderToolTip.Hide(); selected1 = -1; selected2 = -1; if (element is List<MovieList>) { List<MovieList> movieLists = (List<MovieList>)element; fillInForm(movieLists); } else { MovieList movieList = (MovieList)element; fillInForm(movieList); } } private void fillInForm(List<MovieList> movieLists) { listDataGrid.ColumnHeadersVisible = false; listTitleLabel.Text = "My Lists"; editNameButton.Hide(); editContentsButton.Show(); editOrderButton.Show(); listIDLabel.Hide(); listDataGrid.DataSource = movieLists; listDataGrid.Columns[0].Visible = false; listDataGrid.Columns[2].Visible = false; newListButton.Show(); } private void fillInForm(MovieList movieList) { listDataGrid.ColumnHeadersVisible = true; listTitleLabel.Text = movieList.name; listIDLabel.Hide(); listIDLabel.Text = "" + movieList.ID; if(ApplicationManager.loggedIn != null && ApplicationManager.loggedIn.username.Equals(movieList.user)) { editNameButton.Show(); editContentsButton.Show(); editOrderButton.Show(); } else { editNameButton.Hide(); editContentsButton.Hide(); editOrderButton.Hide(); } listDataGrid.DataSource = MovieManager.getMovies(movieList.movies); newListButton.Hide(); } public override void processData(FormData data) { if(data.data_type.Equals("NEWLIST")) { object[] objs = new object[1]; data.data.CopyTo(objs); string listName = (string)objs[0]; //if() } } private void newListButton_Click(object sender, EventArgs e) { ModifyListNameForm form = new ModifyListNameForm(ApplicationManager.loggedIn.username); form.ShowDialog(); } private void selectCell(object sender, DataGridViewCellEventArgs e) { if(e.RowIndex > -1) { if (editable) { attemptSwap(e.RowIndex); } else { if (listTitleLabel.Text.Equals("My Lists")) { List<MovieList> lists = (List<MovieList>)listDataGrid.DataSource; MovieList list = lists[e.RowIndex]; ApplicationManager.changeForm("LISTS", list); } else { Movie movie = ((List<Movie>)listDataGrid.DataSource)[e.RowIndex]; ApplicationManager.changeForm("MOVIE", movie); } } } } private void attemptSwap(int index) { if (selected1 == -1) { selected1 = index; } else if(selected2 == -1) { selected2 = index; if (listTitleLabel.Text.Equals("My Lists")) { MovieList list1 = ((List<MovieList>)listDataGrid.DataSource)[selected1]; MovieList list2 = ((List<MovieList>)listDataGrid.DataSource)[selected2]; ((List<MovieList>)listDataGrid.DataSource)[selected1] = list2; ((List<MovieList>)listDataGrid.DataSource)[selected2] = list1; } else { Movie item1 = ((List<Movie>)listDataGrid.DataSource)[selected1]; Movie item2 = ((List<Movie>)listDataGrid.DataSource)[selected2]; ((List<Movie>)listDataGrid.DataSource)[selected1] = item2; ((List<Movie>)listDataGrid.DataSource)[selected2] = item1; } selected1 = -1; selected2 = -1; listDataGrid.ClearSelection(); listDataGrid.Refresh(); } } private void editNameButton_Click(object sender, EventArgs e) { editName(); } public void editName() { ModifyListNameForm form = new ModifyListNameForm(long.Parse(listIDLabel.Text)); form.ShowDialog(); } private void editContentsButton_Click(object sender, EventArgs e) { RemoveFromListsForm form; if(listTitleLabel.Text.Equals("My Lists")) { form = new RemoveFromListsForm(MovieListManager.getMovieLists(ApplicationManager.loggedIn.username)); } else { form = new RemoveFromListsForm(MovieListManager.getMovieList(long.Parse(listIDLabel.Text))); } form.ShowDialog(); } private void editOrderButton_Click(object sender, EventArgs e) { if(editable) { editable = false; editOrderButton.Text = "Edit Order"; reorderToolTip.Hide(); selected1 = -1; selected2 = -1; listDataGrid.ClearSelection(); if (listTitleLabel.Text.Equals("My Lists")) { List<MovieList> lists = (List<MovieList>)listDataGrid.DataSource; MovieListManager.updateListOrder(ApplicationManager.loggedIn, lists); } else { List<Movie> movies = (List<Movie>)listDataGrid.DataSource; MovieListManager.updateListOrder(long.Parse(listIDLabel.Text), movies); } } else { editable = true; editOrderButton.Text = "Save Order"; reorderToolTip.Show(); listDataGrid.ClearSelection(); } } } }
namespace BalkanAir.Tests.Common { using Data.Models; public static class Constants { // All tests public const int ENTITY_VALID_ID = 1; // Aircraft Manufacturers public const string MANUFACTURER_VALID_NAME = "Manufacturer Name Test"; // Aircrafts public const string AIRCRAFT_VALID_MODEL = "Aircraft Model Test"; public const int AIRCRAFT_TOTAL_SEATS = 1; // Airprots public const string AIRPROT_VALID_NAME = "Airport Name Test"; public const string AIRPORT_VALID_ABBREVIATION = "ABC"; // Categories public const string CATEGORY_VALID_NAME = "Category Test"; // Countries public const string COUNTRY_VALID_NAME = "Country Test"; public const string COUNTRY_VALID_ABBREVIATION = "CT"; // Fares public const int FARE_VALID_PRICE = 1; // Leg Instances public const string FLIGHT_VALID_STATUS = "Test"; public const string FLIGHT_VALID_NUMBER = "TEST12"; // Routes public const string ROUTE_VALID_ORIGIN_NAME = "Test Origin"; public const string ROUTE_VALID_ORIGIN_ABBREVIATION = "ABC"; public const string ROUTE_VALID_DESTINATION_NAME = "Test Destination"; public const string ROUTE_VALID_DESTINATION_ABBREVIATION = "DEF"; // Users public const Gender USER_VALID_GENDER = Gender.Male; public const string USER_VALID_NATIONALITY = "Test Nationality"; } }
using System.Collections.Generic; using System.Threading.Tasks; namespace Elsa.Services { public class EventPublisher : IEventPublisher { private readonly IServiceBusFactory _serviceBusFactory; public EventPublisher(IServiceBusFactory serviceBusFactory) { _serviceBusFactory = serviceBusFactory; } public async Task PublishAsync(object message, IDictionary<string, string>? headers = default) { var bus = await _serviceBusFactory.GetServiceBusAsync(message.GetType(), default); await bus.Publish(message, headers); } } }
using System; using Windows.UI; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Media; namespace UWPSwitchExpressionSample.Utilities { public class TrafficLightToBrushConverter : IValueConverter { private readonly Brush _redBrush = new SolidColorBrush(Colors.Red); private readonly Brush _yellowBrush = new SolidColorBrush(Colors.Yellow); private readonly Brush _greenBrush = new SolidColorBrush(Colors.Green); private readonly Brush _blackBrush = new SolidColorBrush(Colors.Black); public object Convert(object value, Type targetType, object parameter, string language) { if (value is LightState lightState) { return parameter switch { "Red" => lightState == LightState.Red ? _redBrush : _blackBrush, "Yellow" => lightState == LightState.Yellow ? _yellowBrush : _blackBrush, "Green" => lightState == LightState.Green ? _greenBrush : _blackBrush, _ => throw new ArgumentException($"{parameter} is an invalid value for {nameof(parameter)}") }; } return null; } public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new InvalidOperationException(); } }
using System; using System.IO; using System.Threading.Tasks; using StackExchange.Redis; using Xunit; namespace RGeoIP.Tests { public class GeoIPTests : IDisposable { private ConnectionMultiplexer _conn; private GeoIP _geoIP; public GeoIPTests() { _conn = ConnectionMultiplexer.Connect("localhost:6379, allowadmin=true"); _geoIP = new GeoIP(() => _conn.GetDatabase()); using (var reader = new StreamReader("GeoIPCountryWhois-small.csv")) { _geoIP.ImportGeoLiteLegacyAsync(reader).Wait(); } } [Fact] public async Task Should_have_imported_data() { var count = await _geoIP.CountAsync(); Assert.Equal(60, count); } [Fact] public async Task Should_be_able_to_lookup_IP_within_range() { var auAddresses = new[] { "1.0.0.24", "1.0.4.245", "1.4.0.222" }; foreach (var ip in auAddresses) { var au = await _geoIP.LookupAsync(ip); Assert.NotNull(au); Assert.Equal("AU", au.Code); Assert.Equal("Australia", au.Name); } var cnAddresses = new[] { "1.0.1.245", "1.1.2.245", "1.1.62.255" }; foreach (var ip in cnAddresses) { var cn = await _geoIP.LookupAsync(ip); Assert.NotNull(cn); Assert.Equal("CN", cn.Code); Assert.Equal("China", cn.Name); } } [Fact] public async Task Should_throw_exception_for_invalid_ip_address() { Exception thrown = null; try { await _geoIP.LookupAsync("255.255.255.256"); } catch (FormatException ex) { thrown = ex; } Assert.NotNull(thrown); } public void Dispose() { _conn.GetServer("localhost:6379").FlushDatabase(); } } }
namespace Hspi { /// <summary> /// Class for the main program. /// </summary> public static class Program { private static void Main(string[] args) { Logger.ConfigureLogging(false, false); logger.Info("Starting..."); try { using var plugin = new HSPI_Tasmota.HSPI(); plugin.Connect(args); } finally { logger.Info("Bye!!!"); } } private static readonly NLog.Logger logger = NLog.LogManager.GetCurrentClassLogger(); } }
namespace Swagger.ObjectModel { using System.Collections.Generic; using Swagger.ObjectModel.Attributes; /// <summary> /// Describes a single response from an API Operation. /// </summary> public class Response : SwaggerModel { /// <summary> /// A short description of the response. GFM syntax can be used for rich text representation. /// </summary> [SwaggerProperty("description", true)] public string Description { get; set; } /// <summary> /// A definition of the response structure. /// </summary> [SwaggerProperty("schema")] public Schema Schema { get; set; } /// <summary> /// A list of headers that are sent with the response. /// The name of the property corresponds to the name of the header. The value describes the type of the header. /// </summary> [SwaggerProperty("headers")] public IDictionary<string, Header> Headers { get; set; } /// <summary> /// An example of the response message. /// The name of the property MUST be one of the Operation produces values (either implicit or inherited). /// The value SHOULD be an example of what such a response would look like. /// </summary> [SwaggerProperty("examples")] public IDictionary<string, object> Examples { get; set; } } }
using Lime; using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace Tangerine.UI { public class CommandCategoryInfo { public string Id { get; } public string Title { get; } public Dictionary<string, CommandInfo> Commands { get; } = new Dictionary<string, CommandInfo>(); public CommandCategoryInfo(string id) { Id = id; Title = Regex.Replace(id, @"(\S)(\p{Lu}|\d)", "$1 $2"); } } public class CommandInfo { public ICommand Command { get; } public CommandCategoryInfo CategoryInfo { get; } public string Id { get; } public string Title { get; } public Shortcut Shortcut { get; set; } /// <summary> /// True if the command is not Tangerine built-in. /// </summary> public bool IsProjectSpecific { get; set; } = true; public CommandInfo(ICommand command, CommandCategoryInfo categoryInfo, string id) { Command = command; CategoryInfo = categoryInfo; Id = id; Title = string.IsNullOrEmpty(command.Text) ? Regex.Replace(id, @"(\S)(\p{Lu}|\d)", "$1 $2") : command.Text; } public override int GetHashCode() { return Id.GetHashCode(); } } public static class CommandRegistry { private static readonly Dictionary<string, CommandCategoryInfo> categories = new Dictionary<string, CommandCategoryInfo>(); public static readonly CommandCategoryInfo AllCommands = new CommandCategoryInfo("All"); /// <param name="isProjectSpecific">True if the command is not tangerine built-in.</param> public static void Register( ICommand command, string categoryId, string commandId, bool @override = false, bool isProjectSpecific = true ) { if (!categories.ContainsKey(categoryId)) { categories.Add(categoryId, new CommandCategoryInfo(categoryId)); } var categoryInfo = categories[categoryId]; var commandInfo = new CommandInfo(command, categoryInfo, commandId) { IsProjectSpecific = isProjectSpecific }; if (AllCommands.Commands.ContainsKey(commandId)) { if (!@override) { throw new ArgumentException($"Command with id:'{commandId}' has already been registered. " + $"Use @override=true to override previous command", nameof(commandId)); } if (categoryInfo.Commands.ContainsKey(commandId)) { categoryInfo.Commands[commandId] = commandInfo; } else { categoryInfo.Commands.Add(commandId, commandInfo); } AllCommands.Commands[commandId] = commandInfo; return; } categoryInfo.Commands.Add(commandId, commandInfo); AllCommands.Commands.Add(commandId, commandInfo); } public static bool TryGetCommandInfo( CommandCategoryInfo categoryInfo, string commandId, out CommandInfo commandInfo ) { return categoryInfo.Commands.TryGetValue(commandId, out commandInfo); } public static bool TryGetCommandInfo(string commandId, out CommandInfo commandInfo) { return TryGetCommandInfo(AllCommands, commandId, out commandInfo); } public static IEnumerable<CommandInfo> RegisteredCommandInfo(CommandCategoryInfo categoryInfo) { foreach (var commandInfo in categoryInfo.Commands.Values) { yield return commandInfo; } } public static IEnumerable<ICommand> RegisteredCommands() { foreach (var commandInfo in AllCommands.Commands.Values) { yield return commandInfo.Command; } } public static IEnumerable<CommandCategoryInfo> RegisteredCategories() { foreach (var categoryInfo in categories.Values) { yield return categoryInfo; } } } }
using System.Data; using System.Data.Common; using Microsoft.VisualStudio.TestTools.UnitTesting; using Pqsql; namespace PqsqlTests { [TestClass] public class PqsqlCommandBuilderTests { private static string connectionString = string.Empty; #region Additional test attributes [ClassInitialize] public static void ClassInitialize(TestContext context) { connectionString = context.Properties["connectionString"].ToString(); } [TestInitialize] public void TestInitialize() { } [TestCleanup] public void TestCleanup() { } #endregion [TestMethod] public void PqsqlCommandBuilderTest1() { PqsqlCommandBuilder builder = new PqsqlCommandBuilder(); Assert.AreEqual(builder.QuotePrefix, "\""); Assert.AreEqual(builder.QuoteSuffix, "\""); string qid = builder.QuoteIdentifier("a\"bc"); Assert.AreEqual("\"a\"\"bc\"", qid, "wrong QuoteIdentifier"); builder.QuotePrefix = null; builder.QuoteSuffix = null; qid = builder.QuoteIdentifier("a\"bc"); Assert.AreEqual("a\"bc", qid, "wrong QuoteIdentifier"); builder.QuotePrefix = "\""; builder.QuoteSuffix = "\""; string uqid = builder.UnquoteIdentifier("\"a\"\"bc\""); Assert.AreEqual(qid, uqid, "wrong UnquoteIdentifier"); } [TestMethod] public void PqsqlCommandBuilderTest2() { using (PqsqlConnection connection = new PqsqlConnection(connectionString)) using (PqsqlCommand command = connection.CreateCommand()) { PqsqlTransaction transaction = connection.BeginTransaction(); command.Transaction = transaction; command.CommandText = "create temp table temptab (c0 int4 primary key, c1 float8)"; command.CommandType = CommandType.Text; command.ExecuteNonQuery(); transaction.Commit(); // temp table must be visible in the next transaction transaction = connection.BeginTransaction(); PqsqlDataAdapter adapter = new PqsqlDataAdapter("select * from temptab", connection) { SelectCommand = { Transaction = transaction }, }; adapter.RowUpdated += Adapter_RowUpdated; PqsqlCommandBuilder builder = new PqsqlCommandBuilder(adapter); DataSet ds = new DataSet(); adapter.FillSchema(ds, SchemaType.Source); adapter.Fill(ds, "temptab"); DataTable temptab = ds.Tables["temptab"]; DataRow row = temptab.NewRow(); row["c0"] = 123; row["c1"] = 1.23; temptab.Rows.Add(row); adapter.Update(ds, "temptab"); command.CommandText = "select * from temptab"; command.CommandType = CommandType.Text; using (PqsqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Assert.AreEqual(123, reader.GetInt32(0)); Assert.AreEqual(1.23, reader.GetDouble(1)); } } transaction.Rollback(); } } private void Adapter_RowUpdated(object sender, RowUpdatedEventArgs e) { Assert.AreEqual(UpdateStatus.Continue, e.Status); } [TestMethod] public void PqsqlCommandBuilderTest3() { using (PqsqlConnection connection = new PqsqlConnection(connectionString)) using (PqsqlCommand command = connection.CreateCommand()) { PqsqlTransaction transaction = connection.BeginTransaction(); command.Transaction = transaction; command.CommandText = "create temp table temptab (c0 int4 primary key, c1 float8)"; command.CommandType = CommandType.Text; command.ExecuteNonQuery(); transaction.Commit(); // temp table must be visible in the next transaction transaction = connection.BeginTransaction(); PqsqlDataAdapter adapter = new PqsqlDataAdapter("select * from temptab", connection) { SelectCommand = { Transaction = transaction } }; PqsqlCommandBuilder builder = new PqsqlCommandBuilder(adapter); // INSERT INTO "postgres"."pg_temp_2"."temptab" ("c0", "c1") VALUES (:p1, :p2) PqsqlCommand inserter = builder.GetInsertCommand(); inserter.Parameters["p1"].Value = 1; inserter.Parameters["p2"].Value = 2.1; int inserted = inserter.ExecuteNonQuery(); Assert.AreEqual(1, inserted); // UPDATE "postgres"."pg_temp_2"."temptab" // SET "c0" = :p1, "c1" = :p2 // WHERE (("c0" = :p3) AND ((:p4 = 1 AND "c1" IS NULL) OR ("c1" = :p5))) PqsqlCommand updater = builder.GetUpdateCommand(); updater.Parameters["p1"].Value = 2; updater.Parameters["p2"].Value = 2.2; updater.Parameters["p3"].Value = 1; updater.Parameters["p4"].Value = 0; updater.Parameters["p5"].Value = 2.1; int updated = updater.ExecuteNonQuery(); Assert.AreEqual(1, updated); // DELETE FROM "postgres"."pg_temp_2"."temptab" // WHERE (("c0" = :p1) AND ((:p2 = 1 AND "c1" IS NULL) OR ("c1" = :p3))) PqsqlCommand deleter = builder.GetDeleteCommand(); deleter.Parameters["p1"].Value = 2; deleter.Parameters["p2"].Value = 0; deleter.Parameters["p3"].Value = 2.2; int deleted = deleter.ExecuteNonQuery(); Assert.AreEqual(1, deleted); transaction.Rollback(); } } [TestMethod] public void PqsqlCommandBuilderTest4() { using (PqsqlConnection connection = new PqsqlConnection(connectionString)) using (PqsqlCommand command = connection.CreateCommand()) { PqsqlTransaction transaction = connection.BeginTransaction(); command.Transaction = transaction; command.CommandText = "create temp table temptab (c0 int4 primary key, c1 float8, c2 timestamp);"; command.CommandType = CommandType.Text; command.ExecuteNonQuery(); transaction.Commit(); // temp table must be visible in the next transaction transaction = connection.BeginTransaction(); PqsqlDataAdapter adapter = new PqsqlDataAdapter("select * from temptab", connection) { SelectCommand = { Transaction = transaction }, }; adapter.RowUpdated += Adapter_RowUpdated; PqsqlCommandBuilder builder = new PqsqlCommandBuilder(adapter); DataTableMapping mapping = adapter.TableMappings.Add("Table", "temptab"); mapping.ColumnMappings.Add("c0", "id"); mapping.ColumnMappings.Add("c2", "time"); DataSet ds = new DataSet(); adapter.FillSchema(ds, SchemaType.Mapped); adapter.Fill(ds); DataTable tab = ds.Tables[0]; Assert.AreEqual("id", tab.Columns[0].ColumnName); Assert.AreEqual("c1", tab.Columns[1].ColumnName); Assert.AreEqual("time", tab.Columns[2].ColumnName); transaction.Rollback(); } } } }
// Copyright (c) Pixel Crushers. All rights reserved. using UnityEngine; namespace PixelCrushers.DialogueSystem { /// <summary> /// This abstract subclass of AbstractDialogueUI is used for dialogue UIs /// that use a UI Canvas. It allows the Dialogue System to identify that /// the dialogue UI requires a Canvas. /// </summary> public abstract class CanvasDialogueUI : AbstractDialogueUI { } }
using BuildVersioning.Entities; namespace BuildVersioningManager.Models.ProjectModels { public class PrepareToDeleteProjectModel { public Project Project { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace BeachTowelShop.Models.Products { public class GalleryProductViewModel { public GalleryProductViewModel() { PictureList = new List<string>(); } public string Id { get; set; } public string Name { get; set; } public List<string> PictureList { get; set; } public double LowestPrice { get; set; } public double HighPrice { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Drawing; namespace CertiPath.BlockchainGateway.Service.Helper.Chart { internal static class ColorHelper { private static List<string> chartColors = new List<string>() { "119, 81, 246", "241, 26, 100", "142, 36, 170", "30, 136, 229", "0, 149, 152", "251, 140, 0", "146, 254, 157", "255, 133, 88", "0, 137, 123", "30, 136, 229", "255, 141, 96", "56, 184, 242", "255, 80, 99", "94, 53, 177", "124, 179, 66" }; internal static string GetNextColor(int index) { if (index >= chartColors.Count) { index = index % chartColors.Count; } return chartColors[index]; } internal static string GetNextColor(int index, bool lHex) { string colorStr = GetNextColor(index); string[] colorArr = colorStr.Split(','); Color myColor = Color.FromArgb( Convert.ToInt32(colorArr[0].Trim()), Convert.ToInt32(colorArr[1].Trim()), Convert.ToInt32(colorArr[2].Trim())); string color = colorArr[0].Trim().PadLeft(3, '0'); color += colorArr[1].Trim().PadLeft(3, '0'); color += colorArr[2].Trim().PadLeft(3, '0'); return String.Format("#{0:X6}", myColor.ToArgb() & 0x00FFFFFF); } internal static string GetNextColorRgba(int index, string opacity) { string color = GetNextColor(index); return String.Format("rgba({0}, {1})", color, opacity); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Text; using Orleans; namespace Orleans.StorageProvider.RavenDB.TestInterfaces { /// <summary> /// Orleans grain communication interface IPerson /// </summary> public interface IPerson : IGrain { Task SetPersonalAttributes(PersonalAttributes person); Task<string> FirstName { get; } Task<string> LastName { get; } Task<int> Age { get; } Task<GenderType> Gender { get; } } public enum GenderType { Male, Female } [Serializable] public class PersonalAttributes { public string FirstName { get; set; } public string LastName { get; set; } public int Age { get; set; } public GenderType Gender { get; set; } } }
namespace _08.RecursiveFibonacci { using System; public class RecursiveFibonacci { private static long[] fibonacciArray; public static void Main(string[] args) { fibonacciArray = new long[50]; fibonacciArray[0] = 1; fibonacciArray[1] = 1; var n = long.Parse(Console.ReadLine()); var result = GetFibonacci(n); Console.WriteLine(result); } public static long GetFibonacci(long n) { if (n <= 2) { return 1; } if (fibonacciArray[n - 1] != 0) { return fibonacciArray[n - 1]; } fibonacciArray[n - 1] = GetFibonacci(n - 1) + GetFibonacci(n - 2); return fibonacciArray[n - 1]; } } }
namespace LinkedList.Core { /// <summary> /// Defines the <see cref="INode{T}" />. /// Common interface for Node that is used in LinkedList. /// </summary> /// <typeparam name="T">.</typeparam> public interface INode<T> { /// <summary> /// Gets or sets the Value. /// </summary> T Value { get; set; } } }
using System; using System.Text; using System.Collections.Generic; using System.Reflection; using System.Linq; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Tests.Unit.Core.Extensions { [TestClass] public class MemberInfoExtensionsTest { protected class PracticeAttribute : Attribute { } protected class TestClass { [Practice] public string Name { get; set; } public string NotFound { get; set; } } [TestMethod] public void GettingCustomAttributeForAMemberDoesntFindOne() { var obj = new TestClass(); var attrib = obj.GetType().GetProperty("NotFound").GetCustomAttribute<PracticeAttribute>(false); Assert.IsNull(attrib); } [TestMethod] public void GettingCustomAttributeForAMemberWorksOK() { var obj = new TestClass(); var attrib = obj.GetType().GetProperty("Name").GetCustomAttribute<PracticeAttribute>(false); Assert.IsNotNull(attrib); } [TestMethod] public void GettingCustomAttributesForAMemberDoesntFindOne() { var obj = new TestClass(); var attrib = obj.GetType().GetProperty("NotFound").GetCustomAttributes<PracticeAttribute>(false); Assert.AreEqual(0, attrib.Length); } [TestMethod] public void GettingCustomAttributesForAMemberWorksOK() { var obj = new TestClass(); var attrib = obj.GetType().GetProperty("Name").GetCustomAttributes<PracticeAttribute>(false); Assert.IsNotNull(attrib); Assert.AreEqual(1, attrib.Length); } } }
namespace Santase.Logic.WinnerLogic { public interface IRoundWinnerPointsLogic { RoundWinnerPoints GetWinnerPoints( int firstPlayerPoints, int secondPlayerPoints, PlayerPosition gameClosedBy, PlayerPosition noTricksPlayer, IGameRules gameRules); } }
using System.Threading.Tasks; namespace ServiceBus.Distributed.Events { public interface IEventBus { Task PublishAsync<TEvent>(TEvent @event) where TEvent : IEvent; } }
using System.ComponentModel.DataAnnotations; namespace Basset.Data { public class FeatureWeights { public ulong Id { get; set; } public ulong GuildId { get; set; } public bool? Mode { get; set; } [Range(-1, 11)] public int? Key { get; set; } [Range(1, int.MaxValue)] public int? TimeSignature { get; set; } [Range(0.1, 1.0)] public float? Danceability { get; set; } [Range(0.1, 1.0)] public float? Energy { get; set; } [Range(-60, 0)] public float? Loudness { get; set; } [Range(0.1, 1.0)] public float? Speechiness { get; set; } [Range(0.1, 1.0)] public float? Acousticness { get; set; } [Range(0.1, 1.0)] public float? Instrumentalness { get; set; } [Range(0.1, 1.0)] public float? Liveness { get; set; } [Range(0.1, 1.0)] public float? Valence { get; set; } [Range(0, 250)] public float? Tempo { get; set; } public Guild Guild { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Problem01 { class GSMTest { //Field private GSM[] arr; //Constr public GSMTest(GSM[] arr) { this.Arr = arr; } // public GSM[] Arr { get {return this.arr; } set {arr = value; } } public override string ToString() { StringBuilder finalResult = new StringBuilder(); foreach (GSM item in this.arr) { finalResult.Append(item.ToString()); } finalResult.Append(GSM.Iphone4); return finalResult.ToString(); } //public GSMTest(params GSM[] arr) //{ // this.arr = arr; //} //public GSM[] Arr //{ // get { return this.arr; } //} //public override string ToString() //{ // StringBuilder finalResult = new StringBuilder(); // foreach (GSM item in this.Arr) // { // finalResult.Append(item.ToString()); // } // finalResult.Append(GSM.Iphone4); // return finalResult.ToString(); //} } }
using System; namespace AMV.CQRS { [AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] public class TransactedCommandAttribute : Attribute { // marker attribute for commands to be wrapped into a transaction // to be applied on ICommand objects } }
using Couchbase; using Couchbase.Authentication; using Couchbase.Configuration.Client; using Couchbase.Core; using Storage.Couchbase; using System; using System.Threading.Tasks; namespace Orleans.Persistence.Couchbase { //Bucket Instance needs to be a singleton to prevent connection inefficiency in Couchbase public class CbBucket { private IBucket _bucket; private static readonly Lazy<CbBucket> _lazy = new Lazy<CbBucket>(() => new CbBucket()); private static CouchbaseGrainStorageOptions _config; private CbBucket() { } public static CbBucket GetInstance(CouchbaseGrainStorageOptions config) { _config = config; return _lazy.Value; } public IBucket Bucket { get { try { if (_bucket == null) InitConnection().Wait(); } catch(Exception ex) { throw ex; } return _bucket; } } private async Task InitConnection() { //Initialize bucket if it doesn't exist ClusterHelper.Initialize(new ClientConfiguration { Servers = _config.Uris }, new PasswordAuthenticator(_config.UserName, _config.Password)); //Connects to bucket _bucket = await ClusterHelper.GetBucketAsync(_config.BucketName); } } }