text
stringlengths
13
6.01M
using cyrka.api.common.identities; namespace cyrka.api.domain.projects { public class ProjectState { public CompositeSerialId ProjectId { get; set; } public ProjectStatus Status { get; set; } = ProjectStatus.Draft; public ProductState Product { get; set; } public JobState[] Jobs { get; set; } = { }; public PaymentsState Payments { get; set; } public IncomeStatement Money { get; set; } } }
using System.Collections.Generic; using SafeLightning.CommandParsing.Commands; using StardewModdingAPI; namespace SafeLightning.CommandParsing { /// <summary> /// Registers and parses command line arguments. /// </summary> internal class CommandParser { private readonly IList<ICommand> commands; private readonly IDictionary<string, string> descriptions = new Dictionary<string, string>(); private readonly IMonitor monitor; public CommandParser(SafeLightningMod mod) { this.monitor = mod.Monitor; //Get available commands this.commands = new List<ICommand> { new PrintLocationCommand(), new SetLightningCommand(), new GrowTreesCommand(), new RemoveFeaturesCommand() }; //Register both a long and short command, hiding dangerous commands foreach (string s in new List<string> {"safe_lightning", "sl"}) { string helpString = "Safe lightning related debug commands.\n\nUsage:\n"; foreach (ICommand command in this.commands) { if (command.Dangerous) continue; helpString += $" {s} {command.Description} \n"; } this.descriptions.Add(s, helpString); mod.Helper.ConsoleCommands.Add(s, helpString, this.ParseCommand); } } /// <summary> /// Parses the given command. /// </summary> /// <param name="commandName">Name used to call this method</param> /// <param name="args">Command arguments</param> private void ParseCommand(string commandName, string[] args) { if (args.Length == 0) { this.monitor.Log(this.descriptions[commandName], LogLevel.Info); } else if (!Context.IsWorldReady) { this.monitor.Log("Commands require a save to be loaded.", LogLevel.Error); } else { foreach (ICommand command in this.commands) if (command.Handles(args[0])) { //If the command is dangerous, only show how to use it if user guessed name exactly right. if (command.Dangerous) { if (args.Length > 2 || args.Length == 1 || args.Length == 2 && args[1] != "--force") this.PrintInvalidUsageError(commandName, $"Unrecognized command '{args[0]}'."); else this.monitor.Log(command.Parse(args), LogLevel.Info); return; } if (args.Length != 1) this.PrintInvalidUsageError(commandName, $"Too many arguments for command '{args[0]}'."); else this.monitor.Log(command.Parse(args), LogLevel.Info); return; } this.PrintInvalidUsageError(commandName, $"Unrecognized command '{args[0]}'."); } } private void PrintInvalidUsageError(string commandName, string type, bool append = true) { string toAppend = $"See help {commandName} for more info."; string[] split = type.Split('\n'); if (split.Length == 1) { this.monitor.Log($"{type} {(append ? toAppend : "")}", LogLevel.Error); } else { foreach (string s in split) this.monitor.Log($"{s}", LogLevel.Error); if (append) this.monitor.Log(toAppend, LogLevel.Error); } } } }
#region Using directives using System; using System.Collections; using System.Data; using UFSoft.UBF.UI.MD.Runtime; using UFSoft.UBF.UI.MD.Runtime.Implement; #endregion namespace FollowServiceUIModel { public partial class FollowServiceUIModelModel { //初始化UIMODEL之后的方法 public override void AfterInitModel() { //this.Views[0].Fields[0].DefaultValue = thsi.co this.FollowService.FieldBusinessDate.DefaultValue = UFIDA.U9.UI.PDHelper.PDContext.Current.LoginDate; this.FollowService.PropertySHIP_Type.DefaultValue = "SM6010"; this.FollowService.PropertySHIP_Type.Value = "SM6010"; } //UIModel提交保存之前的校验操作. public override void OnValidate() { base.OnValidate() ; OnValidate_DefualtImpl(); //your coustom code ... } } }
using System; using System.Collections.Generic; namespace CollaborativeFiltering { public class PearsonCorrelation : MemoryBasedAlgorithm { public PearsonCorrelation(IEnumerable<IRating> ratings) : base(ratings) {} internal override decimal Weight(IRater baseRater, IRater neighbour) { var helper = GetRatingService(); var baseUsersMean = RatersMeanVote(baseRater); var neighbourMean = RatersMeanVote(neighbour); var numerator = 0M; var denominatorSumBase = 0M; var denominatorSumNeigh = 0M; foreach (var pair in helper.GetCommonRatings(baseRater, neighbour)) { var ratingBase = (decimal) pair.FirstRating.Value; var ratingNeigh = (decimal) pair.SecondRating.Value; var diffBase = ratingBase - baseUsersMean; var diffNeigh = ratingNeigh - neighbourMean; numerator += diffBase*diffNeigh; denominatorSumBase += diffBase*diffBase; denominatorSumNeigh += diffNeigh*diffNeigh; }; var tmp = (double)(denominatorSumBase*denominatorSumNeigh); var denominator = (decimal)Math.Sqrt(tmp); if (denominator == 0) return 0; var result = numerator / denominator; return result; } protected virtual IRatingService GetRatingService() { return new RatingService(); } public override string ToString() { return "Pearson Correlation"; } } }
namespace _02._BasicStackOperations { using System; using System.Collections.Generic; using System.Linq; public class Startup { public static void Main() { int[] inputParts = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int numbersToPop = inputParts[1]; int searchedNumber = inputParts[2]; int[] numbers = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); Stack<int> stack = new Stack<int>(numbers); for (int i = 0; i < numbersToPop; i++) { stack.Pop(); } if (stack.Contains(searchedNumber)) { Console.WriteLine("true"); } else { if (stack.Count != 0) { Console.WriteLine(stack.Min()); } else { Console.WriteLine(0); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Environment : MonoBehaviour { public bool settingAdventurersRoom; public bool settingHeart; public bool addingMonster; public int monsterNum; public bool gameOver; public int day; public int baseAdventurersToInvoke; public int adventurersToInvoke; public int adventurersNumber; public int startingH; public int startingW; public int heartH; public int heartW; public int baseAttack; public int baseHP; public int priceHP; public int priceAttack; public int gold; void Start() { baseAdventurersToInvoke = 5; day = 1; baseAttack = 10; baseHP = 100; priceHP = 1; priceAttack = 5; } void Update() { if (gameOver) { StartCoroutine (GameOver ()); } } public void newDay() { adventurersNumber = 0; adventurersToInvoke = baseAdventurersToInvoke; } IEnumerator GameOver() { GameObject.Find ("TextOverlay").GetComponent<Canvas> ().enabled = true; GameObject.Find ("TextOverlay").GetComponent<TextOverlay> ().SetTextOverlay (); GameObject.Find ("CanvasDay").GetComponent<GameSpeed> ().SetGameSpeed(1); GameObject.Find ("CanvasDay").GetComponent<Canvas> ().enabled = false; yield return new WaitForSeconds (4); SceneManager.LoadScene ("StartScene"); } }
using UnityEngine; using System.Collections; public class CharacterController : MonoBehaviour { public float speed; public float gravity; public float maxVelocityChange; public float jumpHeight; public float airControl; [SerializeField] private bool grounded; private bool isCrouching; [SerializeField] private bool isJumping; private bool isInAir; private Vector3 targetVelocity; private float turnSpeed; private float slopeLimit; private int jumpTime; private int timeOnGround; private Vector3 velocity; private Vector3 velocityChange; private Rigidbody rBody; private Animator animator; void Awake () { rBody = GetComponent<Rigidbody> (); animator = GetComponent<Animator> (); rBody.freezeRotation = true; rBody.useGravity = false; } void Start() { speed = 5.0f; gravity = 10.0f; maxVelocityChange = 10.0f; jumpHeight = 0.5f; airControl = 3.0f; turnSpeed = 50.0f; slopeLimit = 50.0f; timeOnGround = 1; grounded = false; isCrouching = false; isJumping = false; } void Update() { Crouch(); } void FixedUpdate () { MovePlayer (); Jump (); } private void MovePlayer() { if (grounded) { isJumping = true; animator.SetBool("onGround", true); targetVelocity = new Vector3 (Input.GetAxis ("Horizontal"), 0, Input.GetAxis ("Vertical")).normalized; targetVelocity *= speed; targetVelocity = Camera.main.transform.TransformDirection(targetVelocity); velocity = rBody.velocity; velocityChange = (targetVelocity - velocity); velocityChange.x = Mathf.Clamp (velocityChange.x, -maxVelocityChange, maxVelocityChange); velocityChange.z = Mathf.Clamp (velocityChange.z, -maxVelocityChange, maxVelocityChange); velocityChange.y = 0; Rotate(targetVelocity.x, targetVelocity.z); rBody.AddForce(velocityChange, ForceMode.VelocityChange); if(targetVelocity != Vector3.zero) { animator.SetFloat("speed", 5.0f); } else { animator.SetFloat("speed", 0.0f); } } else { float h = Input.GetAxis("Horizontal"); float v = Input.GetAxis("Vertical"); if(h != 0 || v != 0) { targetVelocity = new Vector3(h, 0.0f, v); targetVelocity = Camera.main.transform.TransformDirection (targetVelocity); Quaternion targetRotation = Quaternion.LookRotation(targetVelocity); Quaternion newRotation = Quaternion.Lerp(rBody.rotation, targetRotation, turnSpeed * Time.deltaTime); rBody.MoveRotation(newRotation); rBody.AddForce(new Vector3 (h, 0.0f, v)); } animator.SetFloat("speed", 0.0f); } } private void Crouch() { if(Input.GetButton("Crouch") && grounded) { isCrouching = true; animator.SetBool ("Crouching", true); } if(Input.GetButtonUp("Crouch") && grounded) { isCrouching = false; animator.SetBool ("Crouching", false); } } private void Rotate(float horizontal, float vertical) { if(targetVelocity != Vector3.zero) { targetVelocity = new Vector3(horizontal, 0.0f, vertical); Quaternion targetRotation = Quaternion.LookRotation(targetVelocity); Quaternion newRotation = Quaternion.Lerp(rBody.rotation, targetRotation, turnSpeed * Time.deltaTime); rBody.MoveRotation(newRotation); } } private void Jump() { if (Input.GetButtonDown("Jump") && isJumping) { animator.SetBool("onGround", false); rBody.velocity = new Vector3 (0, CalculateJumpVerticalSpeed (), 0); isJumping = false; } else { rBody.AddForce(new Vector3 (0, -gravity * rBody.mass, 0)); } } void OnCollisionStay(Collision collision) { foreach(ContactPoint contact in collision.contacts) { if(Vector3.Angle(contact.normal, Vector3.up) < slopeLimit) { grounded = true; } } } void OnCollisionExit() { grounded = false; } private float CalculateJumpVerticalSpeed () { return Mathf.Sqrt(2 * jumpHeight * gravity); } }
using ListCoreApp.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ListCoreApp.Responses.ItemList { public class SuccessfulGetListResponse { public string Name { get; set; } public string AccessCode { get; set; } public bool IsPublic { get; set; } public bool IsStarred { get; set; } public IEnumerable<Object> Items { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CheckIt.Tests.Data { public class Class1 { } }
using SharpEngine.Editor.View; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static SharpEngine.Editor.View.EditorViewportView; namespace SharpEngine.Editor.ViewModel { public class EditorViewportViewModel : DockWindowViewModel { public string Text { get; set; } = "Test"; private EditorViewportView _view; public EditorViewportView View { get { return _view; } set { _view = value; _view.HWNDInitialised += ReadyToInitOgre; } } public EditorViewportViewModel() : base(false) { } public void ReadyToInitOgre(object sender, WindowEventArgs args) { GameWPF.Singleton.ExternalWindowHandle = args.WinPtr; if (GameWPF.Singleton.getRoot() == null) { GameWPF.Singleton.initApp(); } } } }
using FluentValidation; using CPClient.Domain.Entities; using System; using System.Collections.Generic; using System.Text; namespace CPClient.Service.Interfaces { public interface IClienteService : IService<Cliente> { } }
using System.Collections.Generic; namespace BestMeetingSpot.Model { public class Distance { public string text { get; set; } public int value { get; set; } } public class Duration { public string text { get; set; } public int value { get; set; } } public class Element { public Distance distance { get; set; } public Duration duration { get; set; } public string status { get; set; } } public class Row { public List<Element> elements { get; set; } } public class DistanceApiResults { public List<string> destination_addresses { get; set; } public List<string> origin_addresses { get; set; } public List<Row> rows { get; set; } public string status { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApplication1.Models { public class DsTraLoi { public List<Test> listdata; } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ProjManagerOWIN.Models { public class Create { [Required(ErrorMessage = "This is a required field")] [DisplayName("Project name")] public string ProjectName { get; set; } [Required(ErrorMessage = "This is a required field")] [DisplayName("Project reference")] public string ProjectRef { get; set; } [DisplayName("Project tags")] public string Tags { get; set; } [Required(ErrorMessage = "This is a required field")] [DisplayName("Project description")] public string ProjectDescription { get; set; } } }
using UnityEngine; using System.Collections; public class LevelManager : MonoBehaviour { /* * Since this minigame was first written in using a two year old version of the Unity C# API, some of the physics * implementation does not function as we had hoped. Due to time restraints we opted to make quick fixes regarding * some deprecated functions, switching them out for what Unity had suggested. The result of this is that the ball * bounces in an awkward way. */ public GameObject endGameCanvas; public void LoadLevel(string name){ Debug.Log ("New Level load: " + name); Brick.breakableCount = 0; Application.LoadLevel (name); } public void QuitRequest(){ Debug.Log ("Quit requested"); Application.Quit (); } public void LoadNextLevel() { Brick.breakableCount = 0; Application.LoadLevel(Application.loadedLevel + 1); } public void BrickDestoyed() { if (Brick.breakableCount <= 0) { LoadNextLevel(); } } public void endGameScreen(){ endGameCanvas.SetActive (true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Threading.Tasks; namespace MiNETDevTools.UI.Util { public static class Native { [DllImport("user32.dll")] internal static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags); ///The SetWindowLongPtr function changes an attribute of the specified window [DllImport("user32.dll", EntryPoint = "SetWindowLong")] internal static extern int SetWindowLong32 (HandleRef hWnd, int nIndex, int dwNewLong); [DllImport("user32.dll", EntryPoint = "SetWindowLong")] internal static extern int SetWindowLong32 (IntPtr windowHandle, int nIndex, int dwNewLong); [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] internal static extern IntPtr SetWindowLongPtr64 (IntPtr windowHandle, int nIndex, IntPtr dwNewLong); [DllImport("user32.dll", EntryPoint = "SetWindowLongPtr")] internal static extern IntPtr SetWindowLongPtr64 (HandleRef hWnd, int nIndex, IntPtr dwNewLong); // Get a handle to an application window. [DllImport("user32.dll", SetLastError = true)] internal static extern IntPtr FindWindow(string lpClassName, string lpWindowName); // Find window by Caption only. Note you must pass IntPtr.Zero as the first parameter. [DllImport("user32.dll", EntryPoint = "FindWindow", SetLastError = true)] internal static extern IntPtr FindWindowByCaption(IntPtr ZeroOnly, string lpWindowName); public static int SetWindowLong(IntPtr windowHandle, int nIndex, int dwNewLong) { if (IntPtr.Size == 8) //Check if this window is 64bit { return (int)SetWindowLongPtr64(windowHandle, nIndex, new IntPtr(dwNewLong)); } return SetWindowLong32(windowHandle, nIndex, dwNewLong); } public static IntPtr Find(string moduleName, string mainWindowTitle) { //Search the window using Module and Title IntPtr WndToFind = FindWindow(moduleName, mainWindowTitle); if (WndToFind.Equals(IntPtr.Zero)) { if (!string.IsNullOrEmpty(mainWindowTitle)) { //Search window using TItle only. WndToFind = FindWindowByCaption(WndToFind, mainWindowTitle); if (WndToFind.Equals(IntPtr.Zero)) return new IntPtr(0); } } return WndToFind; } public const int GWL_EXSTYLE = -20; //Sets a new extended window style public const int GWL_HINSTANCE = -6; //Sets a new application instance handle. public const int GWL_HWNDPARENT = -8; //Set window handle as parent public const int GWL_ID = -12; //Sets a new identifier of the window. public const int GWL_STYLE = -16; // Set new window style public const int GWL_USERDATA = -21; //Sets the user data associated with the window. //This data is intended for use by the application //that created the window. Its value is initially zero. public const int GWL_WNDPROC = -4; //Sets a new address for the window procedure. } [Flags] internal enum PositioningFlags { SWP_ASYNCWINDOWPOS = 0x4000, SWP_DEFERERASE = 0x2000, SWP_DRAWFRAME = 0x20, SWP_FRAMECHANGED = 0x20, SWP_HIDEWINDOW = 0x80, SWP_NOACTIVATE = 0x10, SWP_NOCOPYBITS = 0x100, SWP_NOMOVE = 2, SWP_NOOWNERZORDER = 0x200, SWP_NOREDRAW = 8, SWP_NOREPOSITION = 0x200, SWP_NOSENDCHANGING = 0x400, SWP_NOSIZE = 1, SWP_NOZORDER = 4, SWP_SHOWWINDOW = 0x40 } }
using System; using System.Collections.Generic; using System.Text; namespace FightingArena { public class Gladiator { public Gladiator(string name, Stat stat, Weapon weapon ) { this.Name = name; this.Stat = stat; this.Weapon = weapon; } public string Name { get; set; } public Stat Stat { get; set; } public Weapon Weapon { get; set; } public int GetTotalPower() { int weaponPower = this.GetWeaponPower(); int statPower = this.GetStatPower(); int totalPower = weaponPower + statPower; return totalPower; } public int GetWeaponPower() { int sharpness = this.Weapon.Sharpness; int size = this.Weapon.Size; int solidity = this.Weapon.Solidity; int sumOfWeaponPower = sharpness + size + solidity; return sumOfWeaponPower; } public int GetStatPower() { int strength = this.Stat.Strength; int flexibility = this.Stat.Flexibility; int agility = this.Stat.Agility; int skills = this.Stat.Skills; int intelligence = this.Stat.Intelligence; int sumOfStatPower = strength + flexibility + agility + skills + intelligence; return sumOfStatPower; } public override string ToString() { StringBuilder sb = new StringBuilder(); sb.AppendLine($"{this.Name} - {this.GetTotalPower()}"); sb.AppendLine($" Weapon Power: {this.GetWeaponPower()}"); sb.AppendLine($" Stat Power: {this.GetStatPower()}"); string result = sb.ToString().TrimEnd(); return result; } } }
using System.Collections; using System.Collections.Generic; using BP12.Collections; using BP12.Events; using DChild.Gameplay.Combat; using DChild.Gameplay.Objects; using DChild.Gameplay.Systems.Subroutine; using UnityEngine; namespace DChild.Gameplay.Environment.Obstacles { public class Acid : Obstacle { [SerializeField] private AttackDamage m_damage; public enum Form { falls, pond, }; [SerializeField] private Form acidForm; [SerializeField] private CountdownTimer m_DamageIntervalTimer; private IDamageable m_player; private IVisualTime m_visualTime; private ICombatRoutine m_combatRoutine; protected override AttackInfo attackInfo => new AttackInfo(m_damage, 0, null, null); protected override DamageFXType damageFXType => DamageFXType.None; private void OnTriggerStay2D(Collider2D collision) { var hitbox = collision.GetComponent<Hitbox>(); if (hitbox != null && collision.GetComponentInParent<Player.Player>() != null) { if (acidForm == Form.falls) { damagePlayer(hitbox); } else if (acidForm == Form.pond) { if (m_DamageIntervalTimer.hasEnded) { damagePlayer(hitbox); m_DamageIntervalTimer.Reset(); } } } } private void damagePlayer(Hitbox hitbox) { m_player = hitbox.damageable; m_combatRoutine.ApplyDamage(m_player, damageFXType, m_damage); } private void Update() { var tick = Time.deltaTime; m_DamageIntervalTimer.Tick(tick); } private void Start() { m_combatRoutine = GameplaySystem.GetRoutine<ICombatRoutine>(); if (acidForm == Form.pond) { m_visualTime = GetComponent<IVisualTime>(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Microsoft.Master2.excel { class StatisticUtil { public int classRevisits = 0; public int classVisits = 0; public int methodRevisits = 0; public int methodVisits = 0; public int classInthePastModelRevisits = 0; // public int classInthePastModelVisits = 0; public int methodInthePastModelRevisits = 0; //public int methodInthePastModelVisits = 0; public int methodInProActiveModelVisits = 0; public int classInProActiveModelVisits = 0; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GamePrepareInit : MonoBehaviour { // Use this for initialization void Start () { TeamPlayerManager.Instance().PrepareSyncTeamInfo(TeamData.Instance().proTeamRoleData); TeamData.Instance().Reset(); } // Update is called once per frame void Update () { } }
using System; using JCI.ITC.Nuget.Logging; using JCI.ITC.Nuget.TopShelf; using Serilog; namespace Ajf.NugetWatcher { internal class Program { private static void Main(string[] args) { Log.Logger = StandardLoggerConfigurator .GetLoggerConfig().MinimumLevel .Debug() .CreateLogger(); Log.Logger.Information("Starting Service with args: " + string.Join("|",args)); using (var container = ServiceIoC.Initialize()) { Log.Logger.Debug("WhatDoIHave" + "\n" + container.WhatDoIHave()); Log.Logger.Information("Container created."); using (var wrapper = new TopshelfWrapper<WorkerDirWatcher>( () =>{}, s => { s.ConstructUsing(name => { try { var instance = container.GetInstance<WorkerDirWatcher>(); Log.Logger.Debug("I have instance of WorkerDirWatcher!"); return instance; } catch (Exception e) { Console.WriteLine(e); throw; } }); })) { try { wrapper.Run(); } catch (Exception e) { Console.WriteLine(e); throw; } } } } } }
// <copyright file="ChangePassword.cs" company="Caspian Pacific Tech"> // Copyright (c) Caspian Pacific Tech. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace SmartLibrary.Models { using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; /// <summary> /// Change Password Model /// </summary> /// <CreatedBy>Tirthak Shah</CreatedBy> /// <CreatedDate>14-Aug-2018</CreatedDate> /// <ModifiedBy></ModifiedBy> /// <ModifiedDate></ModifiedDate> /// <ReviewBy></ReviewBy> /// <ReviewDate></ReviewDate> public class ChangePassword { /// <summary> /// Gets or sets Id /// </summary> public int Id { get; set; } /// <summary> /// Gets or sets Current Password /// </summary> [Required(ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "RequiredFieldMessage")] [StringLength(125, MinimumLength = 6, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "PasswordLengthMessageMinMax")] [DataType(DataType.Password)] [Display(Name = "CurrentPassword", ResourceType = typeof(Resources.Account))] [RegularExpression(SmartLibrary.Models.RegularExpressions.HtmlTag, ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "InvalidCurrentPassword")] public string CurrentPassword { get; set; } /// <summary> /// Gets or sets Current Password /// </summary> [NotMapped] public string EncryptedCurrentPassword { get; set; } /// <summary> /// Gets or sets Password /// </summary> [Required(ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "RequiredFieldMessage")] [StringLength(125, MinimumLength = 6, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "PasswordLengthMessageMinMax")] [DataType(DataType.Password)] [Display(Name = "NewPassword", ResourceType = typeof(Resources.Account))] [RegularExpression(SmartLibrary.Models.RegularExpressions.HtmlTag, ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "InvalidNewPassword")] public string NewPassword { get; set; } /// <summary> /// Gets or sets Current Password /// </summary> [NotMapped] public string EncryptedNewPassword { get; set; } /// <summary> /// Gets or sets Password /// </summary> [Required(ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "RequiredFieldMessage")] [StringLength(125, MinimumLength = 6, ErrorMessageResourceType = typeof(Resources.Messages), ErrorMessageResourceName = "PasswordLengthMessageMinMax")] [DataType(DataType.Password)] [Display(Name = "ConfirmPassword", ResourceType = typeof(Resources.Account))] [Compare("NewPassword", ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "NewPasswordAndConfirmPasswordNotMatch")] [RegularExpression(SmartLibrary.Models.RegularExpressions.HtmlTag, ErrorMessageResourceType = typeof(Resources.Account), ErrorMessageResourceName = "InvalidConfirmPassword")] public string ConfirmPassword { get; set; } /// <summary> /// Gets or sets Current Password /// </summary> [NotMapped] public string EncryptedConfirmPassword { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hoofdstuk_7_Facade { class Program { static void Main(string[] args) { Amplifier amp = new Amplifier(); DvdPlayer dvd = new DvdPlayer(); PopcornPopper pop = new PopcornPopper(); Projector projector = new Projector(); Screen screen = new Screen(); TheaterLights lights = new TheaterLights(); HomeTheaterFacade theater = new HomeTheaterFacade(amp, dvd, projector, screen, lights, pop); theater.WatchMovie("Frozen"); theater.EndMovie(); Console.ReadLine(); } } }
using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { Transform _main_Camera; //每半个周期的帧数 private int _once_Frames; //每帧移动的距离 private float _once_Distance; //帧数计数器 int _times; /// <summary> /// 相机震动开关 /// </summary> static bool _is_Shake_Camera; /// <summary> /// 相机震动开关 /// </summary> public static bool Is_Shake_Camera { set { _wait_Bool = true; _is_Shake_Camera = value; } } static bool _wait_Bool; // Use this for initialization void Start () { _wait_Bool = false; _times = 0; _main_Camera = this.transform; _is_Shake_Camera = false; _once_Frames = 2; _once_Distance = 0.1f; } // Update is called once per frame void Update () { //if (_wait_Bool) //{ // StartCoroutine(Wait()); // _wait_Bool = false; //} if (_is_Shake_Camera) { Move( 0, _once_Distance, 0, _main_Camera, _once_Frames,ref _times, ref _is_Shake_Camera); } } IEnumerator Wait() { MyKeys.Pause_Game = true; yield return new WaitForSeconds(0.05f); MyKeys.Pause_Game = false; } void Move(float x,float y,float z, Transform camera,int frames,ref int times,ref bool is_Shake) { if (times < frames) { times++; camera.Translate(-x, -y, -z); } else if (times >= frames && times < 3 * frames) { times++; camera.Translate(x, y, z); } else if (times >= 3 * frames && times < 5 * frames) { times++; camera.Translate(-x, -y, -z); } else if (times >= 5 * frames && times < 6 * frames) { times++; camera.Translate(x, y, z); } else { is_Shake = false; times = 0; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using SecuritySite.Models; using SecuritySite.Providers; using System.Web.Security; using System.Web.Profile; namespace SecuritySite.Controllers { public class PersonalController : Controller { [AllowAnonymous] [HttpGet] public ActionResult Index(string login) { if (login == null || login.Length < 1) { throw new HttpException(404, "NotFoundError"); } ProfileInfoProvider inf = new ProfileInfoProvider(); Profile profile = new Profile(); List<string> name = inf.GetFullName(login); profile.CommentCount = inf.GetCommentCount(login); profile.ArticleCount = inf.GetArticleCount(login); profile.Score = inf.GetScore(login); profile.FirstName = name.FirstOrDefault(); profile.LastName = name.LastOrDefault(); profile.Age = inf.GetAge(login); profile.LastVisitDate = inf.GetLastVisiteDate(login); ViewBag.Login = login; if (this.User.Identity.Name == login) { try { this.HttpContext.Profile["CommentCount"] = profile.CommentCount; this.HttpContext.Profile["ArticleCount"] = profile.ArticleCount; } catch { } } if (Roles.GetRolesForUser(login).FirstOrDefault() == "readonly") { ViewBag.IsReadonly = true; ViewBag.IsAuthor = false; } else if (Roles.GetRolesForUser(login).FirstOrDefault() == "author") { ViewBag.IsReadonly = false; ViewBag.IsAuthor = true; } else { ViewBag.IsReadonly = false; ViewBag.IsAuthor = false; } return View(profile); } [Authorize] public ActionResult Edit() { Profile model = new Profile(); model.FirstName = (string)this.HttpContext.Profile["FirstName"]; model.LastName = (string)this.HttpContext.Profile["LastName"]; model.Age = this.HttpContext.Profile["Age"] == null ? 0 : (int)this.HttpContext.Profile["Age"]; return View(model); } [Authorize] [HttpPost] public ActionResult Edit(Profile model) { if(ModelState.IsValid) { this.HttpContext.Profile["FirstName"] = model.FirstName; this.HttpContext.Profile["LastName"] = model.LastName; this.HttpContext.Profile["Age"] = model.Age; return RedirectToAction("Index", new { login = this.User.Identity.Name }); } return View(model); } } }
using System; using FluentAssertions; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; using Xunit; namespace NetEscapades.AspNetCore.SecurityHeaders.Test { public class CrossOriginResourcePolicyBuilderTests { [Fact] public void Build_WhenNoValues_ReturnsNullValue() { var builder = new CrossOriginResourcePolicyBuilder(); var result = builder.Build(); result.ConstantValue.Should().BeNullOrEmpty(); } [Fact] public void Build_AddSameSite_AddsValue() { var builder = new CrossOriginResourcePolicyBuilder(); builder.SameSite(); var result = builder.Build(); result.ConstantValue.Should().Be("same-site"); } [Fact] public void Build_AddSameSite_WithReportEndpoint_AddsValue() { var builder = new CrossOriginResourcePolicyBuilder(); builder.SameSite(); builder.AddReport().To("default"); var result = builder.Build(); result.ConstantValue.Should().Be("same-site; report-to=\"default\""); } [Fact] public void Build_AddSameOrigin_AddsValue() { var builder = new CrossOriginResourcePolicyBuilder(); builder.SameOrigin(); var result = builder.Build(); result.ConstantValue.Should().Be("same-origin"); } [Fact] public void Build_AddSameOrigin_WithReportEndpoint_AddsValue() { var builder = new CrossOriginResourcePolicyBuilder(); builder.SameOrigin(); builder.AddReport().To("default"); var result = builder.Build(); result.ConstantValue.Should().Be("same-origin; report-to=\"default\""); } [Fact] public void Build_AddCrossOrigin_AddsValue() { var builder = new CrossOriginResourcePolicyBuilder(); builder.CrossOrigin(); var result = builder.Build(); result.ConstantValue.Should().Be("cross-origin"); } [Fact] public void Build_AddCrossOrigin_WithReportEndpoint_AddsValue() { var builder = new CrossOriginResourcePolicyBuilder(); builder.CrossOrigin(); builder.AddReport().To("default"); var result = builder.Build(); result.ConstantValue.Should().Be("cross-origin; report-to=\"default\""); } } }
using System.Collections.Generic; using System.Reflection; using JetBrains.Annotations; namespace iSukces.Code.Ui.DataGrid { public class BasicDataGridColumn { public string Name { get; set; } public int? Width { get; set; } public object HeaderSource { get; set; } public string DataFormatString { get; set; } public bool IsReadOnly { get; set; } public bool IsSortable { get; set; } public bool IsResizable { get; set; } = true; public string CategoryName { get; set; } public object CategoryHeaderSource { get; set; } /// <summary> /// Reflected property if possible. For complicated paths can be declared in other than Row types /// </summary> public PropertyInfo Member { get; set; } [NotNull] public Dictionary<string, object> CustomValues { get; } = new Dictionary<string, object>(); } }
using UnityEngine; namespace DChild.Gameplay.Cameras { public class CameraDefaultSetter : MonoBehaviour { [SerializeField] private VirtualCamera m_vCam; #if UNITY_EDITOR public void Set(VirtualCamera camera) => m_vCam = camera; #endif private void OnTriggerEnter2D(Collider2D collision) { if (collision.tag == "Hitbox") { var player = collision.GetComponentInParent<Player.Player>(); if (player != null) { var cameraRoutine = GameplaySystem.GetRoutine<ICameraRoutine>(); cameraRoutine.SetDefaultCam(m_vCam); cameraRoutine.TransistionToDefaultCamera(); } } } } }
using Entities.DTOs; using System; using System.Collections.Generic; using System.Text; namespace Entities.Responses { public class PersonResponse : BaseResponse { public PersonDto PersonDto{ get; set; } private PersonResponse(bool success, string message, PersonDto personDto) : base(success, message) { PersonDto = personDto; } public PersonResponse(PersonDto personDto) : this(true, string.Empty, personDto) { } public PersonResponse(string message) : this(false, message, null) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; namespace IMtest { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); int UserId = LoginPhase(); if (UserId > 0) { OpenSocket(); MainboardPhase(UserId); } return; } private static int LoginPhase() { frmLogin form = new frmLogin(); form.ShowDialog(); //Application.Run(form); if (form.DialogResult == DialogResult.OK) { return form.UserId; } return 0; } private static void OpenSocket() { //SocketServer.StartListening(); SocketClient.StartClient(); } private static void MainboardPhase(int UserId) { frmMainboard form = new frmMainboard(UserId); form.ShowDialog(); return; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using PeopleSearch.Models; using PeopleSearch.Controllers; using System.Collections.Generic; using System.Web.Http.Results; using System.Linq; using Moq; using System.Data.Entity; namespace PeopleSearch.Tests { [TestClass] public class SearchControllerTest { [TestMethod] public void GetPeople_ShouldFindMatchingFirstName() { //Arrange const string expectedFirstName = "FN"; var expected = TestUtils.GetDemoPeople(1); var data = new List<People> { expected, TestUtils.GetDemoPeople(2), TestUtils.GetDemoPeople(3), TestUtils.GetDemoPeople(4), new People { Id = 5, FirstName = "FIRSTNAME" , LastName = "LN", Address = " S State st", Age = 10, Interests = "Interest" } }.AsQueryable(); var dbSetMock = new Mock<IDbSet<People>>(); dbSetMock.Setup(m => m.Provider).Returns(data.Provider); dbSetMock.Setup(m => m.Expression).Returns(data.Expression); dbSetMock.Setup(m => m.ElementType).Returns(data.ElementType); dbSetMock.Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator()); var customDbContextMock = new Mock<PeopleContext>(); customDbContextMock .Setup(x => x.People) .Returns(dbSetMock.Object); var classUnderTest = new SearchController(customDbContextMock.Object); //Action var actual = classUnderTest.GetPeople(expectedFirstName); //Assert Assert.IsNotNull(actual); Assert.AreEqual(4, actual.Count()); Assert.IsTrue(actual.ElementAt(0).FirstName.StartsWith(expectedFirstName)); Assert.IsTrue(actual.ElementAt(1).FirstName.StartsWith(expectedFirstName)); Assert.IsTrue(actual.ElementAt(2).FirstName.StartsWith(expectedFirstName)); Assert.IsTrue(actual.ElementAt(3).FirstName.StartsWith(expectedFirstName)); } } }
using UnityEngine; using UnityEngine.Profiling; using System.Collections.Generic; public class EffectObject { #region EffectTarget struct EffectTarget { public bool hasTransform; public Transform root; public Transform bpTrans; public Vector3 position; public Quaternion rotation; public void Clear() { hasTransform = false; root = null; bpTrans = null; position = Vector3.zero; rotation = Quaternion.identity; } public void SetTransform(Transform root, string bp) { this.hasTransform = true; this.root = root; if (!string.IsNullOrEmpty(bp)) this.bpTrans = root.Search(bp); if (this.bpTrans == null) this.bpTrans = root; this.position = bpTrans.position; this.rotation = bpTrans.rotation; } public void SetPosition(Vector3 position, Quaternion rotation) { this.hasTransform = false; this.root = null; this.bpTrans = null; this.position = position; this.rotation = rotation; } public Vector3 TransformPoint(Vector3 point) { if (hasTransform && bpTrans != null) { return bpTrans.TransformPoint(point); } else { return position + point; } } public Quaternion TransformRotation(Quaternion localRotation) { if (hasTransform && bpTrans != null) { return bpTrans.rotation * localRotation; } else { return this.rotation * localRotation; } } public Vector3 TransformScale(Vector3 localScale) { if (hasTransform && bpTrans != null) { Vector3 lossyScale = bpTrans.lossyScale; lossyScale.x *= localScale.x; lossyScale.y *= localScale.y; lossyScale.z *= localScale.z; return lossyScale; } else { return localScale; } } public bool IsValid() { return !hasTransform || bpTrans != null; } } #endregion enum EffectStates { Initial, Delay, Playing, FadeOut, Expired, } // ------------- EffectCfg config; public GameObject gameObject; Transform transform; GameObject modelGo; Transform modelTrans; Renderer[] renderers; int activelayer = 0; AssetBundleLoadAssetOperation assetLoadOperation; string assetBundleName; ParticleSystem[] particleSystems; // ------------- public EffectCfg Config { get { return this.config; } } public int EffectID { protected set; get; } public bool Expired { get { return state == EffectStates.Expired; } } public bool IsLoaded { get { return modelGo != null; } } public GameObject Model { get { return modelGo; } } public bool IsLoop { get { if (config == null) { return false; } return config.Lifetime <= 0; } } EffectTarget target; int stateElapsed; EffectStates state; EffectRuntimeQuality runtimeQuality; AudioObject audioObject; List<EffectObject> companionEffects; EffectFadeOut fadeout; EffectQualitySwitcher qualitySwitcher; System.Action<EffectObject> onLoadCallback; System.Func<Renderer, bool> applyOnRenderersCallback; string effectBundlePath = "effect/effect_{0}.bundle"; public EffectObject(EffectCfg config, Transform root) { this.config = config; this.EffectID = config.ID; this.gameObject = new GameObject(config.ID.ToString()); this.transform = gameObject.transform; this.transform.SetParent(root); this.assetBundleName = string.Format(effectBundlePath, config.AssetName.ToLower()); this.activelayer = LayerManager.DefaultLayer; assetLoadOperation = AssetLoadManager.LoadAssetAsync(assetBundleName, config.AssetName, typeof(GameObject)); } public void Start(Transform trans, System.Action<EffectObject> onLoad, EffectRuntimeQuality quality) { target.Clear(); target.SetTransform(trans, config.BindPoint); StartInternal(onLoad, quality); } public void Start(Vector3 position, Quaternion rotation, System.Action<EffectObject> onLoad, EffectRuntimeQuality quality) { target.Clear(); target.SetPosition(position, rotation); StartInternal(onLoad, quality); } private void StartInternal(System.Action<EffectObject> onLoad, EffectRuntimeQuality quality) { onLoadCallback = onLoad; applyOnRenderersCallback = null; runtimeQuality = quality; if (qualitySwitcher != null) qualitySwitcher.SetQuality(runtimeQuality); ResetState(); UpdatePosition(); UpdateScale(); if (config.InitFollowRotation) UpdateRotation(); } public void Stop() { Profiler.BeginSample("EffectStop"); if (this.state == EffectStates.Playing) MoveToNextState(); else if (this.state == EffectStates.FadeOut) { } else StopImmediate(); Profiler.EndSample(); if (companionEffects != null && companionEffects.Count > 0) { for (int i = 0; i < companionEffects.Count; i++) { Profiler.BeginSample("StopcompanionEffects"); companionEffects[i].Stop(); Profiler.EndSample(); } } } public void StopImmediate() { state = EffectStates.Expired; Hide(); if (companionEffects != null && companionEffects.Count > 0) { for (int i = 0; i < companionEffects.Count; i++) { companionEffects[i].StopImmediate(); } companionEffects.Clear(); } } public void ApplyOnRenderers(System.Func<Renderer, bool> callback) { if (IsLoaded) { ApplyOnRenderersInternal(callback); } else { applyOnRenderersCallback = callback; } } private void ApplyOnRenderersInternal(System.Func<Renderer, bool> callback) { if (modelGo == null) return; if (renderers == null) { renderers = modelGo.GetComponentsInChildren<Renderer>(); } if (renderers.Length == 0) return; for (int i = 0; i < renderers.Length; i++) { var next = callback(renderers[i]); if (!next) break; } } public void Destroy() { ResetState(); if (assetLoadOperation != null) { assetLoadOperation.Unload(); assetLoadOperation = null; } if (gameObject != null) { Object.Destroy(gameObject); gameObject = null; } } private void ResetState() { if (state == EffectStates.Initial) return; stateElapsed = 0; state = EffectStates.Initial; Hide(); StopAudio(); } private void MoveToNextState() { EffectStates curState = this.state; this.stateElapsed = 0; switch (curState) { case EffectStates.Initial: if (config.Delay > 0) { this.state = EffectStates.Delay; } else { this.state = EffectStates.Playing; Show(); OnBeginPlay(); PlayAudio(); } break; case EffectStates.Delay: this.state = EffectStates.Playing; Show(); OnBeginPlay(); PlayAudio(); break; case EffectStates.Playing: if (config.FadeOutTime > 0) { this.state = EffectStates.FadeOut; } else { StopImmediate(); } OnEndPlay(); StopAudio(); BeginFadeOut(); break; case EffectStates.FadeOut: StopImmediate(); break; } } private void UpdateState() { stateElapsed += (int)(Time.deltaTime * 1000); switch (state) { case EffectStates.Initial: MoveToNextState(); break; case EffectStates.Delay: if (stateElapsed > config.Delay) MoveToNextState(); break; case EffectStates.Playing: if (config.Lifetime > 0 && stateElapsed > config.Lifetime) MoveToNextState(); break; case EffectStates.FadeOut: if (stateElapsed > config.FadeOutTime) MoveToNextState(); break; } if (!target.IsValid()) { Stop(); return; } } private void Show() { if (fadeout != null) { fadeout.EnableFadeOut(); } LayerManager.SetLayer(renderers,activelayer); if (config.Priority != (int)EffectPriority.High) EffectManager.AddParticleSystems(particleSystems); } private void Hide() { LayerManager.SetLayer(renderers, LayerManager.InvisibleLayer); if (config.Priority != (int)EffectPriority.High) EffectManager.RemoveParticleSystem(particleSystems); } private void PlayAudio() { if (audioObject == null && config.Audio != 0) { if (target.hasTransform && target.bpTrans != null) { audioObject = AudioManager.PlayAudio(config.Audio, target.bpTrans); } else { audioObject = AudioManager.PlayAudio(config.Audio, target.position); } } } private void StopAudio() { if (audioObject != null) { if (audioObject.IsLoop) { audioObject.Stop(); } audioObject = null; } } private void OnBeginPlay() { if (config.OnBeginPlayArray != null) { for (int i = 0; i < config.OnBeginPlayArray.Length; i++) { int effID = config.OnBeginPlayArray[i]; PlayEffectOnSameTarget(effID); } } } private void OnEndPlay() { if (config.OnEndPlayArray != null) { for (int i = 0; i < config.OnEndPlayArray.Length; i++) { int effID = config.OnEndPlayArray[i]; PlayEffectOnSameTarget(effID); } } } private void BeginFadeOut() { if (fadeout != null) { fadeout.BeginFadeOut(); } } private void PlayEffectOnSameTarget(int effID) { if (companionEffects == null) companionEffects = new List<EffectObject>(10); EffectObject companionEffect = null; if (target.hasTransform && target.root != null) { companionEffect = EffectManager.Play(effID, target.root); } else { companionEffect = EffectManager.Play(effID, target.position, target.rotation); } if (companionEffect != null && companionEffect.IsLoop) { companionEffects.Add(companionEffect); } } public void Update() { if (modelGo == null) { CheckLoading(); return; } if (onLoadCallback != null) { if (modelGo != null) { onLoadCallback(this); onLoadCallback = null; } } if (applyOnRenderersCallback != null) { ApplyOnRenderersInternal(applyOnRenderersCallback); applyOnRenderersCallback = null; } UpdateState(); } public void LateUpdate() { if (state == EffectStates.Expired) return; if (config.FollowPosition) UpdatePosition(); if (config.FollowRotation) UpdateRotation(); if (config.FollowScale) UpdateScale(); UpdateVisiblilty(); } void CheckLoading() { if (assetLoadOperation != null) { if (assetLoadOperation.IsDone()) { GameObject prefab = assetLoadOperation.GetAsset<GameObject>(); if(prefab == null) { assetLoadOperation.Unload(); assetLoadOperation = null; StopImmediate(); }else { InstantiateModel(prefab); } } } } private void UpdatePosition() { if (transform == null) { DebugLogger.LogFormat("[EffectObject]:UpdatePosition() error config id: {0}", config.ID); return; } transform.position = target.TransformPoint(config.LocalPositionVec3); } private void UpdateRotation() { transform.rotation = target.TransformRotation(config.LocalRotationQuaternion); } private void UpdateScale() { transform.localScale = target.TransformScale(config.LocalScaleVec3); } private void UpdateVisiblilty() { if (state == EffectStates.Playing || state == EffectStates.FadeOut) { if (target.hasTransform && target.bpTrans != null && !target.bpTrans.gameObject.activeInHierarchy) { Hide(); } else { Show(); } } } private void InstantiateModel(GameObject prefab) { modelGo = Object.Instantiate<GameObject>(prefab); modelGo.SetActive(true); modelTrans = modelGo.transform; modelTrans.SetParent(transform); modelTrans.ResetPRS(); if (renderers == null) { renderers = modelGo.GetComponentsInChildren<Renderer>(); } fadeout = modelGo.GetComponent<EffectFadeOut>(); qualitySwitcher = modelGo.GetComponent<EffectQualitySwitcher>(); particleSystems = modelGo.GetComponentsInChildren<ParticleSystem>(); if (qualitySwitcher != null) qualitySwitcher.SetQuality(runtimeQuality); } }
using System; using System.IO; using iSukces.Code.Tests.EqualityGenerator; using Xunit; namespace iSukces.Code.Tests { public class TestUtils { public static void CompareWithResource(string actual, string resourcePrefix, string method, string file, string ext) { method = method .Replace("_Should_create_", "_") .Replace("_Should_", "_"); void Save(bool addSubfolder) { var dir = new FileInfo(file).Directory.FullName; if (addSubfolder) dir = Path.Combine(dir, "new"); var fn = Path.Combine(dir, method + ext); new FileInfo(fn).Directory.Create(); File.WriteAllText(fn, actual); } var name = resourcePrefix + method + ext; var s = typeof(EqualityGeneratorTests).Assembly.GetManifestResourceStream(name); if (s is null) { Save(false); throw new Exception("Resource not found, please recompile"); } string expected; try { using(var reader = new StreamReader(s)) { expected = reader.ReadToEnd(); } } finally { s.Dispose(); } var isNullOrEmpty = string.IsNullOrEmpty(expected.Trim()); if (expected != actual || isNullOrEmpty) Save(!isNullOrEmpty); Assert.Equal(expected, actual); } } }
namespace Tests.Data.Oberon { public class EmailAccount { public EmailAccount(string domain, string userName, string password, string address, string displayName) { this.UserName = userName; this.Domain = domain; this.Password = password; this.Address = address; this.DisplayName = displayName; } public string Address { get; private set; } public string Domain { get; private set; } public string Password { get; private set; } public string UserName { get; private set; } public string DisplayName { get; private set; } public static EmailAccount AccountOne { get { return new EmailAccount("NGPVAN", "oberonemail1", "389Wf4eyJ9CR", "oberonemail1@ngpvan.com", "Oberon Email1"); } } public static EmailAccount AccountTwo { get { return new EmailAccount("NGPVAN", "oberonemail2", "wYMMJ3mfoTyi", "oberonemail2@ngpvan.com", "Oberon Email2"); } } public static EmailAccount AccountThree { get { return new EmailAccount("NGPVAN", "oberonemail3", "in28Mh7Ba53v88uiZo7wQXUxzxL278TB", "oberonemail3@ngpvan.com", "Oberon Email3"); } } public static EmailAccount AccountFour { get { return new EmailAccount("NGPVAN", "oberonemail4", "v9X09f1XY3VF889370x153EAz33810c0", "oberonemail4@ngpvan.com", "Oberon Email4"); } //get { return new EmailAccount("NGPVAN", "oberonemail4", "v9X09f1XY3VF889370x153EAz33810c0", "ECPTestAdmin@ngpvan.com", "Oberon Email4"); } } public static EmailAccount AccountFive { get { return new EmailAccount("NGPVAN", "ECPTestAdmin", "0beron!1", "ECPTestAdmin@ngpvan.com", "ECP Test Admin"); } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProyectoBolera { public partial class AlquilerForm : Form { public static Form pista1 = null, pista2 = null; public AlquilerForm() { InitializeComponent(); } public void llenarHoraInicioPista1(string hora) { //lbGlobalPista1.Text = ""; } public void llenarHoraInicioPista2(string hora) { lbGlobalPista2.Text = hora; } private void PictureBox2_Click(object sender, EventArgs e) { if (pista2 == null) { pista2 = new PistaFacturaForm("2","pis2"); openChildForm(pista2); } else { pista2.Show(); } } private void PictureBox1_Click_1(object sender, EventArgs e) { if (pista1 == null) { pista1 = new PistaFacturaForm("1", "pis1"); openChildForm(pista1); } else { pista1.Show(); } } private void AlquilerPanel_Paint(object sender, PaintEventArgs e) { } private void openChildForm(Form childForm) { childForm.TopLevel = false; childForm.FormBorderStyle = FormBorderStyle.None; childForm.Dock = DockStyle.Fill; alquilerPanel.Controls.Add(childForm); alquilerPanel.Tag = childForm; childForm.BringToFront(); childForm.Show(); } } }
using Effigy.DataObject.UnitOfWork; using Effigy.Entity.DBContext; using Effigy.Entity.Entity; using Effigy.Service.Contract; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Effigy.Service.Factory { public class UserPayment : BaseFactory, IUserPaymentService { public int SavePaymentDetail(PaymentDetails objVALLoginDetail) { int result = 0; try { result = objPayment.SavePaymentDetail(objVALLoginDetail); if (result != 0) { objPayment.UpdateUserAfterPayment(objVALLoginDetail.UserID, objVALLoginDetail.PaymentDateTime); } } catch (Exception) { throw; } return result; } } }
using System.Windows.Controls; namespace tweetz.core.Controls.SettingsBlock { public partial class SettingsBlockTips : UserControl { public SettingsBlockTips() { InitializeComponent(); } } }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Shipwreck.TypeScriptModels.Expressions { // 4.4 public sealed class RegExpExpression : Expression { public override ExpressionPrecedence Precedence => ExpressionPrecedence.Grouping; public string Pattern { get; set; } public string Option { get; set; } public override void Accept<T>(IExpressionVisitor<T> visitor) => visitor.VisitRegExp(this); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using KartObjects; using KartObjects.Entities; namespace KartSystem { public class GoodViewSettings:Entity { public override string FriendlyName { get { return "Свойства компонента поиска товара"; } } public Good Good { get; set; } } }
using AutoFixture; using Moq; using NUnit.Framework; using SFA.DAS.CommitmentsV2.Api.Client; using SFA.DAS.ProviderCommitments.Web.Mappers.Cohort; using SFA.DAS.ProviderCommitments.Web.Models.Cohort; using System; using System.Threading; using System.Threading.Tasks; namespace SFA.DAS.ProviderCommitments.Web.UnitTests.Mappers.Cohort { [TestFixture] public class WhenIMapConfirmEmployerRequestToConfirmEmployerViewModel { private ConfirmEmployerRequestToViewModelMapper _mapper; private ConfirmEmployerRequest _source; private Func<Task<ConfirmEmployerViewModel>> _act; private CommitmentsV2.Api.Types.Responses.AccountLegalEntityResponse _accountLegalEntityResponse; [SetUp] public void Arrange() { var fixture = new Fixture(); _accountLegalEntityResponse = fixture.Create<CommitmentsV2.Api.Types.Responses.AccountLegalEntityResponse>(); _source = fixture.Create<ConfirmEmployerRequest>(); var icommitmentApiClient = new Mock<ICommitmentsApiClient>(); icommitmentApiClient.Setup(x => x.GetAccountLegalEntity(It.IsAny<long>(), It.IsAny<CancellationToken>())).ReturnsAsync(_accountLegalEntityResponse); _mapper = new ConfirmEmployerRequestToViewModelMapper(icommitmentApiClient.Object); _act = async () => await _mapper.Map(_source); } [Test] public async Task ThenEmployerAccountLegalEntityPublicHashedIdIsMappedCorrectly() { var result = await _act(); Assert.AreEqual(_source.EmployerAccountLegalEntityPublicHashedId, result.EmployerAccountLegalEntityPublicHashedId); } [Test] public async Task ThenEmployerAccountNameIsMappedCorrectly() { var result = await _act(); Assert.AreEqual(_accountLegalEntityResponse.AccountName, result.EmployerAccountName); } [Test] public async Task ThenEmployerAccountLegalEntityNameIsMappedCorrectly() { var result = await _act(); Assert.AreEqual(_accountLegalEntityResponse.LegalEntityName, result.EmployerAccountLegalEntityName); } [Test] public async Task ThenProviderIdMappedCorrectly() { var result = await _act(); Assert.AreEqual(_source.ProviderId, result.ProviderId); } [Test] public async Task ThenAccountLegalEntityIdIsNotMapped() { var result = await _act(); Assert.AreEqual(0, result.AccountLegalEntityId); } } }
using System; namespace LotSystem { public class Lot { public static int count30Mins = 30; // displays the quantity of each type of space public static int count60Mins = 30; public static int count24Hours = 20; public static int countUnlimited = 20; public static int UpdateSpaceQuantity(int UserSpaceType){ // calculations to update the quantity of available spaces switch (UserSpaceType) { case 1: count30Mins -= 1; return count30Mins; case 2: count60Mins -= 1; return count60Mins; case 3: count24Hours -= 1; return count24Hours; case 4: countUnlimited -= 1; break; } return count24Hours; } } }
using System; using ApiTemplate.Common.Enums.Exceptions; namespace ApiTemplate.Common.Exceptions { public class BadRequestException : AppException { public BadRequestException() : base(CustomStatusCodes.BadRequest) { } public BadRequestException(string message) : base(CustomStatusCodes.BadRequest, message) { } public BadRequestException(object additionalData) : base(CustomStatusCodes.BadRequest, additionalData) { } public BadRequestException(string message, object additionalData) : base(CustomStatusCodes.BadRequest, message, additionalData) { } public BadRequestException(string message, Exception exception) : base(CustomStatusCodes.BadRequest, message, exception) { } public BadRequestException(string message, Exception exception, object additionalData) : base(CustomStatusCodes.BadRequest, message, exception, additionalData) { } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Runtime.CompilerServices; using System.Web; namespace DanialProject.Models.Database { public class Features { [Display(Name="Icon:")] [DanialProject.Models.Database.FileExtensions("jpg,jpeg,png,JPG,JPEG,PNG", ErrorMessage="Only Image files allowed.")] [NotMapped] public HttpPostedFileBase File { get; set; } [MaxLength(100)] public string Icon { get; set; } [MaxLength(100)] public string IconType { get; set; } public int ID { get; set; } [MaxLength(100)] public string ListingType { get; set; } [MaxLength(100)] public string Name { get; set; } public Features() { } } }
using System; using System.Collections.Generic; using System.Data; using System.Data.Entity; using System.Data.Entity.Core.Objects; using System.Linq; using System.Net; using System.Web; using System.Web.Mvc; using WebsiteQuanLyPhatHanhSach.Models; namespace WebsiteQuanLyPhatHanhSach.Controllers { public class RevenuesController : Controller { private QLPhatHanhSachEntities db = new QLPhatHanhSachEntities(); // GET: Revenues public ActionResult Index() { return View(); } public JsonResult GetAllRevenue() { var rev = db.Revenues.Include(a => a.IssueInvoice).Join(db.Agencies, a => a.IssueInvoice.AgencyID, b => b.AgencyID, (a, b) => new { Id = a.Id, InvoiceID = a.InvoiceID, AgencyID = a.IssueInvoice.AgencyID, AgencyName = b.AgencyName, InvoiceRevenue = a.InvoiceRevenue, RevenueTotal = a.RevenueTotal, RevenueDate = a.RevenueDate }); return Json(rev.ToList(), JsonRequestBehavior.AllowGet); } public JsonResult GetRevenues(DateTime start, DateTime end) { var rev = db.Revenues.Include(a => a.IssueInvoice).Join(db.Agencies, a => a.IssueInvoice.AgencyID, b => b.AgencyID, (a, b) => new { Id = a.Id, InvoiceID = a.InvoiceID, AgencyID = a.IssueInvoice.AgencyID, AgencyName = b.AgencyName, InvoiceRevenue = a.InvoiceRevenue, RevenueTotal = a.RevenueTotal, RevenueDate = a.RevenueDate }).Where(a => DateTime.Compare((DateTime)DbFunctions.TruncateTime(a.RevenueDate), start.Date) >= 0 && DateTime.Compare((DateTime)DbFunctions.TruncateTime(a.RevenueDate), end.Date) <= 0 ); return Json(rev.ToList(), JsonRequestBehavior.AllowGet); } } }
using DamianTourBackend.Core.Entities; using System; using System.Collections.Generic; namespace DamianTourBackend.Core.Interfaces { public interface IRegistrationRepository { Registration GetBy(Guid id, string email); Registration GetLast(string email); void Add(Registration registration, string email); void Delete(Registration registration, string email); ICollection<Registration> GetAllFromUser(string email); IEnumerable<Registration> GetAll(); ICollection<Registration> GetAllFromRoute(Guid id); void Update(Registration registration, string email); } }
using System; using System.IO; using System.Reflection; using System.Text; namespace EmailSender { public class HtmlContentProvider { private const string userEmail = "$USEREMAIL$"; private const string generatedCode = "$GENERATEDCODE$"; private const string unwantedMessage = "$UNWANTEDMESSAGE$"; private const string mainMessage = "$MAINMESSAGE$"; private const string resetPasswordFileName = "resetpassword.html"; private const string confirmAccountFileName = "confirmaccount.html"; private string _email; public HtmlContentProvider(string email) { _email = email; } public string GetContentWithCode(ContentType type, string code) { string filename = string.Empty; string mainMessageContent = string.Empty; switch (type) { case ContentType.ResetPassword: filename = resetPasswordFileName; mainMessageContent = "In order to reset your password use code below."; break; case ContentType.ActivateAccount: filename = confirmAccountFileName; mainMessageContent = "In order to confirm your account use code below."; break; default: throw new ArgumentOutOfRangeException(); } string htmlContent = StaticFileReader.GetFileText($"EmailSender.templates.{filename}"); htmlContent = htmlContent.Replace(userEmail, _email); htmlContent = htmlContent.Replace(generatedCode, code); htmlContent = htmlContent.Replace(unwantedMessage, "If this message is unwanted, please let us know contact@snowapp.com"); htmlContent = htmlContent.Replace(mainMessage, mainMessageContent); return htmlContent; } } }
using Labo2.Oefening2.PresentationModels; using Oefening_2; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace Labo2.Oefening2.Controllers { public class AgendaController : Controller { // GET: Agenda public ActionResult Index() { return View(); } public ActionResult Show() { PMAgenda pm = new PMAgenda(); pm.Slot1 = Data.GetSessions(1); pm.Slot2 = Data.GetSessions(2); pm.Slot3 = Data.GetSessions(3); return View(pm); } public ActionResult Detail(int id) { if (id == null || id < 0 || id > 9) { return RedirectToAction("Show"); //return View("Show"); } Labo2.Oefening2.Models.Session session = Data.GetSession(id); return View(session); } } }
namespace Models { public class EmitterModel : IItem { public ItemType Type { get { return ItemType.Emitter; } } public string Name { get { return "Enemy emitter"; } } } }
using BenefitDeduction.Employees; namespace BenefitDeduction.EmployeesSalary { public interface ISalaryRepository { ISalary GetSalary(IEmployee employee); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace SqlServerWebAdmin.Toolbars { public partial class servertoolbar : System.Web.UI.UserControl { private string selected = ""; public string Selected { get { return selected; } set { selected = value.ToLower(); } } public servertoolbar() { this.Init += new System.EventHandler(Page_Init); } protected void Page_Load(object sender, System.EventArgs e) { } protected string CheckLink(string link) { if(string.IsNullOrEmpty(selected)) { selected = Request.FilePath.Trim('/').Replace(".aspx", ""); } return (selected == link) ? "selectedLink" : ""; } protected void Page_Init(object sender, EventArgs e) { if (Page.User.Identity.IsAuthenticated) { Page.ViewStateUserKey = Page.Session.SessionID; } } } }
using NfePlusAlpha.Application.ViewModels.ViewModel; using NfePlusAlpha.UI.Wpf.Apoio.Controles; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace NfePlusAlpha.UI.Wpf.Views.Cadastros { /// <summary> /// Interaction logic for winAlterarSenha.xaml /// </summary> public partial class winAlterarSenha : NfePlusAlphaWindow { public LoginViewModel objLogin; private bool blnAlteracaoObrigatoria; public winAlterarSenha(LoginViewModel _objLogin) { InitializeComponent(); this.objLogin = _objLogin; if (!string.IsNullOrEmpty(this.objLogin.usu_senha)) this.blnAlteracaoObrigatoria = true; else this.blnAlteracaoObrigatoria = false; } private void NfePlusAlphaWindow_Loaded(object sender, RoutedEventArgs e) { this.LayoutRoot.DataContext = this.objLogin; if (this.blnAlteracaoObrigatoria) { txtNovaSenha.Focus(); txtSenha.IsEnabled = false; } else txtSenha.Focus(); } private void btnAlterar_Click(object sender, RoutedEventArgs e) { string strMensagem = string.Empty; if (!objLogin.AlterarSenha(out strMensagem)) { if (!string.IsNullOrEmpty(strMensagem)) MessageBox.Show(strMensagem, "AVISO", MessageBoxButton.OK, MessageBoxImage.Error); } else { this.objLogin.usu_senha = string.Empty; this.Close(); } } private void btnSair_Click(object sender, RoutedEventArgs e) { this.Close(); } private void NfePlusAlphaWindow_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) this.btnSair_Click(null, null); } } }
using System; namespace FourthCode { public interface IDatabase { void Create(int id, string content); string Read(int id); bool Exists(int id); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TDCPluginImportExport10 { class AutoDeskFBXCommon { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OK_Play_Click : MonoBehaviour { public GameObject Idle; public AudioSource ThisOne; // Use this for initialization void Start() { } // Update is called once per frame void Update() { PointScreen(); } // Raycast when click to display objects. void PointScreen() { if (Input.GetMouseButtonDown(0)) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit, 100.0f)) { if (hit.collider.gameObject.layer == 8) { print("Hit something!"); //ThisOne.Play(); Idle.SetActive(true); Destroy(gameObject); } } } } }
using System; using Android.Widget; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using Kuromori; using Kuromori.Droid; using Android.Views; using Android.Graphics; [assembly: ExportRenderer(typeof(Kuromori.MenuTableView), typeof(Kuromori.Droid.MenuTableViewRenderer))] namespace Kuromori.Droid { public class MenuTableViewRenderer : TableViewRenderer { private bool _firstElementAdded = false; protected override void OnElementChanged(ElementChangedEventArgs<TableView> e) { base.OnElementChanged(e); if (Control == null) return; var listView = Control as global::Android.Widget.ListView; listView.DividerHeight = 0; listView.SetFooterDividersEnabled(false); listView.SetHeaderDividersEnabled(false); listView.Alpha = 1; listView.Divider = new NoDivider(); if (Control == null) return; listView.ChildViewAdded += (sender, args) => { if (!_firstElementAdded) { args.Child.Visibility = ViewStates.Gone; _firstElementAdded = true; } }; } } public class NoDivider : Android.Graphics.Drawables.Drawable { public override int Opacity { get { return 0; } } public override void Draw(Canvas canvas) { string n; } public override void SetAlpha(int alpha) { string n; } public override void SetColorFilter(ColorFilter colorFilter) { string n; } } }
namespace iSukces.Code.Ui.DataGrid { public class LookupInfo { public static LookupInfo Empty { get { return new LookupInfo(); } } public object Source { get; set; } public string SelectedValuePath { get; set; } public string DisplayMemberPath { get; set; } public bool IsEmpty { get { return Source == null; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProgramaOperaciones { public partial class FormCuadrado : Form { public FormCuadrado() { InitializeComponent(); } private void buttonCuadrado_Click(object sender, EventArgs e) { double lado, respuesCuadrado; lado = double.Parse(textBoxLado.Text); respuesCuadrado = lado * lado; textBoxCuadradoRespuesta.Text = respuesCuadrado.ToString(); } private void buttonRegresar_Click(object sender, EventArgs e) { FormPrincipal fp = new FormPrincipal(); fp.StartPosition = FormStartPosition.CenterScreen; fp.Show(); this.Hide(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Modelo; using SQL; using QueryExecutor; using Controles; namespace Inventarios { public partial class frmPrincipal : Form { // Catalagos List<UnidadProducto> catUnidades; List<Departamento> catDepartamentos; List<Proveedor> catProveedores; List<Cliente> catClientes; List<Producto> catProductos; // Seleccionados Departamento tdDepartamentoSeleccionado; Proveedor tpProveedorSeleccionado; Cliente tcClienteSeleccionado; Producto tpProductoSeleccionado; Producto tsProcuto; // Filtros Departamento filtroDepartamento; Proveedor filtroProveedor; int decimales = 0; int maxDecimales = 2; bool punto; #region Inicializar public frmPrincipal() { InitializeComponent(); // Se inicializan los parametros de MySQL DBQueriesGeneral.executor = new MySQLExecutor(new MySQLParameters("localhost", 3306, "arelipos", "root", "")); } private void frmPrincipal_Load(object sender, EventArgs e) { Inicializar(); } #endregion #region Funciones Generales private void Inicializar() { // Clientes tcMuestraClientes(); // Unidades catUnidades = DBQueriesGeneral.ConsultaUnidadesProducto(); //MuestraUnidades(); // Departamentos tdMuestraDepartamentos(); // Proveedores tpMuestraProveedores(); // Productos tpMuestraProductos(); } private void frmPrincipal_Resize(object sender, EventArgs e) { // Repinta el fondo de los tabPages tabPrincipal.SelectedTab.Refresh(); } #endregion #region Inicio // #endregion #region Clientes private void tcMuestraClientes() { catClientes = DBQueriesGeneral.ConsultaClientes(); dgvClientes.Rows.Clear(); foreach (Cliente cliente in catClientes) { dgvClientes.Rows.Add(cliente["rfc"].Value, cliente["nombre"].Value, cliente["activo"].ToBool()); } } private void btnAgregarCliente_Click(object sender, EventArgs e) { try { if (sender == btnAgregarCliente) { frmCliente cliente = new frmCliente("Agregar"); if (cliente.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tcMuestraClientes(); } } if (sender == btnEditarCliente) { if (tcClienteSeleccionado["sololectura"].ToBool()) { MessageBox.Show(this, "No se puede modificar este cliente.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { frmCliente cliente = new frmCliente("Editar", ref tcClienteSeleccionado); if (cliente.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tcMuestraCliente(tcClienteSeleccionado); } } } if (sender == btnEliminaCliente) { if (tcClienteSeleccionado["sololectura"].ToBool()) { MessageBox.Show(this, "No se puede eliminar este cliente.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (MessageBox.Show(this, "¿Esta seguro de eliminar el cliente seleccionado?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { if (DBQueriesGeneral.EliminaCliente(tcClienteSeleccionado)) { int row = dgvClientes.SelectedRows[0].Index; dgvClientes.Rows.RemoveAt(row); catClientes.RemoveAt(row); } else { MessageBox.Show(this, "No se puedo eliminar el cliente seleccionado.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } } catch (Exception ex) { MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void tcMuestraCliente(Cliente cliente) { cliente.Update(DBQueriesGeneral.executor); int row = dgvClientes.SelectedRows[0].Index; dgvClientes[0, row].Value = cliente["rfc"].Value; dgvClientes[1, row].Value = cliente["nombre"].Value; dgvClientes[2, row].Value = cliente["activo"].Value; } private void dgvClientes_SelectionChanged(object sender, EventArgs e) { // Se selecciona el cliente if (dgvClientes.SelectedRows.Count > 0) tcClienteSeleccionado = catClientes[dgvClientes.SelectedRows[0].Index]; else tcClienteSeleccionado = null; } #endregion #region Proveedores private void tpMuestraProveedores() { catProveedores = DBQueriesGeneral.ConsultaProveedoresProductos(); dgvProveedores.Rows.Clear(); cmbFiltroProveedor.Items.Clear(); foreach (Proveedor prov in catProveedores) { dgvProveedores.Rows.Add(prov["nombre"].Value, prov["domingo"].ToBool(), prov["lunes"].ToBool(), prov["martes"].ToBool(), prov["miercoles"].ToBool(), prov["jueves"].ToBool(), prov["viernes"].ToBool(), prov["sabado"].ToBool(), prov["activo"].ToBool()); dgvProveedores.Rows[dgvProveedores.RowCount - 1].Visible = !prov["filtro"].ToBool(); cmbFiltroProveedor.Items.Add(prov["nombre"].ToString()); } if (cmbFiltroProveedor.Items.Count > 0) { cmbFiltroProveedor.SelectedIndex = 0; } } private void btnAgregarProveedor_Click(object sender, EventArgs e) { try { if (sender == btnAgregarProveedor) { frmProveedor prov = new frmProveedor("Agregar"); if (prov.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tpMuestraProveedores(); } } if (sender == btnEditarProveedor) { if (tpProveedorSeleccionado["sololectura"].ToBool()) { MessageBox.Show(this, "No se puede modificar este proveedor.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { frmProveedor prov = new frmProveedor("Editar", ref tpProveedorSeleccionado); if (prov.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tpMuestraProveedor(tpProveedorSeleccionado); } } } if (sender == btnEliminaProveedor) { if (tpProveedorSeleccionado["sololectura"].ToBool()) { MessageBox.Show(this, "No se puede eliminar este proveedor.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (MessageBox.Show(this, "¿Esta seguro de eliminar el proveedor seleccionado?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { if (DBQueriesGeneral.EliminaProveedor(tpProveedorSeleccionado)) { int row = dgvProveedores.SelectedRows[0].Index; dgvProveedores.Rows.RemoveAt(row); catProveedores.RemoveAt(row); cmbFiltroProveedor.Items.RemoveAt(row); } else { MessageBox.Show(this, "No se pudo eliminar el proveedor seleccionado.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } } } catch (Exception ex) { MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void tpMuestraProveedor(Proveedor proveedor) { // Se actualiza el proveedor proveedor.Update(DBQueriesGeneral.executor); // Actualiza el DataGridView int row = dgvProveedores.SelectedRows[0].Index; dgvProveedores[0, row].Value = proveedor["nombre"].Value; dgvProveedores[1, row].Value = proveedor["domingo"].Value; dgvProveedores[2, row].Value = proveedor["lunes"].Value; dgvProveedores[3, row].Value = proveedor["martes"].Value; dgvProveedores[4, row].Value = proveedor["miercoles"].Value; dgvProveedores[5, row].Value = proveedor["jueves"].Value; dgvProveedores[6, row].Value = proveedor["viernes"].Value; dgvProveedores[7, row].Value = proveedor["sabado"].Value; dgvProveedores[8, row].Value = proveedor["activo"].Value; // Se actualiza el ComboBox cmbFiltroProveedor.Items.RemoveAt(row); cmbFiltroProveedor.Items.Insert(row, proveedor["nombre"]); } private void dgvProveedores_SelectionChanged(object sender, EventArgs e) { if (dgvProveedores.SelectedRows.Count > 0) { tpProveedorSeleccionado = catProveedores[dgvProveedores.SelectedRows[0].Index]; } else { tpProveedorSeleccionado = null; } } #endregion #region Departamentos private void btnAgregaDepartamento_Click(object sender, EventArgs e) { try { if (sender == btnAgregaDepartamento) { frmDepartamento dep = new frmDepartamento("Agregar"); if (dep.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tdMuestraDepartamentos(); } } if (tdDepartamentoSeleccionado == null) { MessageBox.Show(this, "Debe seleccionar un departamento.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (sender == btnEditarDepartamento) { if (tdDepartamentoSeleccionado["sololectura"].ToBool()) { MessageBox.Show(this, "No se puede modificar este proveedor.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { frmDepartamento dep = new frmDepartamento("Editar", tdDepartamentoSeleccionado); if (dep.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tdMuestraDepartamento(tdDepartamentoSeleccionado); } } } if (sender == btnEliminaDepartamento) { if (tdDepartamentoSeleccionado["sololectura"].ToBool()) { MessageBox.Show(this, "No se puede eliminar este proveedor.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (MessageBox.Show(this, "¿Esta seguro de eliminar el proveedor seleccionado?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { if (DBQueriesGeneral.EliminaDepartamento(tdDepartamentoSeleccionado)) { int row = dgvDepartamentos.SelectedRows[0].Index; dgvDepartamentos.Rows.RemoveAt(row); catDepartamentos.RemoveAt(row); cmbFiltroDepartamento.Items.RemoveAt(row); } else { if(MessageBox.Show(this, "No se puedo eliminar el proveedor seleccionado.", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes) { tdDepartamentoSeleccionado["activo"].Value = false.ToString(); tdDepartamentoSeleccionado.Update(DBQueriesGeneral.executor); tdMuestraDepartamento(tdDepartamentoSeleccionado); } } } } } } } catch (Exception ex) { MessageBox.Show(this, ex.Message, Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void tdMuestraDepartamento(Departamento dep) { // Se actualiza la base de datos dep.Update(DBQueriesGeneral.executor); // Se actualiza el DataGridView int row = dgvDepartamentos.SelectedRows[0].Index; dgvDepartamentos[0, row].Value = dep["nombre"].Value; dgvDepartamentos[1, row].Value = dep["agranel"].Value; dgvDepartamentos[2, row].Value = dep["activo"].Value; // Se actualiza el ComboBox cmbFiltroDepartamento.Items.RemoveAt(row); cmbFiltroDepartamento.Items.Insert(row, dep["nombre"]); } private void tdMuestraDepartamentos() { catDepartamentos = DBQueriesGeneral.ConsultaDepartamentosProductos(); dgvDepartamentos.Rows.Clear(); cmbFiltroDepartamento.Items.Clear(); foreach (Departamento dep in catDepartamentos) { dgvDepartamentos.Rows.Add(dep["nombre"].Value, dep["agranel"].ToBool(), dep["activo"].ToBool()); dgvDepartamentos.Rows[dgvDepartamentos.RowCount - 1].Visible = !dep["filtro"].ToBool(); cmbFiltroDepartamento.Items.Add(dep["nombre"].ToString()); } if (cmbFiltroDepartamento.Items.Count > 0) { cmbFiltroDepartamento.SelectedIndex = 0; } } private void dgvDepartamentos_SelectionChanged(object sender, EventArgs e) { if (dgvDepartamentos.SelectedRows.Count > 0) { tdDepartamentoSeleccionado = catDepartamentos[dgvDepartamentos.SelectedRows[0].Index]; } else { tdDepartamentoSeleccionado = null; } } #endregion #region Productos private void tpMuestraProductos() { catProductos = DBQueriesGeneral.ConsultaProductos(); dgvProductos.RowCount = catProductos.Count; } private void btnAgregarProducto_Click(object sender, EventArgs e) { if (sender == btnAgregarProducto) { frmProducto prod = new frmProducto("Agregar"); if (prod.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tpMuestraProductos(); /*catProductos[dgvProductos.SelectedRows[0].Index] = prod.Producto; dgvProductos.Refresh();*/ } } if (tpProductoSeleccionado == null) { MessageBox.Show(this, "Debe seleccionar un producto.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { if (sender == btnEditarProducto) { // Si solo es un producto if (dgvProductos.SelectedRows.Count == 1) { frmProducto prod = new frmProducto("Editar", tpProductoSeleccionado); if (prod.ShowDialog(this) == System.Windows.Forms.DialogResult.OK) { tpMuestraProducto(dgvProductos.SelectedRows[0].Index, tpProductoSeleccionado, dgvProductos); } } if (dgvProductos.SelectedRows.Count > 1) { List<Producto> seleccionados = new List<Producto>(); for (int i = 0; i < dgvProductos.SelectedRows.Count; i++) { seleccionados.Add(catProductos[dgvProductos.SelectedRows[i].Index]); } frmModificaProductos prods = new frmModificaProductos(seleccionados.ToArray()); if (prods.ShowDialog() == System.Windows.Forms.DialogResult.OK) { for (int i = 0; i < seleccionados.Count; i++) { tpMuestraProducto(dgvProductos.SelectedRows[i].Index, seleccionados[i], dgvProductos); } } } } if (sender == btnEliminaProducto) { bool plural = dgvProductos.SelectedRows.Count > 1; if (MessageBox.Show(this, !plural ? "¿Esta seguro de eliminar el producto seleccionado?" : "¿Esta seguro de eliminar los productos seleccionados?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.Yes) { foreach (DataGridViewRow row in dgvProductos.SelectedRows) { if (DBQueriesGeneral.EliminaProducto(catProductos[row.Index])) { int rowIdx = dgvProductos.SelectedRows[0].Index; dgvProductos.Rows.RemoveAt(rowIdx); catProductos.RemoveAt(rowIdx); } else { if (MessageBox.Show(this, "No se puedo eliminar el producto seleccionado, ¿desea desactivarlo?", Application.ProductName, MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes) { catProductos[row.Index]["activo"].Value = false.ToString(); catProductos[row.Index].Update(DBQueriesGeneral.executor); tpMuestraProducto(dgvProductos.SelectedRows[0].Index, catProductos[row.Index], dgvProductos); } } } } } } } private void tpMuestraProducto(int row, Producto producto, DataGridView dgv) { dgv[0, row].Value = producto["codigo"].Value; dgv[1, row].Value = producto["descripcion"].Value; dgv[2, row].Value = producto["preciocosto"].Value; dgv[3, row].Value = producto["precioventa"].Value; dgv[4, row].Value = producto["existencia"].Value; dgv[5, row].Value = producto["minimo"].Value; dgv[6, row].Value = producto["nombredepartamento"].Value; dgv[7, row].Value = producto["nombreproveedor"].Value; dgv[8, row].Value = producto["nombreunidadproducto"].Value; dgv[9, row].Value = producto["inventario"].Value; } #endregion private void dgvProductos_SelectionChanged(object sender, EventArgs e) { tpProductoSeleccionado = (dgvProductos.SelectedRows.Count > 0) ? catProductos[dgvProductos.SelectedRows[0].Index] : null; } private void tabPrincipal_SelectedIndexChanged(object sender, EventArgs e) { switch (tabPrincipal.SelectedIndex) { case 0: break; case 1: tbProducto.Focus(); break; } } private void tbProductoSurtir_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { e.Handled = true; BuscarProducto(); } } private void tbCantidadSurtir_KeyPress(object sender, KeyPressEventArgs e) { string validas = ".0123456789"; if (!char.IsControl(e.KeyChar)) { punto = e.KeyChar == '.'; if (!validas.Contains(e.KeyChar) && decimales < maxDecimales) { e.Handled = true; } } } private void btnSurtir_Click(object sender, EventArgs e) { if (tsProcuto == null) { MessageBox.Show(this, "Debe seleccionar un producto", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { double surtir = Convert.ToDouble(ntbSurtir.Text); bool agranel = tsProcuto["agranel"].ToBool(); int isuritr = (int)surtir; bool iguales = surtir == isuritr; if (!agranel && surtir != isuritr) { MessageBox.Show(this, "Este producto solo permite valores enteros.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); ntbSurtir.Focus(); return; } tsProcuto["existencia"].Value = tsProcuto["existencia"].ToDouble() + surtir; tsProcuto.Update(DBQueriesGeneral.executor); tbExistencia.Text = tsProcuto["existencia"].ToDouble().ToString("N2"); ntbSurtir.Clear(); MessageBox.Show(this, "Se ha surtido correctamente.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Information); } } private void BuscarProducto() { tsProcuto = DBQueriesGeneral.ConsultaProductoPorCodigo(tbProducto.Text); if (tsProcuto != null) { tbProducto.SelectAll(); tbDescripcion.Text = tsProcuto["descripcion"].ToString(); tbExistencia.Text = tsProcuto["existencia"].ToDouble().ToString("N2"); ntbSurtir.Focus(); } else { MessageBox.Show(this, "No se encontró un producto con ese código.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } } private void tbFiltroDescripcion_TextChanged(object sender, EventArgs e) { BuscaProductoFiltros(); } private void BuscaProductoFiltros() { dgvProductos.RowCount = 0; catProductos = DBQueriesGeneral.ConsultaProductosFiltros(tbFiltroDescripcion.Text, filtroDepartamento, filtroProveedor); dgvProductos.RowCount = catProductos.Count; } private void cmbFiltroDepartamento_SelectedIndexChanged(object sender, EventArgs e) { filtroDepartamento = (cmbFiltroDepartamento.Items.Count >= 0) ? catDepartamentos[cmbFiltroDepartamento.SelectedIndex] : null; BuscaProductoFiltros(); dgvProductos.Focus(); } private void cmbFiltroProveedor_SelectedIndexChanged(object sender, EventArgs e) { filtroProveedor = (cmbFiltroProveedor.Items.Count >= 0) ? catProveedores[cmbFiltroProveedor.SelectedIndex] : null; BuscaProductoFiltros(); dgvProductos.Focus(); } private void dgvProductos_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e) { if (e.RowIndex < catProductos.Count) { switch (e.ColumnIndex) { case 0: e.Value = catProductos[e.RowIndex]["codigo"]; break; case 1: e.Value = catProductos[e.RowIndex]["descripcion"]; break; case 2: e.Value = catProductos[e.RowIndex]["preciocosto"]; break; case 3: e.Value = catProductos[e.RowIndex]["precioventa"]; break; case 4: e.Value = catProductos[e.RowIndex]["existencia"]; break; case 5: e.Value = catProductos[e.RowIndex]["minimo"]; break; case 6: e.Value = catProductos[e.RowIndex]["nombredepartamento"]; break; case 7: e.Value = catProductos[e.RowIndex]["nombreproveedor"]; break; case 8: e.Value = catProductos[e.RowIndex]["nombreunidadproducto"]; break; case 9: e.Value = catProductos[e.RowIndex]["inventario"].ToBool(); break; case 10: e.Value = catProductos[e.RowIndex]["activo"].ToBool(); break; } } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using MySql.Data.Protocol.Serialization; using MySql.Data.Serialization; namespace MySql.Data.MySqlClient { internal sealed class ConnectionPool { public async Task<MySqlSession> GetSessionAsync(MySqlConnection connection, IOBehavior ioBehavior, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); // if all sessions are used, see if any have been leaked and can be recovered // check at most once per second (although this isn't enforced via a mutex so multiple threads might block // on the lock in RecoverLeakedSessions in high-concurrency situations if (m_sessionSemaphore.CurrentCount == 0 && unchecked(((uint) Environment.TickCount) - m_lastRecoveryTime) >= 1000u) RecoverLeakedSessions(); // wait for an open slot (until the cancellationToken is cancelled, which is typically due to timeout) if (ioBehavior == IOBehavior.Asynchronous) await m_sessionSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); else m_sessionSemaphore.Wait(cancellationToken); try { // check for a waiting session MySqlSession session = null; lock (m_sessions) { if (m_sessions.Count > 0) { session = m_sessions.First.Value; m_sessions.RemoveFirst(); } } if (session != null) { bool reuseSession; if (session.PoolGeneration != m_generation) { reuseSession = false; } else { if (m_connectionSettings.ConnectionReset) { reuseSession = await session.TryResetConnectionAsync(m_connectionSettings, ioBehavior, cancellationToken).ConfigureAwait(false); } else { reuseSession = await session.TryPingAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } } if (!reuseSession) { // session is either old or cannot communicate with the server await session.DisposeAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } else { // pooled session is ready to be used; return it session.OwningConnection = new WeakReference<MySqlConnection>(connection); lock (m_leasedSessions) m_leasedSessions.Add(session.Id, session); return session; } } // create a new session session = new MySqlSession(this, m_generation, Interlocked.Increment(ref m_lastId)); await session.ConnectAsync(m_connectionSettings, ioBehavior, cancellationToken).ConfigureAwait(false); session.OwningConnection = new WeakReference<MySqlConnection>(connection); lock (m_leasedSessions) m_leasedSessions.Add(session.Id, session); return session; } catch { m_sessionSemaphore.Release(); throw; } } private bool SessionIsHealthy(MySqlSession session) { if (!session.IsConnected) return false; if (session.PoolGeneration != m_generation) return false; if (session.DatabaseOverride != null) return false; if (m_connectionSettings.ConnectionLifeTime > 0 && (DateTime.UtcNow - session.CreatedUtc).TotalSeconds >= m_connectionSettings.ConnectionLifeTime) return false; return true; } public void Return(MySqlSession session) { try { lock (m_leasedSessions) m_leasedSessions.Remove(session.Id); session.OwningConnection = null; if (SessionIsHealthy(session)) lock (m_sessions) m_sessions.AddFirst(session); else session.DisposeAsync(IOBehavior.Synchronous, CancellationToken.None).ConfigureAwait(false); } finally { m_sessionSemaphore.Release(); } } public async Task ClearAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { // increment the generation of the connection pool Interlocked.Increment(ref m_generation); RecoverLeakedSessions(); await CleanPoolAsync(ioBehavior, session => session.PoolGeneration != m_generation, false, cancellationToken).ConfigureAwait(false); } public async Task ReapAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { RecoverLeakedSessions(); if (m_connectionSettings.ConnectionIdleTimeout == 0) return; await CleanPoolAsync(ioBehavior, session => (DateTime.UtcNow - session.LastReturnedUtc).TotalSeconds >= m_connectionSettings.ConnectionIdleTimeout, true, cancellationToken).ConfigureAwait(false); } /// <summary> /// Examines all the <see cref="MySqlSession"/> objects in <see cref="m_leasedSessions"/> to determine if any /// have an owning <see cref="MySqlConnection"/> that has been garbage-collected. If so, assumes that the connection /// was not properly disposed and returns the session to the pool. /// </summary> private void RecoverLeakedSessions() { var recoveredSessions = new List<MySqlSession>(); lock (m_leasedSessions) { m_lastRecoveryTime = unchecked((uint) Environment.TickCount); foreach (var pair in m_leasedSessions) { var session = pair.Value; if (!session.OwningConnection.TryGetTarget(out var _)) recoveredSessions.Add(session); } } foreach (var session in recoveredSessions) session.ReturnToPool(); } private async Task CleanPoolAsync(IOBehavior ioBehavior, Func<MySqlSession, bool> shouldCleanFn, bool respectMinPoolSize, CancellationToken cancellationToken) { // synchronize access to this method as only one clean routine should be run at a time if (ioBehavior == IOBehavior.Asynchronous) await m_cleanSemaphore.WaitAsync(cancellationToken).ConfigureAwait(false); else m_cleanSemaphore.Wait(cancellationToken); try { var waitTimeout = TimeSpan.FromMilliseconds(10); while (true) { // if respectMinPoolSize is true, return if (leased sessions + waiting sessions <= minPoolSize) if (respectMinPoolSize) lock (m_sessions) if (m_connectionSettings.MaximumPoolSize - m_sessionSemaphore.CurrentCount + m_sessions.Count <= m_connectionSettings.MinimumPoolSize) return; // try to get an open slot; if this fails, connection pool is full and sessions will be disposed when returned to pool if (ioBehavior == IOBehavior.Asynchronous) { if (!await m_sessionSemaphore.WaitAsync(waitTimeout, cancellationToken).ConfigureAwait(false)) return; } else { if (!m_sessionSemaphore.Wait(waitTimeout, cancellationToken)) return; } try { // check for a waiting session MySqlSession session = null; lock (m_sessions) { if (m_sessions.Count > 0) { session = m_sessions.Last.Value; m_sessions.RemoveLast(); } } if (session == null) return; if (shouldCleanFn(session)) { // session should be cleaned; dispose it and keep iterating await session.DisposeAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } else { // session should not be cleaned; put it back in the queue and stop iterating lock (m_sessions) m_sessions.AddLast(session); return; } } finally { m_sessionSemaphore.Release(); } } } finally { m_cleanSemaphore.Release(); } } public static ConnectionPool GetPool(ConnectionSettings cs) { if (!cs.Pooling) return null; var key = cs.ConnectionString; if (!s_pools.TryGetValue(key, out var pool)) { pool = s_pools.GetOrAdd(cs.ConnectionString, newKey => new ConnectionPool(cs)); } return pool; } public static async Task ClearPoolsAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { foreach (var pool in s_pools.Values) await pool.ClearAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } public static async Task ReapPoolsAsync(IOBehavior ioBehavior, CancellationToken cancellationToken) { foreach (var pool in s_pools.Values) await pool.ReapAsync(ioBehavior, cancellationToken).ConfigureAwait(false); } private ConnectionPool(ConnectionSettings cs) { m_connectionSettings = cs; m_generation = 0; m_cleanSemaphore = new SemaphoreSlim(1); m_sessionSemaphore = new SemaphoreSlim(cs.MaximumPoolSize); m_sessions = new LinkedList<MySqlSession>(); m_leasedSessions = new Dictionary<int, MySqlSession>(); } static readonly ConcurrentDictionary<string, ConnectionPool> s_pools = new ConcurrentDictionary<string, ConnectionPool>(); #if DEBUG static readonly TimeSpan ReaperInterval = TimeSpan.FromSeconds(1); #else static readonly TimeSpan ReaperInterval = TimeSpan.FromMinutes(1); #endif static readonly Task Reaper = Task.Run(async () => { while (true) { var task = Task.Delay(ReaperInterval); try { await ReapPoolsAsync(IOBehavior.Asynchronous, new CancellationTokenSource(ReaperInterval).Token).ConfigureAwait(false); } catch { // do nothing; we'll try to reap again } await task.ConfigureAwait(false); } }); int m_generation; readonly SemaphoreSlim m_cleanSemaphore; readonly SemaphoreSlim m_sessionSemaphore; readonly LinkedList<MySqlSession> m_sessions; readonly ConnectionSettings m_connectionSettings; readonly Dictionary<int, MySqlSession> m_leasedSessions; int m_lastId; uint m_lastRecoveryTime; } }
using Akka.Actor; using AkkaOverview.Streaming.ActorSystem; namespace AkkaOverview.Gateway { public class ApiGateway : IGateway { public void Candles(string instrument) { var system = ActorSystem.Create("Streaming"); var actor = system.ActorOf<StreamActor>("stream"); actor.Tell(new GetTickMessage(instrument)); } } public interface IGateway { void Candles(string instrument); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ValidationExtensions.Enums; using System.Security.Cryptography.X509Certificates; using ValidationExtensions.Model; namespace ValidationExtensions.Service.ExpiryDate { public interface ExpiryDateService { ValidationResponse ValidateCertificate(X509Certificate2 certificate); } }
/* * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * * == AUCTION MASTER == * * Author: Henrique Fantini * Contact: contact@henriquefantini.com * * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + * * Auction Master is a software with the objective to collect and process data * from World of Warcraft's auction house. The idea behind this is display data * and graphics about the market of each realm and analyse your movimentation. * * + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + */ // == IMPORTS // ============================================================================== using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; // == NAMESPACE // ============================================================================== namespace AuctionMaster.App.Enumeration { // == ENUM // ========================================================================== public enum ApiResponseType { OK = 1, FAIL = 2 } }
using System; using NUnit.Framework; [TestFixture] class EntpTests29 { [Test] public void getEmployeesBySalaryThrowException() { IEnterprise enterprise = new Enterprise(); Employee employee = new Employee("pesho", "123", 777, Position.Hr, DateTime.Now); Employee employee1 = new Employee("a", "321", 123, Position.Owner, DateTime.Now); Employee employee2 = new Employee("c", "111", 1, Position.Hr, DateTime.Now); Employee employee3 = new Employee("d", "11111", 231, Position.Developer, DateTime.Now); enterprise.Add(employee); enterprise.Add(employee1); enterprise.Add(employee2); enterprise.Add(employee3); Employee[] employees = new Employee[] { employee1, employee2, employee3, employee }; Assert.Throws<InvalidOperationException>(() => enterprise.GetBySalary(1000000)); } }
using System; using System.Text; namespace Sky { // Общие константы и методы для астрономических объектов static class Astronomy { public static double SolarMassKg() { return 1.989E30; } public static double KmInParsek() { return 3.086E13; } public static double KmInLightYear() { return 9.461E12; } public static double KmInAstronomicalUnit() { return 1.496E8; } public static double SolarRadiusKm() { return 6.96E5; } public static double GravitationalConstant() { return 6.674E-11; } public static double EarthGravity() { return 9.80665; } public static double LightSpeedMS() { return 299792458; } public static StringBuilder GenerateRandomObjectName() { Random random = new Random(); StringBuilder name = new StringBuilder(); int len = random.Next(20) + 10; for (int i = 0; i < len; i++) { name.Append((char)random.Next('A', 'Z')); } return name; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace VerifyParameter.Data.ResultData { public class AttributeData { public string AttributeCode { get; set; } public string AttributeName { get; set; } public bool Status { get; set; } private List<string> _ErrorList; public List<string> ErrorList { get { if (_ErrorList == null) { _ErrorList = new List<string>(); } return _ErrorList; } set { _ErrorList = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Rocket.API; using System.Xml.Serialization; using UnityEngine; using Steamworks; namespace AnomWhitelist { public class PluginConfiguration : IRocketPluginConfiguration { public ulong? WhiteListedID; public void LoadDefaults() { WhiteListedID = 76561198271849972; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using DelftTools.Functions; using DelftTools.Utils.Data; using GeoAPI.Extensions.Coverages; using GeoAPI.Extensions.Networks; using ValidationAspects; namespace NetTopologySuite.Extensions.Coverages { /// <summary> /// Class to convert Networklocations to NetCdf formats.Id now needed for NHibernate :( /// </summary> //TODO : get rid of this ID and map this class as a component of the store. // Note this might conflict with the Network reference public class NetworkLocationTypeConverter : TypeConverterBase<INetworkLocation> { public virtual INetwork Network { get; set; } public override Type[] StoreTypes { get { return new[] {typeof (int), typeof (double), typeof (double), typeof (double)}; } } public override string[] VariableNames { get { return new[] { "branch_index", "branch_offset", "x", "y" }; } } /// <summary> /// Network coverage associated with this network location (if any). /// TODO: check if we can't incapsulate it in the NetCDF class, or as a NetworkCoverageTypeConverter, otherwise rename this class to NetworkCoverageLocationTypeConverter /// </summary> public virtual INetworkCoverage Coverage { get; set; } public override INetworkLocation ConvertFromStore(object source) { var sourceTuple = (object[]) source; var branchIdx = Convert.ToInt32(sourceTuple[0]); var offset = Convert.ToDouble(sourceTuple[1]); var branch = Network.Branches[branchIdx];// First(b => b.Id == branchId); var location = new NetworkLocation(branch, offset); return location; } public override object[] ConvertToStore(INetworkLocation source) { //a tuple of brand ID and offset. Long is not supported by netcdf!? var idx = source.Network.Branches.IndexOf(source.Branch); return new object[] {idx, source.Offset, source.Geometry.Centroid.X, source.Geometry.Centroid.Y }; } public NetworkLocationTypeConverter() { } public NetworkLocationTypeConverter(INetwork network) { Network = network; } } }
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Magic.Spells; using StardewValley; using StardewValley.Monsters; using StardewValley.Projectiles; using StardewValley.TerrainFeatures; using System; namespace Magic.Game { class SpellProjectile : Projectile { private readonly Farmer source; private readonly ProjectileSpell spell; private readonly int damage; private readonly float dir; private readonly float vel; private Texture2D tex; private string texId; public SpellProjectile(Farmer theSource, ProjectileSpell theSpell, int dmg, float theDir, float theVel ) { source = theSource; spell = theSpell; damage = dmg; dir = theDir; vel = theVel; theOneWhoFiredMe.Set(theSource.currentLocation, source ); position.Value = source.getStandingPosition(); position.X += source.GetBoundingBox().Width; position.Y += source.GetBoundingBox().Height; rotation = theDir; xVelocity.Value = (float) Math.Cos(dir) * vel; yVelocity.Value = (float) Math.Sin(dir) * vel; damagesMonsters.Value = true; tex = Content.loadTexture("magic/" + spell.ParentSchoolId + "/" + spell.Id + "/projectile.png"); texId = Content.loadTextureKey("magic/" + spell.ParentSchoolId + "/" + spell.Id + "/projectile.png"); } public override void behaviorOnCollisionWithMineWall(int tileX, int tileY) { //disappear(loc); } public override void behaviorOnCollisionWithMonster(NPC npc, GameLocation loc) { if (!(npc is Monster)) return; loc.damageMonster(npc.GetBoundingBox(), damage, damage + 1, false, source); if (source != null) source.addMagicExp(damage); disappear(loc); } public override void behaviorOnCollisionWithOther(GameLocation loc) { disappear(loc); } public override void behaviorOnCollisionWithPlayer(GameLocation loc, Farmer farmer) { } public override void behaviorOnCollisionWithTerrainFeature(TerrainFeature t, Vector2 tileLocation, GameLocation loc) { disappear( loc ); } public override Rectangle getBoundingBox() { return new Rectangle(( int )(position.X - Game1.tileSize), (int)(position.Y - Game1.tileSize), Game1.tileSize / 2, Game1.tileSize / 2); } public override void updatePosition(GameTime time) { //if (true) return; position.X += xVelocity; position.Y += yVelocity; } /* public override bool isColliding(GameLocation location) { Log.trace("iscoll"); return false; if (!location.isTileOnMap(this.position / (float)Game1.tileSize) || !this.ignoreLocationCollision && location.isCollidingPosition(this.getBoundingBox(), Game1.viewport, false, 0, true, this.theOneWhoFiredMe, false, true, false) || !this.damagesMonsters && Game1.player.GetBoundingBox().Intersects(this.getBoundingBox())) return true; if (this.damagesMonsters) return location.doesPositionCollideWithCharacter(this.getBoundingBox(), false) != null; return false; }*/ public override void draw(SpriteBatch b) { Vector2 drawPos = Game1.GlobalToLocal(new Vector2(getBoundingBox().X + getBoundingBox().Width / 2, getBoundingBox().Y + getBoundingBox().Height / 2)); b.Draw(tex, drawPos, new Rectangle( 0, 0, tex.Width, tex.Height ), Color.White, dir, new Vector2( tex.Width / 2, tex.Height / 2 ), 2, SpriteEffects.None, (float)(((double)this.position.Y + (double)(Game1.tileSize * 3 / 2)) / 10000.0)); //Vector2 bdp = Game1.GlobalToLocal(new Vector2(getBoundingBox().X, getBoundingBox().Y)); //b.Draw(Mod.instance.manaFg, new Rectangle((int)bdp.X, (int)bdp.Y, getBoundingBox().Width, getBoundingBox().Height), Color.White); } private static Random rand = new Random(); private void disappear( GameLocation loc ) { if ( spell.SoundHit != null ) Game1.playSound( spell.SoundHit ); //Game1.createRadialDebris(loc, 22 + rand.Next( 2 ), ( int ) position.X / Game1.tileSize, ( int ) position.Y / Game1.tileSize, 3 + rand.Next(5), false); Game1.createRadialDebris(loc, texId, Game1.getSourceRectForStandardTileSheet(Projectile.projectileSheet,0), 4, (int)this.position.X, (int)this.position.Y, 6 + rand.Next( 10 ), (int)((double)this.position.Y / (double)Game1.tileSize) + 1, new Color( 255, 255, 255, 8 + rand.Next( 64 ) ), 2.0f); //Game1.createRadialDebris(loc, tex, new Rectangle(0, 0, tex.Width, tex.Height), 0, ( int ) position.X, ( int ) position.Y, 3 + rand.Next(5), ( int ) position.Y / Game1.tileSize, Color.White, 5.0f); destroyMe = true; } } }
namespace WeatherForecast.Tests { class HomeControllerTests { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BroomScript : MonoBehaviour { private Vector3 startPos; private Vector3 endPos; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (Input.GetKey (KeyCode.A) || Input.GetKey (KeyCode.LeftArrow)) { transform.position += new Vector3 (0f, 0f, 1f) * 0.5f; } if (Input.GetKey (KeyCode.D) || Input.GetKey (KeyCode.RightArrow)) { transform.position -= new Vector3 (0f, 0f, 1f) * 0.5f; } } }
using System; namespace ReferenceTypes { class Program { static void Main(string[] args) { Console.WriteLine("=======REFERENCE TYPES=======\n"); string metin1 = "Merhaba"; string metin2 = "Güle Güle"; metin1 = metin2; metin2 = "Hoşça kal\n"; Console.WriteLine(metin2); int[] sayilar1 = new int[] { 1, 2, 3 }; int[] sayilar2 = new int[] { 10, 20, 30 }; sayilar1 = sayilar2; sayilar2[0] = 1000; Console.WriteLine(sayilar2[0]+"\n"); Console.WriteLine("=======VALUE TYPES=======\n"); int sayi1 = 10; int sayi2 = 20; sayi1 = sayi2; sayi2 = 200; Console.WriteLine(sayi1); } } }
using System; using System.Collections.Generic; using LoLInfo.Models; using Xamarin.Forms; namespace LoLInfo.Views { public partial class ChampionSkinsView : CarouselPage { public ChampionSkinsView(List<Skin> skins) { InitializeComponent(); ItemsSource = skins; } } }
using AnotherApp.Data; namespace AnotherApp.Client { class Startup { static void Main(string[] args) { var context = new AnotherAppEntities(); } } }
using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using Reacher.Notification.Pushover; using Reacher.Shared.Extensions; using Reacher.Shared.Utils; using Reacher.Source.Twitter.Configuration; using Reacher.Storage.Data.Models; using Reacher.Storage.File.Json; using System; using System.Collections.Generic; using System.Linq; using Tweetinvi; using Tweetinvi.Models; using Tweetinvi.Parameters; namespace Reacher.Source.Twitter { public class SourceTwitterService { private readonly IOptions<SourceTwitterConfiguration> _configuration; private readonly ILogger<SourceTwitterService> _logger; private readonly INotificationPushoverService _pushoverNotification; private readonly IStorageFileJsonService _storageFileJson; private readonly ITwitterCredentials _twitterCredentials; public SourceTwitterService( IOptions<SourceTwitterConfiguration> configuration, ILogger<SourceTwitterService> logger, INotificationPushoverService pushoverNotification, IStorageFileJsonService storageFileJson) { _configuration = configuration; _logger = logger; _pushoverNotification = pushoverNotification; _storageFileJson = storageFileJson; _twitterCredentials = Auth.CreateCredentials( _configuration.Value.AccessKeys.ConsumerKey, _configuration.Value.AccessKeys.ConsumerSecret, _configuration.Value.AccessKeys.UserAccessToken, _configuration.Value.AccessKeys.UserAccessSecret); } public void Collect() { var newContent = new Content(); Auth.ExecuteOperationWithCredentials(_twitterCredentials, () => { var timeline = Timeline.GetUserTimeline(_configuration.Value.Accounts.First()); if(timeline.AnyAndNotNull()) { var firstTweet = timeline.First(); newContent.Id = firstTweet.IdStr; newContent.Message = firstTweet.Text; } }); try { var allContent = _storageFileJson.GetAll(); if (!allContent.Any()) { Store(newContent); } else { if (!allContent.Any(c => string.Equals(c.Id, newContent.Id))) { Store(newContent); } else { _logger.LogInformation($"{newContent.ToString()} already prepared for publish."); } } } catch (Exception) { var message = $"{newContent.ToString()} not stored for publish."; _logger.LogError(message); _pushoverNotification.Send(Titles.CollectorTwitterHeader, message); } } private void Store(Content newContent) { if(newContent.IsProvided) { _storageFileJson.Save(newContent); var message = $"{newContent.ToString()} stored for publish."; _logger.LogInformation(message); _pushoverNotification.Send(Titles.CollectorTwitterHeader, message); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; interface Movable { void MovementController(); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using GodMorgon.Sound; namespace GodMorgon.StateMachine { public class Player_Turn : State { public override void OnStartState() { //Debug.Log("On Player turn State"); GameManager.Instance.DownPanelBlock(false); GameManager.Instance.UpdateCardDataDisplay(); GameManager.Instance.ShowPlayerTurnImage(); GameManager.Instance.UnlockDragCardHandler(true); } } }
using System; using System.Collections.Generic; using System.Text; namespace UDemyCSharpIntermediate { abstract class DbConnection { private readonly string _connectionString; protected TimeSpan _timeout = TimeSpan.FromSeconds(60); public DbConnection(string connectionString) { if (string.IsNullOrWhiteSpace(connectionString)) { throw new ArgumentException("Cannot create a DbConnection with a null or empty connection."); } this._connectionString = connectionString; } public abstract void OpenConnection(); public abstract void CloseConnection(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CCF.WatchLog { public interface ILoger { void WriteLog(List<LogEntity> logs); } }
namespace VMDiagrammer.Models { /// <summary> /// A base class for all model objects in the VM Diagrammer program. /// Handles unique ID creation /// </summary> public class BaseVMObject { private static double currentIndex = 0; private double m_Index = 0; // our object's id private double m_Thickness = 1; // the line thickness of this object public BaseVMObject() { m_Index = currentIndex; currentIndex++; } public double Index { get { return m_Index; } private set { m_Index = value; } } public double Thickness { get { return m_Thickness; } set { m_Thickness = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WindowsFormsApp6 { public class myDBconnection { public string conStr = @"Data Source=DESKTOP-UUJDJS9;Initial Catalog=atmApp;Integrated Security=True"; public int AccountNumber() { Random rand = new Random(); int accountNumber = rand.Next(000000000, 999999999); return accountNumber; } public int UniqueAccountNumber() { Random random = new Random(); int _uniqueNum = random.Next(000000000, 999999999); return _uniqueNum; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Globalization; namespace PolynomialTask1 { public struct Monomial { public int power; public double coefficient; } public class Polynomial : IComparable<Polynomial>, ICloneable, IEquatable<Polynomial> { #region Monomial int[] power; double[] coefficient; int length; #endregion #region ctor public Polynomial() : this(16) { } private void Initialize(int len) { if (len < 1) len = 1; power = new int[len]; coefficient = new double[len]; length = 0; } public Polynomial(params Monomial[] param) : this(param.Length) { for (int i = 0; i < param.Length; i++) { InsertMonomial(this, param[i].power, param[i].coefficient); } Normalization(this); } public Polynomial(int len) { Initialize(len); } public Polynomial(Polynomial polynomial) { if (polynomial != null) { Initialize(polynomial.length); Array.Copy(polynomial.power, power, polynomial.length); Array.Copy(polynomial.coefficient, coefficient, polynomial.length); length = polynomial.length; } else Initialize(16); } public Polynomial(string param) { if (!string.IsNullOrEmpty(param)) { Initialize(16); GetPolynomialFromString(this, param); Normalization(this); } else Initialize(16); } #endregion #region operators #region polinomial polinomial public static Polynomial operator +(Polynomial a, Polynomial b) { if (a == null) return b; else if (b == null) return a; return Normalization(PolynomialMerge(a, b, +1)); } public static Polynomial operator -(Polynomial a, Polynomial b) { if (a == null) return b; else if (b == null) return a; return Normalization(PolynomialMerge(a, b, -1)); } public static Polynomial operator *(Polynomial a, Polynomial b) { if (a == null) return b; else if (b == null) return a; Polynomial result = GetProduct(a, b.power[0], b.coefficient[0]); Polynomial temp; for (int i = 1; i < b.length; i++) { temp = GetProduct(a, b.power[i], b.coefficient[i]); result = PolynomialMerge(result, temp, +1); } return Normalization(result); } public static Polynomial operator /(Polynomial a, Polynomial b) { if (a == null) return b; else if (b == null) return a; Polynomial rem; return Normalization(GetDevideResult(a, b, out rem)); } public static Polynomial operator %(Polynomial a, Polynomial b) { if (a == null) return b; else if (b == null) return a; Polynomial rem; GetDevideResult(a, b, out rem); return Normalization(rem); } #endregion #region string polinomial public static Polynomial operator +(string str, Polynomial b) { Polynomial a = new Polynomial(); GetPolynomialFromString(a, str); return a+b; } public static Polynomial operator -(string str, Polynomial b) { Polynomial a = new Polynomial(); GetPolynomialFromString(a, str); return a - b; } public static Polynomial operator *(string str, Polynomial b) { Polynomial a = new Polynomial(); GetPolynomialFromString(a, str); return a * b; } public static Polynomial operator /(string str, Polynomial b) { Polynomial a = new Polynomial(); GetPolynomialFromString(a, str); return a / b; } public static Polynomial operator %(string str, Polynomial b) { Polynomial a = new Polynomial(); GetPolynomialFromString(a, str); return a % b; } #endregion #region polinomial string public static Polynomial operator +(Polynomial a, string str) { Polynomial b = new Polynomial(); GetPolynomialFromString(b, str); return a + b; } public static Polynomial operator -(Polynomial a, string str) { Polynomial b = new Polynomial(); GetPolynomialFromString(b, str); return a - b; } public static Polynomial operator *(Polynomial a, string str) { Polynomial b = new Polynomial(); GetPolynomialFromString(b, str); return a * b; } public static Polynomial operator /(Polynomial a, string str) { Polynomial b = new Polynomial(); GetPolynomialFromString(b, str); return a / b; } public static Polynomial operator %(Polynomial a, string str) { Polynomial b = new Polynomial(); GetPolynomialFromString(b, str); return a % b; } #endregion #endregion #region alternative for operators #region polinomial polinomial public static Polynomial Add(Polynomial a, Polynomial b) { return a + b; } public static Polynomial Subtract(Polynomial a, Polynomial b) { return a - b; } public static Polynomial Multiply(Polynomial a, Polynomial b) { return a * b; } public static Polynomial Divide(Polynomial a, Polynomial b) { return a / b; } public static Polynomial Mod(Polynomial a, Polynomial b) { return a % b; } #endregion #region string polinomial public static Polynomial Add(string a, Polynomial b) { return a + b; } public static Polynomial Subtract(string a, Polynomial b) { return a - b; } public static Polynomial Multiply(string a, Polynomial b) { return a * b; } public static Polynomial Divide(string a, Polynomial b) { return a / b; } public static Polynomial Mod(string a, Polynomial b) { return a % b; } #endregion #region polinomial string public static Polynomial Add(Polynomial a, string b) { return a + b; } public static Polynomial Subtract(Polynomial a, string b) { return a - b; } public static Polynomial Multiply(Polynomial a, string b) { return a * b; } public static Polynomial Divide(Polynomial a, string b) { return a / b; } public static Polynomial Mod(Polynomial a, string b) { return a % b; } #endregion #endregion #region interface realisation public object Clone() { return new Polynomial(this); } public int CompareTo(Polynomial other) { if (other == null) return 1; int lenOther = other.length - 1, len = length - 1; while (len >= 0 && lenOther >= 0) { if (other.power[lenOther] < power[len]) return 1; if (other.power[lenOther] > power[len]) return -1; if (other.coefficient[lenOther] < coefficient[len]) return 1; if (other.coefficient[lenOther] > coefficient[len]) return -1; len--; lenOther--; } if (len >= 0) return 1; else if (lenOther >= 0) return 1; else return 0; } public bool Equals(Polynomial other) { return this.ToString() == other.ToString(); } #endregion #region overrides public override string ToString() { StringBuilder sb = new StringBuilder(); for (int i = length - 1; i >= 0; i--) { if ((power[i] == 0) || (power[i] != 0 && coefficient[i] != 1)) { sb.AppendFormat("{0:0.00}", coefficient[i]); } if (power[i] != 0) { sb.Append("x"); if (power[i] != 1) sb.AppendFormat("^{0}", power[i]); } if ((i > 0) && (coefficient[i - 1] >= 0)) sb.Append("+"); } string str; if ((str = sb.ToString()) == "") str = "0"; return str; } public override bool Equals(object other) { if (!(other is Polynomial)) return false; return Equals((Polynomial)other); } public override int GetHashCode() { return this.ToString().GetHashCode(); } #endregion //removes zero coefficient monomials private static Polynomial Normalization(Polynomial a) { int skip = 0, i = 0; while ((i < a.length) && (!DoubleEqual(a.coefficient[i], 0))) i++; for (; i < a.length; i++) { if (DoubleEqual(a.coefficient[i], 0)) { skip++; } else { a.coefficient[i - skip] = a.coefficient[i]; a.power[i - skip] = a.power[i]; } } a.length -= skip; return a; } private static bool DoubleEqual(double a, double b) { const double eps = 1E-2; return Math.Abs(a - b) < eps; } private static Polynomial GetProduct(Polynomial a, int power, double coefficient) { Polynomial result = new Polynomial(a); for (int i = 0; i < a.length; i++) { result.power[i] += power; result.coefficient[i] *= coefficient; } return result; } private static Polynomial GetDevideResult(Polynomial a, Polynomial b, out Polynomial remainder) { int lastA = a.length - 1, lastB = b.length - 1; int countOfIteration = (a.power[lastA] - a.power[0]) - (b.power[lastB] - b.power[0]) + 1; Polynomial temp; Polynomial result = new Polynomial(countOfIteration); remainder = a; if (countOfIteration > 0) { for (int i = 0; i < countOfIteration; i++) { int powerMul = remainder.power[lastA] - b.power[lastB]; double coefficientMul = remainder.coefficient[lastA] / b.coefficient[lastB]; InsertMonomial(result, powerMul, coefficientMul); temp = GetProduct(b, powerMul, coefficientMul); remainder = Normalization(PolynomialMerge(remainder, temp, -1)); lastA = remainder.length - 1; } } else { result = new Polynomial(); remainder = new Polynomial(a); } return result; } private static void InsertMonomial(Polynomial a, int power, double coefficient) { int j = 0; while ((a.power[j] < power) && (j < a.length)) j++; if (j < a.length) { if (a.power[j] > power) AddMonomial(a, power, coefficient, j); else { a.coefficient[j] += coefficient; } } else { a.power[a.length] = power; a.coefficient[a.length] = coefficient; a.length++; } } private static Polynomial PolynomialMerge(Polynomial a, Polynomial b, int sign) { Polynomial result = new Polynomial(a); for (int i = 0; i < b.length; i++) { int j = 0; while ((j < result.length) && (b.power[i] > result.power[j])) { j++; continue; } if (j == result.length) AddMonomial(result, b.power[i], (sign * b.coefficient[i]), result.length); else if (b.power[i] == result.power[j]) { result.coefficient[j] += (sign * b.coefficient[i]); } else AddMonomial(result, b.power[i], (sign * b.coefficient[i]), j); } return result; } private static void AddMonomial(Polynomial a, int power, double coefficient, int position) { int[] tempPower; double[] tempCoefficient; if (a.length == a.power.Length) { tempPower = new int[a.length * 2]; tempCoefficient = new double[a.length * 2]; } else { tempPower = new int[a.power.Length]; tempCoefficient = new double[a.coefficient.Length]; } tempPower[position] = power; tempCoefficient[position] = coefficient; int shift = 0; for (int i = 0; i <= a.length; i++) { if (i == position) { shift--; } else { tempPower[i] = a.power[i + shift]; tempCoefficient[i] = a.coefficient[i + shift]; } } a.length++; a.power = tempPower; a.coefficient = tempCoefficient; } private static void GetPolynomialFromString(Polynomial a, string polinom) { int power = 0; double coefficient = 0; while (GetMonomialFromString(ref polinom, ref power, ref coefficient)) { InsertMonomial(a, power, coefficient); } } private static bool GetMonomialFromString(ref string polinom, ref int power, ref double coefficient) { power = 0; coefficient = 1; Regex regular = new Regex(@"-?[0-9]+([.,][0-9]+)?"); Match teg = regular.Match(polinom); string str = teg.ToString(); int countIndex = polinom.IndexOf(str); int xIndex = polinom.IndexOf('x'); if (((xIndex < 0) || (xIndex > countIndex)) && (teg.Success)) { coefficient = double.Parse(str.Replace(',', '.'), CultureInfo.InvariantCulture); polinom = polinom.Remove(0, countIndex + teg.ToString().Length); } else if (xIndex > 0) { polinom = polinom.Remove(0, xIndex); } if (string.IsNullOrEmpty(polinom)) { if (teg.Success) return true; else return false; } if (polinom[0] == 'x') { if ((polinom.Length>1)&&(polinom[1] == '^')) { regular = new Regex(@"-?[0-9]+"); teg = regular.Match(polinom); if (int.TryParse(teg.ToString(), out power)) { polinom = polinom.Remove(polinom.IndexOf(teg.ToString()) - 2, teg.ToString().Length + 2); } else { power = 1; polinom = polinom.Remove(0, 2); } } else { power = 1; polinom = polinom.Remove(0, 1); } } return true; } } }
using System.Security.Claims; using System.Threading.Tasks; using AspNetCore.Security.CAS; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CookieSample { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } public void ConfigureServices(IServiceCollection services) { // Setup based on https://github.com/aspnet/Security/tree/rel/2.0.0/samples/SocialSample services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme) .AddCookie(o => { o.LoginPath = new PathString("/login"); o.AccessDeniedPath = new PathString("/access-denied"); o.Cookie = new CookieBuilder { Name = ".AspNetCore.CasSample" }; o.Events = new CookieAuthenticationEvents { // Add user roles to the existing identity. // This example is giving every user "User" and "Admin" roles. // You can use services or other logic here to determine actual roles for your users. OnSigningIn = context => { // Use `GetRequiredService` if you have a service that is using DI or an EF Context. // var username = context.Principal.Identity.Name; // var userSvc = context.HttpContext.RequestServices.GetRequiredService<UserService>(); // var roles = userSvc.GetRoles(username); // Hard coded roles. var roles = new[] { "User", "Admin" }; // `AddClaim` is not available directly from `context.Principal.Identity`. // We can add a new empty identity with the roles we want to the principal. var identity = new ClaimsIdentity(); foreach (var role in roles) { identity.AddClaim(new Claim(ClaimTypes.Role, role)); } context.Principal.AddIdentity(identity); return Task.FromResult(0); } }; }) .AddCAS(o => { o.CasServerUrlBase = Configuration["CasBaseUrl"]; // Set in `appsettings.json` file. o.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; }); services.AddMvc(); //// You can make the site require Authorization on all endpoints by default: //var globalAuthPolicy = new AuthorizationPolicyBuilder() // .RequireAuthenticatedUser() // .Build(); //services.AddMvc(options => //{ // options.Filters.Add(new AuthorizeFilter(globalAuthPolicy)); //}); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseAuthentication(); app.UseMvcWithDefaultRoute(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameMode : MonoBehaviour { public static GameMode instance; [HideInInspector] public GameObject guidObj; //引导物体 public Transform guideTrs; //存储下一步生成道路坐标以及位置信息 public GameObject roadTemplate; //道路模板 int buidfound = 0; //确定转向后的回合数 public List<GameObject> roads; //保存现在能够进行还原的道路 public bool isBuidDirRoad; //是否生成方向道路 int dirRoadType; //方向道路的类型 int dirRoadNumber; //方向道路的数量 [HideInInspector] public int goldNumber; //吃到的金币数 public Text numberText; //数量的显示文本 private void Awake() { instance = this; } private void Start() { numberText = GameObject.Find("Canvas/GoldNumber").GetComponent<Text>(); guidObj = Instantiate(roadTemplate); guidObj.transform.position = Vector3.zero; guidObj.transform.rotation = Quaternion.identity; guidObj.name = "Guid"; guideTrs = guidObj.transform; //上面实例化生成引导物体并存储下一步的道路信息 for (int i=0;i<20;i++) //预先生成20格道路作为跑道 { var tmpRoad = Instantiate(roadTemplate,guideTrs.position,guideTrs.rotation); guideTrs.position += guideTrs.forward; //每生成一个道路,引导物体的位置改变 } for (int i=0;i<30;i++) { BuidRoad(); //先生成30个动画效果 } } private void Update() { numberText.text ="当前金币数:"+ goldNumber.ToString(); } /// <summary> /// 生成道路的方法 /// </summary> public void BuidRoad() { if (isBuidDirRoad && dirRoadNumber > 0) { switch (dirRoadType) { case 1: BuidUpTerrain(); dirRoadNumber--; break; case 2: BuidDownTerrain(); dirRoadNumber--; break; case 3: BuidLeftTerrain(); dirRoadNumber--; break; case 4: BuidRightTerrain(); dirRoadNumber--; break; } if (dirRoadNumber <= 0) { isBuidDirRoad = false; } } else { int turnSeed = Random.Range(1, 12); //用于确定是否转向 if (turnSeed == 1 && buidfound <= 0) { buidfound = 10; //回合数更新 int dictSeed = Random.Range(1, 3); for (int i = 0; i < 3; i++) //先生成3个格子的道路,作为转向区 { var tmpRoad = Instantiate(roadTemplate, guideTrs.position, guideTrs.rotation); PlayRoadAnimator(tmpRoad); roads.Add(tmpRoad); guideTrs.position += guideTrs.forward; } if (dictSeed == 1) { guideTrs.position -= guideTrs.forward * 2; //转向区域生成完成后,引导物体回退2格 guideTrs.Rotate(Vector3.up, 90); //转向 guideTrs.position += guideTrs.forward * 2; //转向后引导物体的forward轴改变,改变pos值,到达下一个道路的生成地点 } else { guideTrs.position -= guideTrs.forward * 2; guideTrs.Rotate(Vector3.up, -90); guideTrs.position += guideTrs.forward * 2; } } else if (turnSeed == 3) { int trunTerrain = Random.Range(1, 5); isBuidDirRoad = true; dirRoadType = trunTerrain; dirRoadNumber = 10; switch (trunTerrain) { case 1: BuidUpTerrain(); dirRoadNumber--; break; case 2: BuidDownTerrain(); dirRoadNumber--; break; case 3: BuidLeftTerrain(); dirRoadNumber--; break; case 4: BuidRightTerrain(); dirRoadNumber--; break; } } else if (turnSeed==6) { BuidTrapRoad(); } else { var tmpRoad = Instantiate(roadTemplate, guideTrs.position, guideTrs.rotation); PlayRoadAnimator(tmpRoad); roads.Add(tmpRoad); guideTrs.position += guideTrs.forward; //每生成一个道路,引导物体的位置改变 } buidfound--; } } /// <summary> /// 生成上升地形 /// </summary> public void BuidUpTerrain() { var tmpRoad = Instantiate(roadTemplate, guideTrs.position, guideTrs.rotation); PlayRoadAnimator(tmpRoad); roads.Add(tmpRoad); guideTrs.position += guideTrs.forward; guideTrs.position += guideTrs.up * 0.2f; } /// <summary> /// 生成下降地图 /// </summary> public void BuidDownTerrain() { var tmpRoad = Instantiate(roadTemplate, guideTrs.position, guideTrs.rotation); PlayRoadAnimator(tmpRoad); roads.Add(tmpRoad); guideTrs.position += guideTrs.forward; guideTrs.position -= guideTrs.up * 0.2f; } /// <summary> /// 生成左斜地图 /// </summary> public void BuidLeftTerrain() { var tmpRoad = Instantiate(roadTemplate, guideTrs.position, guideTrs.rotation); PlayRoadAnimator(tmpRoad); roads.Add(tmpRoad); guideTrs.position += guideTrs.forward; guideTrs.position -= guideTrs.right * 0.2f; } /// <summary> /// 生成右斜地图 /// </summary> public void BuidRightTerrain() { var tmpRoad = Instantiate(roadTemplate, guideTrs.position, guideTrs.rotation); PlayRoadAnimator(tmpRoad); roads.Add(tmpRoad); guideTrs.position += guideTrs.forward; guideTrs.position += guideTrs.right * 0.2f; } /// <summary> /// 生成陷阱地图 /// </summary> public void BuidTrapRoad() { guideTrs.position += guideTrs.forward; var tmpRoad = Instantiate(roadTemplate, guideTrs.position, guideTrs.rotation); var tmpController = tmpRoad.GetComponent<RoadController>(); tmpController.ChangeRoadType(); tmpRoad.transform.Rotate(Vector3.up,90); int trapType = Random.Range(1,4); //用于确定陷阱的相对位置--1左边,2居中,3右边! switch (trapType) { case 1: tmpRoad.transform.position += tmpRoad.transform.forward; break; case 2: break; case 3: tmpRoad.transform.position -= tmpRoad.transform.forward; break; } guideTrs.position += guideTrs.forward * 2.0f; PlayRoadAnimator(tmpRoad); roads.Add(tmpRoad); } /// <summary> /// 播放道路动画 /// </summary> /// <param name="road"></param> public void PlayRoadAnimator(GameObject road) { var tmpRoadController = road.GetComponent<RoadController>(); if (tmpRoadController==null) { return; } tmpRoadController.ChangeChildrens(); } /// <summary> /// 关闭动画 /// </summary> public void CloseRoadAnimator() { if (roads.Count<=0) { return; } var tmpRoadController = roads[0].GetComponent<RoadController>(); if (tmpRoadController!=null) { tmpRoadController.InitChildrens(); } roads.RemoveAt(0); } }
using RRExpress.Service.Entity; namespace RRExpress.AppCommon.Models { /// <summary> /// 选择的区域 /// </summary> public class ChoicedRegion { public string FullName { get; set; } public Region Region { get; set; } public string ProvinceName { get; set; } public string CityName { get; set; } public string CountyName { get; set; } public string TownName { get; set; } public string DetailAddress { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Fractions { class Fractions { public int nom;//числитель public int denom;//знаменатель public int full;//множитель числителя static int resNom;//числитель - результат операции static int resDenom;//знаменатель - результат операции static int resFull;//множитель - результат операции public Fractions(int denom, int nom,int full)//конструктор для инициализации данных нового объекта. Класс может иметь несколько конструкторов,принимающих различные аргументы. { this.full = full;//отмечаем, что обращение идёт именно к полям класса. this.nom = nom; this.denom = denom; } static int NOK(int denom1, int denom2)//вычисление НОК(наименьшего общего кратного) знаменателя дробей. { int newDenom = 0; if (denom1 < denom2) { do { newDenom += denom1; } while (newDenom % denom2 != 0); // oneDenom = newDenom; } else { do { newDenom += denom2; } while (newDenom % denom1 != 0); // oneDenom += newDenom; } return newDenom; } static int NomCoef(int nom, int denom, int resDenom)//Умножение числителя на коэфициент, полученный через деление общего знаменателя на частный. { int sum = nom*(resDenom / denom); return sum; } static int ForFull(int full1,int full2, int nom, int denom)//вычисление множителя для объекта сложения { int full = full1 + full2; while (nom > denom) { if (nom > denom) { full++; nom -= denom; } } return full; } static int ForNom(int nom, int denom)//уменьшение числителя { while (nom > denom) { if (nom > denom) { nom -= denom; } } return nom; } static int ReductionNom(int nom, int denom)//сокращение числителя { for (int i = 10; i > 1; i--) { if (nom % i == 0 && denom % i == 0) { nom /= i; denom /= i; } } return nom; } static int ReductionDenom(int nom, int denom)//сокращение знаменателя { for (int i = 10; i > 1; i--) { if (nom % i == 0 && denom % i == 0) { nom /= i; denom /= i; } } return denom; } static int ForDivide(int num1, int num2, int full)//Умножение множителя на числитель/знаменатель для объекта деления { for (int i = 0; i < full; i++) { num1 += num2; } return num1; } public static Fractions Plus(Fractions fract1, Fractions fract2)//метод, в котором за основу берётся класс, как переменная. { resDenom = NOK(fract1.denom, fract2.denom);// записываем результат вычисления общего знаменателя resNom = ForNom(NomCoef(fract1.nom, fract1.denom, resDenom) + NomCoef(fract2.nom, fract2.denom,resDenom), resDenom);//записываем результат расчёта числителей resFull = ForFull(fract1.full, fract2.full, NomCoef(fract1.nom, fract1.denom, resDenom) + NomCoef(fract2.nom, fract2.denom, resDenom), resDenom);//рез.расч.множителя return new Fractions(ReductionDenom(resNom, resDenom), ReductionNom(resNom, resDenom), resFull);//Экземпляр класса с заданными параметрами. (можно было сразу с рассчётом на месте каждого аргумента). } public static Fractions Multi(Fractions fract1, Fractions fract2) { resNom = (fract1.nom + (fract1.full * fract1.denom)) * (fract2.nom + (fract2.full * fract2.denom));//записываем результат вычисления числителя resDenom = fract1.denom * fract2.denom;//записываем результат вычисления знаменателя resFull = resNom / resDenom;//записываем множитель resNom = ForNom(resNom, resDenom); return new Fractions(ReductionDenom(resNom, resDenom), ReductionNom(resNom,resDenom), resFull); } public static Fractions Substraction(Fractions fract1, Fractions fract2)//объект для вычитания дробей { resDenom = NOK(fract1.denom, fract2.denom); resNom = ForNom(NomCoef(fract1.nom, fract1.denom, resDenom) - NomCoef(fract2.nom, fract2.denom, resDenom), resDenom); resFull = fract1.full - fract2.full; if (resFull > 0 && resNom <= 0) { resNom += resDenom; resFull -= 1; } return new Fractions(ReductionDenom(resNom, resDenom), ReductionNom(resNom, resDenom), resFull); } public static Fractions Divide(Fractions fract1, Fractions fract2)//объект для деления дробей { resNom = ForDivide(fract1.nom, fract1.denom, fract1.full) * fract2.denom;//складываем числитель 1 помноженный на множитель 1 со знаменателем 2 resDenom = fract1.denom * ForDivide(fract2.nom, fract2.denom, fract2.full);//складываем знаменатель 1 с числителем 2 помноженным на множитель 2 resNom = ForNom(resNom, resDenom); resFull = resNom / resDenom; return new Fractions(ReductionDenom(resNom, resDenom), ReductionNom(resNom, resDenom), resFull); } } }
using UnityEngine; using System.Collections; public class EnemySpawner : MonoBehaviour { [SerializeField]private GameObject _enemy; [SerializeField]private float _spawnCooldown; private float _timer; void Update () { UpdateTimer(); SpawnEnemy(); } void SpawnEnemy() { //Spawn position for the enemy Vector2 spawnPos = transform.position; //Spawn an enemy when the timer is equal to or surpasses the spawn cooldown if (_timer >= _spawnCooldown) { GameObject newEnemy = Instantiate(_enemy,spawnPos, transform.rotation) as GameObject; _timer = 0; } } void UpdateTimer() { //constantly updates the timer _timer += Time.deltaTime; } }
using System; namespace SharpNES.Core { public enum MirrorModes { MirrorHorizontal = 0, MirrorVertical = 1, MirrorSingle0 = 2, MirrorSingle1 = 3, MirrorFour = 4, } public interface IMemory { byte Read(UInt16 address); byte Write(UInt16 address); } // CPU Memory Map public class CPUMemory : IMemory { public CPUMemory(Console console) { _console = console; } public byte Read(ushort address) { throw new NotImplementedException(); } public byte Write(ushort address) { throw new NotImplementedException(); } private Console _console; } public class PPUMemory : IMemory { private Console _console; public PPUMemory(Console console) { _console = console; } public byte Read(ushort address) { throw new NotImplementedException(); } public byte Write(ushort address) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using System.Threading.Tasks; namespace TransferData.Business.Dto { [DataContract] public class TaskSEICDto : APIBaseTaskIntegrateInfo { [DataMember(Name = "claim")] public APITaskNA Na { get; set; } [DataMember(Name = "car_insurer")] public APICarInsurer CarInsurer { get; set; } [DataMember(Name = "car_parties")] public List<APICarParty> CarParties { get; set; } [DataMember(Name = "summary_of_case")] public APISummaryOfCase SummaryOfCase { get; set; } [DataMember(Name = "woundeds")] public List<APIWounded> Woundeds { get; set; } [DataMember(Name = "property_damages")] public List<APIPropertyDamage> PropertyDamages { get; set; } [DataMember(Name = "surveyor_charges")] public List<APISurveyorCharge> SurveyorCharges { get; set; } } [DataContract] public class APICarInsurer { [DataMember(Name = "task_id")] public string TaskId { get; set; } [DataMember(Name = "summary_damage_insurer_car")] public double? SummaryDamageInsurerCar { get; set; } [DataMember(Name = "car_insurer_info")] public APICarInformation CarInsurerInfo { get; set; } [DataMember(Name = "car_insurer_driver")] public APICarDriver CarInsurerDriver { get; set; } [DataMember(Name = "car_insurer_damages")] public List<APICarDamage> CarInsurerDamages { get; set; } } [DataContract] public class APICarParty { [DataMember(Name = "task_id")] public string TaskId { get; set; } [DataMember(Name = "car_party_id")] public string CarPartyId { get; set; } [DataMember(Name = "summary_damage_car")] public double? SummaryDamageCar { get; set; } [DataMember(Name = "car_party_info")] public APICarInformation CarPartyInfo { get; set; } [DataMember(Name = "car_party_driver")] public APICarDriver CarPartyDriver { get; set; } [DataMember(Name = "car_party_damages")] public List<APICarDamage> CarPartyDamages { get; set; } } [DataContract] public class APISummaryOfCase { [DataMember(Name = "task_id")] public string TaskId { get; set; } [DataMember(Name = "accident_type")] public SyncAccidentType AccidentType { get; set; } [DataMember(Name = "copy_dialy")] public bool? CopyDialy { get; set; } [DataMember(Name = "evidence_party")] public bool? EvidenceParty { get; set; } [DataMember(Name = "document_confess")] public bool? DocumentConfess { get; set; } [DataMember(Name = "contact_card")] public bool? ContactCard { get; set; } [DataMember(Name = "recovery_amount")] public double? RecoveryAmount { get; set; } [DataMember(Name = "receive_recovery_amount")] public double? ReceiveRecoveryAmount { get; set; } [DataMember(Name = "accident_detail")] public string AccidentDetail { get; set; } [DataMember(Name = "accident_result_detail")] public string AccidentResultDetail { get; set; } [DataMember(Name = "accident_date")] public string AccidentDate { get; set; } [DataMember(Name = "schedule_place")] public string SchedulePlance { get; set; } [DataMember(Name = "accident_date_text")] public string AccidentDateText { get; set; } [DataMember(Name = "accident_time_text")] public string AccidentTimeText { get; set; } [DataMember(Name = "result_case_id")] public string ResultCaseId { get; set; } [DataMember(Name = "accident_location")] public APILocationPlace AccidentLocation { get; set; } } [DataContract] public class APIWounded { [DataMember(Name = "wounded_id")] public string WoundedId { get; set; } [DataMember(Name = "wounded_id_card")] public string WoundedIdCard { get; set; } [DataMember(Name = "wounded_age")] public string WoundedAge { get; set; } [DataMember(Name = "wounded_gender")] public string WoundedGender { get; set; } [DataMember(Name = "wounded_tel")] public string WoundedTel { get; set; } [DataMember(Name = "wounded_hospital_name")] public string WoundedHospitalName { get; set; } [DataMember(Name = "wounded_accident_type")] public SyncWoundedAccidentType WoundedAccidentType { get; set; } [DataMember(Name = "wounded_accident_amount")] public double? WoundedAccidentAmount { get; set; } [DataMember(Name = "wounded_description")] public string WoundedDescription { get; set; } [DataMember(Name = "task_id")] public string TaskId { get; set; } [DataMember(Name = "wounded_address")] public string WoundedAddress { get; set; } [DataMember(Name = "wounded_location_place")] public APILocationPlace WoundedLocationPlace { get; set; } [DataMember(Name = "wounded_name_info")] public APIPersonInfo WoundedNameInfo { get; set; } [DataMember(Name = "wounded_type")] public SyncWoundedType WoundedType { get; set; } } [DataContract] public class APISurveyorCharge { [DataMember(Name = "surveyor_charge_id")] public string SurveyorChargeId { get; set; } [DataMember(Name = "service_type")] public SyncServiceType ServiceType { get; set; } [DataMember(Name = "service_desc")] public string ServiceDesc { get; set; } [DataMember(Name = "quantity")] public double? Quantity { get; set; } [DataMember(Name = "unitprice")] public double? UnitPrice { get; set; } [DataMember(Name = "total")] public double? Total { get; set; } [DataMember(Name = "task_id")] public string TaskId { get; set; } } [DataContract(Name = "service_type")] public class SyncServiceType { [DataMember(Name = "id")] public int ServiceTypeId { get; set; } [DataMember(Name = "name")] public string ServiceTypeName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool IsActive { get; set; } [DataMember(Name = "is_cal_percent")] public bool IsCalPercent { get; set; } [DataMember(Name = "default_percent")] public double DefaultPercent { get; set; } } [DataContract] public class APICarInformation { [DataMember(Name = "car_policy_insurer")] public APIInsurer CarPolicyInsurer { get; set; } [DataMember(Name = "car_regis")] public string CarRegis { get; set; } [DataMember(Name = "car_regis_province")] public APIProvince CarRegisProvice { get; set; } [DataMember(Name = "car_policy_no")] public string CarPolicyNo { get; set; } [DataMember(Name = "car_policy_type")] public string CarPolicyType { get; set; } [DataMember(Name = "car_policy_startdate")] public string PolicyStartDate { get; set; } [DataMember(Name = "car_policy_enddate")] public string PolicyEndDate { get; set; } [DataMember(Name = "car_brand")] public APICarBrand CarBrand { get; set; } [DataMember(Name = "car_model")] public APICarModel CarModel { get; set; } [DataMember(Name = "car_color")] public APICarColor CarColor { get; set; } [DataMember(Name = "car_type")] public APICarType CarType { get; set; } [DataMember(Name = "car_policy_owner")] public string CarPolicyOwner { get; set; } [DataMember(Name = "car_engine")] public string CarEngine { get; set; } [DataMember(Name = "car_chassis")] public string CarChassis { get; set; } [DataMember(Name = "policy_driver1")] public string PolicyDriverName1 { get; set; } [DataMember(Name = "policy_driver2")] public string PolicyDriverName2 { get; set; } [DataMember(Name = "car_capacity")] public SyncCarCapacity CarCapacity { get; set; } [DataMember(Name = "car_notice_no")] public string CarPartyNoticeNo { get; set; } } [DataContract] public class APIInsurer { [DataMember(Name = "id")] public string InsurerId { get; set; } [DataMember(Name = "name_en")] public string InsurerNameEN { get; set; } [DataMember(Name = "name_th")] public string InsurerNameTH { get; set; } } [DataContract] public class APICarBrand { [DataMember(Name = "id")] public string carBrandId { get; set; } [DataMember(Name = "name")] public string carBrandName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APICarColor { [DataMember(Name = "id")] public int? colorID { get; set; } [DataMember(Name = "name")] public string colorName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APICarType { [DataMember(Name = "id")] public int CarTypeID { get; set; } [DataMember(Name = "name")] public string CarTypeName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract(Name = "car_capacity")] public class SyncCarCapacity { [DataMember(Name = "id")] public int CapacityCode { get; set; } [DataMember(Name = "name")] public string CapacityName { get; set; } [DataMember(Name = "code")] public string CapacitySubCode { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract] public class APICarModel { [DataMember(Name = "id")] public string carModelId { get; set; } [DataMember(Name = "name")] public string carModelName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APIProvince { [DataMember(Name = "id")] public string provinceCode { get; set; } [DataMember(Name = "name")] public string provinceName { get; set; } [DataMember(Name = "geo_id")] public int geoID { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APIAumphur { [DataMember(Name = "aumphur_code")] public string aumphurCode { get; set; } [DataMember(Name = "aumphur_name")] public string aumphurName { get; set; } [DataMember(Name = "sort")] public int sort { get; set; } } [DataContract] public class APICarDriver { [DataMember(Name = "car_driver_gender")] public string CarDriverGender { get; set; } [DataMember(Name = "car_driver_birthday")] public string CarDriverBirthday { get; set; } [DataMember(Name = "car_driver_age")] public int? CarDriverAge { get; set; } [DataMember(Name = "car_driver_idcard")] public string CarDriverIdCard { get; set; } [DataMember(Name = "car_driver_address")] public string CarDriverAddress { get; set; } [DataMember(Name = "car_driver_tel")] public string CarDriverTel { get; set; } [DataMember(Name = "car_driver_license_card")] public string CarDriverLicenseCard { get; set; } [DataMember(Name = "car_driver_license_card_type")] public SyncLicenseCardType CarDriverLicenseCardType { get; set; } [DataMember(Name = "car_driver_license_card_expire_date")] public string CarDriverLicenseCardExpireDate { get; set; } [DataMember(Name = "car_driver_license_card_issued_date")] public string CarDriverLicenseCardIssuedDate { get; set; } [DataMember(Name = "car_driver_name_info")] public APIPersonInfo CarDriverNameInfo { get; set; } [DataMember(Name = "car_driver_location")] public APILocationPlace CarDriverLocation { get; set; } [DataMember(Name = "car_driver_relationship")] public SyncRelationship CarDriverRelationship { get; set; } } [DataContract(Name = "relationship")] public class SyncRelationship { [DataMember(Name = "id")] public string RelationshipCode { get; set; } [DataMember(Name = "name")] public string RelationshipName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract] public class APICarDamage { [DataMember(Name = "car_damage_id")] public int CarDamageId { get; set; } [DataMember(Name = "car_damage_level")] public SyncDamageLevel DamageLevel { get; set; } [DataMember(Name = "car_damage_part")] public SyncDamagePart DamagePart { get; set; } [DataMember(Name = "car_damage_part_text")] public string DamagePartText { get; set; } } [DataContract(Name = "damage_part")] public class SyncDamagePart { [DataMember(Name = "id")] public int PicturePartId { get; set; } [DataMember(Name = "name")] public string PicturePartName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } [DataMember(Name = "car_type")] public string CarTypePart { get; set; } } [DataContract(Name = "damage_level")] public class SyncDamageLevel { [DataMember(Name = "id")] public string DamageLevelCode { get; set; } [DataMember(Name = "name")] public string DamageLevelDescription { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract] public class APILocationPlace { [DataMember(Name = "province")] public SyncProvince Province { get; set; } [DataMember(Name = "aumphur")] public SyncAmphur Amphur { get; set; } [DataMember(Name = "district")] public SyncDistrict District { get; set; } [DataMember(Name = "place")] public string Place { get; set; } [DataMember(Name = "latitude")] public string Latitude { get; set; } [DataMember(Name = "longitude")] public string Longitude { get; set; } } [DataContract(Name = "province")] public class SyncProvince { [DataMember(Name = "id")] public string ProvinceCode { get; set; } [DataMember(Name = "name")] public string ProvinceName { get; set; } [DataMember(Name = "geo_id")] public int GeoID { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract(Name = "amphur")] public class SyncAmphur { [DataMember(Name = "id")] public string AmphurCode { get; set; } [DataMember(Name = "name")] public string AmphurName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract(Name = "district")] public class SyncDistrict { [DataMember(Name = "id")] public string DistrictCode { get; set; } [DataMember(Name = "name")] public string DistrictName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract] public class APIPersonInfo { [DataMember(Name = "first_name")] public string FirstName { get; set; } [DataMember(Name = "last_name")] public string LastName { get; set; } [DataMember(Name = "title")] public SyncTitleName Title { get; set; } } [DataContract(Name = "title_name")] public class SyncTitleName { [DataMember(Name = "id")] public string TitleCode { get; set; } [DataMember(Name = "name")] public string TitleName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract(Name = "license_card_type")] public class SyncLicenseCardType { [DataMember(Name = "id")] public int SyncLicenseCardTypeId { get; set; } [DataMember(Name = "name")] public string SyncLicenseCardTypeName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract] public class APITaskNA { [DataMember(Name = "claim_accident_date")] public string ClaimAccidentDate { get; set; } [DataMember(Name = "is_same_inform")] public bool? IsSameInform { get; set; } [DataMember(Name = "not_inform_detail")] public string NotInformDetail { get; set; } [DataMember(Name = "is_wounded")] public bool? IsWounded { get; set; } [DataMember(Name = "wounded_total")] public int? WoundedTotal { get; set; } [DataMember(Name = "is_deceased")] public bool? IsDeceased { get; set; } [DataMember(Name = "deceased_total")] public int? DeceasedTotal { get; set; } [DataMember(Name = "damage_insurer_car")] public double? DamageInsurerCar { get; set; } [DataMember(Name = "damage_thirdparty_car")] public double? DamageThirdPartyCar { get; set; } [DataMember(Name = "claim_request")] public double? ClaimRequest { get; set; } [DataMember(Name = "deduct")] public double? Deduct { get; set; } [DataMember(Name = "excess")] public double? Excess { get; set; } [DataMember(Name = "na_note")] public string NaNote { get; set; } [DataMember(Name = "results_case_id")] public string ResultsCaseId { get; set; } [DataMember(Name = "accident_location")] public APILocationPlace AccidentLocation { get; set; } } [DataContract] public class APIBaseTaskIntegrateInfo { [DataMember(Name = "task_id")] public string TaskID { get; set; } [DataMember(Name = "informer_name")] public string InformerName { get; set; } [DataMember(Name = "informer_tel")] public string InformerTel { get; set; } [DataMember(Name = "informer_tel2")] public string InformerTel2 { get; set; } [DataMember(Name = "informer_tel3")] public string InformerTel3 { get; set; } [DataMember(Name = "task_type")] public APITaskType TaskType { get; set; } [DataMember(Name = "task_process")] public APITaskProcess TaskProcess { get; set; } [DataMember(Name = "create_date")] public string CreateDate { get; set; } [DataMember(Name = "car_brand")] public APICarBrand CarBrand { get; set; } [DataMember(Name = "car_model")] public APICarModel CarModel { get; set; } [DataMember(Name = "car_year")] public string CarYear { get; set; } [DataMember(Name = "car_regis")] public string CarRegis { get; set; } [DataMember(Name = "car_regis_province")] public APIProvince CarRegisProvice { get; set; } [DataMember(Name = "schedule_latitude")] public string ScheduleLatitude { get; set; } [DataMember(Name = "schedule_longitude")] public string ScheduleLongitude { get; set; } [DataMember(Name = "schedule_date")] public string ScheduleDate { get; set; } [DataMember(Name = "schedule_place")] public string SchedulePlance { get; set; } [DataMember(Name = "schedule_date_text")] public string ScheduleDateText { get; set; } [DataMember(Name = "schedule_time_text")] public string ScheduleTimeText { get; set; } [DataMember(Name = "claim_accident_detail")] public string ClaimAccidentDetail { get; set; } [DataMember(Name = "policy_owner")] public string PolicyOwner { get; set; } // CarInfo.policy_owner [DataMember(Name = "policy_driver1")] public string PolicyDriverName1 { get; set; } // CarInfo.policy_driver1 [DataMember(Name = "policy_driver2")] public string PolicyDriverName2 { get; set; } // CarInfo.policy_driver2 [DataMember(Name = "policy_no")] public string PolicyNo { get; set; } // CarInfo.policy_no [DataMember(Name = "policy_type")] public string PolicyType { get; set; } // CarInfo.policy_type [DataMember(Name = "policy_enddate")] public string PolicyEndDate { get; set; }// CarInfo.policy_enddate [DataMember(Name = "policy_insurer")] public APIInsurer PolicyInsurer { get; set; } [DataMember(Name = "policy_claim_no")] public string PolicyClaimNo { get; set; } } [DataContract] public class APITaskType { [DataMember(Name = "task_type_id")] public string TaskTypeId { get; set; } [DataMember(Name = "task_type_name")] public string TaskTypeName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } } [DataContract] public class APITaskProcess { [DataMember(Name = "task_process_id")] public string TaskProcessId { get; set; } [DataMember(Name = "task_process_name")] public string TaskProcessName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } } [DataContract(Name = "accident_type")] public class SyncAccidentType { [DataMember(Name = "id")] public int SyncAccidentTypeId { get; set; } [DataMember(Name = "name")] public string SyncAccidentTypeName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract(Name = "wounded_accident_type")] public class SyncWoundedAccidentType { [DataMember(Name = "id")] public int SyncWoundedAccidentTypeId { get; set; } [DataMember(Name = "name")] public string SyncWoundedAccidentTypeName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } } [DataContract(Name = "wounded_type")] public class SyncWoundedType { [DataMember(Name = "id")] public int SyncWoundedTypeId { get; set; } [DataMember(Name = "name")] public string SyncWoundedTypeName { get; set; } [DataMember(Name = "sort")] public int Sort { get; set; } [DataMember(Name = "is_active")] public bool isActive { get; set; } [DataMember(Name = "type_use")] public int TypeUse { get; set; } } [DataContract] public class APIPropertyDamage { [DataMember(Name = "property_damage_id")] public string PropertyDamageId { get; set; } [DataMember(Name = "property_damage_name")] public string PropertyDamageName { get; set; } [DataMember(Name = "property_damage_owner_tel")] public string PropertyDamageOwnerTel { get; set; } [DataMember(Name = "property_damage_owner_address")] public string PropertyDamageOwnerAddress { get; set; } [DataMember(Name = "property_damage_amount")] public double? PropertyDamageAmount { get; set; } [DataMember(Name = "property_damage_description")] public string PropertyDamageDescription { get; set; } [DataMember(Name = "task_id")] public string TaskId { get; set; } [DataMember(Name = "property_damage_owner_location_place")] public APILocationPlace PropertyDamageOwnerLocationPlace { get; set; } [DataMember(Name = "property_damage_type")] public SyncWoundedType PropertyDamageType { get; set; } [DataMember(Name = "property_damage_owner_name_info")] public APIPersonInfo PropertyDamageOwnerNameInfo { get; set; } } }
using System; namespace CarFinanceCalculator.Domain { public class AmortizationScheduleLine { public DateTime PaymentDate { get; set; } public int MonthNumber { get; set; } public decimal Payment { get; set; } public decimal Principal { get; set; } public decimal Interest { get; set; } public decimal RemainingPrincipal { get; set; } public AmortizationScheduleLine( DateTime paymentDate, int monthNumber, decimal payment, decimal principal, decimal interest, decimal remainingPrincipal) { PaymentDate = paymentDate; MonthNumber = monthNumber; Payment = payment; Principal = principal; Interest = interest; RemainingPrincipal = remainingPrincipal; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Boss_idle : StateMachineBehaviour { //Distancia mínima jugadores y fase private float pushRange = 3f; int phase; //Tiempo entre ataque de la primera fase float attackDelay = 2f; //Players GameObject player1; GameObject player2; //Animator Rigidbody2D rb; Boss boss; override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //Players player1 = GameObject.FindGameObjectWithTag("Player1"); player2 = GameObject.FindGameObjectWithTag("Player2"); //Animator boss = animator.GetComponent<Boss>(); rb = animator.GetComponent<Rigidbody2D>(); //Referenciamos la fase en la que nos encontramos phase = animator.GetInteger("Phase"); } override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //Comprobamos distancia entre pj-boss checkDistance(animator); //Chekeamos la fase para lanzar el próximo ataque checkPhase(animator); } override public void OnStateExit(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) { //Reseteamos los triggers para que no se lancen más de una vez como prevención animator.ResetTrigger("Push"); animator.ResetTrigger("Throw"); animator.ResetTrigger("ThrowRed"); animator.ResetTrigger("Jump"); } private void checkDistance(Animator anim) { var distance1 = (player1.transform.position - rb.transform.position).magnitude; var distance2 = (player2.transform.position - rb.transform.position).magnitude; //Si estamos a menos distancia lanzamos el trigger push y empunamos a los jugadores if (distance1 <= pushRange || distance2 <= pushRange) { anim.SetTrigger("Push"); } } private void checkPhase(Animator anim) { attackDelay -= Time.deltaTime; //Dependiendo de la fase en la que nos encontremos lanzaremos un ataque u otro //con una frecuencia de tiempo distinta if (attackDelay <= 0f) { if (phase == 1) { anim.SetTrigger("Throw"); attackDelay = 4f; } else if (phase == 2) { anim.SetTrigger("Jump"); attackDelay = 4f; } else if (phase == 3) { anim.SetTrigger("ThrowRed"); attackDelay = 10f; } } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Drawing; using System.Threading; using System.Text; using System.Threading.Tasks; using AForge.Video; using AForge.Video.DirectShow; namespace SelfieServer { public class Webcam { private FilterInfoCollection _videoDevices; private FilterInfo _currentDevice; private VideoCaptureDevice _videoSource; private Bitmap _frame; private Boolean _takePicture; #region Singleton Stuff private Webcam() { _videoDevices = new FilterInfoCollection(FilterCategory.VideoInputDevice); _currentDevice = _videoDevices.Cast<FilterInfo>().First(); _videoSource = new VideoCaptureDevice(_currentDevice.MonikerString); _videoSource.NewFrame += _videoSource_NewFrame; _takePicture = false; } void _videoSource_NewFrame(object sender, NewFrameEventArgs eventArgs) { if (!_takePicture) return; if (eventArgs.Frame.Width == 0) { return; } _frame = eventArgs.Frame.Clone() as Bitmap; _videoSource.SignalToStop(); } private static Webcam _instance; public static Webcam Instance { get { if (_instance == null) { _instance = new Webcam(); } return _instance; } } #endregion public Bitmap TakePicture() { Task.Run(() => { Thread.Sleep(5000); _takePicture = true; }); _videoSource.Start(); _videoSource.WaitForStop(); _takePicture = false; return _frame; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SingleGameScene : MonoBehaviour { public GameObject[] mBlockContainer = new GameObject[7]; public Tetrimino CurBlock; public Tetrimino NextBlock; public Tetrimino SaveBlock; public int mGridHeight = 23; public int mGridWidth = 11; public Camera mCamera; public Transform NextBlockUIPos; public Transform SaveBlockUIPos; public Transform[,] mGrid; public int[,] mTestGrid = new int[11, 23]; public int mScore = 0; private void Awake() { Init(); } // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public virtual void Init() { SpawnBlock(); mGrid = new Transform[mGridWidth, mGridHeight]; StartCoroutine(FallDown()); } public void LeftBtnAction() { CurBlock.LeftMove(); } public void RightBtnAction() { CurBlock.RightMove(); } public void DownBtnAction() { CurBlock.DownMove(); } public void RotateBtnAction() { CurBlock.Rotation(); } public void BlockSaveBtnAction() { if (SaveBlock == null) { SaveBlock = CurBlock; SaveGridInit(SaveBlock); SaveBlock.transform.position = CoordBlockPos(SaveBlockUIPos.position); SaveBlock.enabled = false; SpawnBlock(); } else { Tetrimino temp; Vector3 CurPos = CurBlock.transform.position; SaveGridInit(CurBlock); temp = SaveBlock; SaveBlock = CurBlock; CurBlock = temp; SaveBlock.transform.position = CoordBlockPos(SaveBlockUIPos.position); CurBlock.transform.position = CurPos; } } public void StraightFallBtnAction() { } public void SpawnBlock() { int tCurType = Random.Range(0, 7); int tNextType = Random.Range(0, 7); if (NextBlock == null) { CurBlock = Instantiate<Tetrimino>(mBlockContainer[tCurType].GetComponentInChildren<Tetrimino>()); CurBlock.transform.position = new Vector3((mGridWidth + 1) / 2, mGridHeight - 2, 0); NextBlock = Instantiate<Tetrimino>(mBlockContainer[tNextType].GetComponentInChildren<Tetrimino>()); NextBlock.transform.position = CoordBlockPos(NextBlockUIPos.position); NextBlock.enabled = false; } else { CurBlock = NextBlock; CurBlock.transform.position = new Vector3((mGridWidth + 1) / 2, mGridHeight - 2, 0); NextBlock = Instantiate<Tetrimino>(mBlockContainer[tNextType].GetComponentInChildren<Tetrimino>()); NextBlock.transform.position = CoordBlockPos(NextBlockUIPos.position); } CurBlock.SetScene(this); } public bool CheckIsInside(Vector3 tVec) { return (((int)tVec.x >= 0) && ((int)tVec.x < mGridWidth) && (tVec.y > 0)); } public Vector2 Round(Vector2 tVec) { return new Vector2(Mathf.Round(tVec.x), Mathf.Round(tVec.y)); } public void GridUpdate(Tetrimino tTetrimino) { for (int tx = 0; tx < mGridWidth; tx++) { for (int ty = 0; ty < mGridHeight; ty++) { if (mGrid[tx, ty] != null) { if (mGrid[tx, ty].parent == tTetrimino.transform) { mGrid[tx, ty] = null; } } } } foreach (Transform Block in tTetrimino.transform) { Vector2 tVec = Round(Block.position); if (tVec.y < mGridHeight) { mGrid[(int)tVec.x, (int)tVec.y] = Block; } } } public void SaveGridInit(Tetrimino SaveBlock) { foreach (Transform Block in SaveBlock.transform) { Vector2 tVec = Round(Block.position); if (tVec.y < mGridHeight) { mGrid[(int)tVec.x, (int)tVec.y] = null; } } } public Transform GetGridTransform(Vector2 tVec) { if (tVec.y > mGridHeight - 1) { return null; } else { return mGrid[(int)tVec.x, (int)tVec.y]; } } public virtual IEnumerator FallDown() { for (; ; ) { CurBlock.DownMove(); yield return new WaitForSeconds(0.5f); } } public bool IsRowFull(int tGridY) // 해당 열이 전부 차있는지 체크 { for (int tx = 0; tx < mGridWidth; tx++) { if (mGrid[tx, tGridY] == null) { return false; } } return true; } public void DeleteBlock(int tGridY) //전부 차있는 열의 블록 삭제 { for (int tx = 0; tx < mGridWidth; tx++) { Destroy(mGrid[tx, tGridY].gameObject); mGrid[tx, tGridY] = null; } } public void RowDown(int tGridY) { for (int tx = 0; tx < mGridWidth; tx++) { if (mGrid[tx, tGridY] != null) { mGrid[tx, tGridY - 1] = mGrid[tx, tGridY]; mGrid[tx, tGridY] = null; mGrid[tx, tGridY - 1].position += new Vector3(0, -1, 0); } } } public void AllRowDown(int tGridY) //블록 삭제 후 해당 열 위에 위치한 모든 열의 블록을 y축으로 -1씩 내림 { for (int ti = tGridY; ti < mGridHeight; ti++) { RowDown(ti); } } public void DeleteRow() { for (int ty = 0; ty < mGridHeight; ty++) { if (IsRowFull(ty) == true) { DeleteBlock(ty); AllRowDown(ty + 1); ty--; ScoreUp(); } } } public void ScoreUp() { mScore += 100; } public Vector3 CoordBlockPos(Vector3 tUIPos) // NextBlock, SaveBlock 배치를 위한 UI POS 보정(Screen->world) { Vector3 tCoordVec; mCamera = Camera.main; tCoordVec = mCamera.ScreenToWorldPoint(tUIPos); tCoordVec = new Vector3(tCoordVec.x, tCoordVec.y - 3, 0); return tCoordVec; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ETS.logic.Domain { public class EmpHours { // Properties public int EmpHoursID { get; set; } public Employee Emp { get; set; } public DateTime Date { get; set; } public string Hours { get; set; } // Constructors public EmpHours(Employee emp, int empHoursID, DateTime date, string hours) { this.Emp = emp; this.EmpHoursID = empHoursID; this.Date = date; this.Hours = hours; } public EmpHours(Employee emp) { this.Emp = emp; } public override string ToString() { string[] date = this.Date.ToString().Split(null); string empInfo = ""; empInfo += "EmpHoursID: " + this.EmpHoursID + "\n" + "Employee ID: " + this.Emp.EmpID + "\n" + "Date: " + date[0] + "\n" + "Hours: " + this.Hours + "\n\n"; return empInfo; } } }
using DDMedi.DependencyInjection; using Microsoft.Extensions.DependencyInjection; using System; namespace DDMedi.Test.Tests { public class DependencyInjectionTest : BaseDependencyInjectionTest { protected override void AddSingleton<TInstance>(object Collection, TInstance instance) => (Collection as ServiceCollection).AddSingleton(instance); protected override ISupplierScopeFactory BuildNewScopeFactory(DDMediFactory ddMediFactory) => new ServiceCollection().AddDDMediFactory(ddMediFactory).BuildServiceProvider() .GetService<ISupplierScopeFactory>(); protected override IServiceProvider BuildNewServiceProvider(DDMediFactory ddMediFactory) => new ServiceCollection().AddDDMediFactory(ddMediFactory).BuildServiceProvider(); protected override IServiceProvider BuildServiceProvider(object Collection, DDMediFactory ddMediFactory) => (Collection as ServiceCollection).AddDDMediFactory(ddMediFactory).BuildServiceProvider(); protected override object CreateCollection() => new ServiceCollection(); } }
using System.Web.Mvc; using Umbraco.Web; using Umbraco.Web.Models; using Umbraco.Web.Mvc; namespace Vendr.Checkout.Web.Controllers { public class VendrCheckoutCheckoutStepPageController : RenderMvcController { public override ActionResult Index(ContentModel model) { // If the page has a template, use it if (model.Content.TemplateId.HasValue && model.Content.TemplateId.Value > 0) return base.Index(model); // Get the current step from the page and render the appropriate view return View(PathHelper.GetVendrCheckoutViewPath($"VendrCheckout{model.Content.Value<string>("vendrStepType")}Page"), model); } } }
// Programming Using C# @MAH // Assignment 5 // Author: Per Jonsson // Version 1 // Created: 2013-07-11 // Project: CustomerRegistry // Class: MainForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ContactRegistry { /// <summary> /// The Interactive GUI Class /// </summary> public partial class MainForm : Form { #region Fields private ContactManager contacts; private Contact contact; #endregion /// <summary> /// Constructor /// </summary> public MainForm() { // Default InitializeComponent(); // Create an instance of the contact registry this.contacts = new ContactManager(); // Initialize user interface InitializeGUI(); } #region Methods /// <summary> /// Provide the relevant info at app startup /// </summary> private void InitializeGUI() { // Set focus on the first field txtFirstName.Select(); // No. of registered users lblCount.Text = contacts.Count.ToString(); // Fill the ComboBox with the valeus from the Countries enum cmbCountry.Items.AddRange(Enum.GetNames(typeof(Countries))); //Set an option as the default option cmbCountry.SelectedIndex = (int)Countries.Sverige; } /// <summary> /// This method is called when textual information needs to be refreshed /// </summary> private void UpdateGUI() { lstResults.Items.Clear(); lstResults.Items.AddRange(this.contacts.GetContactsInfo()); lblCount.Text = lstResults.Items.Count.ToString(); } /// <summary> /// Fill the input boxes with information for the highlighted contacts in the ListBox /// </summary> private void UpdateContactInfoFromRegistry() { Contact contact = this.contacts.GetContact(GetSelectedIndex()); if (contact != null) { cmbCountry.SelectedIndex = (int)contact.AddressData.Country; txtFirstName.Text = contact.FirstName; txtLastName.Text = contact.LastName; txtCity.Text = contact.AddressData.City; txtStreet.Text = contact.AddressData.Street; txtZip.Text = contact.AddressData.Zip; } } /// <summary> /// Reads names and address information and saves it /// </summary> /// <returns>True or false</returns> private bool ReadInput() { // User input string firstName, lastName; Address address; // MessageBox info string message = String.Empty; string caption = "Input Error"; if (!(ReadName(out firstName, out lastName))) { // Assemble messagebox info depending on which error message = "Name must contain at least one character, and may not consist of only empty spaces"; MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } if (!(ReadAddress(out address))) { message = "Address fields must contain at least one character, and may not consist of only empty spaces"; MessageBox.Show(message, caption, MessageBoxButtons.OK, MessageBoxIcon.Error); return false; } // Save info this.contact = new Contact(firstName, lastName, address); return true; } /// <summary> /// Reads and validates first and last name /// </summary> /// <param name="firstName"></param> /// <param name="lastName"></param> /// <returns>True/false</returns> private bool ReadName(out string firstName, out string lastName) { // Fetch values firstName = txtFirstName.Text; lastName = txtLastName.Text; // Check Validity return (InputUtility.ValidateString(firstName) && InputUtility.ValidateString(lastName)); } /// <summary> /// Reads and validates Address information /// </summary> /// <returns>True/false</returns> private bool ReadAddress(out Address address) { // Fetch values string street = txtStreet.Text; string city = txtCity.Text; string zip = txtZip.Text; Countries country = (Countries)cmbCountry.SelectedIndex; // Check Validity if (InputUtility.ValidateString(street) && InputUtility.ValidateString(city) && InputUtility.ValidateString(zip)) { address = new Address(street, city, zip, country); return true; } address = null; return false; } #endregion #region Events /// <summary> /// This method will be automatically called when the user highlights /// an entry in the ListBox (clicks on a row in the ListBox). /// /// It takes the information related to the entry from the registry and /// fill the input boxes with the data to make it easier for the user to edit. /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void lstContacts_SelectedIndexChanged(object sender, EventArgs e) { UpdateContactInfoFromRegistry(); } /// <summary> /// Updates the list if a contact is to be added /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnAdd_Click(object sender, EventArgs e) { if (ReadInput()) { if (contacts.AddContact(this.contact)) UpdateGUI(); } } /// <summary> /// Changes an item in the list /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnChange_Click(object sender, EventArgs e) { if (CheckSelectedIndex() && ReadInput()) { if (contacts.ChangeContact(this.contact, GetSelectedIndex())) UpdateGUI(); } } /// <summary> /// Deletes an item in the contact list /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnDelete_Click(object sender, EventArgs e) { if (CheckSelectedIndex() && contacts.DeleteContact(GetSelectedIndex())) UpdateGUI(); else MessageBox.Show("Invalid delete", "Selection Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } /// <summary> /// Check if ListBox items are selected /// </summary> /// <returns>true if selection was made or false otherwise</returns> private bool CheckSelectedIndex() { return (lstResults.SelectedIndex >= 0); } /// <summary> /// Return selected ListBox index /// </summary> /// <returns></returns> private int GetSelectedIndex() { return lstResults.SelectedIndex; } #endregion } }
using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using PolicyMicroservice.Controllers; using PolicyMicroservice.Models; using PolicyMicroservice.Repository; using System; using System.Collections.Generic; namespace PolicyMicroserviceTest { /// <summary> /// Contributed by Anupam Bhattacharyya(848843) /// Test for GetEligibleBenefit of PolicyMicroservice /// </summary> class EligibleBenefitTest { List<MemberPolicy> memberPolicies; List<Benefits> benefitLists; string s = ""; [SetUp] public void Setup() { memberPolicies = new List<MemberPolicy> { new MemberPolicy{MemberId=1,PolicyId=1,PolicyNo=101,BenefitId=1,Tenure=3,SubscriptionDate=new DateTime(2020, 03, 15),CapAmountBenefits=100000.00}, new MemberPolicy{MemberId=2,PolicyId=1,PolicyNo=101,BenefitId=1,Tenure=3,SubscriptionDate=new DateTime(2019, 04, 18),CapAmountBenefits=120000.00}, new MemberPolicy{MemberId=3,PolicyId=2,PolicyNo=102,BenefitId=1,Tenure=5,SubscriptionDate=new DateTime(2019, 05, 10),CapAmountBenefits=80000.00} }; benefitLists = new List<Benefits> { new Benefits{BenefitId=1,BenefitName="Medical Checkup"}, new Benefits{BenefitId=2,BenefitName="Accidental"} }; } /// <summary> /// Pass Test for GetEligibleBenefit Repository /// </summary> /// <param name="policyId"></param> /// <param name="memberId"></param> [TestCase(1,1)] [TestCase(1, 2)] public void EligibleBenefitTest_Repo_ValidInput_ReturnsRightValue(int policyId,int memberId) { string p = ""; Mock<IPolicyRepo> policyContextMock = new Mock<IPolicyRepo>(); var policyRepo = new PolicyRepo(); policyContextMock.Setup(x => x.GetEligibleBenefits(policyId, memberId)).Returns(p); var result = policyRepo.GetEligibleBenefits(policyId, memberId); Assert.IsNotNull(result); Assert.AreEqual("MedicalCheckup", result); } /// <summary> /// Fail Test for GetEligibleBenefit Repository /// </summary> /// <param name="policyId"></param> /// <param name="memberId"></param> [TestCase(9,1)] [TestCase(9, 12)] public void EligibleBenefitTest_Repo_InvalidInput_ReturnsWrongValue(int policyId, int memberId) { string p = ""; Mock<IPolicyRepo> policyContextMock = new Mock<IPolicyRepo>(); var policyRepo = new PolicyRepo(); policyContextMock.Setup(x => x.GetEligibleBenefits(policyId, memberId)).Returns(p); var result = policyRepo.GetEligibleBenefits(policyId, memberId); Assert.AreNotEqual("MedicalCheckup",result); Assert.AreEqual("Invalid Data", result); } /// <summary> /// Pass Test for GetEligibleBenefit Controller /// </summary> /// <param name="policyId"></param> /// <param name="memberId"></param> [TestCase(1,1)] [TestCase(1, 2)] public void EligibleBenefitTest_Controller_ValidInput_ReturnsOkResultStatus(int policyId,int memberId) { Mock<IPolicyRepo> mock = new Mock<IPolicyRepo>(); mock.Setup(p => p.GetEligibleBenefits(policyId, memberId)).Returns(s); PolicyController pc = new PolicyController(mock.Object); var result = pc.GetEligibleBenefit(policyId, memberId)as OkObjectResult; Assert.AreEqual(200, result.StatusCode); } /// <summary> /// Fail Test for GetEligibleBenefit Controller /// </summary> /// <param name="policyId"></param> /// <param name="memberId"></param> [TestCase(-1, -1)] [TestCase(-14, 1)] public void EligibleBenefitTest_Controller_InvalidInput_ReturnsBadRequestStatus(int policyId, int memberId) { Mock<IPolicyRepo> mock = new Mock<IPolicyRepo>(); mock.Setup(p => p.GetEligibleBenefits(policyId, memberId)).Returns(s); PolicyController pc = new PolicyController(mock.Object); var result = (BadRequestResult)pc.GetEligibleBenefit(policyId, memberId); Assert.AreEqual(400, result.StatusCode); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using needle.EditorPatching; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; namespace Needle.Demystify { public class DemystifySettingsProvider : SettingsProvider { public const string SettingsPath = "Preferences/Needle/Demystify"; [SettingsProvider] public static SettingsProvider CreateDemystifySettings() { try { DemystifySettings.instance.Save(); return new DemystifySettingsProvider(SettingsPath, SettingsScope.User); } catch (Exception e) { Debug.LogException(e); } return null; } private DemystifySettingsProvider(string path, SettingsScope scopes, IEnumerable<string> keywords = null) : base(path, scopes, keywords) { } public override void OnActivate(string searchContext, VisualElement rootElement) { base.OnActivate(searchContext, rootElement); ThemeNames = null; } [MenuItem("Tools/Demystify/Enable Development Mode", true)] private static bool EnableDevelopmentModeValidate() => !DemystifySettings.DevelopmentMode; [MenuItem("Tools/Demystify/Enable Development Mode")] private static void EnableDevelopmentMode() => DemystifySettings.DevelopmentMode = true; [MenuItem("Tools/Demystify/Disable Development Mode", true)] private static bool DisableDevelopmentModeValidate() => DemystifySettings.DevelopmentMode; [MenuItem("Tools/Demystify/Disable Development Mode")] private static void DisableDevelopmentMode() => DemystifySettings.DevelopmentMode = false; private Vector2 scroll; public override void OnGUI(string searchContext) { base.OnGUI(searchContext); var settings = DemystifySettings.instance; EditorGUI.BeginChangeCheck(); using (var s = new EditorGUILayout.ScrollViewScope(scroll)) { scroll = s.scrollPosition; DrawActivateGUI(settings); DrawSyntaxGUI(settings); EditorGUILayout.Space(10); EditorGUILayout.LabelField("Console Options", EditorStyles.boldLabel); settings.Separator = EditorGUILayout.TextField(new GUIContent("Stacktrace Separator", "Adds a separator to Console stacktrace output between each stacktrace"), settings.Separator); settings.AllowCodePreview = EditorGUILayout.Toggle(new GUIContent("Allow Code Preview", "Show code context in popup window when hovering over console log line with file path"), settings.AllowCodePreview); settings.CodePreviewKeyCode = (KeyCode)EditorGUILayout.EnumPopup(new GUIContent("Code Preview Key", "If None: code preview popup will open on hover. If any key assigned: code preview popup will only open if that key is pressed on hover"), settings.CodePreviewKeyCode); settings.ShortenFilePaths = EditorGUILayout.Toggle(new GUIContent("Shorten File Paths", "When enabled demystify tries to shorten package paths to <package_name>@<version> <fileName><line>"), settings.ShortenFilePaths); settings.ShowFileName = EditorGUILayout.Toggle(new GUIContent("Show Filename", "When enabled demystify will prefix console log entries with the file name of the log source"), settings.ShowFileName); EditorGUILayout.LabelField("Experimental", EditorStyles.boldLabel); settings.AutoFilter = EditorGUILayout.Toggle(new GUIContent("Auto Filter", "When enabled demystify will set the search filter for project asset selection and hierarchy selection (first component it finds)"), settings.AutoFilter); using (var scope = new EditorGUI.ChangeCheckScope()) { settings.ColorMarker = EditorGUILayout.TextField(new GUIContent("Color Marker", "Colored marker added before console log"), settings.ColorMarker); if(scope.changed) DemystifyProjectSettings.RaiseColorsChangedEvent(); } if(DemystifySettings.DevelopmentMode) // using(new EditorGUI.DisabledScope(!settings.DevelopmentMode)) { EditorGUILayout.Space(10); EditorGUILayout.LabelField("Development Settings", EditorStyles.boldLabel); if (GUILayout.Button("Refresh Themes List")) Themes = null; } } // GUILayout.FlexibleSpace(); // EditorGUILayout.Space(10); // using (new EditorGUILayout.HorizontalScope()) // { // settings.DevelopmentMode = EditorGUILayout.ToggleLeft("Development Mode", settings.DevelopmentMode); // } if (EditorGUI.EndChangeCheck()) { settings.Save(); DemystifySettings.RaiseChangedEvent(); } } private static bool SyntaxHighlightSettingsThemeFoldout { get => SessionState.GetBool("Demystify.SyntaxHighlightingThemeFoldout", true); set => SessionState.SetBool("Demystify.SyntaxHighlightingThemeFoldout", value); } public static event Action ThemeEditedOrChanged; private static readonly string[] AlwaysInclude = new[] {"keywords", "link", "string_literal", "comment"}; private static void DrawSyntaxGUI(DemystifySettings settings) { EditorGUILayout.Space(10); EditorGUILayout.LabelField("Syntax Highlighting", EditorStyles.boldLabel); EditorGUI.BeginChangeCheck(); settings.SyntaxHighlighting = (Highlighting) EditorGUILayout.EnumPopup("Syntax Highlighting", settings.SyntaxHighlighting); if (EditorGUI.EndChangeCheck()) { SyntaxHighlighting.OnSyntaxHighlightingModeHasChanged(); ThemeEditedOrChanged?.Invoke(); } DrawThemePopup(); SyntaxHighlightSettingsThemeFoldout = EditorGUILayout.Foldout(SyntaxHighlightSettingsThemeFoldout, "Colors"); if (SyntaxHighlightSettingsThemeFoldout) { var theme = settings.CurrentTheme; if (theme != null) { EditorGUI.BeginChangeCheck(); EditorGUI.indentLevel++; DrawThemeColorOptions(theme); EditorGUI.indentLevel--; if (EditorGUI.EndChangeCheck()) { theme.SetActive(); ThemeEditedOrChanged?.Invoke(); } } } } internal static void DrawThemeColorOptions(Theme theme, bool skipUnused = true) { var currentPattern = SyntaxHighlighting.CurrentPatternsList; for (var index = 0; index < theme.Entries?.Count; index++) { var entry = theme.Entries[index]; var usedByCurrentRegex = AlwaysInclude.Contains(entry.Key) || (currentPattern?.Any(e => e.Contains("?<" + entry.Key)) ?? true); if (skipUnused && !usedByCurrentRegex) continue; // using(new EditorGUI.DisabledScope(!usedByCurrentRegex)) { var col = GUI.color; GUI.color = !usedByCurrentRegex || Theme.Ignored(entry.Color) ? Color.gray : col; entry.Color = EditorGUILayout.ColorField(entry.Key, entry.Color); GUI.color = col; } } } private static void DrawActivateGUI(DemystifySettings settings) { if (!UnityDemystify.Patches().All(PatchManager.IsActive)) { if (GUILayout.Button(new GUIContent("Enable Demystify", "Enables patches:\n" + string.Join("\n", UnityDemystify.Patches()) ))) UnityDemystify.Enable(true); EditorGUILayout.HelpBox("Demystify is disabled, click the Button above to enable it", MessageType.Info); } else { if (GUILayout.Button(new GUIContent("Disable Demystify", "Disables patches:\n" + string.Join("\n", UnityDemystify.Patches()) ))) UnityDemystify.Disable(); } } /// <summary> /// this is just for internal use and "visualizing" via GUI /// </summary> internal static void ApplySyntaxHighlightingMultiline(ref string str, Dictionary<string, string> colorDict = null) { var lines = str.Split('\n'); str = ""; // Debug.Log("lines: " + lines.Count()); foreach (var t in lines) { var line = t; var pathIndex = line.IndexOf("C:/git/", StringComparison.Ordinal); if (pathIndex > 0) line = line.Substring(0, pathIndex - 4); if (!line.TrimStart().StartsWith("at ")) line = "at " + line; SyntaxHighlighting.AddSyntaxHighlighting(ref line, colorDict); line = line.Replace("at ", ""); str += line + "\n"; } } private static string[] ThemeNames; private static Theme[] Themes; private static void EnsureThemeOptions() { if (ThemeNames == null || Themes == null) { var themeAssets = AssetDatabase.FindAssets("t:" + nameof(SyntaxHighlightingTheme)).Select(AssetDatabase.GUIDToAssetPath).ToArray(); ThemeNames = new string[themeAssets.Length]; Themes = new Theme[ThemeNames.Length]; for (var index = 0; index < themeAssets.Length; index++) { var path = themeAssets[index]; var asset = AssetDatabase.LoadAssetAtPath<SyntaxHighlightingTheme>(path); if (asset.theme == null) asset.theme = new Theme("Unknown"); ThemeNames[index] = asset.theme.Name; Themes[index] = asset.theme; } } else if(ThemeNames != null && Themes != null && ThemeNames.Length == Themes.Length) { for (var index = 0; index < Themes.Length; index++) { var t = Themes[index]; ThemeNames[index] = t.Name; } } } private static int ActiveThemeIndex() { var active = DemystifySettings.instance.CurrentTheme; for (var index = 0; index < Themes.Length; index++) { var theme = Themes[index]; if (theme.Equals(active) || theme.Name == active.Name) return index; } return -1; } private static void DrawThemePopup() { EnsureThemeOptions(); EditorGUI.BeginChangeCheck(); var selected = EditorGUILayout.Popup("Theme", ActiveThemeIndex(), ThemeNames); if(selected >= 0 && selected < Themes.Length) DemystifySettings.instance.CurrentTheme = Themes[selected]; if (EditorGUI.EndChangeCheck()) { DemystifySettings.instance.Save(); ThemeEditedOrChanged?.Invoke(); } } private class AssetProcessor : AssetPostprocessor { private void OnPreprocessAsset() { ThemeNames = null; Themes = null; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Cedvel { public partial class Form1 : Form { public int id { get; set; } public int AutoIncrement { get; set; } public List<Person> people { get; set; } public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { people = new List<Person>(); Person person = new Person() { Id = 1, Name = "Rufat", Surname = "Gasimov", Email = "rufatfq@code.edu.az" }; people.Add(person); AutoIncrement = 1; FillList(); } public void FillList() { dgv.DataSource = null; dgv.DataSource = people; } private void btnAdd_Click(object sender, EventArgs e) { Person person = new Person() { Id = ++AutoIncrement, Name = txbName.Text, Surname = txbSurname.Text, Email = txbEmail.Text }; people.Add(person); FillList(); } private void dgv_RowHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e) { id = Convert.ToInt32(dgv.Rows[e.RowIndex].Cells[0].Value); var person = people.Where(p => p.Id == id).FirstOrDefault(); txbEmail.Text = person.Email; txbName.Text = person.Name; txbSurname.Text = person.Surname; btnUpdate.Visible = true; btnRemove.Visible = true; } private void btnRemove_Click(object sender, EventArgs e) { DialogResult res = MessageBox.Show("Are you sure you want to Delete", "Confirmation", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); if (res == DialogResult.OK) { var person = people.Where(p => p.Id == id).FirstOrDefault(); people.Remove(person); FillList(); } if (res == DialogResult.Cancel) { MessageBox.Show("You have clicked Cancel Button"); //Some task… } } private void btnUpdate_Click(object sender, EventArgs e) { var person = people.Where(p => p.Id == id).FirstOrDefault(); person.Name = txbName.Text; person.Surname = txbSurname.Text; person.Email = txbEmail.Text; FillList(); } } }
using System.Net; namespace AxiEndPoint.EndPointClient { public interface IEndPointClientService { IResponse Send(IRequest request); bool TrySend<TResult>(IRequest request, out TResult result); IResponse Send(IRequest request, IPEndPoint ipEndPoint); bool TrySend<TResult>(IRequest request, IPEndPoint ipEndPoint, out TResult result); } }