text
stringlengths
13
6.01M
using System.Collections.Generic; using System.Linq; using Umbraco.Core.Models.PublishedContent; namespace Uintra.Features.CentralFeed.Providers { public abstract class ContentProviderBase { //protected virtual IPublishedContent GetContent(IEnumerable<string> xPath) => // _umbracoHelper.ContentSingleAtXPath(XPathHelper.GetXpath(xPath)); protected virtual IPublishedContent GetContent(IEnumerable<string> aliasesPath) { IEnumerable<IPublishedContent> targetContents = Umbraco.Web.Composing.Current.UmbracoHelper.ContentAtRoot(); foreach (var alias in aliasesPath) { targetContents = targetContents.Where(x => x.ContentType.Alias == alias).SelectMany(x => x.Children); } return targetContents.FirstOrDefault(); } protected virtual IEnumerable<IPublishedContent> GetDescendants(IEnumerable<string> aliasesPath) { return GetContent(aliasesPath).Children; } } }
using UnityEngine; using System.Collections; using System.Collections.ObjectModel; using System.Collections.Generic; using System.Threading; using MainCharacter; using InControl; public class MainCharacterDriver : CharacterDriver { GameObject[] colorPieces; float currentCooldown = 0; int rainbowCooldown = 2; public float invulnTime; public float invulnCounter = 0; bool pause = false; public string inputRed = "OffRed"; public string inputBlue = "OffBlue"; public string inputYellow = "OffYellow"; public string inputGreen = "OffGreen"; public string inputOrange = "OffOrange"; public string inputPurple = "OffPurple"; public string inputHorizontal = "Horizontal"; public string inputVertical = "Vertical"; /*These are the Forms of the ship *The forms comprise of * - Projectile Cooldown * - Projectile itself * - Projectile Speed * - Color of ship * - Speed of ship */ //Arcus Animator private const float ALPHA_PER_SEC = 0.1f; //Used for returning to the form we were in before switching to secondary public static Form previousForm; private SecondaryForm greenForm; private SecondaryForm orangeForm; private SecondaryForm purpleForm; private RainbowForm rainbowForm; private bool isInSecondary = false; public static string arcusName = ""; //Sounds public AudioClip bulletSound; public AudioClip bumpSound; public AudioClip absorbSound; //Pause screenshot public GameObject pauseScreen; // Use this for initialization new void Start () { base.Start(); Application.targetFrameRate = 60; arcusName = gameObject.name; colorPieces = GameObject.FindGameObjectsWithTag ("ArcusColor"); redForm = GetComponent<RedForm>(); blueForm = GetComponent<BlueForm>(); yellowForm = GetComponent<YellowForm>(); greenForm = GetComponent<GreenForm>(); orangeForm = GetComponent<OrangeForm>(); purpleForm = GetComponent<PurpleForm>(); rainbowForm = GetComponent<RainbowForm>(); if (previousForm == null) { previousForm = redForm; } else { if (previousForm.shipColor == ShipColor.RED) { previousForm = redForm; } else if (previousForm.shipColor == ShipColor.BLUE) { previousForm = blueForm; } else if (previousForm.shipColor == ShipColor.YELLOW) { previousForm = yellowForm; } else { previousForm = redForm; } } if (currentForm == null) { currentForm = redForm; } else { if (currentForm.shipColor == ShipColor.RED) { currentForm = redForm; } else if (currentForm.shipColor == ShipColor.BLUE) { currentForm = blueForm; } else if (currentForm.shipColor == ShipColor.YELLOW) { currentForm = yellowForm; } else if (currentForm.shipColor == ShipColor.GREEN) { currentForm = greenForm; } else if (currentForm.shipColor == ShipColor.ORANGE) { currentForm = orangeForm; } else if (currentForm.shipColor == ShipColor.PURPLE) { currentForm = purpleForm; } else if (currentForm.shipColor == ShipColor.RAINBOW) { currentForm = rainbowForm; } else { currentForm = redForm; } } if (lostGame) { health = 100; ColorPower.Instance.powerRed = 0; ColorPower.Instance.powerBlue = 0; ColorPower.Instance.powerYellow = 0; } else { redForm.setPower(ColorPower.Instance.powerRed); blueForm.setPower(ColorPower.Instance.powerBlue); yellowForm.setPower(ColorPower.Instance.powerYellow); } switchForm (currentForm); uiDriver = gameObject.GetComponent<UIDriver>(); if (currentForm.shipColor == ShipColor.BLUE) { uiDriver.RotateToBlue(); } else if (currentForm.shipColor == ShipColor.RED) { uiDriver.RotateToRed(); } else if (currentForm.shipColor == ShipColor.YELLOW) { uiDriver.RotateToYellow(); } uiDriver.UpdateBars(); lostGame = false; if(ControlScheme.isOneHanded){ InputManager.AttachDevice(new UnityInputDevice(new KeyboardPlayerSoloAlternateProfile())); }else{ InputManager.AttachDevice(new UnityInputDevice(new KeyboardPlayerSoloProfile())); } } // Update is called once per frame protected override void Update () { //ZH 3-14: Moved code to actually pause to BackGround UI //Not sure what this does though, leaving it if(Input.GetKeyDown(KeyCode.Escape)){ pause = !pause; } if (gameOver || pause) { return; } invulnCounter -= Time.deltaTime; if (invulnCounter > 0) { foreach (Renderer obj in GetComponentsInChildren<Renderer>()) { obj.enabled = ! obj.enabled; } } else { foreach (Renderer obj in GetComponentsInChildren<Renderer>()) { obj.enabled = true; } } //Get the most recent input device from incontrol //Keyboard controls can be represented as an InputDevice using a CustomController device = InputManager.ActiveDevice; //Get where to move given user input PressMove(device.Direction.X, device.Direction.Y); //change the cooldown of the main weapon, as one frame has passed currentCooldown -= Time.deltaTime; //FIRE!!! if (device.RightTrigger) { PressFire(); } if (currentForm.shipColor == ShipColor.RAINBOW) { if (rainbowCooldown % 3 == 0) { //Color newColor = new Color(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f), 1.0f); for (int i = 0; i < colorPieces.Length; i++) { Color newColor = new Color (Random.Range (0.0f, 1.0f), Random.Range (0.0f, 1.0f), Random.Range (0.0f, 1.0f), 1.0f); colorPieces [i].renderer.material.color = newColor; } } rainbowCooldown = rainbowCooldown - 1; if (rainbowCooldown <= 0) { rainbowCooldown = 10; setRedPower(ColorPower.Instance.powerRed - 1); setBluePower(ColorPower.Instance.powerRed - 1); setYellowPower(ColorPower.Instance.powerRed - 1); uiDriver.UpdateBars (); } if (ColorPower.Instance.powerBlue <= 0) { previousForm = previousForm.shipColor == ShipColor.RAINBOW ? redForm : previousForm; switchForm (previousForm); blueForm.resetCooldown (); redForm.resetSpeed (); } return; } else if (isInSecondary) { if (((SecondaryForm)currentForm).isDeactivated()) { switchForm(previousForm); isInSecondary = false; } } //Take input //For multiplayer these will need to be exclusive, but for now both can move ship if (device.Action4) { PressYellow(); } else if (device.Action3) { PressBlue(); } else if (device.Action2) { PressRed(); } else if (Input.GetKeyDown(KeyCode.PageDown)) { setRedPower(100); setBluePower(100); setYellowPower(100); redForm.setSpeed (redForm.getSpeed () + ColorPower.Instance.powerRed / 30); blueForm.setCooldown (blueForm.getCooldown () - 0.15f); uiDriver.UpdateBars(); } base.Update(); } public void PressFire() { //FIRE!!! if (currentCooldown <= 0) { currentCooldown = currentForm.getCooldown(); Fire(); } } //Switch to Yellow Form public void PressYellow() { if (!isInSecondary) { switchForm(yellowForm); uiDriver.RotateToYellow(); } } //Switch to Red Form public void PressRed() { if (!isInSecondary) { switchForm(redForm); uiDriver.RotateToRed(); } } //Switch to Blue Form public void PressBlue() { if (!isInSecondary) { switchForm(blueForm); uiDriver.RotateToBlue(); } } //Switch to PURPLE FORM public override void UsePurple() { setRedPower(ColorPower.Instance.powerRed); setBluePower(ColorPower.Instance.powerBlue); switchForm(purpleForm); purpleForm.Activate(); uiDriver.UpdateBars(); isInSecondary = true; } //Switch to GREEN FORM public override void UseGreen() { setBluePower(ColorPower.Instance.powerBlue); setYellowPower(ColorPower.Instance.powerYellow); //For Green form, we just want to heal and not do stuff //switchForm(greenForm); greenForm.Activate(); uiDriver.UpdateBars(); //isInSecondary = true; } //Switch to ORANGE Form public override void UseOrange() { setRedPower(ColorPower.Instance.powerRed); setYellowPower(ColorPower.Instance.powerYellow); switchForm(orangeForm); orangeForm.Activate(); uiDriver.UpdateBars(); isInSecondary = true; } public void OnTriggerEnter(Collider col){ if(col.gameObject.layer == LayerMask.NameToLayer("Asteroid")){ // Only handle hit if not invulnerable if (invulnCounter <= 0) { // Set invulnerability invulnCounter = currentForm.shipColor == ShipColor.RAINBOW ? 0 : invulnTime; audio.PlayOneShot(bumpSound); if (currentForm.shipColor != ShipColor.RAINBOW) { TakeDamage(); } } } } public void OnCollisionEnter(Collision col) { // Form.TakeHit() returns true if the bullet cannot be absorbed, else it returns false if (/*col.gameObject.layer == LayerMask.NameToLayer("Enemy") ||*/ currentForm.TakeHit(col)) { // Only handle hit if not invulnerable if (invulnCounter <= 0) { // Set invulnerability invulnCounter = currentForm.shipColor == ShipColor.RAINBOW ? 0 : invulnTime; audio.PlayOneShot(bumpSound); // If in a secondary form, switch back to the previous form /*if (currentForm.shipColor == ShipColor.PURPLE || currentForm.shipColor == ShipColor.ORANGE || currentForm.shipColor == ShipColor.GREEN) { switchForm(previousForm); // Only take damage if not in rainbow mode } else */ if (currentForm.shipColor != ShipColor.RAINBOW) { TakeDamage(); } } // Absorbed the bullet } else { ColorPower.Instance.powerBlue = blueForm.power; ColorPower.Instance.powerRed = redForm.power; ColorPower.Instance.powerYellow = yellowForm.power; uiDriver.UpdateBars(); audio.PlayOneShot(absorbSound); } if (yellowForm.atMaxPower() && blueForm.atMaxPower() && redForm.atMaxPower()) { previousForm = currentForm; switchForm(rainbowForm); } } protected override void GameOver() { base.GameOver(); BackgroundUI.Instance.ShowLoseScreen(); } void Fire() { audio.PlayOneShot(bulletSound); currentForm.Fire(); } void switchForm(Form form){ previousForm = currentForm; currentForm = form; for (int i = 0; i < colorPieces.Length; i++) { colorPieces[i].renderer.material = currentForm.material; } currentCooldown = currentForm.getCooldown(); } public void ResetForm(){ switchForm (redForm); } private void setRedPower(float p) { redForm.power = p; ColorPower.Instance.powerRed = p; } private void setBluePower(float p) { blueForm.power = p; ColorPower.Instance.powerBlue = p; } private void setYellowPower(float p) { yellowForm.power = p; ColorPower.Instance.powerYellow = p; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Memory { class GameClass { Square[] all = new Square[17]; List<Square> listSelected; List<Square> listGuessed; public GameClass() { } Random random = new Random(); public Square[] shuffle(Square[] allArray) { for (int i = allArray.Length - 1; i >= 1; i--) { int j = random.Next(0, i); swap(allArray[j], allArray[i]); } return allArray; } public void swap(Square x, Square y) { Square z = null; z = x; x = y; y = z; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace Zombies3 { class Camera { Player player; Vector2 position; Rectangle screen; Game game; Matrix transform; public Camera(Game game, Rectangle screen) { this.screen = screen; this.game = game; position = new Vector2(screen.Width / 2, screen.Height / 2); } public void Initialize() { this.player = game.Services.GetService(typeof(Player)) as Player; } public Matrix Transform(GraphicsDevice graphics) { float ViewPortWidth = graphics.Viewport.Width; float ViewPortHeight = graphics.Viewport.Height; transform = Matrix.CreateTranslation(new Vector3(-player.Position.X, -player.Position.Y, 0)) * //Matrix.CreateRotationZ(-player.Rotation - (float)(3.141/2)) * Matrix.CreateTranslation(new Vector3(ViewPortWidth * 0.5f, ViewPortHeight * 0.5f, 0)); return transform; } public Vector2 GlobalToLocal(Vector2 pos) { GraphicsDevice g; //pos -= (pos - new Vector2(screen.Width / 2, screen.Height / 2)); pos = Vector2.Transform(pos,transform); return pos; } public Vector2 LocalToGLobal(Vector2 pos) { Matrix inv; inv = Matrix.Invert(transform); pos = Vector2.Transform(pos,inv); return pos; } } }
#version 450 layout (local_size_x = 32, local_size_y = 32) in; layout (binding = 0, rgba32f) readonly uniform image2D img_input; layout (binding = 1) writeonly uniform image2D img_output; //const float weights[] = float[](0.0024499299678342, 0.0043538453346397, 0.0073599963704157, 0.0118349786570722, 0.0181026699707781, 0.0263392293891488, 0.0364543006660986, 0.0479932050577658, 0.0601029809166942, 0.0715974486241365, 0.0811305381519717, 0.0874493212267511, 0.0896631113333857, 0.0874493212267511, 0.0811305381519717, 0.0715974486241365, 0.0601029809166942, 0.0479932050577658, 0.0364543006660986, 0.0263392293891488, 0.0181026699707781, 0.0118349786570722, 0.0073599963704157, 0.0043538453346397, 0.0024499299678342); const float kernel[3][3] = {{1/16.0, 2/16.0, 1/16.0}, {2/16.0, 4/16.0, 2/16.0}, {1/16.0, 2/16.0, 1/16.0}}; shared vec4 mem[32][32]; void main() { ivec2 pixel_coords = ivec2(gl_GlobalInvocationID.xy); vec4 pixel = vec4(0.0f); mem[gl_LocalInvocationID.y][gl_LocalInvocationID.x] = imageLoad(img_input, pixel_coords); barrier(); //memoryBarrierShared(); for(int i = 0; i < 2; i++) for(int y = 0; y < kernel.length(); y++) for(int x = 0; x < kernel[0].length(); x++) pixel += mem[gl_LocalInvocationID.y+y-1][gl_LocalInvocationID.x+x-1] * max(0.0, kernel[y][x]); barrier(); //pixel = vec4(1.0f) - pixel; imageStore(img_output, pixel_coords, pixel); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using DigitalFormsSteamLeak.Entity.IModels; namespace DigitalFormsSteamLeak.Entity.Models { [Table("T_Malfunction_Session")] public class MalfunctionSession : IMalfunctionSession { [Key] [Column("Malfunction_Id")] public Guid MalfunctionId { get; set; } [Required] [Column("Malfunction_Comments")] public string MalfunctionComments { get; set; } [Required] [Column("Is_LokRing_Job_Required")] public string IsLokRingJobRequired { get; set; } [Required] [Column("Is_Break_In")] public string IsBreakIn { get; set; } [Required] [Column("Is_Turn_Around_Item")] public string IsTurnAroudItem { get; set; } [Required] [Column("Is_Down_Time_Required")] public string IsDownTimeRequired { get; set; } [Required] [Column("Is_Man_Lift_Required")] public string IsManLiftRequired { get; set; } [Required] [Column("Is_First_Time_Pump")] public string IsFirstTimePump { get; set; } [Required] [Column("Is_Re_Pump")] public string IsRePump { get; set; } [Required] [Column("Is_Install_Clamp_Required")] public string IsInstallClampRequired { get; set; } [Required] [Column("Is_Wire_Wrap_Required")] public string IsWirewrapRequired { get; set; } [Required] [Column("OnHold")] public string OnHold { get; set; } [Required] [Column("Leak_Details_Id")] public Guid LeakDetailsId { get; set; } public virtual LeakDetails LeakDetails { get; set; } } }
using Microsoft.Extensions.Options; using Microsoft.WindowsAzure.Storage; using Microsoft.WindowsAzure.Storage.Blob; using PlatformStatusTracker.Core.Configuration; using PlatformStatusTracker.Core.Enum; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PlatformStatusTracker.Core.Repository { public interface IStatusRawDataRepository { Task InsertAsync(StatusDataType dataType, DateTime date, string content); Task<string> GetByDateAsync(StatusDataType dataType, DateTime date); } public class StatusRawDataAzureStorageRepository : IStatusRawDataRepository { private readonly string _connectionString; private bool _tableExists; public StatusRawDataAzureStorageRepository(IOptions<ConnectionStringOptions> connectionStringOptions) : this(connectionStringOptions.Value.AzureStorageConnectionString) { } public StatusRawDataAzureStorageRepository(string connectionString) { _connectionString = connectionString; } public async Task InsertAsync(StatusDataType dataType, DateTime date, string content) { var container = await GetContainerAsync(); var typeNameV2 = dataType == StatusDataType.InternetExplorer ? "Edge" : dataType.ToString(); var data = Encoding.UTF8.GetBytes(content); await container.GetBlockBlobReference($"{typeNameV2}/{date.ToString("yyyyMMdd")}.json").UploadFromByteArrayAsync(data, 0, data.Length).ConfigureAwait(false); } public async Task<string> GetByDateAsync(StatusDataType dataType, DateTime date) { var container = await GetContainerAsync(); var typeNameV2 = dataType == StatusDataType.InternetExplorer ? "Edge" : dataType.ToString(); return await container.GetBlockBlobReference($"{typeNameV2}/{date.ToString("yyyyMMdd")}.json").DownloadTextAsync().ConfigureAwait(false); } private async Task<CloudBlobContainer> GetContainerAsync() { var storageAccount = CloudStorageAccount.Parse(_connectionString); var blobClient = storageAccount.CreateCloudBlobClient(); var container = blobClient.GetContainerReference("statuses"); if (!_tableExists) { await container.CreateIfNotExistsAsync().ConfigureAwait(false); _tableExists = true; } return container; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Ejercicio_29 { public class Equipo { private short cantidadDeJugadores; private List<Jugador> jugadores; private string nombre; private Equipo() { jugadores = new List<Jugador>(); } public Equipo(short cantidad, string nombre) :this() { this.cantidadDeJugadores = cantidad; this.nombre = nombre; } public StringBuilder MostrarJugadores(Equipo e) { StringBuilder sb = new StringBuilder(); sb.AppendLine($"Los jugadores de {e.nombre} son:\n"); foreach (Jugador jugador in e.jugadores) { sb.AppendLine($"{jugador.MostrarDatos()}\n"); } return sb; } //La sobrecarga del operador + agregará jugadores a la lista siempre y cuando este no exista aun en el equipo y la cantidad de jugadores no supere el límite establecido por el atributo cantidadDeJugadores public static bool operator +(Equipo e, Jugador j) { bool existe = false; foreach (Jugador jug in e.jugadores) { if(jug == j) { existe = true; break; } } if (!existe && (e.jugadores.Count < e.cantidadDeJugadores || e.jugadores == null)) // si no lo contiene y si la lista tiene menos jugadores de lo establecido { e.jugadores.Add(j); return true; } else { return false; } } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; namespace ISE.SM.Utility { public static class ImageCombiner { private static readonly EncoderParameters encoderParameters = new EncoderParameters(1); private static readonly RectangleF sizeLocation1 = new RectangleF(0.0F, 0.0F, 400.0F, 400.0F); private static readonly RectangleF sizeLocation2 = new RectangleF(400.0F, 0.0F, 400.0F, 400.0F); private static readonly ImageCodecInfo jpgDecoder = ImageCodecInfo.GetImageDecoders().Single(codec => codec.FormatID == ImageFormat.Jpeg.Guid); private static readonly byte[] emptyImage = new byte[0]; static ImageCombiner() { encoderParameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L); } public static System.Drawing.Bitmap CombineBitmap(List<Image> images) { //read all images into memory System.Drawing.Bitmap finalImage = null; try { int width = 0; int height = 0; foreach (Image image in images) { //create a Bitmap from the file and add it to the list System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(image); //update the size of the final bitmap width += bitmap.Width; height = bitmap.Height > height ? bitmap.Height : height; images.Add(bitmap); } //create a bitmap to hold the combined image finalImage = new System.Drawing.Bitmap(width, height); //get a graphics object from the image so we can draw on it using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(finalImage)) { //set background color g.Clear(System.Drawing.Color.Black); //go through each image and draw it on the final image int offset = 0; foreach (System.Drawing.Bitmap image in images) { g.DrawImage(image, new System.Drawing.Rectangle(offset, 0, image.Width, image.Height)); offset += image.Width; } } return finalImage; } catch (Exception ex) { if (finalImage != null) finalImage.Dispose(); throw ex; } finally { //clean up memory foreach (System.Drawing.Bitmap image in images) { image.Dispose(); } } } // Crops two squares out of two separate images // And then combines them into single image that's returned as byte[] public static Image CombineImages(Image image1,Image image2) { try { int width = image1.Width*2; int height = image1.Height; using (var ms = new MemoryStream()) using (var bitmap = new Bitmap(width, height, image1.PixelFormat)) using (var img1 = image1) using (var img2 = image2) using (var g = Graphics.FromImage(bitmap)) { g.DrawImage(img1, sizeLocation1, GetCropParams(img1), GraphicsUnit.Pixel); g.DrawImage(img2, sizeLocation2, GetCropParams(img2), GraphicsUnit.Pixel); bitmap.Save(ms, jpgDecoder, encoderParameters); return Image.FromStream(ms); } } catch { return null; } } private static RectangleF GetCropParams(Image img) { return img.Width > img.Height ? new RectangleF( (img.Width / 2) - (img.Height / 2), 0.0F, 2 * (img.Height / 2), img.Height) : new RectangleF( 0.0F, (img.Height / 2) - (img.Width / 2), img.Width, 2 * (img.Width / 2)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.UI; using CAPCO.Infrastructure.Domain; using CAPCO.Infrastructure.Data; using CAPCO.Models; using CAPCO.Infrastructure.Services; using CAPCO.Infrastructure.Mailers; using System.Web.Security; using CAPCO.Helpers; using CAPCO.Areas.Admin.Models; using PagedList; using CAPCO.Infrastructure.Specifications; using Mvc.Mailer; namespace CAPCO.Areas.Admin.Controllers { public class UsersController : BaseAdminController { private readonly IApplicationUserService _AppUserService; private readonly IRepository<PickupLocation> _LocationRepository; private readonly IRepository<DiscountCode> _DiscountCodeRepository; private readonly IRepository<ApplicationUser> applicationuserRepository; public UsersController(IRepository<ApplicationUser> applicationuserRepository, IApplicationUserService appUserService, IRepository<PickupLocation> locationRepository, IRepository<DiscountCode> discountCodeRepository) { _DiscountCodeRepository = discountCodeRepository; _LocationRepository = locationRepository; _AppUserService = appUserService; this.applicationuserRepository = applicationuserRepository; } private void Init() { ViewBag.PossibleDiscountCodes = _DiscountCodeRepository.All.ToList(); ViewBag.PossibleLocations = _LocationRepository.All.ToList(); } public ViewResult Index(PagedViewModel<ApplicationUser> model) { var results = applicationuserRepository.All.OrderBy(x => x.UserName); model.TotalCount = results.Count(); model.Entities = results.ToPagedList(model.Page ?? 1, 100); return View("Index", model); } public ActionResult Search(PagedViewModel<ApplicationUser> model) { var results = applicationuserRepository.FindBySpecification(new UsersByUserNameOrCompanyNameSpecification(model.Criteria)).OrderBy(x => x.UserName); model.TotalCount = results.Count(); model.Entities = results.ToPagedList(model.Page ?? 1, 100); return View("Index", model); } public ActionResult Show(int id) { ApplicationUser user = applicationuserRepository.AllIncluding(x => x.DiscountCode, x => x.DefaultLocation, x => x.Notifications).FirstOrDefault(x => x.Id == id); if (user == null) { this.FlashError("There is no user with that id."); return RedirectToAction("index"); } return View(user); } public ActionResult New() { Init(); return View(); } [HttpPost, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Create(ApplicationUser applicationuser) { if (ModelState.IsValid) { try { var selectedRole = Request["SelectedRole"] != null ? (UserRoles)Enum.Parse(typeof(UserRoles), Request["SelectedRole"]) : UserRoles.ApplicationUsers; var newUser = _AppUserService.CreateNewUser(applicationuser, selectedRole); newUser.CanReceiveSystemEmails = true; newUser.CanReceiveMarketingEmails = true; newUser.PricePreference = PricePreferences.None.ToString(); newUser.State = Request["SelectedState"] != null ? ((States)Enum.Parse(typeof(States), Request["SelectedState"])).ToString() : ""; string selectedStatus = Request["SelectedStatus"] ?? AccountStatus.Active.ToString(); newUser.Status = ((AccountStatus)Enum.Parse(typeof(AccountStatus), selectedStatus)).ToString(); int locationId = 0; if (Int32.TryParse(Request["SelectedLocation"], out locationId)) { newUser.DefaultLocation = _LocationRepository.Find(locationId); } int discontCodeId = 0; if (Int32.TryParse(Request["SelectedDiscountCode"], out discontCodeId)) { newUser.DiscountCode = _DiscountCodeRepository.Find(discontCodeId); } applicationuserRepository.InsertOrUpdate(newUser); applicationuserRepository.Save(); new ApplicationUserMailer().Activation(newUser).Send(); this.FlashInfo("The user was successfully created. A welcome email with their username and password has been sent."); return RedirectToAction("Index", "Users", new { area = "admin" }); } catch (Exception ex) { // ensure user roll back _AppUserService.DeleteMember(applicationuser.UserName); //ModelState.AddModelError("MembershipException", ex); this.FlashError(ex.Message); } } //this.FlashError("There was a problem creating the user."); ViewBag.SelectedRole = Request["SelectedRole"]; ViewBag.SelectedState = Request["SelectedState"]; Init(); return View("New", applicationuser); } public ActionResult Edit(int id) { ApplicationUser user = applicationuserRepository.AllIncluding(x => x.DiscountCode, x => x.DefaultLocation, x => x.Notifications).FirstOrDefault(x => x.Id == id); if (user == null) { this.FlashError("There is no user with that id."); return RedirectToAction("index"); } Init(); return View(user); } [HttpPut, ValidateAntiForgeryToken, ValidateInput(false)] public ActionResult Update(ApplicationUser applicationuser) { try { var user = applicationuserRepository.Find(applicationuser.Id); var memUser = Membership.GetUser(user.UserName); user.Email = applicationuser.Email; try { memUser.Email = applicationuser.Email; Membership.UpdateUser(memUser); } catch (Exception ex) { throw new Exception("The email address is invalid or is already in use."); } user.AccountNumber = applicationuser.AccountNumber; user.City = applicationuser.City; user.CompanyName = applicationuser.CompanyName; user.Fax = applicationuser.Fax; user.FirstName = applicationuser.FirstName; user.IsActivated = applicationuser.IsActivated; user.LastName = applicationuser.LastName; user.Phone = applicationuser.Phone; user.StreetAddressLine1 = applicationuser.StreetAddressLine1; user.StreetAddressLine2 = applicationuser.StreetAddressLine2; user.State = applicationuser.State; user.Zip = applicationuser.Zip; user.State = Request["SelectedState"] != null ? ((States)Enum.Parse(typeof(States), Request["SelectedState"])).ToString() : user.State; int locationId = 0; if (Int32.TryParse(Request["SelectedLocation"], out locationId)) { user.DefaultLocation = _LocationRepository.Find(locationId); } int discontCodeId = 0; if (Int32.TryParse(Request["SelectedDiscountCode"], out discontCodeId)) { user.DiscountCode = _DiscountCodeRepository.Find(discontCodeId); } user.Status = Request["SelectedStatus"] != null && !String.IsNullOrWhiteSpace(Request["SelectedStatus"]) ? ((AccountStatus)Enum.Parse(typeof(AccountStatus), Request["SelectedStatus"])).ToString() : AccountStatus.Active.ToString(); var selectedRole = Request["SelectedRole"] != null && !String.IsNullOrWhiteSpace(Request["SelectedRole"]) ? (UserRoles)Enum.Parse(typeof(UserRoles), Request["SelectedRole"]) : UserRoles.ApplicationUsers; // clear user from all roles Roles.RemoveUserFromRoles(user.UserName, Roles.GetRolesForUser(user.UserName)); // add user to selected role Roles.AddUserToRole(user.UserName, selectedRole.ToString()); applicationuserRepository.InsertOrUpdate(user); applicationuserRepository.Save(); this.FlashInfo("The user was successfully saved."); return RedirectToAction("Index"); } catch (Exception ex) { this.FlashError("There was a problem saving the user: " + ex.Message); } Init(); return View("Edit", applicationuser); } public ActionResult Delete(int id) { try { var user = applicationuserRepository.Find(id); string username = user.UserName; applicationuserRepository.Detach(user); applicationuserRepository.Delete(id); applicationuserRepository.Save(); _AppUserService.DeleteMember(username); this.FlashInfo("The user was successfully deleted."); return RedirectToAction("Index"); } catch (Exception ex) { this.FlashError("There was a problem deleting the user: " + ex.Message); } return RedirectToAction("edit", new { id = id }); } public ActionResult ResetPassword(int id) { var appUser = applicationuserRepository.Find(id); if (appUser != null) { try { var user = Membership.GetUser(appUser.UserName); var newPassword = user.ResetPassword(); // send the user an email stating their password has changed. new ApplicationUserMailer().PasswordReset(!String.IsNullOrWhiteSpace(appUser.FirstName) ? appUser.FirstName : appUser.CompanyName, appUser.UserName, newPassword, user.Email).Send(); this.FlashInfo("The user's password was reset and sent to the email address on file."); } catch (Exception ex) { this.FlashError("There was a problem resetting the user's password: " + ex.Message); } } else { this.FlashError("I could not find a user with that id."); } return RedirectToAction("Show", new { id }); } public ActionResult UnlockUser(int id) { var appUser = applicationuserRepository.Find(id); if (appUser != null) { try { var user = Membership.GetUser(appUser.UserName); if (user.IsLockedOut) user.UnlockUser(); // send the user an email stating their password has changed. this.FlashInfo("The user has been unlocked."); } catch (Exception ex) { this.FlashError("There was a problem unlocking the user: " + ex.Message); } } else { this.FlashError("I could not find a user with that id."); } return RedirectToAction("Show", new { id }); } } }
using System; namespace DEV_7 { public class CommonTriangle : Triangle { private double a, b, c; public CommonTriangle (double aSide, double bSide, double cSide) { a = aSide; b = bSide; c = cSide; } public override string GetType() { return "Common triangle"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UNO.Model.Karten { class FarbwechselKarte:IKarte { public KartenTyp Typ => KartenTyp.Farbwechsel; public KartenFarbe Farbe { get; set; } public int KartenZiehen { get; } public int Zahl { get; } public FarbwechselKarte() { Farbe = KartenFarbe.Schwarz; } } }
using System.Collections.Generic; using Lanches.Web.Models; using Lanches.Web.ViewModels; using Microsoft.AspNetCore.Mvc; namespace Lanches.Web.Components { public class CarrinhoCompraResumo : ViewComponent { private readonly CarrinhoCompra _carrinhoCompra; public CarrinhoCompraResumo (CarrinhoCompra carrinhoCompra) { _carrinhoCompra = carrinhoCompra; } public IViewComponentResult Invoke () { var itens = _carrinhoCompra.GetCarrinhoCompraItens(); //var itens = new List<CarrinhoCompraItem>(){ // new CarrinhoCompraItem(), // new CarrinhoCompraItem() // }; _carrinhoCompra.CarrinhoCompraItens = itens; var carrinhoCompraVm =new CarrinhoCompraViewModel(){ CarrinhoCompra = _carrinhoCompra, CarrinhoCompraTotal = _carrinhoCompra.GetValorTotal() }; return View(carrinhoCompraVm); } } }
using System; using System.Windows.Forms; namespace BlackJack { public partial class Form_black_jack : Form { public Form_black_jack() { InitializeComponent(); } #region Button private void btn_Single_Player_Click(object sender, EventArgs e) { Form_Single_Game f_single = new Form_Single_Game(); this.Hide(); f_single.Show(); } private void btn_Multi_Player_Click(object sender, EventArgs e) { Form_multi_player f_multi = new Form_multi_player(); this.Hide(); f_multi.Show(); } private void btn_About_Click(object sender, EventArgs e) { Form_about f_about = new Form_about(); this.Hide(); f_about.Show(); } private void btn_Exit_Click(object sender, EventArgs e) { Application.Exit(); } #endregion #region Event private void Form_black_jack_FormClosed(object sender, FormClosedEventArgs e) { Application.Exit(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WcfServiceHost.ITS_Service { public class MethodResult { public Status Status { get; set; } public string Result { get; set; } } public enum Status { Error, Success, information } }
using Newtonsoft.Json; namespace BigEgg.PDFOrganizer.Models { [JsonObject("block")] public class SplitBlockModel { [JsonProperty("name", Required = Required.Always)] public string Name { get; set; } [JsonProperty("start", Required = Required.Always)] public int StartPage { get; set; } [JsonProperty("end", Required = Required.Always)] public int EndPage { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameGuide : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void OnSkipClick() { GameSceneManager.LoadScene("HomeScreen"); } }
/********************************************************* * Hyukin Kwon * Save The Date * * PlatformMovement * Created: 27 November 2019 * Last Modified: 17 Jan 2020 * * Inherits from Monobehaviour * * * - Moving Platform through waypoints * - Player moves with platform only when colliding * - Adding start delay time * *******************************************************/ using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlatformMovement : MonoBehaviour { [SerializeField] List<Transform> waypoints = new List<Transform>(); int m_curWaypoint = 0; bool m_dir = true; [SerializeField] float m_speed; //time that platform will stay in position once it reaches a waypoint and start moving onto next waypoint. [SerializeField] float m_stopTime; //if false it will stop moving once it reaches to the last waypoint [SerializeField] bool m_loop = true; [SerializeField] bool m_isMoving = true; //if false, platform won't move bool GetIsMoving() { return m_isMoving; } void SetIsMoving(bool isMoving) { m_isMoving = isMoving; } //Start Delay related bool m_isStartMoving = false; [SerializeField] float m_starDelayTime; // private void FixedUpdate() { MovePlatform(); } private void MovePlatform() { if (!m_isStartMoving) { StartCoroutine(StartMovingTimer()); return; } if (!m_isMoving) return; if (transform.position != waypoints[m_curWaypoint].transform.position) { transform.position = Vector3.MoveTowards(transform.position, waypoints[m_curWaypoint].transform.position, m_speed * Time.fixedDeltaTime); } if (transform.position == waypoints[m_curWaypoint].transform.position) { StartCoroutine(StopMovingForCertainTime()); m_curWaypoint = m_dir ? (m_curWaypoint + 1) : (m_curWaypoint - 1); if (m_curWaypoint >= waypoints.Count || m_curWaypoint < 0) { m_curWaypoint = (m_curWaypoint >= waypoints.Count) ? (waypoints.Count - 1) : 0; if (m_loop) { m_dir = !m_dir; } else { m_isMoving = false; } } } } private IEnumerator StartMovingTimer() { yield return new WaitForSeconds(m_starDelayTime); m_isStartMoving = true; } private IEnumerator StopMovingForCertainTime() { m_isMoving = false; yield return new WaitForSeconds(m_stopTime); m_isMoving = true; } private void OnCollisionStay(Collision collision) { if (collision.transform.tag == "Player") collision.transform.parent.parent = transform; } private void OnCollisionExit(Collision collision) { if (collision.transform.tag == "Player") collision.transform.parent.parent = null; } }
using LeadChina.CCDMonitor.Web.Helper; using LeadChina.CCDMonitor.Web.Models; namespace LeadChina.CCDMonitor.Web.Services { /// <summary> /// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“MonitorWcfService”。 /// 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 MonitorWcfService.svc 或 MonitorWcfService.svc.cs,然后开始调试。 /// </summary> public class MonitorWcfService : IMonitorWcfService { /// <summary> /// /// </summary> /// <param name="photo"></param> public void SavePhoto(SourceData photo) { FileHelper.StreamToFile(photo.ImageStream, "D:\\1.jpg"); } } }
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 Автошкола { public partial class AddEditCarrierForm : Form { public AddEditCarrierForm(AutoschoolDataSet.CarriersDataTable carriersDataTable, AutoschoolDataSet.CategoriesDataTable categoriesDataTable, AutoschoolDataSet.CarriersStatusesDataTable carriersStatusesDataTable, AutoschoolDataSet.TransmissionsDataTable transmissionsDataTable, DataRow row) { InitializeComponent(); this.carriersDataTable = carriersDataTable; this.categoriesDataTable = categoriesDataTable; this.carriersStatusesDataTable = carriersStatusesDataTable; this.transmissionsDataTable = transmissionsDataTable; dataRow = row; } BusinessLogic BusinessLogic = new BusinessLogic(); AutoschoolDataSet.CarriersDataTable carriersDataTable; AutoschoolDataSet.CategoriesDataTable categoriesDataTable; AutoschoolDataSet.CarriersStatusesDataTable carriersStatusesDataTable; AutoschoolDataSet.TransmissionsDataTable transmissionsDataTable; DataRow dataRow; private void AddEditCarrierForm_Load(object sender, EventArgs e) { Transmission_comboBox.DataSource = transmissionsDataTable; Transmission_comboBox.DisplayMember = "Transmission"; Transmission_comboBox.ValueMember = "ID"; Transmission_comboBox.AutoCompleteMode = AutoCompleteMode.Append; Transmission_comboBox.AutoCompleteSource = AutoCompleteSource.ListItems; Category_comboBox.DataSource = categoriesDataTable; Category_comboBox.DisplayMember = "Name"; Category_comboBox.ValueMember = "ID"; //Category_comboBox.AutoCompleteMode = AutoCompleteMode.Append; //Category_comboBox.AutoCompleteSource = AutoCompleteSource.ListItems; Status_comboBox.DataSource = carriersStatusesDataTable; Status_comboBox.DisplayMember = "Name"; Status_comboBox.ValueMember = "ID"; Status_comboBox.AutoCompleteMode = AutoCompleteMode.Append; Status_comboBox.AutoCompleteSource = AutoCompleteSource.ListItems; if (dataRow != null) { Brand_textBox.Text = dataRow["Brand"].ToString(); Model_textBox.Text = dataRow["Model"].ToString(); StateNumber_textBox.Text = dataRow["StateNumber"].ToString(); Color_textBox.Text = dataRow["Color"].ToString(); Transmission_comboBox.SelectedValue = dataRow["Transmission"].ToString(); Category_comboBox.SelectedValue = dataRow["Category"].ToString(); Status_comboBox.SelectedValue = dataRow["Status"].ToString(); } else { Brand_textBox.Text = ""; Model_textBox.Text = ""; StateNumber_textBox.Text = ""; Color_textBox.Text = ""; Transmission_comboBox.SelectedIndex = -1; Category_comboBox.SelectedIndex = -1; Status_comboBox.SelectedIndex = -1; } } private void AddEditCarrierForm_FormClosing(object sender, FormClosingEventArgs e) { if (DialogResult == DialogResult.OK) { try { if (Brand_textBox.Text.Trim() == "") { Brand_textBox.Focus(); throw new Exception("Не указана марка транспортного средства"); } if (Model_textBox.Text.Trim() == "") { Model_textBox.Focus(); throw new Exception("Не указана модель транспортного средства"); } if (StateNumber_textBox.Text.Trim() == "") { StateNumber_textBox.Focus(); throw new Exception("Не указан государственный регистрационный номер транспортного средства"); } if (Color_textBox.Text.Trim() == "") { Color_textBox.Focus(); throw new Exception("Не указан цвет транспортного средства"); } if (Transmission_comboBox.SelectedIndex == -1) { Transmission_comboBox.Focus(); throw new Exception("Не выбрана трансмиссия транспортного средства"); } if (Category_comboBox.SelectedIndex == -1) { Category_comboBox.Focus(); throw new Exception("Не выбрана категория транспортного средства"); } if (Status_comboBox.SelectedIndex == -1) { Status_comboBox.Focus(); throw new Exception("Не выбран статус транспортного средства"); } if (dataRow != null) { for (int i = 0; i < carriersDataTable.Rows.Count; i++) { if ((carriersDataTable[i][0].ToString() != dataRow[0].ToString()) && (carriersDataTable[i][3].ToString().ToLower() == StateNumber_textBox.Text.Trim().ToLower())) { throw new Exception("ТС с таким государственным регистрационным номером уже имеется в базе"); } } } else { for (int i = 0; i < carriersDataTable.Rows.Count; i++) { if (carriersDataTable[i][3].ToString().ToLower() == StateNumber_textBox.Text.Trim().ToLower()) { throw new Exception("ТС с таким государственным регистрационным номером уже имеется в базе"); } } } } catch (Exception exp) { MessageBox.Show(exp.Message, "Ошибка"); e.Cancel = true; return; } if (dataRow != null) { dataRow["Brand"] = Brand_textBox.Text; dataRow["Model"] = Model_textBox.Text; dataRow["StateNumber"] = StateNumber_textBox.Text; dataRow["Color"] = Color_textBox.Text; dataRow["Transmission"] = Transmission_comboBox.SelectedValue; dataRow["Category"] = Category_comboBox.SelectedValue; dataRow["Status"] = Status_comboBox.SelectedValue; } else { carriersDataTable.AddCarriersRow(Brand_textBox.Text, Model_textBox.Text, StateNumber_textBox.Text, Color_textBox.Text, transmissionsDataTable[Transmission_comboBox.SelectedIndex], categoriesDataTable[Category_comboBox.SelectedIndex], carriersStatusesDataTable[Status_comboBox.SelectedIndex]); } } } private void Brand_textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((Brand_textBox.TextLength - Brand_textBox.SelectionLength) >= 50 && (char)e.KeyChar != (Char)Keys.Back) e.Handled = true; else { if ((char)e.KeyChar == (Char)Keys.Back) return; if ((char)e.KeyChar == (Char)Keys.Space) return; if ((char)e.KeyChar == (Char)Keys.ControlKey) return; if (char.IsLetter(e.KeyChar)) return; e.Handled = true; } } private void Color_textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((Color_textBox.TextLength - Color_textBox.SelectionLength) >= 50 && (char)e.KeyChar != (Char)Keys.Back) e.Handled = true; else { if ((char)e.KeyChar == (Char)Keys.Back) return; if ((char)e.KeyChar == (Char)Keys.ControlKey) return; if (char.IsLetter(e.KeyChar)) return; if (e.KeyChar == '-') return; e.Handled = true; } } private void StateNumber_textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((StateNumber_textBox.TextLength - StateNumber_textBox.SelectionLength) >= 15 && (char)e.KeyChar != (Char)Keys.Back) e.Handled = true; else { if ((char)e.KeyChar == (Char)Keys.Back) return; if ((char)e.KeyChar == (Char)Keys.Space) return; if ((char)e.KeyChar == (Char)Keys.ControlKey) return; if (char.IsLetterOrDigit(e.KeyChar)) return; e.Handled = true; } } private void Model_textBox_KeyPress(object sender, KeyPressEventArgs e) { if ((Model_textBox.TextLength - Model_textBox.SelectionLength) >= 50 && (char)e.KeyChar != (Char)Keys.Back) e.Handled = true; else { if ((char)e.KeyChar == (Char)Keys.Back) return; if ((char)e.KeyChar == (Char)Keys.Space) return; if ((char)e.KeyChar == (Char)Keys.ControlKey) return; if (char.IsLetterOrDigit(e.KeyChar)) return; e.Handled = true; } } } }
using Crainiate.Diagramming; using Crainiate.Diagramming.Flowcharting; using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FlowchartConverter.Nodes { abstract class DecisionNode :BaseNode { protected const int horizontalSpace = 100; protected const int MOVE_UP = 1; protected const int MOVE_DOWN = 2; protected const int MOVE_RIGHT = 3; protected int moveDirection = MOVE_DOWN; private HolderNode trueNode; private HolderNode backNode; protected ConnectorNode trueConnector; // ConnectorNode backConnector; readonly private string holderTag; readonly private string backConnectorTag; readonly private string trueConnectorTag; public bool shifted = false; public override PointF NodeLocation { get { return nodeLocation; } set { if (value.X != NodeLocation.X || value.Y != NodeLocation.Y) { if (value.Y > NodeLocation.Y) { moveDirection = MOVE_DOWN; } else if (value.X > NodeLocation.X) { moveDirection = MOVE_RIGHT; } else { moveDirection = MOVE_UP; } base.NodeLocation = value; moveConnections(); } } } public HolderNode TrueNode { get { return trueNode; } set { trueNode = value; } } public HolderNode BackNode { get { return backNode; } set { backNode = value; } } public ConnectorNode TrueConnector { get { return trueConnector; } set { trueConnector = value; } } public DecisionNode() { Shape.StencilItem = Stencil[FlowchartStencilType.Preparation]; Shape.BackColor = System.Drawing.ColorTranslator.FromHtml("#e06000"); Shape.GradientColor = Color.Black; holderTag = ShapeTag + " holder"; backConnectorTag = ShapeTag + " backConnector"; trueConnectorTag = ShapeTag + " trueConnector"; makeConnections(); } abstract protected void makeConnections(); abstract protected void moveConnections(); public override void addRemoveFlag(bool v) { BackNode.ToBeRemoved = true; TrueNode.ToBeRemoved = true; BaseNode nextNode = TrueNode; while (nextNode.OutConnector.EndNode != BackNode) { nextNode.OutConnector.EndNode.addRemoveFlag(true); nextNode = nextNode.OutConnector.EndNode; } nextNode = null; //base.addRemoveFlag(v); this.ToBeRemoved = true; } override public void addToModel() { base.addToModel(); TrueNode.addToModel(); BackNode.addToModel(); //Controller.Model.Shapes.Add(holderTag,holderNode.Shape); // Model.Lines.Add(backConnectorTag, backConnector.Connector); } protected void attachToTrue(BaseNode newNode, bool addToEnd) { if (addToEnd) //this means that the clicked link is between holder and loop { //add this node to last node in true link BaseNode lastNode = TrueNode; while (!(lastNode.OutConnector.EndNode is HolderNode)) { lastNode = lastNode.OutConnector.EndNode; } lastNode.attachNode(newNode); } else TrueNode.attachNode(newNode); } public override void attachNode(BaseNode newNode, ConnectorNode clickedConnector) { clickedConnector.StartNode.attachNode(newNode); if (OutConnector.EndNode.NodeLocation.Y < BackNode.NodeLocation.Y+shiftY) shiftMainTrack(); //this causes a problem when //backNode shifts dirctely after being attached to another while node } public abstract void shiftMainTrack(int moreShift = 0); override public void setText(String label) { float oldWidth = Shape.Width; base.setText(label); //if the shape is bigger then move nodes to right by the difference if (!Controller.LoadingProject) { TrueNode.shiftRight((int)(Shape.Width - oldWidth)); BackNode.shiftRight((int)(Shape.Width - oldWidth)); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using MonoDroid.Common.Data.Sqlite; namespace MonoDroid.Common.Model.Contacts { public class PhoneInfo { [PrimaryKey] [Column("_id")] public Int64 _id { get; set; } [Column("account_name")] public String account_name { get; set; } [Column("account_type")] public String account_type { get; set; } [Column("account_type_and_data_set")] public String account_type_and_data_set { get; set; } [Column("chat_capability")] public String chat_capability { get; set; } [Column("contact_chat_capability")] public String contact_chat_capability { get; set; } [Column("contact_id")] public String contact_id { get; set; } [Column("contact_presence")] public String contact_presence { get; set; } [Column("contact_status")] public String contact_status { get; set; } [Column("contact_status_icon")] public String contact_status_icon { get; set; } [Column("contact_status_label")] public String contact_status_label { get; set; } [Column("contact_status_res_package")] public String contact_status_res_package { get; set; } [Column("contact_status_ts")] public String contact_status_ts { get; set; } [Column("custom_ringtone")] public String custom_ringtone { get; set; } [Column("data1")] public String data1 { get; set; } [Column("data2")] public String data2 { get; set; } [Column("data3")] public String data3 { get; set; } [Column("data4")] public String data4 { get; set; } [Column("data5")] public String data5 { get; set; } [Column("data6")] public String data6 { get; set; } [Column("data7")] public String data7 { get; set; } [Column("data8")] public String data8 { get; set; } [Column("data9")] public String data9 { get; set; } [Column("data10")] public String data10 { get; set; } [Column("data11")] public String data11 { get; set; } [Column("data12")] public String data12 { get; set; } [Column("data13")] public String data13 { get; set; } [Column("data14")] public String data14 { get; set; } [Column("data15")] public String data15 { get; set; } [Column("data_set")] public String data_set { get; set; } [Column("data_sync1")] public String data_sync1 { get; set; } [Column("data_sync2")] public String data_sync2 { get; set; } [Column("data_sync3")] public String data_sync3 { get; set; } [Column("data_sync4")] public String data_sync4 { get; set; } [Column("data_version")] public String data_version { get; set; } [Column("dirty")] public String dirty { get; set; } [Column("display_name")] public String display_name { get; set; } [Column("display_name_alt")] public String display_name_alt { get; set; } [Column("display_name_source")] public String display_name_source { get; set; } [Column("group_sourceid")] public String group_sourceid { get; set; } [Column("has_phone_number")] public String has_phone_number { get; set; } [Column("in_visible_group")] public String in_visible_group { get; set; } [Column("is_primary")] public String is_primary { get; set; } [Column("is_super_primary")] public String is_super_primary { get; set; } [Column("last_time_contacted")] public String last_time_contacted { get; set; } [Column("lookup")] public String lookup { get; set; } [Column("mimetype")] public String mimetype { get; set; } [Column("mode")] public String mode { get; set; } [Column("name_raw_contact_id")] public String name_raw_contact_id { get; set; } [Column("name_verified")] public String name_verified { get; set; } [Column("phonetic_name")] public String phonetic_name { get; set; } [Column("phonetic_name_style")] public String phonetic_name_style { get; set; } [Column("photo_file_id")] public String photo_file_id { get; set; } [Column("photo_id")] public String photo_id { get; set; } [Column("photo_thumb_uri")] public String photo_thumb_uri { get; set; } [Column("photo_uri")] public String photo_uri { get; set; } [Column("raw_contact_id")] public String raw_contact_id { get; set; } [Column("raw_contact_is_user_profile")] public String raw_contact_is_user_profile { get; set; } [Column("res_package")] public String res_package { get; set; } [Column("send_to_voicemail")] public String send_to_voicemail { get; set; } [Column("sort_key")] public String sort_key { get; set; } [Column("sort_key_alt")] public String sort_key_alt { get; set; } [Column("sourceid")] public String sourceid { get; set; } [Column("starred")] public String starred { get; set; } [Column("status")] public String status { get; set; } [Column("status_icon")] public String status_icon { get; set; } [Column("status_label")] public String status_label { get; set; } [Column("status_res_package")] public String status_res_package { get; set; } [Column("status_ts")] public String status_ts { get; set; } [Column("times_contacted")] public String times_contacted { get; set; } [Column("version")] public String version { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace University.Data { public partial class CategoryUserMapping { public bool? CategoryDeleteorNot { get; set; } public string AdminFirstName { get; set; } public string AdminLastName { get; set; } public string UserFirstName { get; set; } public string UserLastName { get; set; } public string CategoryName { get; set; } public List<Login_tbl> Logintbllst { get; set; } public List<SubCategoryMaster> SubCategoryMasterlst { get; set; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using TestShop.Application.Models.Product; using TestShop.Application.ServiceInterfaces; using TestShop.Domain; using TestShop.Domain.Models; using AutoMapper; namespace TestShop.Application.Services { public class ProductService : IProductService { private readonly ApplicationDbContext context; private readonly IMapper mapper; public ProductService(ApplicationDbContext context, IMapper mapper) { this.context = context; this.mapper = mapper; } public async Task<IList<ProductModel>> GetAllAsync() { return mapper.Map<IList<ProductModel>>(context.Products); } public async Task AddAsync(ProductModel model) { context.Products.Add(mapper.Map<Product>(model)); context.SaveChanges(); } public async Task DeleteAsync(int id) { var product = context.Products.Find(id); if (product != null) { context.Products.Remove(product); context.SaveChanges(); } } public async Task EditAsync(ProductModel model) { context.Products.Update(mapper.Map<Product>(model)); context.SaveChanges(); } public async Task<ProductModel> GetAsync(int id) { return mapper.Map<ProductModel>(context.Products.Find(id)); } public ProductModel GetModel() { return new ProductModel(); } } }
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; namespace Kingdee.CAPP.UI.ProcessDataManagement { /// <summary> /// 类型说明:焊接符号界面 /// 作 者:jason.tang /// 完成时间:2013-03-07 /// </summary> public partial class WeldingSymbolFrm : BaseSkinForm { #region 变量和属性声明 /// <summary> /// 形位公差标图片 /// </summary> private Image image; public Image WeldingSymbolImage { get { return image; } } #endregion #region 窗体控件事件 public WeldingSymbolFrm() { InitializeComponent(); } private void pbWeldingSymbol_Click(object sender, EventArgs e) { WeldingSymbolChooseFrm form = new WeldingSymbolChooseFrm(); form.StartPosition = FormStartPosition.Manual; Point pt = MousePosition;//获取鼠标的屏幕坐标 form.Left = pt.X; form.Top = pt.Y; if (form.ShowDialog() == System.Windows.Forms.DialogResult.OK) { pbWeldingSymbol.Image = form.WeldingImage; picTemp.Image = pbWeldingSymbol.Image; } } private void btnConfirm_Click(object sender, EventArgs e) { Bitmap ibitMap = new Bitmap(picTemp.Image); Color c = new Color(); for (int i = 0; i < ibitMap.Width; i++) { for (int j = 0; j < ibitMap.Height; j++) { c = ibitMap.GetPixel(i, j); if (c.ToArgb() == this.BackColor.ToArgb()) { c = Color.FromArgb(0, c); //如果是背景色就做全透明处理Alpha = 0; } ibitMap.SetPixel(i, j, c); } picTemp.Refresh(); picTemp.Image = ibitMap; } Bitmap bmp = new Bitmap(picTemp.Width, picTemp.Height); picTemp.DrawToBitmap(bmp, new Rectangle(0, 0, picTemp.Width, picTemp.Height)); image = bmp; this.DialogResult = System.Windows.Forms.DialogResult.OK; this.Close(); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void WeldingSymbolFrm_Load(object sender, EventArgs e) { picTemp.Image = pbWeldingSymbol.Image; } #endregion } }
namespace Jypeli { /// <summary> /// Hiiren napit. /// </summary> public enum MouseButton { /// <summary> /// Ei mikään nappi hiiressä. /// </summary> None, /// <summary> /// Vasen nappi hiiressä. /// </summary> Left, /// <summary> /// Oikea nappi hiiressä. /// </summary> Right, /// <summary> /// Keskimmäinen nappi hiiressä (rullan painallus). /// </summary> Middle, /// <summary> /// Hiiren ensimmäinen erikoisnäppäin. /// </summary> XButton1, /// <summary> /// Hiiren toinen erikoisnäppäin. /// </summary> XButton2, /// <summary> /// Hiiren kolmas erikoisnäppäin. /// </summary> XButton3, /// <summary> /// Hiiren neljäs erikoisnäppäin. /// </summary> XButton4, /// <summary> /// Hiiren viides erikoisnäppäin. /// </summary> XButton5, /// <summary> /// Hiiren kuudes erikoisnäppäin. /// </summary> XButton6, /// <summary> /// Hiiren seitsemäs erikoisnäppäin. /// </summary> XButton7, /// <summary> /// Hiiren kahdeksas erikoisnäppäin. /// </summary> XButton8, /// <summary> /// Hiiren yhdeksäs erikoisnäppäin. /// </summary> XButton9, /// <summary> /// Hiiren kymmenes erikoisnäppäin. /// </summary> XButton10, /// <summary> /// Hiiren yhdestoista erikoisnäppäin. /// </summary> XButton11, /// <summary> /// Hiiren kahdestoista erikoisnäppäin. /// </summary> XButton12, } }
using System.Collections; using UnityEngine; namespace QuestSystem { public class QuestIdentifier : IQuestIdentfier { private int questID; private int sourceID; //Where the quest came from private int chainQuestID; // public QuestIdentifier(int _questID) { questID = _questID; } public int _sourceID { get { return sourceID; } } public int _questID { get { return questID; } } public int _chainQuestID { get { return chainQuestID; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class JoinScreenController : MonoBehaviour { public Text player1; public Text player2; public Text player3; public Text player4; public Image crab1; public Image crab2; public Image crab3; public Image crab4; public GameController gameController; int minimumPlayers = 1; int joinedPlayers = 0; public GameObject pressStartPromt; public SoundManager soundManager; // Start is called before the first frame update void Start() { // TODO gameController.player1Active = false; gameController.player2Active = false; gameController.player3Active = false; gameController.player4Active = false; gameController.uiController.SetPlayerEnabled(1, false); gameController.uiController.SetPlayerEnabled(2, false); gameController.uiController.SetPlayerEnabled(3, false); gameController.uiController.SetPlayerEnabled(4, false); gameController.player1.gameObject.SetActive(false); gameController.player2.gameObject.SetActive(false); gameController.player3.gameObject.SetActive(false); gameController.player4.gameObject.SetActive(false); pressStartPromt.SetActive(false); // gameObject.SetActive(false); } // Update is called once per frame void Update() { if (Input.GetButtonDown("Fire1_1") && !gameController.player1Active) { soundManager.PlayJoinSound(); gameController.player1Active = true; gameController.uiController.SetPlayerEnabled(1, true); gameController.player1.gameObject.SetActive(true); crab1.gameObject.SetActive(true); ++joinedPlayers; } if (Input.GetButtonDown("Fire1_2") && !gameController.player2Active) { soundManager.PlayJoinSound(); gameController.player2Active = true; gameController.uiController.SetPlayerEnabled(2, true); gameController.player2.gameObject.SetActive(true); crab2.gameObject.SetActive(true); ++joinedPlayers; } if (Input.GetButtonDown("Fire1_3") && !gameController.player3Active) { soundManager.PlayJoinSound(); gameController.player3Active = true; gameController.uiController.SetPlayerEnabled(3, true); gameController.player3.gameObject.SetActive(true); crab3.gameObject.SetActive(true); ++joinedPlayers; } if (Input.GetButtonDown("Fire1_4") && !gameController.player4Active) { soundManager.PlayJoinSound(); gameController.player4Active = true; gameController.uiController.SetPlayerEnabled(4, true); gameController.player4.gameObject.SetActive(true); crab4.gameObject.SetActive(true); ++joinedPlayers; } if (joinedPlayers >= minimumPlayers && Input.GetButtonDown("Start")) { soundManager.StopJoinMusic(); soundManager.PlayButtonSound(); gameController.StartTimer(); gameObject.SetActive(false); } if (!pressStartPromt.activeInHierarchy && joinedPlayers >= minimumPlayers) { pressStartPromt.SetActive(true); } } }
using System.Net; using Microsoft.Azure.Functions.Worker; using Microsoft.Azure.Functions.Worker.Http; using Microsoft.Extensions.Logging; namespace Sentry.Samples.AzureFunctions.Worker; public class SampleHttpTrigger { [Function(nameof(SampleHttpTrigger))] public async Task<HttpResponseData> RunAsync([HttpTrigger(AuthorizationLevel.Function, "get", "post")] HttpRequestData req, FunctionContext executionContext) { var logger = executionContext.GetLogger<SampleHttpTrigger>(); logger.LogInformation("C# HTTP trigger function processed a request"); var response = req.CreateResponse(HttpStatusCode.OK); response.Headers.Add("Content-Type", "text/plain; charset=utf-8"); BadApple.HttpScenario(); await response.WriteStringAsync("Welcome to Azure Functions!"); return response; } }
using Command.Classes.Technic; using Command.Interfaces; namespace Command.Classes.Commands { public class GarageDoorOpenCommand : ICommand { private readonly Garage _garage; public GarageDoorOpenCommand(Garage garage) => _garage = garage; public void Execute() { _garage.Up(); _garage.LightOn(); } public void Undo() { _garage.Down(); _garage.LightOff(); } } }
using AsiaLabv1.Models; using AsiaLabv1.Repositories; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AsiaLabv1.Services { public class ReferDoctorsService { Repository<Refer> _ReferRepository = new Repository<Refer>(); public void Add(Refer ReferDoctor) { _ReferRepository.Insert(ReferDoctor); } public List<Refer> GetAllReferDoctors() { return _ReferRepository.GetAll(); } public Refer GetReferDoctorById(int Id) { return _ReferRepository.GetById(Id); } public void Update(Refer Doc, int id) { _ReferRepository.Update(Doc, id); } public void Delete(int Doc) { _ReferRepository.DeleteById(Doc); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity.ModelConfiguration; namespace Anywhere2Go.DataAccess.AccountEntity { public class eAccountProfile { public Guid acc_id { get; set; } public string first_name { get; set; } public string last_name { get; set; } public string gender { get; set; } public string tel { get; set; } public string address { get; set; } public string email { get; set; } public string username { get; set; } public string password { get; set; } public string picture { get; set; } public string signature { get; set; } public string dev_id { get; set; } public Int32? role_id { get; set; } public bool isActive { get; set; } public DateTime? createDate { get; set; } public DateTime? updateDate { get; set; } public string createBy { get; set; } public string updateBy { get; set; } public virtual eRole Role { get; set; } public virtual eDepartment Dept { get; set; } } public class AccountProfileConfig : EntityTypeConfiguration<eAccountProfile> { public AccountProfileConfig() { ToTable("eAccountProfile"); Property(t => t.acc_id).HasColumnName("acc_id").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity); Property(t => t.first_name).HasColumnName("first_name"); Property(t => t.last_name).HasColumnName("last_name"); Property(t => t.gender).HasColumnName("gender"); Property(t => t.tel).HasColumnName("tel"); Property(t => t.address).HasColumnName("address"); Property(t => t.email).HasColumnName("email"); Property(t => t.username).HasColumnName("username"); Property(t => t.password).HasColumnName("password"); Property(t => t.picture).HasColumnName("picture"); Property(t => t.signature).HasColumnName("signature"); Property(t => t.role_id).HasColumnName("role_id"); Property(t => t.isActive).HasColumnName("isActive"); Property(t => t.createDate).HasColumnName("create_date"); Property(t => t.updateDate).HasColumnName("update_date"); Property(t => t.createBy).HasColumnName("create_by"); Property(t => t.updateBy).HasColumnName("update_by"); HasKey(t => t.acc_id); HasOptional(t => t.Role).WithMany().HasForeignKey(t => t.role_id); HasOptional(t => t.Dept).WithMany().HasForeignKey(t => t.dev_id); } } }
namespace AreaDotnet { /// <summary>An interface that determines whether a class has <c>Area</c> property.</summary> public interface IHasArea { /// <value>The area of a figure.</value> double Area { get; } } }
using System.Collections.Generic; using System.Linq; using System.Xml.Serialization; namespace BO { public class Organizer : Personne { [XmlIgnore] public virtual List<Race> Races { get; set; } public Organizer() { this.Races = new List<Race>(); } public void UpdateRace(Race race) { var cr = Races.SingleOrDefault(r => r.Id == race.Id); if (cr != null) { Races.Remove(cr); } Races.Add(race); } } }
using System.Collections.Generic; namespace ChessGame.Model { /// <summary> /// Clase base para definir las diferentes piezas de ajedrez /// </summary> abstract class Pieza { /// <summary> /// Inicializa una nueva instancia de <see cref="Pieza"/> /// </summary> /// <param name="color">Color de la pieza</param> public Pieza(ColoresPosibles color) { Color = color; } /// <summary> /// Color de la pieza /// </summary> public ColoresPosibles Color { get; set; } /// <summary> /// Celda en la que se encuentra la pieza /// </summary> public Celda CeldaActual { get; internal set; } /// <summary> /// Devuelve las celdas a las que puede moverse la pieza /// </summary> /// <returns></returns> public abstract IEnumerable<Celda> ListaDeDestinosPosibles(); /// <summary> /// Comprueba si una celda puede ser destino de un movimiento de la pieza: /// si está vacía o contiene una pieza de un color diferente /// </summary> /// <param name="celdaCandidata">Celda a comprobar</param> /// <returns>true o false indicando si puede ser destino del movimiento</returns> protected virtual bool EsUnDestinoPosible(Celda celdaCandidata) { if (celdaCandidata == null) return false; return (celdaCandidata.Pieza == null || celdaCandidata.Pieza.Color != Color); } /// <summary> /// Devuelve la lista de los posibles destinos de movimiento de la pieza /// en una dirección determinada /// La dirección a tomar viene dada por un incremento hacia adelante y /// otro horizontal /// </summary> /// <param name="incrementoHaciaAdelante">Incremento hacia adelante. /// Si la dirección es hacia atrás será un valor negativo.</param> /// <param name="incrementoHaciaDerecha">Incremento hacia la derecha. /// Si la dirección es hacia la izquierda será un valor negativo.</param> /// <returns>Lista de celdas posibles destinos de movimiento</returns> protected IEnumerable<Celda> DestinosPosibles( int incrementoHaciaAdelante, int incrementoHaciaDerecha) { TableroDeAjedrez tablero = CeldaActual.Tablero; List<Celda> celdas = new List<Celda>(); int adelante = incrementoHaciaAdelante; int derecha = incrementoHaciaDerecha; bool piezaOFinalDetectado = false; while (!piezaOFinalDetectado) { Celda destino = tablero.GetSquare(CeldaActual, new Movimiento { unidadesHaciaAdelante = adelante, unidadesHaciaDerecha = derecha }); if (EsUnDestinoPosible(destino)) celdas.Add(destino); piezaOFinalDetectado = (destino == null || destino.Pieza != null); adelante += incrementoHaciaAdelante; derecha += incrementoHaciaDerecha; } return celdas; } /// <summary> /// Devuelve la lista de los posibles destinos de movimiento de la pieza /// a partir de una lista de movimientos /// </summary> /// <param name="moves">Lista de movimientos que puede realizar la pieza</param> /// <returns>Lista de celdas posibles destinos</returns> protected IEnumerable<Celda> CeldasPosiblesParaMovimientosDados(IEnumerable<Movimiento> moves) { TableroDeAjedrez tablero = CeldaActual.Tablero; List<Celda> listaDeCeldasPosibles = new List<Celda>(); foreach (Movimiento move in moves) { Celda celdaCandidata = tablero.GetSquare(CeldaActual, move); if (EsUnDestinoPosible(celdaCandidata)) listaDeCeldasPosibles.Add(celdaCandidata); } return listaDeCeldasPosibles; } } /// <summary> /// Rey /// </summary> class Rey : Pieza { /// <summary> /// Inicializa una nueva instancia de la clase <see cref="Rey"/> /// </summary> /// <param name="color">Color de la pieza</param> public Rey(ColoresPosibles color): base(color) { } /// <summary> /// Movimientos que puede realizar el rey /// </summary> private Movimiento[] movimientos = { new Movimiento() {unidadesHaciaAdelante=1, unidadesHaciaDerecha=-1 }, new Movimiento() {unidadesHaciaAdelante=1, unidadesHaciaDerecha=0 }, new Movimiento() {unidadesHaciaAdelante=1, unidadesHaciaDerecha=1 }, new Movimiento() {unidadesHaciaAdelante=0, unidadesHaciaDerecha=-1 }, new Movimiento() {unidadesHaciaAdelante=0, unidadesHaciaDerecha=1 }, new Movimiento() {unidadesHaciaAdelante=-1, unidadesHaciaDerecha=-1 }, new Movimiento() {unidadesHaciaAdelante=-1, unidadesHaciaDerecha=0 }, new Movimiento() {unidadesHaciaAdelante=-1, unidadesHaciaDerecha=1 } }; /// <summary> /// Devuelve las celdas a las que puede moverse la pieza /// </summary> /// <returns>Lista de celdas</returns> public override IEnumerable<Celda> ListaDeDestinosPosibles() { if (CeldaActual == null) return null; return CeldasPosiblesParaMovimientosDados(movimientos); } } /// <summary> /// Torre /// </summary> class Torre : Pieza { /// <summary> /// Inicializa una nueva clase de <see cref="Torre"/> /// </summary> /// <param name="color">Color de la Pieza</param> public Torre(ColoresPosibles color) : base(color) { } /// <summary> /// Devuelve las celdas a las que puede moverse la pieza /// </summary> /// <returns>Lista de celdas</returns> public override IEnumerable<Celda> ListaDeDestinosPosibles() { if (CeldaActual == null) return null; List<Celda> listaDeCeldasPosibles = new List<Celda>(); // A la izquierda listaDeCeldasPosibles.AddRange(DestinosPosibles(0, -1)); // A la derecha listaDeCeldasPosibles.AddRange(DestinosPosibles(0, 1)); // Hacia adelante listaDeCeldasPosibles.AddRange(DestinosPosibles(1, 0)); // Hacia atrás listaDeCeldasPosibles.AddRange(DestinosPosibles(-1, 0)); return listaDeCeldasPosibles; } } /// <summary> /// Alfil /// </summary> class Alfil : Pieza { /// <summary> /// Inicializa una nueva instancia de <see cref="Alfil"/> /// </summary> /// <param name="color">Color de la pieza</param> public Alfil(ColoresPosibles color) : base(color) { } /// <summary> /// Devuelve las celdas a las que puede moverse la pieza /// </summary> /// <returns>Lista de celdas</returns> public override IEnumerable<Celda> ListaDeDestinosPosibles() { if (CeldaActual == null) return null; List<Celda> listaDeCeldasPosibles = new List<Celda>(); // Hacia adelante a la izquierda listaDeCeldasPosibles.AddRange(DestinosPosibles(1, -1)); // Hacia adelante a la derecha listaDeCeldasPosibles.AddRange(DestinosPosibles(1, 1)); // Hacia atrás a la izquierda listaDeCeldasPosibles.AddRange(DestinosPosibles(-1, -1)); // Hacia atrás a la derecha listaDeCeldasPosibles.AddRange(DestinosPosibles(-1, 1)); return listaDeCeldasPosibles; } } /// <summary> /// Reina /// </summary> class Reina : Pieza { /// <summary> /// Inicializa una nueva instancia de <see cref="Reina"/> /// </summary> /// <param name="color">Color de la pieza</param> public Reina(ColoresPosibles color): base(color) { } /// <summary> /// Devuelve las celdas a las que puede moverse la pieza /// </summary> /// <returns>Lista de celdas</returns> public override IEnumerable<Celda> ListaDeDestinosPosibles() { if (CeldaActual == null) return null; List<Celda> listaDeCeldasPosibles = new List<Celda>(); // Hacia adelante a la izquierda listaDeCeldasPosibles.AddRange(DestinosPosibles(1, -1)); // Hacia adelante listaDeCeldasPosibles.AddRange(DestinosPosibles(1, 0)); // Hacia adelante a la derecha listaDeCeldasPosibles.AddRange(DestinosPosibles(1, 1)); // Hacia la izquierda listaDeCeldasPosibles.AddRange(DestinosPosibles(0, -1)); // Hacia la derecha listaDeCeldasPosibles.AddRange(DestinosPosibles(0, 1)); // Hacia atrás a la izquierda listaDeCeldasPosibles.AddRange(DestinosPosibles(-1, -1)); // Hacia atrás listaDeCeldasPosibles.AddRange(DestinosPosibles(-1, 0)); // Hacia atrás a la derecha listaDeCeldasPosibles.AddRange(DestinosPosibles(-1, 1)); return listaDeCeldasPosibles; } } /// <summary> /// Caballo /// </summary> class Caballo : Pieza { /// <summary> /// Inicializa una nueva instancia de la clase <see cref="Caballo"/> /// </summary> /// <param name="color">Color de la pieza</param> public Caballo(ColoresPosibles color): base(color) { } /// <summary> /// Movimmientos que puede realizar el caballo /// </summary> private Movimiento[] movimientos = { new Movimiento {unidadesHaciaAdelante=1, unidadesHaciaDerecha=-2 }, new Movimiento {unidadesHaciaAdelante=2, unidadesHaciaDerecha=-1 }, new Movimiento {unidadesHaciaAdelante=2, unidadesHaciaDerecha=1 }, new Movimiento {unidadesHaciaAdelante=1, unidadesHaciaDerecha=2 }, new Movimiento {unidadesHaciaAdelante=-1, unidadesHaciaDerecha=-2 }, new Movimiento {unidadesHaciaAdelante=-2, unidadesHaciaDerecha=-1 }, new Movimiento {unidadesHaciaAdelante=-2, unidadesHaciaDerecha=1 }, new Movimiento {unidadesHaciaAdelante=-1, unidadesHaciaDerecha=2 } }; /// <summary> /// Devuelve las celdas a las que puede moverse la pieza /// </summary> /// <returns>Lista de celdas</returns> public override IEnumerable<Celda> ListaDeDestinosPosibles() { if (CeldaActual == null) return null; return CeldasPosiblesParaMovimientosDados(movimientos); } } /// <summary> /// Peón /// </summary> class Peon : Pieza { /// <summary> /// Inicializa una nueva instancia de <see cref="Peon"/> /// </summary> /// <param name="color">Color de la pieza</param> public Peon(ColoresPosibles color): base(color) { } /// <summary> /// Devuelve las celdas a las que puede moverse la pieza /// </summary> /// <returns>Lista de celdas</returns> public override IEnumerable<Celda> ListaDeDestinosPosibles() { if (CeldaActual == null) return null; TableroDeAjedrez tablero = CeldaActual.Tablero; bool estaEnPosicionInicial = (tablero.GetSquare(CeldaActual, new Movimiento { unidadesHaciaAdelante = -2, unidadesHaciaDerecha = 0 }) == null); List<Celda> listaDeCeldasPosibles = new List<Celda>(); Celda celdaDeDestino = tablero.GetSquare(CeldaActual, new Movimiento { unidadesHaciaAdelante = 1, unidadesHaciaDerecha = 0 }); if (celdaDeDestino != null && celdaDeDestino.Pieza == null) { listaDeCeldasPosibles.Add(celdaDeDestino); if (estaEnPosicionInicial) { celdaDeDestino = tablero.GetSquare(CeldaActual, new Movimiento { unidadesHaciaAdelante = 2, unidadesHaciaDerecha = 0 }); if (celdaDeDestino != null && celdaDeDestino.Pieza == null) listaDeCeldasPosibles.Add(celdaDeDestino); } } celdaDeDestino = tablero.GetSquare(CeldaActual, new Movimiento { unidadesHaciaAdelante = 1, unidadesHaciaDerecha = -1 }); if (celdaDeDestino != null && celdaDeDestino.Pieza != null && celdaDeDestino.Pieza.Color != Color) listaDeCeldasPosibles.Add(celdaDeDestino); celdaDeDestino = tablero.GetSquare(CeldaActual, new Movimiento { unidadesHaciaAdelante = 1, unidadesHaciaDerecha = 1 }); if (celdaDeDestino != null && celdaDeDestino.Pieza != null && celdaDeDestino.Pieza.Color != Color) listaDeCeldasPosibles.Add(celdaDeDestino); return listaDeCeldasPosibles; } } }
using UnityEngine; using System.Collections; public class KillEnemy : MonoBehaviour { public void OnTriggerEnter2D(Collider2D col) { var enemyAI = col.GetComponent<EnemyAI>(); if (enemyAI == null) { return; } enemyAI.KillSelf(); } }
using Microsoft.EntityFrameworkCore; using Payment.Application; using Payment.Domain.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Payment.Infrastructure.Contexts { internal class PaymentDbContext : DbContext, IDataContext { private readonly ICurrentUserService _currentUserService; public PaymentDbContext(DbContextOptions<PaymentDbContext> options) : base(options) { } public PaymentDbContext(DbContextOptions<PaymentDbContext> options, ICurrentUserService currentUserService) : base(options) { _currentUserService = currentUserService; } public DbSet<PaymentRequest> Payments { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfigurationsFromAssembly(GetType().Assembly); } public override Task<int> SaveChangesAsync(CancellationToken cancellationToken = default) { return base.SaveChangesAsync(cancellationToken); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; using CoherentSolutions.Extensions.Configuration.AnyWhere.Abstractions; using Microsoft.Extensions.Configuration; namespace CoherentSolutions.Extensions.Configuration.AnyWhere { public class AnyWhereConfiguration { private const int EXE_EXTENSION = 0; private const int DLL_EXTENSION = 1; private const int ANYWHERE_EXTENSION = 2; private static readonly string[] extensions = { ".exe", ".dll", ".anywhere" }; private readonly IAnyWhereConfigurationAdapterArguments adapterArguments; private readonly IAnyWhereConfigurationAdapterProbingPaths adapterProbingPaths; public AnyWhereConfiguration( IAnyWhereConfigurationAdapterArguments adapterArguments, IAnyWhereConfigurationAdapterProbingPaths adapterProbingPaths) { this.adapterArguments = adapterArguments ?? throw new ArgumentNullException(nameof(adapterArguments)); this.adapterProbingPaths = adapterProbingPaths ?? throw new ArgumentNullException(nameof(adapterProbingPaths)); } protected virtual IAnyWhereConfigurationFileSearch GetSearch() { return new AnyWhereConfigurationFileSearch(new AnyWhereConfigurationFileSystem()); } protected virtual IAnyWhereConfigurationTypeSystem GetTypeSystem() { return new AnyWhereConfigurationTypeSystem( new AnyWhereConfigurationFileSearch( new AnyWhereConfigurationFileSystem())); } public void ConfigureAppConfiguration( IConfigurationBuilder configurationBuilder) { if (configurationBuilder is null) { throw new ArgumentNullException(nameof(configurationBuilder)); } var search = this.GetSearch(); if (search is null) { throw new InvalidOperationException($"An instance of {nameof(IAnyWhereConfigurationFileSearch)} is expected but found null."); } var system= this.GetTypeSystem(); if (system is null) { throw new InvalidOperationException($"An instance of {nameof(IAnyWhereConfigurationTypeSystem)} is expected but found null."); } var directories = new HashSet<string>(); foreach (var path in this.adapterProbingPaths.Enumerate()) { directories.Add(path.Path); } if (directories.Count == 0) { return; } foreach (var arg in this.adapterArguments.Enumerate()) { var results = search.Find(directories, arg.Definition.AssemblyName, extensions); if (results is null || results.Count == 0) { throw new InvalidOperationException( AnyWhereConfigurationExceptions.EmptySearchResultsMessage( arg.Definition.AssemblyName, directories)); } if (results.Count > 1) { throw new InvalidOperationException( AnyWhereConfigurationExceptions.AmbiguousSearchResultsMessage(results)); } var assembly = results[0].Files[EXE_EXTENSION] ?? results[0].Files[DLL_EXTENSION]; var config = results[0].Files[ANYWHERE_EXTENSION]; var environment = arg.Environment; var content = config?.GetContentAsString(); if (content != null) { var values = new Dictionary<string, string>(); try { foreach (var kv in new AnyWhereConfigurationDataKeyValueEnumerable(content)) { values[kv.Key] = kv.Value; } } catch (Exception e) { throw new InvalidOperationException( AnyWhereConfigurationExceptions.ErrorLoadingEnvironmentConfigurationMessage(config.Path), e); } environment = new AnyWhereConfigurationEnvironmentWithExtension( environment, new AnyWhereConfigurationEnvironment( new AnyWhereConfigurationEnvironmentFromMemory(values))); } try { var instance = (IAnyWhereConfigurationAdapter) system.Get(assembly, arg.Definition.TypeName).CreateInstance(); instance.ConfigureAppConfiguration( configurationBuilder, new AnyWhereConfigurationEnvironmentReader(environment)); } catch (Exception e) { throw new InvalidOperationException( AnyWhereConfigurationExceptions.ErrorLoadingConfigurationMessage(arg.Definition), e); } } } } }
using System; using System.Linq; namespace _02._Archery_Tournament { class Program { static void Main(string[] args) { int[] targets = Console.ReadLine() .Split("|", StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); string command = Console.ReadLine(); char[] delimeters = { '@', '}', '{', ' ' }; int sumOfPoints = 0; while (command != "Game over") { string[] commandSeparated = command .Split(delimeters, StringSplitOptions.RemoveEmptyEntries); if (commandSeparated[0] == "Shoot") { int startingIndex = int.Parse(commandSeparated[2]); int length = int.Parse(commandSeparated[3]); if (startingIndex >= targets.Length || startingIndex < 0) { command = Console.ReadLine(); continue; } if (commandSeparated[1] == "Left") { int index = ShootLeft(targets, startingIndex, length); if (targets[index] >= 5) { targets[index] -= 5; sumOfPoints += 5; } else { sumOfPoints += targets[index]; targets[index] = 0; } } else if (commandSeparated[1] == "Right") { int index = ShootRight(targets, startingIndex, length); if (targets[index] >= 5) { targets[index] -= 5; sumOfPoints += 5; } else { sumOfPoints += targets[index]; targets[index] = 0; } } } else { targets = targets .Reverse() .ToArray(); } command = Console.ReadLine(); } Console.WriteLine(String.Join(" - ",targets)); Console.WriteLine($"Iskren finished the archery tournament with {sumOfPoints} points!"); } static int ShootLeft(int[] targets, int startingIndex, int length) { int positionAfterMoving = startingIndex - length; if (positionAfterMoving < 0) { positionAfterMoving = targets.Length + ((startingIndex - length) % targets.Length); } return positionAfterMoving; } static int ShootRight(int[] targets, int startingIndex, int length) { int positionAfterMoving = startingIndex + length; if (positionAfterMoving >= targets.Length) { positionAfterMoving = ((startingIndex + length) % targets.Length); } return positionAfterMoving; } } }
using System.Collections; using System.Collections.Generic; using DChild.Gameplay.Combat; using Sirenix.OdinInspector; using UnityEngine; namespace DChild.Gameplay.Objects.Characters.Enemies { public class PoisonToadBrain : MinionAIBrain<PoisonToad>, IAITargetingBrain { [SerializeField] [MinValue(0f)] private float m_attackDistance; private bool CanHitTarget() { var attackDirection = (m_minion.facing == Direction.Left ? Vector2.left : Vector2.right); var hit = Physics2D.Raycast(transform.position, attackDirection, m_attackDistance, 1 << LayerMask.NameToLayer("Player")); Debug.DrawRay(transform.position, attackDirection * m_attackDistance); return hit.collider != null; } public override void Enable(bool value) { enabled = value; } public override void ResetBrain() { m_target = null; } public override void SetTarget(IDamageable target) { m_target = target; } private void Update() { if (m_minion.waitForBehaviourEnd) return; if (m_target != null) { if(CanHitTarget()) { m_minion.Attack(m_target); } else { m_minion.DoIdle(); } } } #if UNITY_EDITOR public float attackDistance => m_attackDistance; #endif } }
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; using System.IO; namespace JenzaBank { public partial class Modificar : Form { public Modificar() { InitializeComponent(); } Validacion val = new Validacion(); private void txtUs_KeyPress(object sender, KeyPressEventArgs e) { val.SoloNumeros(e); } private void txtTe_KeyPress(object sender, KeyPressEventArgs e) { val.SoloNumeros(e); } private void txtCor_KeyPress(object sender, KeyPressEventArgs e) { val.Correo(e); } private void txtClave_KeyPress(object sender, KeyPressEventArgs e) { val.Contrasena(e); } private void txtDir_KeyPress(object sender, KeyPressEventArgs e) { val.Contrasena(e); } private void btModificar_Click(object sender, EventArgs e) { if (txtCor.Text == "" || txtClave.Text == "" || txtTe.Text == "" || txtDir.Text == "" || txtNClave.Text == "") { MessageBox.Show("Revise que haya ingresado correctamente todos los datos.", "Faltan datos", MessageBoxButtons.OK, MessageBoxIcon.Warning); } else { string fileName = "clientes.txt"; //este es el nombre de un archivo de copia string fileCopia = "copia_clientes.txt"; // esto inserta texto en un archivo existente, si el archivo no existe lo crea StreamWriter writer = File.AppendText(fileCopia); StreamReader reader = File.OpenText(fileName); Cliente cliente = new Cliente(); while (!reader.EndOfStream) { string lineaActual = reader.ReadLine(); string[] datos = lineaActual.Split('/'); string a = txtUs.Text; if (datos[0]== a) { if (datos[7] == Convert.ToString(txtClave.Text)) { cliente.direccion = txtDir.Text; cliente.telefono = txtTe.Text; cliente.email = txtCor.Text; cliente.contrasena = txtNClave.Text; writer.WriteLine("{0}/{1}/{2}/{3}/{4}/{5}/{6}/{7}", datos[0], datos[1], datos[2], cliente.direccion, cliente.telefono, cliente.email, datos[6], cliente.contrasena); txtDir.Clear(); txtTe.Clear(); txtCor.Clear(); txtClave.Clear(); txtNClave.Clear(); MessageBox.Show("Los datos han sido modificados correctamente", "Actualización Éxitosa ", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { writer.WriteLine(lineaActual); } } else { writer.WriteLine(lineaActual); } } writer.Close(); reader.Close(); File.Replace(fileCopia, fileName, null, true); this.Close(); } } public struct Cliente { public string codigo; public string nombre; public string apellido; public string direccion; public string telefono; public string email; public string saldo; public string contrasena; } private void UsuarioText_Click(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void label4_Click(object sender, EventArgs e) { } private void label2_Click(object sender, EventArgs e) { } private void label3_Click(object sender, EventArgs e) { } private void txtDir_TextChanged(object sender, EventArgs e) { } private void txtNClave_TextChanged(object sender, EventArgs e) { } private void txtClave_TextChanged(object sender, EventArgs e) { } private void txtCor_TextChanged(object sender, EventArgs e) { } private void txtTe_TextChanged(object sender, EventArgs e) { } private void txtUs_TextChanged(object sender, EventArgs e) { } private void ClaveText_Click(object sender, EventArgs e) { } } }
using Assets.src.battle; namespace ru.pragmatix.orbix.world.units { public interface IUnitPursuingState : IUnitMoveState { } }
using AutomationFramework.KendoWrapper; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TradeProTests.Pages { public class ClaimsDashboardPage { #region WebElements [FindsBy(How = How.Id, Using = "advanceclaimsearchlink")] public IWebElement AdvancedSearch { get; set; } [FindsBy(How = How.Id, Using = "ClaimType")] public IWebElement ClaimType { get; set; } #endregion #region Webelement Methods public void AdvancedSearchlink() { AdvancedSearch.Click(); Console.WriteLine("Clicked Advanced search link"); } public void ClaimTypeDropDown() { KendoMultiSelectDropDownList objKendoMultiSelectDropDownList = new KendoMultiSelectDropDownList(ClaimType); // a.SelectByText("Billback"); //List<string> temString = new List<string>(); //temString.Add("Billback"); //temString.Add("HQ Rebate"); //objKendoMultiSelectDropDownList.Select(temString); objKendoMultiSelectDropDownList.Select("Billback"); } #endregion } }
using System; using System.Linq; using System.Runtime.InteropServices; using System.Text; using System.Timers; namespace SoliditySHA3Miner.Miner { public class OpenCL : IMiner { #region P/Invoke interface public static class Solver { public const string SOLVER_NAME = "OpenCLSoliditySHA3Solver"; public unsafe delegate void GetSolutionTemplateCallback(byte* solutionTemplate); public unsafe delegate void GetKingAddressCallback(byte* kingAddress); public delegate void GetWorkPositionCallback(ref ulong lastWorkPosition); public delegate void ResetWorkPositionCallback(ref ulong lastWorkPosition); public delegate void IncrementWorkPositionCallback(ref ulong lastWorkPosition, ulong incrementSize); public delegate void MessageCallback([In]StringBuilder platform, [In]int deviceID, [In]StringBuilder type, [In]StringBuilder message); public delegate void SolutionCallback([In]StringBuilder digest, [In]StringBuilder address, [In]StringBuilder challenge, [In]StringBuilder target, [In]StringBuilder solution); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void FoundADL_API(ref bool hasADL_API); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void PreInitialize(bool allowIntel, StringBuilder sha3Kernel, ulong sha3KernelSize, StringBuilder sha3KingKernel, ulong sha3KingKernelSize, StringBuilder errorMessage, ref ulong errorSize); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetPlatformNames(StringBuilder platformNames); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceCount(StringBuilder platformName, ref int deviceCount, StringBuilder errorMessage, ref ulong errorSize); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceName(StringBuilder platformName, int deviceEnum, StringBuilder deviceName, ref ulong nameSize, StringBuilder errorMessage, ref ulong errorSize); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern IntPtr GetInstance(); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void DisposeInstance(IntPtr instance); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static unsafe extern GetSolutionTemplateCallback SetOnGetSolutionTemplateHandler(IntPtr instance, GetSolutionTemplateCallback getSolutionTemplateCallback); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static unsafe extern GetKingAddressCallback SetOnGetKingAddressHandler(IntPtr instance, GetKingAddressCallback getKingAddressCallback); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern GetWorkPositionCallback SetOnGetWorkPositionHandler(IntPtr instance, GetWorkPositionCallback getWorkPositionCallback); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern ResetWorkPositionCallback SetOnResetWorkPositionHandler(IntPtr instance, ResetWorkPositionCallback resetWorkPositionCallback); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern IncrementWorkPositionCallback SetOnIncrementWorkPositionHandler(IntPtr instance, IncrementWorkPositionCallback incrementWorkPositionCallback); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern MessageCallback SetOnMessageHandler(IntPtr instance, MessageCallback messageCallback); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern SolutionCallback SetOnSolutionHandler(IntPtr instance, SolutionCallback solutionCallback); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void SetSubmitStale(IntPtr instance, bool submitStale); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void AssignDevice(IntPtr instance, StringBuilder platformName, int deviceEnum, ref float intensity, ref uint pciBusID, StringBuilder deviceName, ref ulong nameSize); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void IsAssigned(IntPtr instance, ref bool isAssigned); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void IsAnyInitialised(IntPtr instance, ref bool isAnyInitialised); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void IsMining(IntPtr instance, ref bool isMining); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void IsPaused(IntPtr instance, ref bool isPaused); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetHashRateByDevice(IntPtr instance, StringBuilder platformName, int deviceEnum, ref ulong hashRate); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetTotalHashRate(IntPtr instance, ref ulong totalHashRate); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void UpdatePrefix(IntPtr instance, StringBuilder prefix); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void UpdateTarget(IntPtr instance, StringBuilder target); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void PauseFinding(IntPtr instance, bool pause); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void StartFinding(IntPtr instance); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void StopFinding(IntPtr instance); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceSettingMaxCoreClock(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int coreClock); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceSettingMaxMemoryClock(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int memoryClock); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceSettingPowerLimit(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int powerLimit); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceSettingThermalLimit(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int thermalLimit); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceSettingFanLevelPercent(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int fanLevel); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceCurrentFanTachometerRPM(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int tachometerRPM); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceCurrentTemperature(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int temperature); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceCurrentCoreClock(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int coreClock); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceCurrentMemoryClock(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int memoryClock); [DllImport(SOLVER_NAME, CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)] public static extern void GetDeviceCurrentUtilizationPercent(IntPtr instance, StringBuilder platformName, int deviceEnum, ref int utilization); } private Solver.GetSolutionTemplateCallback m_GetSolutionTemplateCallback; private Solver.GetKingAddressCallback m_GetKingAddressCallback; private Solver.GetWorkPositionCallback m_GetWorkPositionCallback; private Solver.ResetWorkPositionCallback m_ResetWorkPositionCallback; private Solver.IncrementWorkPositionCallback m_IncrementWorkPositionCallback; private Solver.MessageCallback m_MessageCallback; private Solver.SolutionCallback m_SolutionCallback; #endregion P/Invoke interface #region static public static void PreInitialize(bool allowIntel, out string errorMessage) { errorMessage = string.Empty; var errMsg = new StringBuilder(1024); var errSize = 0ul; var sha3Kernel = new StringBuilder(Properties.Resources.ResourceManager.GetString("sha3Kernel")); var sha3KingKernel = new StringBuilder(Properties.Resources.ResourceManager.GetString("sha3KingKernel")); Solver.PreInitialize(allowIntel, sha3Kernel, (ulong)sha3Kernel.Length, sha3KingKernel, (ulong)sha3KingKernel.Length, errMsg, ref errSize); errorMessage = errMsg.ToString(); } public static string[] GetPlatformNames() { var platformNames = new StringBuilder(1024); Solver.GetPlatformNames(platformNames); return platformNames.ToString().Split('\n'); } public static int GetDeviceCount(string platformName, out string errorMessage) { errorMessage = string.Empty; var errMsg = new StringBuilder(1024); var errSize = 0ul; var deviceCount = 0; Solver.GetDeviceCount(new StringBuilder(platformName), ref deviceCount, errMsg, ref errSize); errorMessage = errMsg.ToString(); return deviceCount; } public static string GetDeviceName(string platformName, int deviceEnum, out string errorMessage) { errorMessage = string.Empty; var errMsg = new StringBuilder(1024); var deviceName = new StringBuilder(256); ulong errSize = 0ul, deviceNameSize = 0ul; Solver.GetDeviceName(new StringBuilder(platformName), deviceEnum, deviceName, ref deviceNameSize, errMsg, ref errSize); errorMessage = errMsg.ToString(); return deviceName.ToString(); } public static string GetDevices(string platformName, out string errorMessage) { errorMessage = string.Empty; var errMsg = new StringBuilder(1024); var deviceName = new StringBuilder(256); var devicesString = new StringBuilder(); ulong errSize = 0ul, nameSize = 0ul; var deviceCount = 0; Solver.GetDeviceCount(new StringBuilder(platformName), ref deviceCount, errMsg, ref errSize); errorMessage = errMsg.ToString(); if (!string.IsNullOrEmpty(errorMessage)) return string.Empty; for (int i = 0; i < deviceCount; i++) { errMsg.Clear(); deviceName.Clear(); Solver.GetDeviceName(new StringBuilder(platformName), i, deviceName, ref nameSize, errMsg, ref errSize); errorMessage = errMsg.ToString(); if (!string.IsNullOrEmpty(errorMessage)) return string.Empty; devicesString.AppendLine(string.Format("{0}: {1}", i, deviceName)); } return devicesString.ToString(); } #endregion static private Timer m_hashPrintTimer; private int m_pauseOnFailedScan; private int m_failedScanCount; private bool m_isCurrentChallengeStopSolving; public readonly IntPtr m_instance; #region IMiner public NetworkInterface.INetworkInterface NetworkInterface { get; } public Device[] Devices { get; } public bool HasAssignedDevices { get { var isAssigned = false; if (m_instance != null && m_instance.ToInt64() != 0) Solver.IsAssigned(m_instance, ref isAssigned); return isAssigned; } } public bool HasMonitoringAPI { get; private set; } public bool UseLinuxQuery { get; private set; } public bool IsAnyInitialised { get { var isAnyInitialised = false; if (m_instance != null && m_instance.ToInt64() != 0) Solver.IsAnyInitialised(m_instance, ref isAnyInitialised); return isAnyInitialised; } } public bool IsMining { get { var isMining = false; if (m_instance != null && m_instance.ToInt64() != 0) Solver.IsMining(m_instance, ref isMining); return isMining; } } public bool IsPaused { get { var isPaused = false; if (m_instance != null && m_instance.ToInt64() != 0) Solver.IsPaused(m_instance, ref isPaused); return isPaused; } } public void StartMining(int networkUpdateInterval, int hashratePrintInterval) { try { NetworkInterface.UpdateMiningParameters(); m_hashPrintTimer = new Timer(hashratePrintInterval); m_hashPrintTimer.Elapsed += m_hashPrintTimer_Elapsed; m_hashPrintTimer.Start(); NetworkInterface.ResetEffectiveHashrate(); Solver.StartFinding(m_instance); } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); StopMining(); } } public void StopMining() { try { m_hashPrintTimer.Stop(); NetworkInterface.ResetEffectiveHashrate(); Solver.StopFinding(m_instance); } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); } } public ulong GetHashrateByDevice(string platformName, int deviceID) { if (IsPaused) return 0ul; var hashrate = 0ul; if (m_instance != null && m_instance.ToInt64() != 0) Solver.GetHashRateByDevice(m_instance, new StringBuilder(platformName), deviceID, ref hashrate); return hashrate; } public ulong GetTotalHashrate() { if (IsPaused) return 0ul; var hashrate = 0ul; if (m_instance != null && m_instance.ToInt64() != 0) Solver.GetTotalHashRate(m_instance, ref hashrate); return hashrate; } public void Dispose() { try { if (m_instance != null && m_instance.ToInt64() != 0) Solver.DisposeInstance(m_instance); m_GetSolutionTemplateCallback = null; m_GetKingAddressCallback = null; m_GetWorkPositionCallback = null; m_ResetWorkPositionCallback = null; m_IncrementWorkPositionCallback = null; m_MessageCallback = null; m_SolutionCallback = null; } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); } } #endregion IMiner public OpenCL(NetworkInterface.INetworkInterface networkInterface, Device[] intelDevices, Device[] amdDevices, bool isSubmitStale, int pauseOnFailedScans) { try { NetworkInterface = networkInterface; m_pauseOnFailedScan = pauseOnFailedScans; m_failedScanCount = 0; var hasADL_API = false; Solver.FoundADL_API(ref hasADL_API); if (!hasADL_API) Program.Print("OpenCL [WARN] ADL library not found."); if (!hasADL_API && RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) UseLinuxQuery = API.AmdLinuxQuery.QuerySuccess(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) && !UseLinuxQuery) Program.Print("OpenCL [WARN] Unable to find AMD devices in Linux kernel."); HasMonitoringAPI = hasADL_API || UseLinuxQuery; NetworkInterface.OnGetTotalHashrate += NetworkInterface_OnGetTotalHashrate; if (!HasMonitoringAPI) Program.Print("OpenCL [WARN] GPU monitoring not available."); m_instance = Solver.GetInstance(); unsafe { m_GetSolutionTemplateCallback = Solver.SetOnGetSolutionTemplateHandler(m_instance, Work.GetSolutionTemplate); m_GetKingAddressCallback = Solver.SetOnGetKingAddressHandler(m_instance, Work.GetKingAddress); } m_GetWorkPositionCallback = Solver.SetOnGetWorkPositionHandler(m_instance, Work.GetPosition); m_ResetWorkPositionCallback = Solver.SetOnResetWorkPositionHandler(m_instance, Work.ResetPosition); m_IncrementWorkPositionCallback = Solver.SetOnIncrementWorkPositionHandler(m_instance, Work.IncrementPosition); m_MessageCallback = Solver.SetOnMessageHandler(m_instance, m_instance_OnMessage); m_SolutionCallback = Solver.SetOnSolutionHandler(m_instance, m_instance_OnSolution); NetworkInterface.OnGetMiningParameterStatus += NetworkInterface_OnGetMiningParameterStatus; NetworkInterface.OnNewMessagePrefix += NetworkInterface_OnNewMessagePrefix; NetworkInterface.OnNewTarget += NetworkInterface_OnNewTarget; networkInterface.OnStopSolvingCurrentChallenge += NetworkInterface_OnStopSolvingCurrentChallenge; Solver.SetSubmitStale(m_instance, isSubmitStale); if ((!Program.AllowIntel && !Program.AllowAMD) || (intelDevices.All(d => !d.AllowDevice) && amdDevices.All(d => !d.AllowDevice))) { Program.Print("OpenCL [INFO] Device not set."); return; } var deviceName = new StringBuilder(256); var deviceNameSize = 0ul; if (Program.AllowIntel) for (int i = 0; i < intelDevices.Length; i++) if (intelDevices[i].AllowDevice) { Solver.AssignDevice(m_instance, new StringBuilder(intelDevices[i].Platform), intelDevices[i].DeviceID, ref intelDevices[i].Intensity, ref intelDevices[i].PciBusID, deviceName, ref deviceNameSize); } if (Program.AllowAMD) for (int i = 0; i < amdDevices.Length; i++) if (amdDevices[i].AllowDevice) { deviceName.Clear(); Solver.AssignDevice(m_instance, new StringBuilder(amdDevices[i].Platform), amdDevices[i].DeviceID, ref amdDevices[i].Intensity, ref amdDevices[i].PciBusID, deviceName, ref deviceNameSize); if (!UseLinuxQuery) amdDevices[i].Name = deviceName.ToString(); else { amdDevices[i].Name = API.AmdLinuxQuery.GetDeviceRealName(amdDevices[i].PciBusID, deviceName.ToString()); Program.Print(string.Format("{0} (OpenCL) ID: {1} [INFO] Assigned OpenCL device ({2})", amdDevices[i].Platform, amdDevices[i].DeviceID, amdDevices[i].Name)); } } if (Program.AllowIntel && Program.AllowAMD) Devices = intelDevices.Union(amdDevices).ToArray(); else if (Program.AllowIntel) Devices = intelDevices; else if (Program.AllowAMD) Devices = amdDevices; } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); } } private void NetworkInterface_OnGetTotalHashrate(NetworkInterface.INetworkInterface sender, ref ulong totalHashrate) { if (IsPaused) return; try { var hashrate = 0ul; Solver.GetTotalHashRate(m_instance, ref hashrate); totalHashrate += hashrate; } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); } } private void m_hashPrintTimer_Elapsed(object sender, ElapsedEventArgs e) { var hashrate = 0ul; var hashString = new StringBuilder(); hashString.Append("OpenCL [INFO] Hashrates:"); foreach (var device in Devices.Where(d => d.AllowDevice)) { if (IsPaused) hashrate = 0ul; else Solver.GetHashRateByDevice(m_instance, new StringBuilder(device.Platform), device.DeviceID, ref hashrate); hashString.AppendFormat(" {0} MH/s", hashrate / 1000000.0f); } Program.Print(hashString.ToString()); if (HasMonitoringAPI) { var coreClock = 0; var temperature = 0; var tachometerRPM = 0; var coreClockString = new StringBuilder(); var temperatureString = new StringBuilder(); var fanTachometerRpmString = new StringBuilder(); coreClockString.Append("OpenCL [INFO] Core clocks:"); foreach (var device in Devices) if (device.AllowDevice) { if (UseLinuxQuery) coreClock = API.AmdLinuxQuery.GetDeviceCurrentCoreClock(device.PciBusID); else Solver.GetDeviceCurrentCoreClock(m_instance, new StringBuilder(device.Platform), device.DeviceID, ref coreClock); coreClockString.AppendFormat(" {0}MHz", coreClock); } Program.Print(coreClockString.ToString()); temperatureString.Append("OpenCL [INFO] Temperatures:"); foreach (var device in Devices) if (device.AllowDevice) { if (UseLinuxQuery) temperature = API.AmdLinuxQuery.GetDeviceCurrentTemperature(device.PciBusID); else Solver.GetDeviceCurrentTemperature(m_instance, new StringBuilder(device.Platform), device.DeviceID, ref temperature); temperatureString.AppendFormat(" {0}C", temperature); } Program.Print(temperatureString.ToString()); fanTachometerRpmString.Append("OpenCL [INFO] Fan tachometers:"); foreach (var device in Devices) if (device.AllowDevice) { if (UseLinuxQuery) tachometerRPM = API.AmdLinuxQuery.GetDeviceCurrentFanTachometerRPM(device.PciBusID); else Solver.GetDeviceCurrentFanTachometerRPM(m_instance, new StringBuilder(device.Platform), device.DeviceID, ref tachometerRPM); fanTachometerRpmString.AppendFormat(" {0}RPM", tachometerRPM); } Program.Print(fanTachometerRpmString.ToString()); } GC.Collect(GC.MaxGeneration, GCCollectionMode.Optimized, false); } private void m_instance_OnMessage(StringBuilder platform, int deviceEnum, StringBuilder type, StringBuilder message) { var sFormat = new StringBuilder(); if (!string.IsNullOrWhiteSpace(platform.ToString())) sFormat.Append(platform.ToString() + " "); if (deviceEnum > -1) sFormat.Append("ID: {0} "); switch (type.ToString().ToUpperInvariant()) { case "INFO": sFormat.Append(deviceEnum > -1 ? "[INFO] {1}" : "[INFO] {0}"); break; case "WARN": sFormat.Append(deviceEnum > -1 ? "[WARN] {1}" : "[WARN] {0}"); break; case "ERROR": sFormat.Append(deviceEnum > -1 ? "[ERROR] {1}" : "[ERROR] {0}"); break; case "DEBUG": default: #if DEBUG sFormat.Append(deviceEnum > -1 ? "[DEBUG] {1}" : "[DEBUG] {0}"); break; #else return; #endif } Program.Print(deviceEnum > -1 ? string.Format(sFormat.ToString(), deviceEnum, message) : string.Format(sFormat.ToString(), message)); } private void NetworkInterface_OnStopSolvingCurrentChallenge(NetworkInterface.INetworkInterface sender, string currentTarget) { m_isCurrentChallengeStopSolving = true; Solver.PauseFinding(m_instance, true); } private void NetworkInterface_OnNewMessagePrefix(NetworkInterface.INetworkInterface sender, string messagePrefix) { try { if (m_instance != null && m_instance.ToInt64() != 0) { Solver.UpdatePrefix(m_instance, new StringBuilder(messagePrefix)); if (m_isCurrentChallengeStopSolving) { Solver.PauseFinding(m_instance, false); m_isCurrentChallengeStopSolving = false; } } } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); } } private void NetworkInterface_OnNewTarget(NetworkInterface.INetworkInterface sender, string target) { try { if (m_instance != null && m_instance.ToInt64() != 0) Solver.UpdateTarget(m_instance, new StringBuilder(target)); } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); } } private void NetworkInterface_OnGetMiningParameterStatus(NetworkInterface.INetworkInterface sender, bool success, NetworkInterface.MiningParameters miningParameters) { try { if (m_instance != null && m_instance.ToInt64() != 0) { if (success) { var isPause = false; Solver.IsPaused(m_instance, ref isPause); if (m_isCurrentChallengeStopSolving) { isPause = true; } else if (isPause) { if (m_failedScanCount > m_pauseOnFailedScan) m_failedScanCount = 0; isPause = false; } Solver.PauseFinding(m_instance, isPause); } else { m_failedScanCount += 1; var isMining = false; Solver.IsMining(m_instance, ref isMining); if (m_failedScanCount > m_pauseOnFailedScan && IsMining) Solver.PauseFinding(m_instance, true); } } } catch (Exception ex) { Program.Print(string.Format("OpenCL [ERROR] {0}", ex.Message)); } } private void m_instance_OnSolution(StringBuilder digest, StringBuilder address, StringBuilder challenge, StringBuilder target, StringBuilder solution) { var difficulty = NetworkInterface.Difficulty.ToString("X64"); NetworkInterface.SubmitSolution(digest.ToString(), address.ToString(), challenge.ToString(), difficulty, target.ToString(), solution.ToString(), this); } } }
using System; namespace _10._Top_Number { class Program { static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); for (int i = 1; i <= n; i++) { if (IsTop(i)) { Console.WriteLine(i); } } } static bool IsTop(int number) { bool isTop = true; bool onlyEvenDig = true; int sumOfDigits = 0; while (number != 0) { sumOfDigits += number % 10; if ((number % 10) % 2 != 0) { onlyEvenDig = false; } number /= 10; } if (sumOfDigits % 8 != 0 || onlyEvenDig) { isTop = false; } return isTop; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using com.Sconit.Entity.MD; namespace com.Sconit.Web.Controllers { public class ReportBaseController : WebAppBaseController { /// <summary> /// 根据工厂,区域或者库位获取需要的库位数据 /// </summary> /// <param name="plantFrom">从***工厂</param> /// <param name="plantTo">到***工厂</param> /// <param name="regionFrom">从***区域</param> /// <param name="regionTo">到***区域</param> /// <param name="locationFrom">从***库位</param> /// <param name="locationTo">到***库位</param> /// <returns>目标库位</returns> public IList<Location> GetReportLocations(string sapLocation, string plantFrom, string plantTo, string regionFrom, string regionTo, string locationFrom, string locationTo) { IList<Location> locationList = new List<Location>(); IList<Region> regionList = new List<Region>(); if (!string.IsNullOrEmpty(sapLocation)) { locationList = this.queryMgr.FindAll<Location>("from Location l where l.SAPLocation = ? ", new object[] { sapLocation }); ViewBag.Location = Resources.View.LocationDetailView.LocationDetailView_SAPLocation; } else if (!string.IsNullOrEmpty(locationFrom)) { if (!string.IsNullOrEmpty(locationTo)) { locationList = this.queryMgr.FindAll<Location>("from Location l where l.Code between ? and ?", new object[] { locationFrom, locationTo }); } else { locationList = this.queryMgr.FindAll<Location>("from Location l where l.Code = ?", new object[] { locationFrom }); } ViewBag.Location = Resources.View.LocationDetailView.LocationDetailView_Location; } else if (!string.IsNullOrEmpty(regionFrom)) { if (!string.IsNullOrEmpty(regionTo)) { regionList = this.queryMgr.FindAll<Region>("from Region r where r.Code between ? and ?", new object[] { regionFrom, regionTo }); } else { regionList = this.queryMgr.FindAll<Region>("from Region r where r.Code = ? ", new object[] { regionFrom }); } ViewBag.Location = Resources.View.LocationDetailView.LocationDetailView_region; } if (regionList.Count > 0 && locationList.Count == 0) { string hql = string.Empty; IList<object> paras = new List<object>(); foreach (var region in regionList) { if (hql == string.Empty) { hql = "from Location l where l.Region in (?"; } else { hql += ", ?"; } paras.Add(region.Code); } hql += ")"; locationList = this.queryMgr.FindAll<Location>(hql, paras.ToArray()); } return locationList; } public IList<Item> GetReportItems(string itemFrom, string itemTo) { IList<Item> itemList = new List<Item>(); if (!string.IsNullOrEmpty(itemFrom)) { if (!string.IsNullOrEmpty(itemTo)) { itemList = this.queryMgr.FindAll<Item>("from Item i where i.Code between ? and ?", new object[] { itemFrom, itemTo }); } else { itemList = this.queryMgr.FindAll<Item>("from Item i where i.Code = ? ", new object[] { itemFrom }); } if (string.IsNullOrEmpty(ViewBag.Location)) ViewBag.Location = Resources.View.LocationDetailView.LocationDetailView_Location; } return itemList; } } }
namespace Ach.Fulfillment.Nacha.Attribute { using System; using Ach.Fulfillment.Shared.Reflection; [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false, AllowMultiple = false)] public sealed class RecordAttribute : Attribute, IReflectAttribute { public bool IsRequired { get; set; } public string RecordType { get; set; } public string ControlPrefix { get; set; } public string Prefix { get; set; } public string Postfix { get; set; } #region IReflectAttribute Members public int Position { get; set; } #endregion } }
// //----------------------------------------------------------------------------- // // <copyright file="BasicStrategyMode.cs" company="DCOM Engineering, LLC"> // // Copyright (c) DCOM Engineering, LLC. All rights reserved. // // </copyright> // //----------------------------------------------------------------------------- namespace NET_GC.Basic_Dispose_Pattern { public enum BasicStrategyMode { Deterministic, Indeterministic } }
using System; using SFA.DAS.Authorization.ModelBinding; using SFA.DAS.CommitmentsV2.Shared.Models; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Types; namespace SFA.DAS.ProviderCommitments.Web.Models.Apprentice { public class ConfirmViewModel : IAuthorizationContextModel { public long ProviderId { get; set; } public string AccountLegalEntityPublicHashedId { get; set; } public long AccountLegalEntityId { get; set; } public string ApprenticeshipHashedId { get; set; } public long ApprenticeshipId { get; set; } public DeliveryModel DeliveryModel { get; set; } public string ApprenticeName { get; set; } public string OldEmployerName { get; set; } public DateTime OldStartDate { get; set; } public DateTime OldEndDate { get; set; } public DateTime StopDate { get; set; } public int OldPrice { get; set; } public int? OldEmploymentPrice { get; set; } public DateTime? OldEmploymentEndDate { get; set; } public string NewEmployerName { get; set; } public string NewStartDate { get; set; } public DateTime NewStartDateTime => string.IsNullOrWhiteSpace(NewStartDate) ? DateTime.MinValue : new MonthYearModel(NewStartDate).Date.Value; public string NewEndDate { get; set; } public DateTime NewEndDateTime => string.IsNullOrWhiteSpace(NewEndDate) ? DateTime.MinValue : new MonthYearModel(NewEndDate).Date.Value; public string NewEmploymentEndDate { get; set; } public DateTime? NewEmploymentEndDateTime => NewEmploymentEndDate == null ? default : new MonthYearModel(NewEmploymentEndDate).Date.Value; public int NewPrice { get; set; } public int? NewEmploymentPrice { get; set; } public int? FundingBandCap { get; set; } public bool ExceedsFundingBandCap { get { if (FundingBandCap.HasValue) { return NewPrice > FundingBandCap.Value; } return false; } } public Guid CacheKey { get; set; } public bool ShowDeliveryModel { get; set; } public bool ShowDeliveryModelChangeLink { get; set; } public CommitmentsV2.Types.DeliveryModel OldDeliveryModel { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using CreativityEdu.Data; using CreativityEdu.Models; using CreativityEdu.VM; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace CreativityEdu.Controllers { public class EmployessController : Controller { private CreativityEduContext _CreativityEduContext; private UserManager<AppUser> _userManager; public EmployessController(CreativityEduContext creativityEduContext, UserManager<AppUser> userManager) { _CreativityEduContext = creativityEduContext; _userManager = userManager; } public IActionResult Index() { var listEmployees = _CreativityEduContext.Employess.Include(x => x.User).Where(x => x.IsDelete == false).ToList(); return View(listEmployees); } public IActionResult Create() { return View(); } [HttpPost] public async Task<IActionResult> Create(EmployeeCreateVm empolyee) { var newUser = new AppUser { FirstName = empolyee.FirstName, LastName = empolyee.LastName, Email = empolyee.Email, Gender = empolyee.Gender, Address = empolyee.Address, PhoneNumber = empolyee.PhoneNumber, UserName = empolyee.Email, }; var result = await _userManager.CreateAsync(newUser, empolyee.Password); var newEmployee = new Employess { Sallary = empolyee.Salary, Department = empolyee.Departmant, UserId = newUser.Id }; await _CreativityEduContext.Employess.AddAsync(newEmployee); await _CreativityEduContext.SaveChangesAsync(); return RedirectToAction("Index"); } //EDIT EMPLOYEE public IActionResult Edit(long id) { //search employee in db by id var employee = _CreativityEduContext.Employess.Include(x => x.User).FirstOrDefault(x => x.Id == id); //mapping data from employee class to createemolyeevm class var updatEmployee = new EmployeeCreateVm() { Id = employee.Id, FirstName = employee.User.FirstName, LastName = employee.User.LastName, Email = employee.User.Email, Db = employee.User.DateOfBirthDate, Departmant = employee.Department, PhoneNumber = employee.User.PhoneNumber, Salary = employee.Sallary }; return View("Edit", updatEmployee); } [HttpPost] public async Task<IActionResult> Edit(EmployeeCreateVm employee) { //search employee in db by id var editEmployee = await _CreativityEduContext.Employess.FirstOrDefaultAsync(x => x.Id == employee.Id); editEmployee.Department = employee.Departmant; await _CreativityEduContext.SaveChangesAsync(); var userDb = await _userManager.FindByIdAsync(editEmployee.UserId); userDb.FirstName = employee.FirstName; userDb.LastName = employee.LastName; userDb.PhoneNumber = employee.PhoneNumber; userDb.Email = employee.Email; userDb.UserName = employee.Email; await _userManager.UpdateAsync(userDb); await _CreativityEduContext.SaveChangesAsync(); return RedirectToAction("index"); } public IActionResult Delete(long id) { var employee = _CreativityEduContext.Employess.FirstOrDefault(x => x.Id == id); employee.IsDelete = true; _CreativityEduContext.SaveChanges(); return RedirectToAction("Index"); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model { public class Grid { #region Properties public GridPoint GridOrigen { get; set; } public GridPoint GridLimit { get; set; } public List<GridPoint> ScentPoints { get; set; } #endregion #region Constructor public Grid() { GridOrigen = new GridPoint(0, 0); ScentPoints = new List<GridPoint>(); } #endregion } }
using System.Collections.Generic; namespace DevExpress.Web.Demos { public static class MicrosoftAnnualRevenueProvider { public static List<RevenueEntry> GetMicrosoftAnnualRevenue() { return new List<RevenueEntry>() { new RevenueEntry("2000", 22.96, 22.96), new RevenueEntry("2001", 25.3, 48.25), new RevenueEntry("2002", 28.36, 76.62), new RevenueEntry("2003", 32.19, 108.8), new RevenueEntry("2004", 36.83, 145.54) }; } } public class RevenueEntry { string year; double annualRevenue; double summaryRevenue; public string Year { get { return year; } } public double AnnualRevenue { get { return annualRevenue; } } public double SummaryRevenue { get { return summaryRevenue; } } public RevenueEntry(string year, double annualRevenue, double summaryRevenue) { this.year = year; this.annualRevenue = annualRevenue; this.summaryRevenue = summaryRevenue; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using KartObjects; namespace KartSystem { public class TradeReportSection : TradeReportSpecRecord { [DBIgnoreReadParam] [DBIgnoreAutoGenerateParam] public override string FriendlyName { get { return "Позиция секционного товарного отчёта"; } } [DisplayName("Секция склада")] public string WhSectionName { get; set; } } }
using System; using System.Collections.Generic; using Windows.ApplicationModel.Background; using Windows.Storage; using Windows.Storage.Pickers; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Navigation; namespace WorkTimeApp { public sealed partial class MainPage : Page { private const string TaskName = "GetTimeBackgroundTask"; private const string TaskEntryPoint = "TileUpdater.GetTimeBackgroundTask"; private const string DefaultFileName = "login-times"; public MainPage() { InitializeComponent(); } protected override void OnNavigatedTo(NavigationEventArgs e) { HandleTaskRegistration(); } private async void HandleTaskRegistration() { await BackgroundExecutionManager.RequestAccessAsync(); UnregisterOldTasks(); RegisterTasks(); } private void UnregisterOldTasks() { foreach (var task in BackgroundTaskRegistration.AllTasks) { if (task.Value.Name == TaskName) { task.Value.Unregister(true); } } } private void RegisterTasks() { var taskBuilder = new BackgroundTaskBuilder { Name = TaskName, TaskEntryPoint = TaskEntryPoint }; RegisterTask(taskBuilder, new SystemTrigger(SystemTriggerType.UserPresent, false)); RegisterTask(taskBuilder, new SystemTrigger(SystemTriggerType.SessionConnected, false)); RegisterTask(taskBuilder, new TimeTrigger(15, false)); } private void RegisterTask(BackgroundTaskBuilder builder, IBackgroundTrigger trigger) { builder.SetTrigger(trigger); builder.Register(); } private async void button_Click(object sender, RoutedEventArgs e) { var savePicker = SetUpFilePicker(); var file = await savePicker.PickSaveFileAsync(); if (file == null) return; StoreFileAccessToken(file); } private FileSavePicker SetUpFilePicker() { var savePicker = new FileSavePicker { SuggestedStartLocation = PickerLocationId.DocumentsLibrary, SuggestedFileName = DefaultFileName }; savePicker.FileTypeChoices.Add("Plain Text", new List<string>() { ".txt" }); return savePicker; } private void StoreFileAccessToken(StorageFile file) { var localSettings = ApplicationData.Current.LocalSettings; var faToken = Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.Add(file); localSettings.Values[TileUpdater.Settings.FileAccessToken] = faToken; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FollowPlayer : MonoBehaviour { public GameObject player; public float speed; public float radius; // Use this for initialization void Start () { } // Update is called once per frame void Update () { float step = speed * Time.deltaTime; Vector3 targetPos = player.transform.position; if(player.GetComponent<Player>().facing == "right") { targetPos.x -= radius; } else { targetPos.x += radius; } targetPos.y = this.transform.position.y; targetPos.z = this.transform.position.z; transform.position = Vector3.MoveTowards(transform.position, targetPos, step); } }
namespace TheMapToScrum.Back.DTO { public class TeamDTO : BaseEntityDTO { public string Label { get; set; } } }
using ManhaleAspNetCore.Models; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace ManhaleAspNetCore.ModelView.Manahel { public class ManahelVM { public int Id { get; set; } [Display(Name="Manhal Code")] public string Ssn { get; set; } [Display(Name = "Manhal Name")] public string NickName { get; set; } [Display(Name = "Manhal Locattion")] public string LocationName { get; set; } [Display(Name = "Flower Name")] public string FlowerName { get; set; } [Display(Name = "Date Created")] public DateTime DateCreated { get; set; } [Display(Name = "Date Last Changes")] public DateTime DateUpdated { get; set; } [Display(Name = "Manhal Images")] [NotMapped] public List<Images> ImageManhals { get; set; } } }
namespace TestDataGenerator.Core.Generators { internal class ContentOptions { public bool IsNegated { get; set; } public bool ContainsAlternation { get; set; } public string Content { get; set; } public int Repeat { get; set; } public bool IsAnagram { get; set; } public string QuantifierContent { get; set; } public ContentOptions() { IsNegated = false; IsAnagram = false; Content = ""; ContainsAlternation = false; Repeat = 1; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace wsApiEPayment.Models.Affipay { public class RespuestaCancelacion { public string Estado { get; set; } public string Id { get; set; } public string Fecha { get; set; } public string Hora { get; set; } public DataRespose respuestaAffipay { get; set; } public string IdPagoElectronico { get; set; } } public class DataRespose { public string Autorizacion { get; set; } public string Descripcion { get; set; } public binInformation Informacion { get; set; } } }
// Utility.cs // using System; using System.Collections; using System.Html; using System.Runtime.CompilerServices; using jQueryApi; namespace SportsLinkScript.Shared { public class SessionContext { public static SessionContext Instance = new SessionContext(); public long FamilyId; public ArrayList ActiveUsers = new ArrayList(); public long ChallengId; } }
// File Prologue // Name: Darren Moody // CS 1400 Section 005 // Project: CS1400_Lab_09 // Date: 9/26/2013 // Description: THE FARMER JOHN PROBLEM - Simple Console application to calculate the area the shaded region // of Farmer John's property, with his new circular irrigation system. // // I declare that the following code was written by me or provided // by the instructor for this project. I understand that copying source // code from any other source constitutes cheating, and that I will receive // a zero on this project if I am found in violation of this policy. // --------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Lab09 { class Program { // Declare const double TIMES_TWO = 2 to use in calculating length of side of square const double TIMES_TWO = 2; static void Main(string[] args) { // Declare variables to store values in double lengthSquare, radiusCircle, areaSquare, areaCircle, areaShaded; // Prompt user to input length of radius of the circle and store it in radiusCircle Console.Write("Please enter the length of the radius of the circle: "); radiusCircle = int.Parse(Console.ReadLine()); // Calculate the lengthSquare by multiplying the radius * 2 lengthSquare = radiusCircle * TIMES_TWO; // Calculate and store the area of square in areaSquare areaSquare = Math.Pow(lengthSquare, TIMES_TWO); // Calculate and store the area of circle in areaCircle (note: there are 4, ¼ pieces of a // whole circle. Rather than calculate ¼ of the circle and * it by 4 we can just take the area of one circle) areaCircle = Math.PI * Math.Pow(radiusCircle, TIMES_TWO); // Calculate and store the area of the shaded region and store in areaShaded areaShaded = areaSquare - areaCircle; // Output the calculated areaShaded Console.WriteLine("\nThe area of the shaded region is: {0:F2} ft. squared.", areaShaded); Console.ReadLine(); }//end Main() }//end class Program }
using Clients.MPD; using Common; using Common.Log; using Common.Presentation; using SessionSettings; using System; using System.Data; using System.Drawing; using System.ServiceModel; using System.Threading; using System.Windows.Forms; namespace MPD.Modals { public partial class ChannelCodes : SkinnableModalBase { #region Private Fields private Point mCancelPt = new Point(17, 318); private ClientPresentation mClientPresentation = new ClientPresentation(); private DataTable mDataSource = null; private Point mOKPt = new Point(282, 318); private MPDProxy mProxy = null; #endregion #region Constructors public ChannelCodes(ParameterStruct parameters, SkinnableFormBase owner) : base(parameters, owner) { InitializeComponent(); ApplySkin(parameters); SetCaption("Channel Codes"); owner.AddOwnedForm(this); Logging.ConnectionString = Settings.ConnectionString; } #endregion #region Private Methods private void Cancel_Click(object sender, EventArgs e) { CleanUpResources(); DoCancel(); } private void ChannelCodes_Load(object sender, EventArgs e) { LoadChannelCodes(); } private void ChannelCodes_Shown(object sender, EventArgs e) { cancel.Location = mCancelPt; ok.Location = mOKPt; } private void CleanUpResources() { if (mDataSource != null) mDataSource.Dispose(); mDataSource = null; } private void CloseProxy() { if (mProxy != null && mProxy.State != CommunicationState.Closed && mProxy.State != CommunicationState.Faulted) { Thread.Sleep(30); mProxy.Close(); } mProxy = null; } private void ExportToExcel() { Cursor = Cursors.AppStarting; try { string fileName = ""; if (ImportExport.Export(codesGrid, "Excel", ref fileName)) { Console.Beep(); MessageBox.Show("The file '" + fileName + "' has been created.", "Save List to File", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception e) { Logging.Log(e, "MPD", "ChannelCodes.ExportToExcel"); mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); } finally { Cursor = Cursors.Default; } } private void LoadChannelCodes() { OpenProxy(); try { mDataSource = mProxy.GetChannelCodes(); codesGrid.DataSource = mDataSource; } catch (Exception e) { Logging.Log(e, "MPD", "ChannelCodes.LoadChannelCodes"); mClientPresentation.ShowError(e.Message + "\n" + e.StackTrace); } finally { CloseProxy(); } } private void OK_Click(object sender, EventArgs e) { ExportToExcel(); CleanUpResources(); DoCancel(); } /// <summary> /// Creates the synchronous proxy. /// </summary> private void OpenProxy() { if (mProxy == null || mProxy.State == CommunicationState.Closed) { mProxy = new MPDProxy(Settings.Endpoints["MPD"]); mProxy.Open(); mProxy.CreateMPDMethods(Settings.ConnectionString, Settings.UserName); } } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class WatchWeaponStamina : MonoBehaviour { Slider slider; public WeaponSlot weaponSlot; public float maxStamina = 100; public float lastStamina; void Start(){ slider = GetComponentInChildren<Slider>(); } void Update(){ if (lastStamina != weaponSlot.weaponStamina) { slider.value = (float)weaponSlot.weaponStamina / maxStamina; } lastStamina = weaponSlot.weaponStamina; } }
using jaytwo.Common.Http; using NUnit.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace jaytwo.Common.Test { public static class TestUtility { public static Uri GetUriFromString(string url) { var kind = (!string.IsNullOrEmpty(url) && Uri.IsWellFormedUriString(url, UriKind.Absolute)) ? UriKind.Absolute : UriKind.Relative; var uri = string.IsNullOrEmpty(url) ? null : new Uri(url, kind); return uri; } public static HttpWebResponse GetResponseFromUrl(string url) { var uri = GetUriFromString(url); if (uri != null) { return HttpProvider.SubmitGet(uri); } else { return null; } } private static bool IsObjectTypeMatch(object a, Type b) { if (a == null) { return b.IsClass; } else { return b.IsInstanceOfType(a); } } public static IEnumerable<TestCaseData> GetTestCasesWithArgumentTypes<T>(IEnumerable<TestCaseData> testCases) { foreach (var item in testCases) { if (item.Arguments.Length == 1 && IsObjectTypeMatch(item.Arguments[0], typeof(T))) { yield return item; } } } public static IEnumerable<TestCaseData> GetTestCasesWithArgumentTypes<T0, T1>(IEnumerable<TestCaseData> testCases) { foreach (var item in testCases) { if (item.Arguments.Length == 2 && IsObjectTypeMatch(item.Arguments[0], typeof(T0)) && IsObjectTypeMatch(item.Arguments[1], typeof(T1))) { yield return item; } } } public static IEnumerable<TestCaseData> GetTestCasesWithArgumentTypes<T0, T1, T2>(IEnumerable<TestCaseData> testCases) { foreach (var item in testCases) { if (item.Arguments.Length == 3 && IsObjectTypeMatch(item.Arguments[0], typeof(T0)) && IsObjectTypeMatch(item.Arguments[1], typeof(T1)) && IsObjectTypeMatch(item.Arguments[2], typeof(T2))) { yield return item; } } } public static IEnumerable<TestCaseData> GetTestCasesWithArgumentTypes<T0, T1, T2, T3>(IEnumerable<TestCaseData> testCases) { foreach (var item in testCases) { if (item.Arguments.Length == 4 && IsObjectTypeMatch(item.Arguments[0], typeof(T0)) && IsObjectTypeMatch(item.Arguments[1], typeof(T1)) && IsObjectTypeMatch(item.Arguments[2], typeof(T2)) && IsObjectTypeMatch(item.Arguments[3], typeof(T3))) { yield return item; } } } public static IEnumerable<TestCaseData> GetTestCasesWithArgumentTypes<T0, T1, T2, T3, T4>(IEnumerable<TestCaseData> testCases) { foreach (var item in testCases) { if (item.Arguments.Length == 5 && IsObjectTypeMatch(item.Arguments[0], typeof(T0)) && IsObjectTypeMatch(item.Arguments[1], typeof(T1)) && IsObjectTypeMatch(item.Arguments[2], typeof(T2)) && IsObjectTypeMatch(item.Arguments[3], typeof(T3)) && IsObjectTypeMatch(item.Arguments[4], typeof(T4))) { yield return item; } } } } }
using AsyncClasses; using Contracts.Callback; using Entity; using System.Collections.Generic; using System.IO; using System.ServiceModel; using System.Threading.Tasks; namespace Contracts.MLA { [ServiceContract(SessionMode = SessionMode.Required, CallbackContract = typeof(IAsyncUpdateCallback), Namespace = "http://www.noof.com/", Name = "AddendumAsyncUpdate")] [ServiceKnownType(typeof(MLATableLoader))] [ServiceKnownType(typeof(MLAAddendum))] public interface IMLAAsyncUpdateService { [OperationContract] void CancelSaveAddendumAsync(); [OperationContract] void CancelUpdateAddendaAsync(); [OperationContract] Task<bool> SaveAddendumAsync(object userState); [OperationContract(IsOneWay = true)] void SendNextChunk(List<int> ids); [OperationContract(IsOneWay = true)] void SendNextChunkAddenda(MLAAddendum[] addenda); [OperationContract(IsOneWay = true)] void SendNextChunkString(List<string> rights); [OperationContract] Task<bool> UpdateAddendaAsync(object userState); } }
using NfePlusAlpha.Application.ViewModels.Apoio; using NfePlusAlpha.Domain.Entities; using NfePlusAlpha.Infra.Data.Classes; using NfePlusAlpha.Infra.Data.Retorno; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NfePlusAlpha.Application.ViewModels.ViewModel { public class NotaFiscalEmailViewModel : ViewModelBase { #region PROPRIEDADES public int intCodigoNota { get; set; } private string _strChaveAcesso; public string strChaveAcesso { get { return _strChaveAcesso; } set { _strChaveAcesso = value; RaisePropertyChanged("strChaveAcesso"); } } private string _strEmail; [Required(ErrorMessage = "O Email é obrigatório")] public string strEmail { get { return _strEmail; } set { _strEmail = value; RaisePropertyChanged("strEmail"); } } #endregion #region METODOS public bool EnviarEmail(out string strMensagem) { strMensagem = string.Empty; NfePlusAlphaRetorno objRetorno = null; using (NotaFiscalEletronica objNota = new NotaFiscalEletronica()) { objRetorno = objNota.ObterNotaFiscalEletronica(this.intCodigoNota); } if (!objRetorno.blnTemErro && objRetorno.objRetorno != null) { tbNotaFiscalEletronica objNota = (tbNotaFiscalEletronica)objRetorno.objRetorno; string strArquivoXml = string.Format("{0}\\Autorizadas\\{1}\\{2}-procNFe.xml", AppDomain.CurrentDomain.BaseDirectory, objNota.nfe_dhEmi.ToString("MMyyyy"), objNota.nfe_chaveAcesso); if (File.Exists(strArquivoXml)) { string strArquivoPdf = string.Format("{0}PDF\\{1}.pdf", AppDomain.CurrentDomain.BaseDirectory, objNota.nfe_chaveAcesso); FileInfo objArquivo = new FileInfo(strArquivoPdf); if (!objArquivo.Directory.Exists) Directory.CreateDirectory(objArquivo.DirectoryName); if (!objArquivo.Exists) { if (!NfeUtilViewModel.GerarPdf(strArquivoXml, strArquivoPdf, objNota.nfe_status)) { strMensagem = "Nâo foi possível gerar o arquivo PDF"; return false; } } using (Configuracao objConfig = new Configuracao()) { objRetorno = objConfig.Obter(); } if (!objRetorno.blnTemErro) { if (string.IsNullOrEmpty(this.strEmail)) this.strEmail = objNota.tbNotaFiscalEletronicaDestinatario.FirstOrDefault().nfd_email; tbConfiguracao objConfiguracao = (tbConfiguracao)objRetorno.objRetorno; if (objConfiguracao != null) { string strAssunto = string.Format("Nota Fiscal Eletrônica {0} - {1}", objNota.nfe_nNF, objNota.nfe_xNome); string strCorpoEmail = objConfiguracao.con_emailMensagem; bool blnEmailEnviado = Util.EnviarEmail(objConfiguracao.con_emailHost, objConfiguracao.con_emailPorta, objConfiguracao.con_emailRequeSSL, objConfiguracao.con_email, objConfiguracao.con_emailSenha, this.strEmail, strAssunto, strCorpoEmail, strArquivoPdf, strArquivoXml, out strMensagem); if (blnEmailEnviado) { using (NotaFiscalEletronica objNotaBLL = new NotaFiscalEletronica()) { objNotaBLL.AlterarStatusEmail(objNota.nfe_codigo); } } return blnEmailEnviado; } } else strMensagem = objRetorno.strMensagemErro; } else strMensagem = "Arquivo XML não encontrado no computador."; } return false; } #endregion } }
using System.Collections.Generic; using System.Linq; using System.Data; using Giusti.Chat.Model; using Giusti.Chat.Data.Library; namespace Giusti.Chat.Data { public class AreaData : DataBase { public Area RetornaArea_Id(int id, int? empresaId) { IQueryable<Area> query = Context.Areas; query = query.Where(d => d.Id == id); if (empresaId.HasValue) query = query.Where(a => a.EmpresaId == empresaId); return query.FirstOrDefault(); } public IList<Area> RetornaAreas(int? empresaId) { IQueryable<Area> query = Context.Areas; if (empresaId.HasValue) query = query.Where(a => a.EmpresaId == empresaId); return query.ToList(); } public void SalvaArea(Area itemGravar) { Area itemBase = Context.Areas.Where(f => f.Id == itemGravar.Id).FirstOrDefault(); if (itemBase == null) { itemBase = Context.Areas.Create(); Context.Entry<Area>(itemBase).State = System.Data.Entity.EntityState.Added; } AtualizaPropriedades<Area>(itemBase, itemGravar); Context.SaveChanges(); itemGravar.Id = itemBase.Id; } public void ExcluiArea(Area itemGravar) { Area itemExcluir = Context.Areas.Where(f => f.Id == itemGravar.Id).FirstOrDefault(); Context.Entry<Area>(itemExcluir).State = System.Data.Entity.EntityState.Deleted; Context.SaveChanges(); } } }
using System; namespace Petanque.Model.Competitions { public class CannotAddTeamInLockedCompetition : Exception { } }
// // ProviderRepository.cs // // Author: // nofanto ibrahim <nofanto.ibrahim@gmail.com> // // Copyright (c) 2011 sejalan // // This library is free software; you can redistribute it and/or modify // it under the terms of the GNU Lesser General Public License as // published by the Free Software Foundation; either version 2.1 of the // License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA using System; using System.Collections.Generic; using Sejalan.Framework.Data.DbLinq; using System.Linq; using System.Collections.Specialized; namespace Sejalan.Framework.Provider.Data.DbLinq.Sqlite { public class ProviderRepository : ProviderRepositoryBase { #region implemented abstract members of Sejalan.Framework.Provider.ProviderRepositoryBase public override ProviderRepositoryInfo GetProviderRepositoryInfo (string providerFactoryKey) { if (String.IsNullOrEmpty(providerFactoryKey)) { throw new ArgumentNullException("providerFactoryKey"); } ProviderRepositoryInfo result = new ProviderRepositoryInfo(); result.DefaultProviderName = GetDefaultProviderName(providerFactoryKey); foreach (ProviderSettings item in GetProviders(providerFactoryKey).Values) { result.ProviderSettings.Add(item); } return result; } private Dictionary<string, ProviderSettings> GetProviders(string providerKey) { var result = new Dictionary<String, ProviderSettings>(); using (ProviderDataContext dc = ProviderFactory.GetInstance<DataContextFactory>(ProviderRepositoryFactory.Instance.Providers[this.Parameters["dataContextProviderRepositoryName"]]).GetProviders<DataContextProviderBase>()[this.Parameters["dataContextProviderName"]].DataContext as ProviderDataContext) { foreach (ProviderValueObject provider in dc.Providers.Where(p => p.Key == providerKey).ToList()) { var newProviderSettings = new ProviderSettings(provider.Name,provider.Type); foreach (ProviderParameterValueObject parameter in dc.ProviderParameters.Where(p => p.FKProviders == provider.Id).ToList()) { newProviderSettings.Parameters.Add(parameter.Name, parameter.Value); } result.Add(newProviderSettings.Name, newProviderSettings); } } return result; } private string GetDefaultProviderName(string providerKey) { string providerName = string.Empty; using (ProviderDataContext dc = ProviderFactory.GetInstance<DataContextFactory>(ProviderRepositoryFactory.Instance.Providers[this.Parameters["dataContextProviderRepositoryName"]]).GetProviders<DataContextProviderBase>()[this.Parameters["dataContextProviderName"]].DataContext as ProviderDataContext) { ProviderValueObject result = dc.Providers.Where(p => p.IsDefault).SingleOrDefault(); if (result != null) { providerName = result.Name; } } return providerName; } public override void SaveProviderRepositoryInfo (string providerFactoryKey, ProviderRepositoryInfo providerRepositoryInfo) { using (ProviderDataContext dc = ProviderFactory.GetInstance<DataContextFactory>(ProviderRepositoryFactory.Instance.Providers[this.Parameters["dataContextProviderRepositoryName"]]).GetProviders<DataContextProviderBase>()[this.Parameters["dataContextProviderName"]].DataContext as ProviderDataContext) { dc.ExecuteCommand(String.Format("DELETE FROM ProviderParameters WHERE FKProviders IN (SELECT Id FROM Providers WHERE Key = '{0}')", providerFactoryKey)); dc.ExecuteCommand(String.Format("DELETE FROM Providers WHERE Key = '{0}'", providerFactoryKey)); foreach (ProviderSettings provider in providerRepositoryInfo.ProviderSettings) { var newProvider = new ProviderValueObject(); newProvider.Key = providerFactoryKey; newProvider.Name = provider.Name; newProvider.Type = provider.Type; newProvider.IsDefault = (providerRepositoryInfo.DefaultProviderName == provider.Name); dc.Providers.InsertOnSubmit(newProvider); dc.SubmitChanges(); foreach (var item in provider.Parameters.Keys) { if (item.ToString().ToUpper() != "NAME" && item.ToString().ToUpper() != "TYPE") { var newParameter = new ProviderParameterValueObject(); newParameter.FKProviders = newProvider.Id; newParameter.Name = item.ToString(); newParameter.Value = provider.Parameters[item.ToString()]; dc.ProviderParameters.InsertOnSubmit(newParameter); } } dc.SubmitChanges(); } } } #endregion public ProviderRepository () { } } }
using StarBastardCore.Website.Code.Game.Gameplay; using StarBastardCore.Website.Code.Game.Gameworld.Units; namespace StarBastardCore.Website.Code.Game.Gameworld.Geography.Buildings { public abstract class BuildingBase : UnitBase, IBuilding { public Resources Produce() { return PlayerBenefit; } public abstract Resources PlayerBenefit { get; } public abstract Resources ConstructionCost { get; } } }
using System; using System.Collections.Generic; using System.Text; namespace Task_03 { class StaticTempConverters { public static double FromCelsToKelv(double temperatureC) { return temperatureC + 273; } public static double FromKelvToCels(double temperatureK) { return temperatureK - 273; } public static double FromCelsToRa(double temperatureC) { return FromCelsToKelv(temperatureC) * 1.8; } public static double FromRaToCels(double temperatureRa) { return FromKelvToCels(temperatureRa / 1.8); } public static double FromCelsToRe(double temperatureC) { return temperatureC * 0.8; } public static double FromReToCels(double temperatureR) { return temperatureR * 1.25; } } }
using System; using DelftTools.Units; using DelftTools.Units.Generics; using NUnit.Framework; namespace DelftTools.Tests.Units { [TestFixture] public class ParameterTest { [Test] public void DefaultValueIsPreDefinedAndAssignableForGenericType() { var parameterInt = new Parameter<int> {DefaultValue = 5}; Assert.AreEqual(5, parameterInt.DefaultValue); } [Test] public void DefaultValueForIntType() { var defaultParameterValue = new Parameter<int>().DefaultValue; const int expectedValue = 0; Assert.AreEqual(expectedValue, defaultParameterValue); } [Test] public void DefaultValueForStringType() { var defaultParameterValue = new Parameter<string>().DefaultValue; var expectedValue = String.Empty; Assert.AreEqual(expectedValue, defaultParameterValue); } [Test] public void CreateWithIntTypeAndNoValue() { var parameter = new Parameter<int>(); const int expectedValue = 0; Assert.AreEqual(expectedValue, parameter.Value); } [Test] public void CreateWithIntTypeAndValue() { const int newParameterValue = 10; var parameter = new Parameter<int> {Value = newParameterValue}; Assert.AreEqual(newParameterValue, parameter.Value); } [Test] public void CreateWithBooleanTypeAndValue() { const bool newParameterValue = true; var parameter = new Parameter<bool> { Value = newParameterValue }; Assert.AreEqual(newParameterValue, parameter.Value); } [Test] public void CreateWithIntTypeAndNoUnit() { var parameter = new Parameter<int>(); Assert.IsNull(parameter.Unit); } [Test] public void CreateWithIntTypeAndDistanceUnit() { const string parameterName = "p1"; var distanceUnit = new Unit("distance", "l"); var parameter = new Parameter<int>(parameterName, distanceUnit); Assert.AreEqual(distanceUnit, parameter.Unit); } [Test] public void HashCodeForMinInt() { var parameter = new Parameter<int>(); parameter.GetHashCode(); var clonedParameter = (Parameter) parameter.Clone(); // stack overflow was thrown } [Test] public void CloneParameter() { var unit = new Unit("test quantity", "TQ") { Id = 3 }; var parameter = new Parameter<int>("original parameter",unit) {ValueType = typeof (double)}; var clonedParameter = (Parameter) parameter.Clone(); Assert.AreEqual(parameter.Name, clonedParameter.Name); Assert.AreEqual(parameter.Unit.Name,clonedParameter.Unit.Name); Assert.AreEqual(parameter.Unit.Symbol, clonedParameter.Unit.Symbol); Assert.AreNotEqual(unit.Id, ((Unit)clonedParameter.Unit).Id); Assert.AreEqual(parameter.ValueType,clonedParameter.ValueType); } [Test] public void CloneDateTimeParameter() { var dateTimeParameter = new Parameter<DateTime>("original parameter"); dateTimeParameter.Value = new DateTime(2000,1,1); var clone = (Parameter<DateTime>)dateTimeParameter.Clone(); Assert.AreEqual(dateTimeParameter.Value,clone.Value); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using static System.Console; namespace First { internal class MyClass { public int Num; public MyClass(int n) { Num = n; } public void Show() { WriteLine($"First namespace with class MyClass where {Num}"); } } } namespace Second { internal class MyClass { public string Txt; public MyClass(string t) { Txt = t; } public void Show() { WriteLine($"Different namespace with class MyClass where \"{Txt}\""); } } } namespace Different { internal class Listing02 { public static void MainListing02() { First.MyClass A = new First.MyClass(13); Second.MyClass B = new Second.MyClass("Hi! I am from another namespase"); A.Show(); B.Show(); } } }
using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace Etherama.DAL.Models.Base { public abstract class DbBaseEntity { [Key, Column("id")] [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long Id { get; set; } [Column("is_enabled"), DefaultValue(true)] public bool IsEnabled { get; set; } [Column("is_deleted")] public bool IsDeleted { get; set; } } }
namespace Thuisbegymmen { public class BetalingStatus { public int orderId { get; set; } public string Iban { get; set; } public string status { get; set; } } }
namespace TwitCreds { public class Settings { public static readonly string CONSUMER_KEY = SettingsProvider.Default.GetValue(nameof(CONSUMER_KEY)); public static readonly string CONSUMER_SECRET = SettingsProvider.Default.GetValue(nameof(CONSUMER_SECRET)); public static readonly string ACCESS_TOKEN = SettingsProvider.Default.GetValue(nameof(ACCESS_TOKEN)); public static readonly string ACCESS_TOKEN_SECRET = SettingsProvider.Default.GetValue(nameof(ACCESS_TOKEN_SECRET)); } }
using System; using System.IO; using System.Linq; using System.Reflection.Emit; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microwave.Entities; using Microwave.Exceptions; using Microwave.IO; namespace MicrowaveTest { [TestClass] public class VerifiersTest { [TestMethod] [ExpectedException(typeof(CustomExceptions))] public void EmptyString() { string text = ""; Verifiers.VerifyName(text); Verifiers.VerifyTimer(text); Verifiers.VerifyChar(text); } [TestMethod] [ExpectedException(typeof(CustomExceptions))] public void OutOfRange() { string minValue = "0"; string maxValue = "121"; Verifiers.VerifyTimer(minValue); Verifiers.VerifyTimer(maxValue); Verifiers.VerifyPower(minValue); Verifiers.VerifyPower(maxValue); } [TestMethod] public void ListContains() { DefaultPrograms.WritePrograms(); DefaultPrograms obj = DefaultPrograms.programsList[0]; string text = obj.ProgramName; Assert.IsTrue(Verifiers.VerifyProgram(text)); } [TestMethod] public void FileNotExist() { string text = "BrokenPath"; try { FileIO.IsFile(text); FileIO.ReadFile(text); } catch (FileNotFoundException) { return; } } [TestMethod] public void FileExist() { string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\teste.txt"; using (StreamWriter sw = File.CreateText(path)) { sw.WriteLine("."); } bool result = FileIO.IsFile(path); File.Delete(path); Assert.IsTrue(result); } } }
using System; namespace ManojTesting { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); Console.WriteLine("Manoj"); Console.WriteLine("Manoj : The Star of GII when Anil is not around"); } } }
using System; using AHAO.TPLMS.Contract; using AHAO.TPLMS.Core; using AHAO.TPLMS.Entitys; using AHAO.TPLMS.Repository; using System.Collections.Generic; using System.Text; using AHAO.TPLMS.Service; using System.Runtime.InteropServices.WindowsRuntime; namespace AHAO.TPLMS.Service { /// <summary> /// 登录服务 /// <para>用户授权服务</para> /// </summary> public class AuthoriseService { private IUserRepository _loginUser; private ModuleService _moduleSvr; private IRoleRepository _roleMgr; private User _user; private List<Module> _modules; //用户可访问的模块 private List<Role> _roles; public AuthoriseService(IUserRepository login, ModuleService msvr, IRoleRepository role) { _loginUser = login; _moduleSvr = msvr; _roleMgr = role; } public List<Module> Modules { get { return _modules; } } public List<Role> Role { get { return _roles; } } public User User { get { return _user; } } public bool Check(string userName, string password) { var _user = _loginUser.FindSingle(u => u.UserId == userName); if (_user == null) { return false; } bool flag = CheckPassword(_user, password); return flag; } public bool CheckPassword(User u, string password) { if (u.Password == password) { return true; } return false; } /// <summary> /// 设置开发者账号 /// </summary> public void SetSysUser() { _user = new User { UserId = "System" }; } public bool IsRole(string roleName) { if (Role.Exists(r => r.Name == roleName)) { return true; } return false; } public void GetUserAccessed(string name) { if (name == "System") { _modules = _moduleSvr.GetModules(1, 1000); } else { _user = _loginUser.FindSingle(u => u.UserId == name); if (_user != null) { _modules = _moduleSvr.LoadForUser(_user.Id); } //用户角色 _roles = _roleMgr.GetRoles(name).ToList(); } } } }
using System; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; using System.Web.Hosting; using System.Web.Http; using PluginDevelopment.DAL; using PluginDevelopment.Helper; using PluginDevelopment.Model; namespace PluginDevelopment.Controllers { public class UploadDataController : ApiController { private static readonly string UploadFolder = ConfigurationHelper.GetAppSetting("FilePath"); //var path = HostingEnvironment.MapPath(UploadFolder);当前项目的地址 /// <summary> /// 根据文件路径获取文件 /// </summary> /// <param name="fileName"></param> /// <returns></returns> public HttpResponseMessage Get(string fileName) { if (string.IsNullOrEmpty(fileName)) { throw new ArgumentNullException(fileName); } if (string.IsNullOrEmpty(UploadFolder)) { throw new ArgumentNullException(UploadFolder); } HttpResponseMessage result; DirectoryInfo directoryInfo = new DirectoryInfo(UploadFolder); FileInfo foundFileInfo = directoryInfo.GetFiles().FirstOrDefault(x => x.Name == fileName); if (foundFileInfo != null) { FileStream fs = new FileStream(foundFileInfo.FullName, FileMode.Open); result = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(fs) }; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = foundFileInfo.Name }; } else { result = new HttpResponseMessage(HttpStatusCode.NotFound); } return result; } /// <summary> /// 获取用户提交的文件上传请求 /// </summary> /// <returns></returns> public Task<IQueryable<FileData>> Post() { try { if (string.IsNullOrEmpty(UploadFolder)) { throw new ArgumentNullException(UploadFolder); } if (!Directory.Exists(UploadFolder)) { Directory.CreateDirectory(UploadFolder); } if (!Request.Content.IsMimeMultipartContent()) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable,"此请求格式不正确")); } var streamProvider = new WithExtensionMultipartFormDataStreamProvider(UploadFolder); var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t => { if (t.IsFaulted || t.IsCanceled) { throw new HttpResponseException(HttpStatusCode.InternalServerError); } var fileInfo = streamProvider.FileData.Select(i => { var info = new FileInfo(i.LocalFileName); return new FileData(info.Name, string.Format("{0}?filename={1}", Request.RequestUri.AbsoluteUri, info.Name), (info.Length / 1024).ToString()); }); return fileInfo.AsQueryable(); }); return task; } catch (Exception ex) { throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.BadRequest, ex.Message)); } } } }
using DTO; using System; using System.Collections.Generic; using System.Linq; using System.Configuration; using System.Text; using System.Threading.Tasks; using System.Web.Helpers; using System.Net.Mail; namespace DAL { public class ContactDB { public static Contact SendContactEmail(int IdContact, String Name, String Email, String Objet, String Message) { //SEND MAIL try { string ToEmail = null; MailMessage mailMessage = new MailMessage(); MailAddress fromAddress = new MailAddress(Email); mailMessage.From = fromAddress; mailMessage.To.Add(ToEmail); String date = DateTime.Now.ToString(); String emailBody = "Bonjour " + "</br>" + "" ; mailMessage.Body = emailBody; mailMessage.IsBodyHtml = true; String objet = IdContact + " - Commande d'extrait public du registre foncier"; mailMessage.Subject = objet; SmtpClient smtpClient = new SmtpClient(); smtpClient.Host = "localhost"; smtpClient.Send(mailMessage); } catch (Exception) { } return null; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Security.Principal; namespace EasyDev.SQMS { public class UserIdentity : GenericIdentity { public UserIdentity(string name) : base(name) { } //public string Password { get; set; } public UserInfo UserInfo { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LeetCode { class Program { //static void Main(string[] args) //{ //int[] nums = { 1, 1, 2 }; //RemoveElement(nums,1); //for (int i = 0; i < nums.Length; i++) //{ // Console.WriteLine(nums[i]); //} //string[] word = { "qwer", "aqw" }; //string[] res = FindWords(word); //Console.WriteLine(res[0]); //printf(ReverseString("qwert")); //} #region easy #region 20171204 //Write a function that takes a string as input and returns the string reversed. public static string ReverseString(string s) { if (s == null) return s; char[] arr = s.ToCharArray(); int len = arr.Length; for (int i = 0; i < arr.Length/2; i++) { char t = arr[i]; arr[i] = arr[len - 1 - i]; arr[len - 1 - i] = t; } return new string(arr); } //Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below. public static string[] FindWords(string[] words) { if (words == null || words.Length == 0) return words; string fir = "qwertyuiop";//1 string sec = "asdfghjkl";//2 string thr = "zxcvbnm";//3 List<string> res = new List<string>(); for (int i = 0; i < words.Length; i++) { char[] arr = words[i].ToLower().ToCharArray(); int flag = 0; for (int j = 0; j < arr.Length; j++) { if (fir.Contains(arr[j])) { if (flag != 0 && flag != 1) { flag = -1; break; } else flag = 1; } else if (sec.Contains(arr[j])) { if (flag != 0 && flag != 2) { flag = -1; break; } else flag = 2; } else if (thr.Contains(arr[j])) { if (flag != 0 && flag != 3) { flag = -1; break; } else flag = 3; } } if (flag != -1 && flag != 0) { res.Add(words[i]); } } return res.ToArray(); } //Given a string, you need to reverse the order of characters in each word within a sentence while still preserving whitespace and initial word order. public static string ReverseWords(string s) { if (s == null) return s; string[] strArr = s.Split(' '); StringBuilder sb = new StringBuilder(); for (int i = 0; i < strArr.Length; i++) { for (int j = strArr[i].Length - 1; j >= 0; j--) { sb.Append(strArr[i][j]); } if (i != strArr.Length - 1) { sb.Append(' '); } } return sb.ToString(); } // 求一个数的补数(未做) //Given a positive integer, output its complement number. The complement strategy is to flip the bits of its binary representation. public static int FindComplement(int num) { int res = 0; return res; } //Implement strStr(). //Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack. public static int StrStr(string haystack, string needle) { if (haystack == null) return -1; return haystack.IndexOf(needle); } //Given an array and a value, remove all instances of that value in-place and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. //The order of elements can be changed. It doesn't matter what you leave beyond the new length. public static int RemoveElement(int[] nums, int val) { int len = nums.Length; int count = 0; for (int i = 0; i < nums.Length; i++) { if (nums[i] != val) { nums[count++] = nums[i]; } } return count; } //Given a sorted array, remove the duplicates in-place such that each element appear only once and return the new length. //Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. public static int removeDuplicates(int[] A) { int len = A.Length; if (len == 0) return 0; int count = 1; for (int i = 1; i < len; i++) { if (A[i] == A[i - 1]) { continue; } else { A[count] = A[i]; count++; } } return count; } #endregion #region 20171203 //Given an array of 2n integers, your task is to group these integers into n pairs of integer, say(a1, b1), (a2, b2), ..., (an, bn) which makes sum of min(ai, bi) for all i from 1 to n as large as possible. public static int ArrayPairSum(int[] nums) { if (nums == null || nums.Length < 0 || nums.Length % 2 != 0) return 0; int sum = 0; Array.Sort(nums); for (int i = 0; i < nums.Length;) { sum += nums[i]; i += 2; } return sum; } //合并两个二叉树的相应节点 //Given two binary trees and imagine that when you put one of them to cover the other, some nodes of the two trees are overlapped while the others are not. public static TreeNode MergeTrees(TreeNode t1, TreeNode t2) { if (t1 == null && t2 == null) return null; if (t1 == null && t2 != null) return t2; if (t1 != null && t2 == null) return t1; t1.val += t2.val; t1.left = MergeTrees(t1.left, t2.left); t1.right = MergeTrees(t1.right, t2.right); return t1; } public class TreeNode { public int val; public TreeNode left; public TreeNode right; public TreeNode(int x) { val = x; } } //Initially, there is a Robot at position(0, 0). Given a sequence of its moves, judge if this robot makes a circle, which means it moves back to the original place. //The move sequence is represented by a string. And each move is represent by a character. The valid robot moves are R (Right), L(Left), U(Up) and D(down). The output should be true or false representing whether the robot makes a circle. public static bool JudgeCircle(string moves) { int up = 0, left = 0; foreach (char c in moves.ToCharArray()) { if (c == 'U') { up++; } else if (c == 'D') { up--; } else if (c == 'L') { left++; } else if (c == 'R') { left--; } } if (up != 0 || left != 0) return false; return true; } #endregion #region 20171202 //A self-dividing number is a number that is divisible by every digit it contains. //For example, 128 is a self-dividing number because 128 % 1 == 0, 128 % 2 == 0, and 128 % 8 == 0. //Also, a self-dividing number is not allowed to contain the digit zero. //Given a lower and upper number bound, output a list of every possible self dividing number, including the bounds if possible. public static IList<int> SelfDividingNumbers(int left, int right) { IList<int> res = new List<int>(); if (left > right) return res; for (int i = left; i <= right; i++) { int t = i % 10; int d = i / 10; bool f = true; do { if (t == 0 || i % t != 0) { f = false; break; } t = d % 10; d = d / 10; } while (t != 0 || d != 0); if (f) res.Add(i); } return res; } public static IList<int> SelfDividingNumbers2(int left, int right) { IList<int> res = new List<int>(); for (int i = left; i < right; i++) { int j = i; for (; j > 0; j /= 0) { if ((j % 10) == 0 || (i % (j % 10) != 0)) { break; } } if (j == 0) res.Add(i); } return res; } //The Hamming distance between two integers is the number of positions at which the corresponding bits are different. //Given two integers x and y, calculate the Hamming distance. public static int HammingDistance(int x, int y) { int res = 0, exc = x ^ y;//异或 for (int i = 0; i < 32; i++) { res += (exc >> i) & 1; } return res; } //合并链表 //Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. public static ListNode MergeTwoLists(ListNode l1, ListNode l2) { if (l1 == null) return l2; if (l2 == null) return l1; ListNode merge = null; if (l1.val < l2.val) { merge = l1; merge.next = MergeTwoLists(l1.next, l2); } else { merge = l2; merge.next = MergeTwoLists(l1, l2.next); } return merge; } public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } } #endregion #region 20171201 //Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. //The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. public static bool IsValid(string s) { if (s == null || s == "") return false; Dictionary<char, char> dic = new Dictionary<char, char>(); dic.Add('(', ')'); dic.Add('{', '}'); dic.Add('[', ']'); Stack<char> stack = new Stack<char>(); stack.Push(s[0]); for (int i = 1; i < s.Length; i ++) { if (stack.Count == 0) { stack.Push(s[i]); } else{ if (dic.ContainsKey(stack.Peek()) && s[i] == dic[stack.Peek()]) { stack.Pop(); } else { stack.Push(s[i]); } } } if (stack.Count == 0) { return true; } return false; } public static bool IsValid2(string s) { Stack<char> stack = new Stack<char>(); foreach(char c in s.ToCharArray()) { if (c == '(') stack.Push(')'); else if (c == '{') stack.Push('}'); else if (c == '[') stack.Push(']'); else if (stack.Count == 0 || stack.Pop() != c) return false; } if (stack.Count == 0) return true; return false; } //Write a function to find the longest common prefix string amongst an array of strings. //最长公共前缀 //假设第一个字符串是公共最长前缀,第二个和第二个比较,从第0个字符开始比较,取出相同的字符返回 //依次比较 public static string LongestCommonPrefix(string[] strs) { if (strs == null || strs.Length <= 0) { return ""; } string res = strs[0]; for (int i = 1; i < strs.Length; i++) { if (res.Length < 0) break; res = getleast(res, strs[i]); } return res; } public static string getleast(string res, string target) { StringBuilder sb = new StringBuilder(); int loop = res.Length > target.Length ? target.Length : res.Length; for (int i = 0; i < loop; i++) { if (res[i] == target[i]) sb.Append(res[i]); else break; } return sb.ToString(); } #endregion #region 20171130 //Given a roman numeral, convert it to an integer. //Input is guaranteed to be within the range from 1 to 3999. public static int RomanToInt(string s) { //单字符 int[] v1 = new int[] { 1000, 500, 100, 50, 10, 5, 1 }; String[] k1 = new String[] { "M", "D", "C", "L", "X", "V", "I" }; //双字符数组 int[] v2 = new int[] { 900, 400, 90, 40, 9, 4 }; String[] k2 = new String[] { "CM", "CD", "XC", "XL", "IX", "IV" }; int res = 0; bool v2f = false;//判断双字符有没有匹配成功 while (s.Length > 0) { if (s.Length > 1) { string str1 = s.Substring(0, 2); for (int i = 0; i < k2.Length; i++) { if (str1 == k2[i]) { res += v2[i]; s = s.Substring(2); v2f = true; break; } } } if (!v2f) { string str2 = s.Substring(0, 1); for (int i = 0; i < k1.Length; i++) { if (str2 == k1[i]) { res += v1[i]; s = s.Substring(1); break; } } } v2f = false; } return res; } /// <summary> /// Determine whether an integer is a palindrome. Do this without extra space. /// 回文 /// </summary> public static bool IsPalindrome(int x) { if (x < 0) return false; int res = 0; int temp = x; while (temp != 0) { int last = temp % 10; int newRes = res * 10 + last; if ((newRes - last) / 10 != res) return false; res = newRes; temp /= 10; } if (res == x) return true; return false; } /// <summary> /// 54321 - > 12345 /// </summary> public static int Reverse(int x) { int res = 0; while (x != 0) { int last = x % 10; int newRes = res * 10 + last; //验证数据 if ((newRes - last) / 10 != res) return 0; res = newRes; x = x / 10; } return res; } //Given an array of integers, return indices of the two numbers such that they add up to a specific target. //You may assume that each input would have exactly one solution, and you may not use the same element twice. public static int[] TwoSum(int[] nums, int target) { if (nums == null) return nums; int[] res = new int[2]; for (int i = 0; i < nums.Length; i++) { for (int j = i + 1; j < nums.Length; j++) { if(nums[i] + nums[j] == target) { res[0] = i; res[1] = j; } } } return res; } #endregion #region tools public static void printf(int v) { Console.WriteLine(v); } public static void printf(string v) { Console.WriteLine(v); } #endregion #endregion } }
using System; using System.Linq; using System.Xml.Schema; using System.Xml.Linq; using System.Collections.Generic; using SaritasaShortestPath.ShortestPathSolver; using SaritasaShortestPath.Dijkstra; using System.Xml; using System.IO; namespace SaritasaShortestPath { public class Program { static Program() { // Make this program emit english error messages only. System.Threading.Thread.CurrentThread.CurrentCulture = System.Threading.Thread.CurrentThread.CurrentUICulture = System.Globalization.CultureInfo.InvariantCulture; } private static IEnumerable<string> FindShortestPathFor(ParseResult parseResult) { return DijkstraAlgorithm.Run( parseResult.Start, parseResult.Finish, parseResult.AllButCrashedNodes ) .Cast<Node>().Select(n => n.GetId()); } /* Public */ public static IEnumerable<string> FindShortestPathForXmlText(string inputXmlText) { var parseResult = XmlGraphParser.ParseGraphDescriptionFromXmlText(inputXmlText); return FindShortestPathFor(parseResult); } public static IEnumerable<string> FindShortestPathForXmlFile(string inputXmlPath) { var parseResult = XmlGraphParser.ParseGraphDescriptionFromXmlFile(inputXmlPath); return FindShortestPathFor(parseResult); } static int Main(string[] args) { if (args.Length != 1) { System.Console.WriteLine("Usage: " + System.Diagnostics.Process.GetCurrentProcess().ProcessName + " <path to road_system.xml file>"); return 1; } try { string inputXmlPath = args[0]; var idsPath = FindShortestPathForXmlFile(inputXmlPath); var result = String.Join(" ->\r\n", idsPath); if (result.Length == 0) System.Console.WriteLine("No route found."); else System.Console.WriteLine(result); return 0; } catch (ClientSafeException e) { System.Console.WriteLine(e.Message); } catch (Exception) { System.Console.WriteLine("A mysterious error happened in some deep inner workings of this program. Sorry."); } return 1; } } }
namespace RockPaperScissors.Enums { /// <summary> /// The playing modes. /// </summary> public enum Mode { /// <summary> /// Two human players. /// </summary> TwoHuman = 1, /// <summary> /// A human agains a computer. /// </summary> AgainstComputer = 2, /// <summary> /// A human againts a computer which always selects a random option. /// </summary> AgainstComputerRandom = 3, } }
using Newtonsoft.Json; namespace gView.Interoperability.GeoServices.Rest.Json.Renderers.SimpleRenderers { public class SimpleLineSymbol { public SimpleLineSymbol() { this.Type = "esriSLS"; } [JsonProperty("type")] public string Type { get; set; } [JsonProperty("style")] public string Style { get; set; } [JsonProperty("color")] public int[] Color { get; set; } [JsonProperty("width")] public float Width { get; set; } } /* Simple Line Symbol Simple line symbols can be used to symbolize polyline geometries or outlines for polygon fills. The type property for simple line symbols is esriSLS. * JSON Syntax { "type" : "esriSLS", "style" : "< esriSLSDash | esriSLSDashDot | esriSLSDashDotDot | esriSLSDot | esriSLSNull | esriSLSSolid >", "color" : <color>, "width" : <width> } JSON Example { "type": "esriSLS", "style": "esriSLSDot", "color": [115,76,0,255], "width": 1 } */ }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVCClient.Models { public class DepartmentVM { public int Deptid { get; set; } public string Dname { get; set; } public string Location { get; set; } } }
using System; using System.Collections; using System.Linq; using System.Text; using System.Threading.Tasks; namespace EnglishDictonary1 { class Program { static void Main(string[] args) { ArrayList word = new ArrayList() { "Boat", "house", "cat", "river", "cupboard" }; foreach(string item in word) { Console.WriteLine(item + "s"); } Console.WriteLine(); //var resultlist = word.ToList(); word.RemoveAt(1); word.Insert(1,"Home"); Console.WriteLine("2nd Element " + word[1]); Console.WriteLine(); word.Add("Shruti"); Console.WriteLine("length of list is =" + word.Count); Console.WriteLine(); var seven = word.FindAll(t => t.Length == 7); Console.WriteLine("The words with 7 characters are:"); foreach (string v in seven) Console.WriteLine(v); Console.WriteLine("3rd possition element is = "+ word[2]); Console.WriteLine(); word.Sort(); Console.WriteLine("After Sort:"); foreach (string item in word) { Console.WriteLine(item); } Console.WriteLine(); word.Reverse(); Console.WriteLine("After Reverse:"); foreach (string item in word) { Console.WriteLine(item); } Console.WriteLine(); Console.ReadKey(); } } }
using Serilog; using System; using System.Threading; using System.Threading.Tasks; using Telegram.Bot; using Telegram.Bot.Polling; using Telegram.Bot.Types; using TelegramFootballBot.Core.Data; using TelegramFootballBot.Core.Exceptions; using TelegramFootballBot.Core.Helpers; using TelegramFootballBot.Core.Models; using TelegramFootballBot.Core.Models.CallbackQueries; namespace TelegramFootballBot.Core.Services { public class UpdateHandler : IUpdateHandler { private readonly CommandFactory _commandFactory; private readonly IMessageService _messageService; private readonly IPlayerRepository _playerRepository; private readonly ISheetService _sheetService; private readonly ILogger _logger; public UpdateHandler(CommandFactory commandFactory, IMessageService messageService, IPlayerRepository playerRepository, ISheetService sheetService, ILogger logger) { _commandFactory = commandFactory; _messageService = messageService; _playerRepository = playerRepository; _sheetService = sheetService; _logger = logger; } public async Task HandleUpdateAsync(ITelegramBotClient _, Update update, CancellationToken cancellationToken) { var handler = update switch { { Message: { } message } => BotOnMessageReceived(message), { CallbackQuery: { } callbackQuery } => BotOnCallbackQueryReceived(callbackQuery), _ => UnknownUpdateHandlerAsync(update) }; await handler; } private async Task BotOnMessageReceived(Message message) { var command = _commandFactory.Create(message); if (command == null) return; try { await command.ExecuteAsync(message); var playerName = await GetPlayerNameAsync(message.From.Id); _logger.Information($"Command {message.Text} processed for user {playerName}"); } catch (Exception ex) { var playerName = await GetPlayerNameAsync(message.From.Id); _logger.Error(ex, $"Error on processing {message.Text} command for user {playerName}"); await _messageService.SendMessageToBotOwnerAsync($"Ошибка у пользователя {playerName}: {ex.Message}"); await _messageService.SendErrorMessageToUserAsync(message.Chat.Id, playerName); } } private async Task BotOnCallbackQueryReceived(CallbackQuery callbackQuery) { try { var callbackData = callbackQuery.Data; if (string.IsNullOrEmpty(callbackData)) return; if (Callback.GetCallbackName(callbackData) == PlayerSetCallback.Name) await DetermineIfPlayerIsReadyToPlayAsync(callbackQuery); _logger.Information($"Processed callback: {callbackQuery.Data}"); } catch (Exception ex) { await ProcessCallbackError(callbackQuery, ex); } } private Task UnknownUpdateHandlerAsync(Update update) { _logger.Information("Unknown update type: {UpdateType}", update.Type); return Task.CompletedTask; } private async Task<string> GetPlayerNameAsync(long userId) { try { return (await _playerRepository.GetAsync(userId)).Name; } catch (UserNotFoundException) { return string.Empty; } } private async Task DetermineIfPlayerIsReadyToPlayAsync(CallbackQuery callbackQuery) { var playerSetCallback = new PlayerSetCallback(callbackQuery.Data); await ClearInlineKeyboardAsync(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); try { await _messageService.DeleteMessageAsync(callbackQuery.Message.Chat.Id, callbackQuery.Message.MessageId); } catch (Exception ex) { _logger.Error(ex, $"Error on deleting message"); } if (IsButtonPressedAfterGame(playerSetCallback.GameDate)) { _logger.Information($"Button pressed after game: now - {DateTime.UtcNow}, game date - {playerSetCallback.GameDate.Date}"); return; } var player = await _playerRepository.GetAsync(callbackQuery.From.Id); await _sheetService.SetApproveCellAsync(player.Name, GetApproveCellValue(playerSetCallback.UserAnswer)); var approvedPlayersMessage = await _sheetService.BuildApprovedPlayersMessageAsync(); player.IsGoingToPlay = playerSetCallback.UserAnswer == Constants.YES_ANSWER; player.ApprovedPlayersMessageId = await SendApprovedPlayersMessageAsync(approvedPlayersMessage, callbackQuery.Message.Chat.Id, player); player.ApprovedPlayersMessage = approvedPlayersMessage; await _playerRepository.UpdateAsync(player); } /// <summary> /// Sends an approved players message if it wasn't sent yet. Otherwise edits it. /// </summary> /// <param name="chatId">Player chat id</param> /// <param name="player">Player</param> /// <returns>Sent message id</returns> private async Task<int> SendApprovedPlayersMessageAsync(string message, ChatId chatId, Player player) { if (player.ApprovedPlayersMessageId != 0) await _messageService.DeleteMessageAsync(chatId, player.ApprovedPlayersMessageId); var messageResponse = await _messageService.SendMessageAsync(chatId, message); return messageResponse.MessageId; } private static string GetApproveCellValue(string userAnswer) { return userAnswer switch { Constants.YES_ANSWER => "1", Constants.NO_ANSWER => "0", Constants.MAYBE_ANSWER => "0.5", _ => throw new ArgumentOutOfRangeException($"userAnswer: {userAnswer}"), }; } private static bool IsButtonPressedAfterGame(DateTime gameDate) { return gameDate.Date < DateTime.Now.Date; } private async Task ClearInlineKeyboardAsync(ChatId chatId, int messageId) { try { await _messageService.ClearReplyMarkupAsync(chatId, messageId); } catch (Exception ex) { _logger.Error(ex, $"Error on clearing inline keyboard"); } } private async Task ProcessCallbackError(CallbackQuery callbackQuery, Exception ex) { var messageForUser = string.Empty; var messageForBotOwner = string.Empty; var userId = callbackQuery.From.Id; var player = ex is UserNotFoundException ? null : await _playerRepository.GetAsync(userId); if (ex is UserNotFoundException) { _logger.Error($"User with id {userId} not found. Name: {callbackQuery.From.FirstName} {callbackQuery.From.LastName}"); messageForUser = "Вы не зарегистрированы. Введите команду /reg Фамилия Имя."; messageForBotOwner = $"Пользователь {callbackQuery.From.FirstName} {callbackQuery.From.LastName} не найден"; } if (ex is TotalsRowNotFoundExeption) { _logger.Error("\"Всего\" row not found in excel-file"); messageForUser = "Не найдена строка \"Всего\" в excel-файле."; messageForBotOwner = $"Не найдена строка \"Всего\" в excel-файле. Пользователь - {player.Name}"; } if (ex is OperationCanceledException) { _logger.Error($"Operation {callbackQuery.Data} cancelled for user {player.Name}."); messageForUser = "Не удалось обработать запрос."; messageForBotOwner = $"Операция обработки ответа отменена для пользователя {player.Name}"; } if (ex is ArgumentOutOfRangeException exception) { _logger.Error($"Unexpected response for user {player.Name}: {exception.ParamName}"); messageForUser = "Непредвиденный вариант ответа."; messageForBotOwner = $"Непредвиденный вариант ответа для пользователя {player.Name}"; } if (messageForUser == string.Empty) { _logger.Error(ex, "Unexpected error"); messageForUser = "Непредвиденная ошибка."; messageForBotOwner = $"Ошибка у пользователя {player.Name}: {ex.Message}"; } await NotifyAboutError(callbackQuery.Message.Chat.Id, messageForUser, messageForBotOwner); } private async Task NotifyAboutError(ChatId chatId, string messageForUser, string messageForBotOwner) { await _messageService.SendMessageAsync(chatId, messageForUser); if (AppSettings.NotifyOwner) await _messageService.SendMessageToBotOwnerAsync(messageForBotOwner); } public Task HandlePollingErrorAsync(ITelegramBotClient botClient, Exception exception, CancellationToken cancellationToken) { _logger.Error("Polling failed with exception: {Exception}", exception); return Task.CompletedTask; } } }
 using System.ComponentModel; namespace proj12.Model { public interface ISimulatorModel : INotifyPropertyChanged { string Time { set; get; } void StartServer(); double Indicated_heading_deg { set; get; } double Gps_indicated_vertical_speed { set; get; } double Gps_indicated_ground_speed_kt { set; get; } double Airspeed_indicator_indicated_speed_kt { set; get; } double Gps_indicated_altitude_ft { set; get; } double Attitude_indicator_internal_roll_deg { set; get; } double Attitude_indicator_internal_pitch_deg { set; get; } double Altimeter_indicated_altitude_ft { set; get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MessageChannel : MonoBehaviour { public GameObject messageArea; public GameObject messageTemplate; public GameObject lastMessage; public float padY=10; public delegate void MessageEvent(Message[] messages); public List<MessageEvent> onRecievedMessage=new List<MessageEvent>(); public List<MessageEvent> onSentMessage=new List<MessageEvent>(); public delegate bool MessageFilter(Message message); public List<MessageFilter> recieveFilter=new List<MessageFilter>(); public List<MessageFilter> sendFilter=new List<MessageFilter>(); protected Queue<Message> recievedQueue=new Queue<Message>(); protected Queue<Message> sendQueue=new Queue<Message>(); public enum Type{ Plain, System }; public class Message{ public string text; public Type type=Type.Plain; } // Start is called before the first frame update void Start() { if(messageArea==null){ messageArea=gameObject; } messageTemplate.SetActive(false); } // Update is called once per frame protected virtual void Update() { if(recievedQueue.Count>0){ NotifyRecieve(recievedQueue.ToArray()); } if(sendQueue.Count>0){ NotifySend(sendQueue.ToArray()); } while(recievedQueue.Count>0){ AddMessage(recievedQueue.Dequeue()); } } protected void NotifySend(Message[] messages){ foreach(MessageEvent listener in onSentMessage){ listener(messages); } } protected void NotifyRecieve(Message[] messages){ foreach(MessageEvent listener in onRecievedMessage){ listener(messages); } } protected void AddMessage(string text){ Message m = new Message(); m.text=text; AddMessage(m); } protected void AddMessage(Message text){ DisplayMessage(text); } /* * push message into the queue and handles it like a received message * ie: plays audio and other new message notifications */ public void QueueRecievedMessage(Message message){ foreach(MessageFilter filter in recieveFilter){ if(!filter(message)){ Debug.Log("Filter out receive"); return; } } recievedQueue.Enqueue(message); } public void SendText(string text){ MessageChannel.Message message=new MessageChannel.Message(); message.text=text; foreach(MessageFilter filter in sendFilter){ if(!filter(message)){ Debug.Log("Filter out send"); return; } } sendQueue.Enqueue(message); // if(client!=null&&client.authenticated){ // client.Send(channel, eventType, EncodeMessage(text)); // NotifySend(new MessageChannel.Message[]{m}); // } } /* * display a message */ public void DisplayMessage(Message text){ GameObject messageObject=(GameObject)Instantiate(messageTemplate, gameObject.transform); ChatMessage message=messageObject.GetComponent<ChatMessage>(); if(message==null){ message=messageObject.AddComponent<ChatMessage>(); } message.SetText(text); if(lastMessage!=null){ SimpleStack.StackVertical(lastMessage, messageObject, padY); // RectTransform rect=messageObject.GetComponent<RectTransform>(); // RectTransform lastRect=lastMessage.GetComponent<RectTransform>(); // Vector2 targetPosition=rect.anchoredPosition; // targetPosition.y=lastRect.anchoredPosition.y-(lastRect.rect.height+padY); // rect.anchoredPosition=targetPosition; } lastMessage=messageObject; messageObject.SetActive(true); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp6 { public abstract class ColdDrink : IItem { public abstract string nombre(); public IPacking packing() { return new Bottle(); } public abstract float valor(); } }
using Microsoft.AspNetCore.Razor.TagHelpers; using System.Threading.Tasks; namespace Wee.UI.Core.TagHelpers { [HtmlTargetElement("div", Attributes = "bootstrap-popover")] [HtmlTargetElement("img", Attributes = "bootstrap-popover")] [HtmlTargetElement("span", Attributes = "bootstrap-popover")] [HtmlTargetElement("nav", Attributes = "bootstrap-popover")] [HtmlTargetElement("button", Attributes = "bootstrap-popover")] [HtmlTargetElement("a", Attributes = "bootstrap-popover")] [HtmlTargetElement("p", Attributes = "bootstrap-popover")] [HtmlTargetElement("h1", Attributes = "bootstrap-popover")] [HtmlTargetElement("h2", Attributes = "bootstrap-popover")] [HtmlTargetElement("h3", Attributes = "bootstrap-popover")] [HtmlTargetElement("h4", Attributes = "bootstrap-popover")] [HtmlTargetElement("h5", Attributes = "bootstrap-popover")] [HtmlTargetElement("h6", Attributes = "bootstrap-popover")] [HtmlTargetElement("bootstrap-button", Attributes = "bootstrap-popover")] public class PopoverTagHelper : TagHelper { [HtmlAttributeName("bootstrap-popover")] public string PopoverTitle { get; set; } [HtmlAttributeName("id")] public string PopoverId { get; set; } [HtmlAttributeName("static")] public bool PopoverStatic { get; set; } [HtmlAttributeName("placement")] public string PopoverPlacement { get; set; } [HtmlAttributeName("title")] public string PopoverTitle1 { get; set; } [HtmlAttributeName("content")] public string PopoverContent { get; set; } public PopoverTagHelper() { } public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output) { (await output.GetChildContentAsync()).GetContent(); if (!this.PopoverStatic) { if (this.PopoverTitle != "") output.PostElement.AppendHtml("<script>$(function() {$('#" + this.PopoverId + "').popover();});</script>"); output.Attributes.SetAttribute("data-toggle", (object) "popover"); output.Attributes.SetAttribute("title", (object) this.PopoverTitle1); output.Attributes.SetAttribute("id", (object) this.PopoverId); } else { output.Content.AppendHtml("<div class='arrow'></div> <h3 class='popover-title'>" + this.PopoverTitle1 + "</h3><div class='popover-content'><p>" + this.PopoverContent + "</p></div>"); output.Attributes.SetAttribute("class", (object) ("popover static " + this.PopoverPlacement)); output.Attributes.SetAttribute("id", (object) this.PopoverId); } // ISSUE: reference to a compiler-generated method } } }
using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace ReducedGrinding.Items { public class Angler_Potion : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Angler Potion"); Tooltip.SetDefault("One botle of this will make the Angler want to give you a new fishing quest right away."); } public override void SetDefaults() { item.width = 20; item.height = 30; item.maxStack = 30; item.rare = 2; item.useAnimation = 45; item.useTime = 45; item.useStyle = 4; item.value = 200; item.UseSound = SoundID.Item3; item.consumable = true; } public override bool CanUseItem(Player player) { return true; } public override bool UseItem(Player player) { Main.NewText("The angler has a new quest for you.", 0, 128, 255); Main.AnglerQuestSwap(); if (Main.netMode == NetmodeID.Server) NetMessage.SendData(7); return true; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(ItemID.BottledWater, 1); recipe.AddIngredient(ItemID.SpecularFish); recipe.AddIngredient(ItemID.Moonglow); recipe.AddTile(TileID.Bottles); recipe.SetResult(this); recipe.AddRecipe(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PauseMenu : MonoBehaviour { public GameObject pauseMenuUI; // Update is called once per frame void Update() { Debug.Log(Time.timeScale); } public void Pause() { pauseMenuUI.SetActive(true); Time.timeScale = 0; } public void Resume() { pauseMenuUI.SetActive(false); Time.timeScale = 1; } }
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class GameController : MonoBehaviour { public GameObject note; public Transform noteSpawn; public Text coordinates; // Start is called before the first frame update void Start() { coordinates.text = "Touch Position : None"; } // Update is called once per frame void Update() { if(Time.frameCount % 45 == 0) { Debug.Log("New note created"); NewNote(10); //Destroy (newNote, 5f); } // if(Input.touchCount > 0) // { // Touch touch = Input.GetTouch(0); // coordinates.text = "Touch Position : " + touch.position.x + " " + touch.position.y; // } } void NewNote(float speed) //normal speed is 6 { GameObject newNote = (GameObject)Instantiate(note, note.transform.position, note.transform.rotation); newNote.GetComponent<Rigidbody>().velocity = newNote.transform.forward * -speed; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Linq; using Microsoft.ML.Data; namespace Microsoft.ML.AutoML { /// <summary> /// interface for all trial runners. /// </summary> public interface ITrialRunner { TrialResult Run(TrialSettings settings); } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ControlLibrary { public partial class ControlTreeView : UserControl { Dictionary<string, TreeNode> types; public ControlTreeView() { InitializeComponent(); types = new Dictionary<string, TreeNode>(); } public void SetList<T>(List<T> mebelList, Func<T, object> getType, Func<T, object> getName) { foreach (T organization in mebelList) { string cat = getType(organization).ToString(); if (!types.Keys.Contains(cat)) { int index = treeView.Nodes.Add(new TreeNode(cat)); types.Add(cat, treeView.Nodes[index]); } types[cat].Nodes.Add(new TreeNode(getName(organization).ToString())); } treeView.ExpandAll(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.ComponentModel.DataAnnotations; using System.Linq.Expressions; using InventoryManager.Data.Models; namespace InventoryManager.Service.ViewModels { public class RegisterClothesViewModel { [Required] [Display(Name = "Id")] public int Id { get; set; } [Required] [Display(Name = "Name")] public string Name { get; set; } [Required] [Display(Name = "Type")] public string Type { get; set; } [Required] [Display(Name = "Quantity")] public int Quantity { get; set; } [Required] [Display(Name = "Size")] public string Size { get; set; } [Required] [Display(Name = "Price")] public decimal SinglePrice { get; set; } [Required] [Display(Name = "Picture")] public string PictureUrl { get; set; } [Required] [Display(Name = "Description")] public string Description { get; set; } public static Expression<Func<Clothes, RegisterClothesViewModel>> Create { get { return u => new RegisterClothesViewModel() { Id=u.Id, Name = u.Name, Type = u.Type, Quantity=u.Quantity, Size=u.Size, SinglePrice=u.SinglePrice, PictureUrl=u.PictureUrl, Description=u.Description }; } } } }
using FBS.Domain.Booking; using FBS.Domain.Booking.Aggregates; using FBS.Domain.Booking.Queries; using FBS.Domain.Core; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; namespace FBS.Booking.Read.API { public class FlightQueryHandler : IQueryHandler<GetFlightByIdQuery, FlightAggregate>, IQueryHandler<GetAllFlightsQuery, IEnumerable<FlightAggregate>> { private readonly IAggregateContext<FlightAggregate> flightContext; public FlightQueryHandler(IAggregateContext<FlightAggregate> flightContext) { this.flightContext = flightContext; } public async Task<FlightAggregate> Handle(GetFlightByIdQuery request, CancellationToken cancellationToken) { return await flightContext.GetAggregateByIdAsync(request.Id); } public async Task<IEnumerable<FlightAggregate>> Handle(GetAllFlightsQuery request, CancellationToken cancellationToken) { return await flightContext.GetAllAggregates(); } } }