text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace online_knjizara.ViewModels { public class KorisnikPrikazVM { public int ID { get; set; } public string Ime { get; set; } public string Prezime { get; set; } public string Adresa { get; set; } public string Email { get; set; } public string Telefon { get; set; } public string Grad { get; set; } public DateTime DatumRodjenja { get; set; } public string KorisnickoIme { get; set; } } }
// -------------------------------------------------------------------------------------------------------------- // <copyright file="LoginRequestParam.cs" company="Tiny开源团队"> // Copyright (c) 2017-2018 Tiny. All rights reserved. // </copyright> // <site>http://www.lxking.cn</site> // <last-editor>ArcherTrister</last-editor> // <last-date>2019/3/13 22:31:30</last-date> // -------------------------------------------------------------------------------------------------------------- namespace Tiny.IdentityService.Models.Account { /// <summary> /// 登录请求参数 /// </summary> public class LoginRequestParam { /// <summary> /// 用户名 /// </summary> public string UserName { get; set; } /// <summary> /// 密码 /// </summary> public string Password { get; set; } /// <summary> /// 终端ID(1、lexun.tiny.mvc 2、lexun.tiny.mobile) /// </summary> public string ClientId { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using MySql.Data.MySqlClient; using System.Reflection; namespace scaner { public class Info { StatusStrip status; ToolStripStatusLabel label; ToolStripProgressBar progress; public Info(StatusStrip status, ToolStripStatusLabel label, ToolStripProgressBar progress) { this.status = status; this.label = label; this.progress = progress; } public void SetLabel(string text) { DateTime time = DateTime.Now; label.Text = "" + text + ": (" + time + ")"; } public void SetProgress(int i) { this.progress.Value = i; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterFactory : MonoBehaviour { public enum CharactersType { Player, Enemy1, Enemy2, Enemy3 } [SerializeField] public CharacterController enemy1Prefab; [SerializeField] public CharacterController enemy2Prefab; [SerializeField] public CharacterController enemy3Prefab; [SerializeField] private CharacterController HumanPlayerPrefab; public CharacterController CreateCharacter(CharactersType characterType) { switch (characterType) { case CharactersType.Player: return Instantiate(HumanPlayerPrefab); case CharactersType.Enemy1: return Instantiate(enemy1Prefab); case CharactersType.Enemy2: return Instantiate(enemy2Prefab); case CharactersType.Enemy3: return Instantiate(enemy3Prefab); default: return null; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WDB { public partial class Form1 : Form { SqlConnection sqlConnection; public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { string rolest; //int k=2; // Hide(); Form2 f2 = new Form2(); Form3 f3 = new Form3(); string startupPath = System.IO.Path.GetFullPath(".\\"); string NameDir = startupPath.Substring(0, startupPath.Length - 10); //MessageBox.Show(NameDir); //string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Desktop\DB\WDB\WDB\Database1.mdf;Integrated Security=True;User Instance=True"; string connection = @"Data Source=.\SQLEXPRESS;AttachDbFilename="+NameDir+"Database1.mdf;Integrated Security=True;User Instance=True"; sqlConnection = new SqlConnection(connection); sqlConnection.Open(); M: if (label3.Visible) label3.Visible = false; if (!string.IsNullOrEmpty(textBox1.Text) && !string.IsNullOrWhiteSpace(textBox1.Text) && !string.IsNullOrEmpty(textBox2.Text) && !string.IsNullOrWhiteSpace(textBox2.Text)) { SqlCommand command = new SqlCommand("SELECT [User].[role] FROM [Autho] JOIN [User] ON [Autho].[user_id] = [User].[id] WHERE [User].[id] = ( Select [Autho].[user_id] FROM [Autho] WHERE [Autho].[login]=@login AND [Autho].[password]=@password) ", sqlConnection); command.Parameters.AddWithValue("login", textBox1.Text); command.Parameters.AddWithValue("password", textBox2.Text); command.ExecuteNonQuery(); rolest = Convert.ToString(command.ExecuteScalar()); textBox2.Text = ""; if (rolest == "student") f2.ShowDialog(); if (rolest == "teacher") f3.ShowDialog(); if (rolest == "") goto M; if (sqlConnection != null && sqlConnection.State != ConnectionState.Closed) sqlConnection.Close(); Hide(); Close(); } else { label3.Visible = true; label3.Text = "Введен неверный логин или пароль"; } } private void Form1_Load(object sender, EventArgs e) { } private void Form1_FormClosing(object sender, FormClosingEventArgs e) { if (sqlConnection != null && sqlConnection.State != ConnectionState.Closed) sqlConnection.Close(); } } }
using Domen; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SystemOperations.OblikLekaSO { public class FindObliciSO : SystemOperationBase { protected override object ExecuteSO(IEntity entity) { OblikLeka oblikLeka = (OblikLeka)entity; return broker.Select(oblikLeka).OfType<OblikLeka>().ToList(); } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerAttack : MonoBehaviour { Animator anim; bool canAttack = true; public float attackDelay = .5f; // Start is called before the first frame update void Start() { anim = GetComponentInChildren<Animator>(); } // Update is called once per frame void Update() { if (Input.GetKeyDown(KeyCode.E) && canAttack){ { anim.SetTrigger("Attack"); GetComponentInChildren<AudioSource>().Play(); StartCoroutine(ToggleAttack()); } } } private IEnumerator ToggleAttack() { canAttack = false; yield return new WaitForSeconds(attackDelay); canAttack = true; } }
namespace Triton.Game.Mapping { using ns26; using System; using Triton.Game; using Triton.Game.Mono; [Attribute38("FatigueSpellController")] public class FatigueSpellController : SpellController { public FatigueSpellController(IntPtr address) : this(address, "FatigueSpellController") { } public FatigueSpellController(IntPtr address, string className) : base(address, className) { } public bool AddPowerSourceAndTargets(PowerTaskList taskList) { object[] objArray1 = new object[] { taskList }; return base.method_11<bool>("AddPowerSourceAndTargets", objArray1); } public void DoFinishFatigue() { base.method_8("DoFinishFatigue", Array.Empty<object>()); } public void OnFatigueActorLoaded(string actorName, GameObject actorObject, object callbackData) { object[] objArray1 = new object[] { actorName, actorObject, callbackData }; base.method_8("OnFatigueActorLoaded", objArray1); } public void OnFatigueDamageFinished(Spell spell, object userData) { object[] objArray1 = new object[] { spell, userData }; base.method_8("OnFatigueDamageFinished", objArray1); } public void OnFatigueDeathSpellFinished(Spell spell, SpellStateType prevStateType, object userData) { object[] objArray1 = new object[] { spell, prevStateType, userData }; base.method_8("OnFatigueDeathSpellFinished", objArray1); } public void OnProcessTaskList() { base.method_8("OnProcessTaskList", Array.Empty<object>()); } public static Vector3 FATIGUE_ACTOR_FINAL_LOCAL_ROTATION { get { return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "FatigueSpellController", "FATIGUE_ACTOR_FINAL_LOCAL_ROTATION"); } } public static Vector3 FATIGUE_ACTOR_FINAL_SCALE { get { return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "FatigueSpellController", "FATIGUE_ACTOR_FINAL_SCALE"); } } public static Vector3 FATIGUE_ACTOR_INITIAL_LOCAL_ROTATION { get { return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "FatigueSpellController", "FATIGUE_ACTOR_INITIAL_LOCAL_ROTATION"); } } public static Vector3 FATIGUE_ACTOR_START_SCALE { get { return MonoClass.smethod_6<Vector3>(TritonHs.MainAssemblyPath, "", "FatigueSpellController", "FATIGUE_ACTOR_START_SCALE"); } } public static float FATIGUE_DRAW_ANIM_TIME { get { return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "FatigueSpellController", "FATIGUE_DRAW_ANIM_TIME"); } } public static float FATIGUE_DRAW_SCALE_TIME { get { return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "FatigueSpellController", "FATIGUE_DRAW_SCALE_TIME"); } } public static float FATIGUE_HOLD_TIME { get { return MonoClass.smethod_6<float>(TritonHs.MainAssemblyPath, "", "FatigueSpellController", "FATIGUE_HOLD_TIME"); } } public Actor m_fatigueActor { get { return base.method_3<Actor>("m_fatigueActor"); } } public Network.HistTagChange m_fatigueTagChange { get { return base.method_3<Network.HistTagChange>("m_fatigueTagChange"); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UniverseState : MonoBehaviour { private static GameObject emptyLayerPrefab; private static GameObject EmptyLayerPrefab { get { if (emptyLayerPrefab == null) { emptyLayerPrefab = Resources.Load<GameObject>("EmptyLayer"); } return emptyLayerPrefab; } } public string m_name; public bool isTransition; public GameObject statics; public GameObject[] background; public GameObject[] midground; public GameObject[] foreground; public GameObject[] game; private List<string> alreadyUsedLayers; private void Awake() { if (isTransition) { alreadyUsedLayers = new List<string>(); Debug.LogWarning(alreadyUsedLayers.Count); } } public GameObject[] getFromLayer(string type) { //Debug.Log(this + "getFromLayer " + type + " " + alreadyUsedLayers.Contains(type)); if (isTransition && alreadyUsedLayers.Contains(type)) { return new GameObject[1] { EmptyLayerPrefab }; } else { GameObject[] result; if (isTransition) { alreadyUsedLayers.Add(type); } switch (type) { case "background": result = background; break; case "midground": result = midground; break; case "foreground": result = foreground; break; case "game": result = game; break; default: result = new GameObject[0]; break; } if (result.Length == 0) { result = new GameObject[1] { EmptyLayerPrefab }; } return result; } } }
using AutoMapper; using CustomerAgenda.Api.ViewModels; using CustomerAgenda.Business.Models; namespace CustomerAgenda.Api.Configurations { public class AutoMapperConfig : Profile { public AutoMapperConfig() { CreateMap<Customer, CustomerViewModel>().ReverseMap(); CreateMap<Customer, CustomerListViewModel>().ReverseMap(); CreateMap<Address, AddressViewModel>().ReverseMap(); CreateMap<PhoneContact, PhoneContacViewModel>().ReverseMap(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LookAtSLegs : MonoBehaviour { private GameObject player; private Vector3 playerPosition; private Vector3 legOffset; // Use this for initialization void Start () { player = GameObject.Find("Player"); playerPosition = player.transform.position; legOffset = this.transform.position; } // Update is called once per frame void Update () { playerPosition = player.transform.position; legOffset = this.transform.position; playerPosition.y = legOffset.y; this.transform.LookAt(playerPosition); } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using AutoMapper; using LuizalabsWishesManager.Domains.Models; using LuizalabsWishesManager.ViewModels; using LuizalabsWishesManager.Services; using Microsoft.AspNetCore.Mvc; namespace LuizalabsWishesManager.Controllers { [Route("api/[controller]")] [ApiController] public class UsersController : ControllerBase { private readonly IUserService _service; private readonly IMapper _mapper; public UsersController(IMapper mapper, IUserService service) { _mapper = mapper; _service = service; } [HttpGet] public ActionResult<IEnumerable<UserViewModel>> Get([FromQuery] int? page_size, int? page) { if(page == null) page = 1; if(page_size == null) page_size = 10; if (page <= 0 || page_size <= 0) return BadRequest(); var users = _service.GetAll((int)page, (int)page_size); if (users == null || !users.Any()) return NotFound(users); var userModels = _mapper.Map<List<UserViewModel>>(users); return Ok(userModels); } // POST api/users [HttpPost] public ActionResult Post([FromBody] NewUserViewModel userModel) { if (userModel == null) return BadRequest(); var user = _mapper.Map<User>(userModel); try { _service.Add(user); return StatusCode(HttpStatusCode.Created.GetHashCode(), user); } catch { return BadRequest(); } } } }
using CourseWork.Entity; using System; using System.Collections.Generic; using System.Linq; using System.Media; using System.Text; using System.Threading.Tasks; using System.Windows.Forms.DataVisualization.Charting; using Microsoft.Office.Interop.Excel; using System.Windows.Forms; namespace OfficeClasses { public class DataSaver : SaverInterface { async void SaverInterface.SaveToExcel(EntityCords entity) { await Task.Run(() => { Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application(); Workbook excelWorkBook = excelApp.Workbooks.Add(); Worksheet excelWorkSheet = excelWorkBook.Worksheets.Add(); List<double> CordsY = entity.GetListY(); List<double> CordsT = entity.GetListT(); int length = CordsT.Count(); excelWorkSheet.Columns[1].Rows[1] = "Step"; excelWorkSheet.Columns[2].Rows[1] = "T"; excelWorkSheet.Columns[3].Rows[1] = "Y (T)"; AddT(CordsT, excelWorkSheet); AddY(CordsY, excelWorkSheet); AddStep(length, excelWorkSheet); CreateChart(length, excelWorkSheet); excelWorkSheet.SaveAs(@"E:\courseWork\CourseProject\CourseWork\CourseWork\exports\excel.xlsx"); excelApp.Quit(); PlayDoneSound(); }); } async void SaverInterface.SaveToWord(EntityCords entity, System.Windows.Forms.DataVisualization.Charting.Chart chart) { SaveImage(chart); await Task.Run(() => { Microsoft.Office.Interop.Word.Application oneWord = new Microsoft.Office.Interop.Word.Application(); var oneDoc = oneWord.Documents.Add(); var paragraphone = oneDoc.Content.Paragraphs.Add(); String info = CreateInfo(entity); paragraphone.Range.Text = info; oneWord.ActiveDocument.Sections[1].Headers[Microsoft.Office.Interop.Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.InlineShapes.AddPicture(@"E:\courseWork\CourseProject\CourseWork\CourseWork\pictures\graphic.png"); oneDoc.SaveAs2(@"E:\courseWork\CourseProject\CourseWork\CourseWork\exports\word.docx"); oneWord.Quit(); PlayDoneSound(); }); } private void SaveImage(System.Windows.Forms.DataVisualization.Charting.Chart chart) { chart.SaveImage(@"E:\courseWork\CourseProject\CourseWork\CourseWork\pictures\graphic.png", System.Drawing.Imaging.ImageFormat.Png); } private void PlayDoneSound() { SoundPlayer doneSound = new SoundPlayer(@"E:\courseWork\CourseProject\CourseWork\CourseWork\sounds\soundSave.wav"); doneSound.Play(); } private String CreateInfo(EntityCords entity) { String info = " R0 = " + entity.GetR() + "\n P = " + entity.GetP() + "\n b = " + entity.GetB() + "\n h = " + entity.GetH() + "\n l = " + entity.GetL() + "\n E = " + entity.GetE() + "\n t0 = " + entity.GetT0() + "\n th = " + entity.GetTH() + "\n tk = " + entity.GetTK(); return info; } private void CreateChart(int length, Worksheet excelWorkSheet) { ChartObjects xlCharts = (ChartObjects)excelWorkSheet.ChartObjects(Type.Missing); ChartObject myChart = (ChartObject)xlCharts.Add(300, 0, length/1.5, 350); Microsoft.Office.Interop.Excel.Chart chart = myChart.Chart; Microsoft.Office.Interop.Excel.SeriesCollection seriesCollection = (Microsoft.Office.Interop.Excel.SeriesCollection)chart.SeriesCollection(Type.Missing); Microsoft.Office.Interop.Excel.Series series = seriesCollection.NewSeries(); series.XValues = excelWorkSheet.get_Range("B2", "B" + (length + 1)); series.Values = excelWorkSheet.get_Range("C2", "C" + (length + 1)); series.Name = "Fluctuation"; chart.ChartType = XlChartType.xlXYScatterSmooth; } private void AddY(List<double> cordsY, Worksheet worksheet) { int j = 1; foreach (double y in cordsY) { worksheet.Columns[3].Rows[j + 1] = y; j++; } } private void AddT(List<double> cordsT, Worksheet worksheet) { int j = 1; foreach (double t in cordsT) { worksheet.Columns[2].Rows[j + 1] = t; j++; } } private void AddStep(int length, Worksheet worksheet) { for (int i = 1; i < length + 1; i++) { worksheet.Columns[1].Rows[i+1] = i; } } } }
using System; namespace Test { class HelloWorld { static void Main(string[] args) { Console.WriteLine("Hello Stranger!"); Console.WriteLine("Please enter your name:"); string name = Console.ReadLine(); bool inputForName = true; while (inputForName) { if (name != "") { inputForName = false; } else { Console.WriteLine("Please enter your name"); name = Console.ReadLine(); } } Console.WriteLine("Please enter your age;"); var age = Console.ReadLine(); bool deadOrNot = true; Console.WriteLine("Are you dead or alive? enter 1 for yes and 2 for no"); var yeet = Convert.ToInt32(Console.ReadLine()); switch (yeet) { case 1: deadOrNot = true; break; case 2: deadOrNot = false; break; } if (deadOrNot == true) { Console.WriteLine("You won't be for too long tho >:)"); } else { Console.WriteLine("Well that's just highly unfortunate :("); } Console.WriteLine(); Console.WriteLine("Your name is: " + name); Console.WriteLine("Your age is: " + age); if (deadOrNot == true) { Console.WriteLine("Life-Status: Alive"); } else { Console.WriteLine("Life-Status: Dead"); } Console.WriteLine(); Console.WriteLine("Type in 5 words"); var words = new String[5]; for (int i = 0; i < 5; i++) { words[i] = Console.ReadLine(); } Console.WriteLine(); Console.WriteLine("Your 5 words: "); foreach (string word in words) Console.WriteLine(word); } } }
 using System; using Abp.Application.Services.Dto; namespace eForm.EFlight.Dtos { public class JobTitleDto : EntityDto { public string Name { get; set; } public string Code { get; set; } } }
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates how to use the two-fingers Pinch and Rotation gesture events to control the scale and orientation of a rectangle on the screen /// </summary> public class PinchRotation : MonoBehaviour { public Transform target; public float pinchScaleFactor = 0.02f; //Material originalMaterial; #region Input Mode public enum InputMode { PinchOnly, RotationOnly, PinchAndRotation } InputMode inputMode = InputMode.PinchAndRotation; #endregion #region Setup #endregion #region Events registeration void OnEnable() { FingerGestures.OnRotationBegin += FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove += FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd += FingerGestures_OnRotationEnd; FingerGestures.OnPinchBegin += FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove += FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd += FingerGestures_OnPinchEnd; } void OnDisable() { FingerGestures.OnRotationBegin -= FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove -= FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd -= FingerGestures_OnRotationEnd; FingerGestures.OnPinchBegin -= FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove -= FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd -= FingerGestures_OnPinchEnd; } #endregion #region Rotation gesture bool rotating = false; bool Rotating { get { return rotating; } set { if( rotating != value ) { rotating = value; UpdateTargetMaterial(); } } } public bool RotationAllowed { get { return inputMode == InputMode.RotationOnly || inputMode == InputMode.PinchAndRotation; } } void FingerGestures_OnRotationBegin( Vector2 fingerPos1, Vector2 fingerPos2 ) { if( RotationAllowed ) { //UI.StatusText = "Rotation gesture started."; Rotating = true; } } void FingerGestures_OnRotationMove( Vector2 fingerPos1, Vector2 fingerPos2, float rotationAngleDelta ) { if( Rotating ) { //UI.StatusText = "Rotation updated by " + rotationAngleDelta + " degrees"; // apply a rotation around the Z axis by rotationAngleDelta degrees on our target object target.Rotate( 0, 0, rotationAngleDelta ); Debug.Log("ROTATION: " + rotationAngleDelta); } } void FingerGestures_OnRotationEnd( Vector2 fingerPos1, Vector2 fingerPos2, float totalRotationAngle ) { if( Rotating ) { //UI.StatusText = "Rotation gesture ended. Total rotation: " + totalRotationAngle; Rotating = false; } } #endregion #region Pinch Gesture bool pinching = false; bool Pinching { get { return pinching; } set { if( pinching != value ) { pinching = value; UpdateTargetMaterial(); } } } public bool PinchAllowed { get { return inputMode == InputMode.PinchOnly || inputMode == InputMode.PinchAndRotation; } } void FingerGestures_OnPinchBegin( Vector2 fingerPos1, Vector2 fingerPos2 ) { if( !PinchAllowed ) return; Pinching = true; } void FingerGestures_OnPinchMove( Vector2 fingerPos1, Vector2 fingerPos2, float delta ) { if( Pinching ) { Vector3 currentScale = target.transform.localScale; Vector3 newScale = delta * pinchScaleFactor * Vector3.one; currentScale += newScale; if(currentScale.x > 0.8f && currentScale.x < 4.3f){ // change the scale of the target based on the pinch delta value target.transform.localScale += newScale; } Debug.Log ("SCALE: " + target.transform.localScale.x ); } } void FingerGestures_OnPinchEnd( Vector2 fingerPos1, Vector2 fingerPos2 ) { if( Pinching ) { Pinching = false; } } #endregion #region Misc void UpdateTargetMaterial() { /*Material m; if( pinching && rotating ) m = pinchAndRotationMaterial; else if( pinching ) m = pinchMaterial; else if( rotating ) m = rotationMaterial; else m = originalMaterial; target.renderer.sharedMaterial = m;*/ } #endregion #region GUI public Rect inputModeButtonRect; void OnGUI() { //SampleUI.ApplyVirtualScreen(); string buttonText; InputMode nextInputMode; switch( inputMode ) { case InputMode.PinchOnly: buttonText = "Pinch Only"; nextInputMode = InputMode.RotationOnly; break; case InputMode.RotationOnly: buttonText = "Rotation Only"; nextInputMode = InputMode.PinchAndRotation; break; default: buttonText = "Pinch + Rotation"; nextInputMode = InputMode.PinchOnly; break; } if( GUI.Button( inputModeButtonRect, buttonText ) ) { inputMode = nextInputMode; } } #endregion }
using System.Text; namespace ProBikeSS16.Workplaces { class WP_8 : Workplace { static int order_d7_1_p1 = 0; static int order_d7_2_p1 = 0; static int order_d7_3_p1 = 0; static int order_d7_1_p2 = 0; static int order_d7_2_p2 = 0; static int order_d7_3_p2 = 0; static int order_d7_1_p3 = 0; static int order_d7_2_p3 = 0; static int order_d7_3_p3 = 0; #region Getter/Setter public int ProdTimeD7_1_p1 { get { return getApproxProdTimeOd7_1_p1(order_d7_1_p1); } } public int ProdTimeD7_2_p1 { get { return getApproxProdTimeOd7_2_p1(order_d7_2_p1); } } public int ProdTimeD7_3_p1 { get { return getApproxProdTimeOd7_3_p1(order_d7_3_p1); } } public int ProdTimeD7_1_p2 { get { return getApproxProdTimeOd7_1_p2(order_d7_1_p2); } } public int ProdTimeD7_2_p2 { get { return getApproxProdTimeOd7_2_p2(order_d7_2_p2); } } public int ProdTimeD7_3_p2 { get { return getApproxProdTimeOd7_3_p2(order_d7_3_p2); } } public int ProdTimeD7_1_p3 { get { return getApproxProdTimeOd7_1_p3(order_d7_1_p3); } } public int ProdTimeD7_2_p3 { get { return getApproxProdTimeOd7_2_p3(order_d7_2_p3); } } public int ProdTimeD7_3_p3 { get { return getApproxProdTimeOd7_3_p3(order_d7_3_p3); } } public int ProdTime { get { return ProdTimeD7_1_p1 + ProdTimeD7_2_p1 + ProdTimeD7_3_p1 + ProdTimeD7_1_p2 + ProdTimeD7_2_p2 + ProdTimeD7_3_p2 + ProdTimeD7_1_p3 + ProdTimeD7_2_p3 + ProdTimeD7_3_p3; } } public int NeedOfD12_1_p1 { get { return NeedOfD12(order_d7_1_p1); } } public int NeedOfD12_2_p1 { get { return NeedOfD12(order_d7_2_p1); } } public int NeedOfD6_p1 { get { return NeedOfD6(order_d7_3_p1); } } public int NeedOfD12_1_p2 { get { return NeedOfD12(order_d7_1_p2); } } public int NeedOfD12_2_p2 { get { return NeedOfD12(order_d7_2_p2); } } public int NeedOfD6_p2 { get { return NeedOfD6(order_d7_3_p2); } } public int NeedOfD12_1_p3 { get { return NeedOfD12(order_d7_1_p3); } } public int NeedOfD12_2_p3 { get { return NeedOfD12(order_d7_2_p3); } } public int NeedOfD6_p3 { get { return NeedOfD6(order_d7_3_p3); } } public static int Order_d7_1_p1 { get { return order_d7_1_p1; } set { order_d7_1_p1 = value; } } public static int Order_d7_2_p1 { get { return order_d7_2_p1; } set { order_d7_2_p1 = value; } } public static int Order_d7_3_p1 { get { return order_d7_3_p1; } set { order_d7_3_p1 = value; } } public static int Order_d7_1_p2 { get { return order_d7_1_p2; } set { order_d7_1_p2 = value; } } public static int Order_d7_2_p2 { get { return order_d7_2_p2; } set { order_d7_2_p2 = value; } } public static int Order_d7_3_p2 { get { return order_d7_3_p2; } set { order_d7_3_p2 = value; } } public static int Order_d7_1_p3 { get { return order_d7_1_p3; } set { order_d7_1_p3 = value; } } public static int Order_d7_2_p3 { get { return order_d7_2_p3; } set { order_d7_2_p3 = value; } } public static int Order_d7_3_p3 { get { return order_d7_3_p3; } set { order_d7_3_p3 = value; } } #endregion public WP_8(int id, double var_machineCosts, double fix_machineCosts, int shiftsToDo = 1, double overTimeToDo = 0) : base(id, var_machineCosts, fix_machineCosts, shiftsToDo, overTimeToDo) { } public override void fillProductionOrders() { } #region Production d7_1_p1 public void produce_one_batch_d7_1_p1() { if (order_d7_1_p1 <= 0 && onMachine == 0) return; if (cur_prod != 1) { cur_prod = 1; setUptime += 15; setUps++; } if (onMachine == 0) { order_d7_1_p1 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < (3 * prod_batch)) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_1_p1(prod_batch); onMachine = 0; } #endregion #region Production d7_2_p1 public void produce_one_batch_d7_2_p1() { if (order_d7_2_p1 <= 0 && onMachine == 0) return; if (cur_prod != 2) { cur_prod = 2; setUptime += 20; setUps++; } if (onMachine == 0) { order_d7_2_p1 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < (3 * prod_batch)) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_2_p1(prod_batch); onMachine = 0; } #endregion #region Production d7_3_p1 public void produce_one_batch_d7_3_p1() { if (order_d7_3_p1 <= 0 && onMachine == 0) return; if (cur_prod != 3) { cur_prod = 3; setUptime += 15; setUps++; } if (onMachine == 0) { order_d7_3_p1 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < prod_batch) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_3_p1(prod_batch); onMachine = 0; } #endregion #region Production d7_1_p2 public void produce_one_batch_d7_1_p2() { if (order_d7_1_p2 <= 0 && onMachine == 0) return; if (cur_prod != 4) { cur_prod = 4; setUptime += 15; setUps++; } if (onMachine == 0) { order_d7_1_p2 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < prod_batch) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_1_p2(prod_batch); onMachine = 0; } #endregion #region Production d7_2_p2 public void produce_one_batch_d7_2_p2() { if (order_d7_2_p2 <= 0 && onMachine == 0) return; if (cur_prod != 5) { cur_prod = 5; setUptime += 25; setUps++; } if (onMachine == 0) { order_d7_2_p2 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < prod_batch) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_2_p2(prod_batch); onMachine = 0; } #endregion #region Production d7_3_p2 public void produce_one_batch_d7_3_p2() { if (order_d7_3_p2 <= 0 && onMachine == 0) return; if (cur_prod != 6) { cur_prod = 6; setUptime += 15; setUps++; } if (onMachine == 0) { order_d7_3_p2 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < prod_batch) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_3_p2(prod_batch); onMachine = 0; } #endregion #region Production d7_1_p3 public void produce_one_batch_d7_1_p3() { if (order_d7_1_p3 <= 0 && onMachine == 0) return; if (cur_prod != 7) { cur_prod = 7; setUptime += 15; setUps++; } if (onMachine == 0) { order_d7_1_p3 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < (3 * prod_batch)) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_1_p3(prod_batch); onMachine = 0; } #endregion #region Production d7_2_p3 public void produce_one_batch_d7_2_p3() { if (order_d7_2_p3 <= 0 && onMachine == 0) return; if (cur_prod != 8) { cur_prod = 8; setUptime += 20; setUps++; } if (onMachine == 0) { order_d7_2_p3 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < (3 * prod_batch)) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_2_p3(prod_batch); onMachine = 0; } #endregion #region Production d7_3_p3 public void produce_one_batch_d7_3_p3() { if (order_d7_3_p3 <= 0 && onMachine == 0) return; if (cur_prod != 9) { cur_prod = 9; setUptime += 15; setUps++; } if (onMachine == 0) { order_d7_3_p3 -= prod_batch; onMachine += prod_batch; } /** TODO DIRECTS **/ if (storage.Content[28].Quantity < prod_batch) return; storage.Content[28].Quantity -= (3 * prod_batch); currentWorkTime += getApproxProdTimeOd7_3_p3(prod_batch); onMachine = 0; } #endregion #region Methods public int getApproxProdTimeOd7_1_p1(int d7Val_p1) { return 1 * d7Val_p1; } public int getApproxProdTimeOd7_2_p1(int d7Val_p1) { return 3 * d7Val_p1; } public int getApproxProdTimeOd7_3_p1(int d7Val_p1) { return 1 * d7Val_p1; } public int getApproxProdTimeOd7_1_p2(int d7Val_p2) { return 2 * d7Val_p2; } public int getApproxProdTimeOd7_2_p2(int d7Val_p2) { return 3 * d7Val_p2; } public int getApproxProdTimeOd7_3_p2(int d7Val_p2) { return 2 * d7Val_p2; } public int getApproxProdTimeOd7_1_p3(int d7Val_p3) { return 2 * d7Val_p3; } public int getApproxProdTimeOd7_2_p3(int d7Val_p3) { return 3 * d7Val_p3; } public int getApproxProdTimeOd7_3_p3(int d7Val_p3) { return 2 * d7Val_p3; } public int NeedOfD12(int d7Val) { return 1 * d7Val; } public int NeedOfD6(int d7Val) { return 1 * d7Val; } #endregion public override string ToString() { StringBuilder s = new StringBuilder(); s.Append(base.ToString()); s.AppendLine("\nOrder d7_1_p1: " + Order_d7_1_p1); s.AppendLine("\nOrder d7_2_p1: " + Order_d7_2_p1); s.AppendLine("\nOrder d7_3_p1: " + Order_d7_3_p1); s.AppendLine("\nOrder d7_1_p2: " + Order_d7_1_p2); s.AppendLine("\nOrder d7_2_p2: " + Order_d7_2_p2); s.AppendLine("\nOrder d7_3_p2: " + Order_d7_3_p2); s.AppendLine("\nOrder d7_1_p3: " + Order_d7_1_p3); s.AppendLine("\nOrder d7_2_p3: " + Order_d7_2_p3); s.AppendLine("\nOrder d7_3_p3: " + Order_d7_3_p3); return s.ToString(); ; } } }
namespace AlphabetArrayAndStringAsArray { using System; public class AlphabetArrayAndStringAsArray { /// <summary> /// Write a program that creates an array containing all letters from the alphabet (A-Z). /// Read a word from the console and print the index of each of its letters in the array. /// </summary> public static void Main(string[] args) { char[] alphabetArray = GetEnglishAlphabetCapitalLetters(true); Console.WriteLine("Please, enter a word (A-Za-z):"); string text = Console.ReadLine(); for (int i = 0; i < text.Length; i++) { Console.WriteLine(text[i] + " - " + Array.IndexOf(alphabetArray, text[i])); } } public static char[] GetEnglishAlphabetCapitalLetters(bool withSmallLetters = true) { int arrayLength = 26; if (withSmallLetters == true) { arrayLength = 52; } char[] array = new char[arrayLength]; for (char letter = 'A'; letter <= 'Z'; letter++) { array[letter - 65] = letter; } if (withSmallLetters == true) { for (char letter = 'a'; letter <= 'z'; letter++) { array[letter - 97 + 26] = letter; } } return array; } } }
using System; using System.ComponentModel.DataAnnotations; using XMLApiProject.Services.Models.PaymentService.Entities; using XMLApiProject.Services.Models.PaymentService.XML.RequestService.Responses; namespace XMLApiProject.Services.Models.PaymentService.XML.RequestService.Request { public class VoidOrRefundRequestMessage: RequestMessageBase { #region Properties public string MerchantCode { get; set; } public string MerchantAccountCode { get; set; } [Required] [StringLength(8)] public uint Amount { get; set; } [Required] [StringLength(12)] public string ReferenceNumber { get; set; } [Required] [StringLength(6)] public string TransactionType { get; set; } [Required] public string TransactionCode { get; set; } public Guid? PurchaseToken { get; set; } public string OriginatingTechnologySource { get; set; } [Required] public string SoftwareVendor { get; set; } public string SecurityTechnology { get; set; } [StringLength(24)] public string CustomerAccountCode { get; set; } [StringLength(24)] public string InvoiceNum { get; set; } [StringLength(40)] public string DeviceMake { get; set; } [StringLength(40)] public string DeviceModel { get; set; } [StringLength(40)] public string DeviceSerial { get; set; } [StringLength(50)] public string DeviceFirmware { get; set; } [StringLength(10)] public string RegistrationKey { get; set; } [StringLength(36)] public string AppHostMachineId { get; set; } [StringLength(6)] public string IntegrationMethod { get; set; } [StringLength(255)] public string EMVTags { get; set; } [StringLength(20)] public string VoidReasonCode { get; set; } #endregion #region Constructors public VoidOrRefundRequestMessage() { } public VoidOrRefundRequestMessage(string merchantCode, string merchantAccountCode, uint amount, string referenceNumber, string transactionType, string transactionCode, Guid? purchaseToken, string originatingTechnologySource, string softwareVendor, string securityTechnology, string customerAccountCode, string invoiceNum, string deviceMake, string deviceModel, string deviceSerial, string deviceFirmware, string registrationKey, string appHostMachineId, string integrationMethod, string emvTags, string voidReasonCode) { MerchantCode = merchantCode; MerchantAccountCode = merchantAccountCode; Amount = amount; ReferenceNumber = referenceNumber; TransactionType = transactionType; TransactionCode = transactionCode; PurchaseToken = purchaseToken; OriginatingTechnologySource = originatingTechnologySource; SoftwareVendor = softwareVendor; SecurityTechnology = securityTechnology; CustomerAccountCode = customerAccountCode; InvoiceNum = invoiceNum; DeviceMake = deviceMake; DeviceModel = deviceModel; DeviceSerial = deviceSerial; DeviceFirmware = deviceFirmware; RegistrationKey = registrationKey; AppHostMachineId = appHostMachineId; IntegrationMethod = integrationMethod; EMVTags = emvTags; VoidReasonCode = voidReasonCode; } public VoidOrRefundRequestMessage(IVoidRefundRequest request, Guid generatedGuid) { MerchantCode = request.MerchantCode; MerchantAccountCode = request.MerchantAccountCode; Amount = request.Amount; ReferenceNumber = request.ReferenceNumber; TransactionType = request.TransactionType; TransactionCode = generatedGuid.ToString(); PurchaseToken = request.PurchaseToken; OriginatingTechnologySource = request.OriginatingTechnologySource; SoftwareVendor = request.SoftwareVendor; SecurityTechnology = request.SecurityTechnology; CustomerAccountCode = request.CustomerAccountCode; InvoiceNum = request.InvoiceNum; DeviceMake = request.DeviceMake; DeviceModel = request.DeviceModel; DeviceSerial = request.DeviceSerial; DeviceFirmware = request.DeviceFirmware; RegistrationKey = request.RegistrationKey; AppHostMachineId = request.AppHostMachineId; IntegrationMethod = request.IntegrationMethod; EMVTags = request.EMVTags; VoidReasonCode = request.VoidReasonCode; } #endregion public override string GetResponseRootName() { return nameof(VoidRefund); } public override RawRequestMessageString ToXmlRequestString() { return ToXmlRequestString<VoidOrRefundRequestMessage>(); } public bool ShouldSerializePurchaseToken() { return PurchaseToken.HasValue; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Basket : MonoBehaviour { private Text scoreText; private int count = 0; // Use this for initialization void Start () { scoreText = GameObject.Find("Canvas").GetComponentInChildren<Text>(); scoreText.text = "Score: 0"; } // Update is called once per frame void Update () { Vector3 mousePos2D = Input.mousePosition; // 主摄像机 z 为 -10,将此 z 设为 10 mousePos2D.z = -Camera.main.transform.position.z ; // 使得此 z 为 0 Vector3 mousePos3D = Camera.main.ScreenToWorldPoint(mousePos2D); Vector3 pos = this.transform.position; pos.x = mousePos3D.x; this.transform.position = pos; } private void OnCollisionEnter(Collision collision) { GameObject collidedWith = collision.gameObject; if(collidedWith.tag == "Apple") { Destroy(collidedWith); count++; scoreText.text = "Scores: " + count * 100; // 更新最高分 if(count * 100 > HighestScore.score) { HighestScore.score = count * 100; } } } }
using System; using UnityEngine.Events; namespace Helpers { [Serializable] public class ScriptableEvent { public string eventName; public UnityEvent unityEvent; } }
using ALM.Empresa.Interfaz.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace ALM.Empresa.Interfaz { public class CustomAuthorizeAttribute : AuthorizeAttribute { public InformacionUsuarioLogueado.Privilegio AccessLevel { get; set; } public string Accion { get; set; } public override void OnAuthorization(AuthorizationContext filterContext) { if (filterContext.HttpContext.User.Identity.IsAuthenticated) { if (InformacionUsuarioLogueado.EsSuperAdministrador && string.IsNullOrEmpty(InformacionUsuarioLogueado.CodigoSuperAdministrador)) { filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Inicio", action = "AccesoDenegado" })); } else { InformacionUsuarioLogueado.FechaActualizacionTimeOut = DateTime.Now; if (!InformacionUsuarioLogueado.ValidarPermiso(filterContext.ActionDescriptor.ControllerDescriptor.ControllerType.Name, Accion, AccessLevel)) { if (HttpContext.Current.Request.UrlReferrer != null) { string[] UrlFragment = HttpContext.Current.Request.UrlReferrer.LocalPath.Split('/'); var routeValues = new RouteValueDictionary(); if (UrlFragment.Length > 2 && !filterContext.HttpContext.Request.IsAjaxRequest()) { routeValues["controller"] = UrlFragment[1]; string[] Action = UrlFragment[2].Split('?'); routeValues["action"] = Action[0]; if (Action.Length < 2) { filterContext.Controller.TempData["SinAutorizacion"] = "No tienes los suficientes permisos para accesar. =("; filterContext.Result = new RedirectToRouteResult(routeValues); } } else { filterContext.Result = new MenuController().PermisoInsuficiente(); } } else { var routeValues2 = new RouteValueDictionary(); routeValues2["controller"] = "Inicio"; routeValues2["action"] = "AccesoDenegado"; filterContext.Result = new RedirectToRouteResult(routeValues2); } } else base.OnAuthorization(filterContext); } } else filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new { controller = "Inicio", action = "AccesoDenegado" })); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EntidadesCompartidas; using Logica.interfaces; using Persistencia; namespace Logica.clasesDeTrabajo { internal class LogicaUsuario : ILogicaUsuario { private static LogicaUsuario _instancia = null; private LogicaUsuario() { } public static LogicaUsuario GetInstancia() { if (_instancia == null) { _instancia = new LogicaUsuario(); } return _instancia; } internal static void validarUsuario(Usuario us) { } public void AltaUsuario(Usuario usuario, Empleado usLog) { validarUsuario(usuario); if (usuario is Empleado) { FabricaPersistencia.GetPersistenciaEmpleado().AltaEmpleado((Empleado)usuario, usLog); } else if (usuario is Empresa) { FabricaPersistencia.GetPersistenciaEmpresa().AltaEmpresa((Empresa)usuario, usLog); } } public void BajaUsuario(Usuario usuario, Empleado usLog) { validarUsuario(usuario); if (usuario is Empleado) { FabricaPersistencia.GetPersistenciaEmpleado().BajaEmpleado((Empleado)usuario, usLog); } else if (usuario is Empresa) { FabricaPersistencia.GetPersistenciaEmpresa().BajaEmpresa((Empresa)usuario, usLog); } } public Usuario BuscarUsuario(string logueo, Empleado usLog) { Usuario usuario = FabricaPersistencia.GetPersistenciaEmpleado().BuscarEmpleado(logueo, usLog); if (usuario == null) { usuario = FabricaPersistencia.GetPersistenciaEmpresa().BuscarEmpresa(logueo, usLog); } return usuario; } public Usuario LogueoUsuario(string logueo, string contraseana) { try { Usuario usuario = FabricaPersistencia.GetPersistenciaEmpleado().LoguearEmpleado(logueo, contraseana); if (usuario == null) { usuario = FabricaPersistencia.GetPersistenciaEmpresa().LoguearEmpresa(logueo, contraseana); } return usuario; } catch (Exception ex) { throw ex; } } public void ModificarUsuario(Usuario usuario, Empleado usLog) { validarUsuario(usuario); if (usuario is Empleado) { FabricaPersistencia.GetPersistenciaEmpleado().ModificarEmpleado((Empleado)usuario, usLog); } else if (usuario is Empresa) { FabricaPersistencia.GetPersistenciaEmpresa().ModificarEmpresa((Empresa)usuario, usLog); } } public void ModificarContrasenaUsuario(Usuario usuario, Usuario usLog) { validarUsuario(usuario); if (usuario is Empleado) { FabricaPersistencia.GetPersistenciaEmpleado().ModificarContrasenaEmpleado((Empleado)usuario, usLog); } else if (usuario is Empresa) { FabricaPersistencia.GetPersistenciaEmpresa().ModificarContrasenaEmpresa((Empresa)usuario, usLog); } } public List<Empresa> ListarEmpresas(Empleado usLog) { return FabricaPersistencia.GetPersistenciaEmpresa().ListarEmpresas(usLog); } } }
using System; using System.Linq; using SubSonic.Extensions; using System.Collections.Generic; using SubSonic.SqlGeneration.Schema; namespace Pes.Core { public enum CloudSortOrder { Ascending, Descending, Random } public partial class Tag { public static Tag GetTagByName(string name) { return Tag.Find(t => t.Name == name).FirstOrDefault(); } public static Tag GetTagByID(int TagID) { return Tag.Single(t => t.TagID == TagID); } public static List<Tag> GetTagsBySystemObjectAndRecordID(int SystemObjectID, long SystemObjectRecordID) { List<Tag> results = null; results = (from t in All() join sot in SystemObjectTag.All() on t.TagID equals sot.TagID where sot.SystemObjectID == SystemObjectID && sot.SystemObjectRecordID == SystemObjectRecordID select t).Distinct().OrderBy(t => t.CreateDate).ToList(); return results; } public static List<Tag> GetTagsBySystemObject(int SystemObjectID, int TagsToTake) { List<Tag> results = null; results = (from t in All() join sot in SystemObjectTag.All() on t.TagID equals sot.TagID where sot.SystemObjectID == SystemObjectID select t).Distinct().OrderByDescending(t => t.Count).Take(TagsToTake).ToList(); return results; } public static List<Tag> GetTagsGlobal(int TagsToTake) { List<Tag> results = null; results = (from t in Tag.All() select t).Distinct().OrderByDescending(t => t.Count).Take(TagsToTake).ToList(); return results; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; using System.Data; namespace YiXiangLibrary { public partial class d_bingli_select : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void Button1_Click(object sender, EventArgs e) { string patientid = TextBox2.Text.Trim(); } protected void Button2_Click(object sender, EventArgs e) { try { string connstr = "server=.;database=yixiang;Integrated Security=SSPI"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); //连接并且打开数据库 SqlCommand cmd = new SqlCommand("select u_name,u_idcard,u_sex,d_id,r_time,r_linic,r_check,r_treat,r_medcine,r_cost from records", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "records"); GridView1.DataSource = ds; GridView1.DataBind(); conn.Close(); } catch (Exception err) { catchLabel.Text = err.ToString(); } } protected void Button1_Click1(object sender, EventArgs e) { if (TextBox2.Text.Trim() == "") { catchLabel.Text = "请输入身份证号!"; } else { try { string connstr = "server=.;database=yixiang;Integrated Security=SSPI"; SqlConnection conn = new SqlConnection(connstr); conn.Open(); //连接并且打开数据库 SqlCommand cmd = new SqlCommand("select u_name,u_idcard,u_sex,d_id,r_time,r_linic,r_check,r_treat,r_medcine,r_cost from records where u_idcard = '" + TextBox2.Text.Trim() + "' ", conn); SqlDataAdapter da = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); da.Fill(ds, "records"); GridView1.DataSource = ds; GridView1.DataBind(); conn.Close(); } catch (Exception err) { catchLabel.Text = err.ToString(); } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace GuardarImagenBaseDatos.GuardarImagen { public partial class ListarImagenes : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { GridView1.DataSource = ImagenesDAL.GetImagenList(); GridView1.DataBind(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Co3 { class Employee { readonly string name, secondname; string posada; int exp; public Employee(string name, string secondname) { this.name = name; this.secondname = secondname; } public double Zarplata() { double zarplata; switch (Posada) { case "maneger": zarplata = 127; break; case "worker": zarplata = 75;break; case "developer": zarplata = 150; break; default: zarplata = 50; break; } switch (exp) { case 1: zarplata *= 1.2; break; case 2: zarplata *= 1.8; break; case 3: zarplata *= 2.1; break; } return zarplata; } public string Name { get { return name; } } public string Secondname { get { return secondname; } } public int Exp { get { return exp; } set { if (value >= 0) exp = value; } } public string Posada { get { if (posada ==null) { return "NotWorking"; } return posada; } set { if(value!=null) posada = value; } } public void money() { Console.WriteLine(Zarplata()+" and lost "+Zarplata()*0.08); } } class Program { static void Main(string[] args) { Console.WriteLine("Enter U name "); var n1 = Console.ReadLine(); Console.WriteLine("Enter U secondname"); var n2 = Console.ReadLine(); Employee employer = new Employee(n1, n2); Console.WriteLine("Chose U work : maneger, worker, developer "); employer.Posada = Console.ReadLine(); Console.WriteLine("Chose U exp :Put 1 if u work to 1year, Put 2 - 1 from 2 yesrs and put 3 - more then 2 years "); employer.Exp = Convert.ToInt32(Console.ReadLine()); Console.Write("{0} {1}, you are {2} and get ", employer.Name,employer.Secondname,employer.Posada); employer.money(); Console.ReadKey(); } } }
using UnityEngine; namespace Voxelizer.Rendering { /// <summary> /// Encapsulate common resources related to shaders for /// voxelization creation and visualization /// </summary> [CreateAssetMenu(menuName = "Voxelizer/VoxelizationResources")] public class VoxelizationResources : ScriptableObject { // _voxelizationShader uniforms name public static int VOLUME_SIZE = Shader.PropertyToID("_VolumeSize"); public static int PROJECTIONS = Shader.PropertyToID("_Projections"); // _voxelizationPostProcessShader values public static string FIND_FILLED_VOXELS_KERNEL = "FindFilledVoxels"; public static int VOXELS = Shader.PropertyToID("_Voxels"); public static int FILLED_VOXELS_INSTANCES = Shader.PropertyToID("_FilledVoxelInstances"); public static int INDEX_TO_POSITION = Shader.PropertyToID("_IndexToPosition"); // _filledVoxelInstanceShader values public static int VOLUME_LOCAL_TO_WORLD = Shader.PropertyToID("_VolumeLocalToWorld"); [SerializeField] [Tooltip("Shader to use for voxelization")] private Shader _voxelizationShader = null; public Shader VoxelizationShader => _voxelizationShader; private Material _voxelizationMaterial; public Material VoxelizationMaterial { get { if (_voxelizationMaterial == null) _voxelizationMaterial = new Material(_voxelizationShader); return _voxelizationMaterial; } } [SerializeField] [Tooltip("Compute shader to use for processing voxelization")] private ComputeShader _voxelizationPostProcessShader = null; public ComputeShader VoxelizationPostProcessShader => _voxelizationPostProcessShader; public int FindFilledVoxelsKernel { get { if (_voxelizationPostProcessShader != null && _voxelizationPostProcessShader.HasKernel(FIND_FILLED_VOXELS_KERNEL)) { return _voxelizationPostProcessShader.FindKernel(FIND_FILLED_VOXELS_KERNEL); } else { return -1; } } } public (int, int, int) FindFilledVoxelsThreadGroupsSize { get { var kernel = FindFilledVoxelsKernel; if (kernel != -1) { uint x, y, z; _voxelizationPostProcessShader.GetKernelThreadGroupSizes(kernel, out x, out y, out z); return ((int)x, (int)y, (int)z); } else { return (0, 0, 0); } } } [SerializeField] [Tooltip("Mesh used to visualize voxels")] private Mesh _filledVoxelInstanceMesh = null; public Mesh FilledVoxelInstanceMesh => _filledVoxelInstanceMesh; [SerializeField] [Tooltip("Material used to visualize voxels")] private Material _filledVoxelInstanceMaterial = null; public Material FilledVoxelInstanceMaterial => _filledVoxelInstanceMaterial; } }
using System; namespace CSharp.DesignPatterns.Builder { class Program { static void Main(string[] args) { //Builder Design Pattern bir Creational'dır //Creational bir nesnenin oluşmasını sağlayan paterndir. //Kompleks yapıda bir objemiz var ise. //Objeyi oluşturmak için belli bir sırayı bozmadan, adım adım işlemler için. //Örnek olarak Değişken içeriğe sahip fast food menüsü gibi //Builder Design Pattern Insance ProductDirector productDirector = new ProductDirector(); var newCustomerBuilder = new NewCustomerBuilder(); productDirector.GenerateBuilder(newCustomerBuilder); var model = newCustomerBuilder.GetProductDto(); Console.WriteLine(model.Id); Console.WriteLine(model.CategoryName); Console.WriteLine(model.ProductName); Console.WriteLine(model.Discount); Console.WriteLine(model.IsDiscount); Console.WriteLine(model.UnitPrice); ProductDirector productDirector1 = new ProductDirector(); var oldBuilder = new OldCustomerBuilder(); productDirector1.GenerateBuilder(oldBuilder); var model1 = oldBuilder.GetProductDto(); Console.WriteLine(model1.Id); Console.WriteLine(model1.CategoryName); Console.WriteLine(model1.ProductName); Console.WriteLine(model1.Discount); Console.WriteLine(model1.IsDiscount); Console.WriteLine(model1.UnitPrice); Console.ReadLine(); } class ProductDto { public int Id { get; set; } public string CategoryName { get; set; } public string ProductName { get; set; } public decimal UnitPrice { get; set; } public decimal Discount { get; set; } public bool IsDiscount { get; set; } } abstract class ProductBuilder { public abstract void GetProductData(); public abstract void ApplyDiscount(); public abstract ProductDto GetProductDto(); } class NewCustomerBuilder : ProductBuilder { ProductDto productDto = new ProductDto(); public override void ApplyDiscount() { productDto.Discount = productDto.UnitPrice * (decimal)0.90; productDto.IsDiscount = true; } public override void GetProductData() { productDto.Id = 1; productDto.CategoryName = "Tech"; productDto.ProductName = "Computer"; productDto.UnitPrice = 100.5m; } public override ProductDto GetProductDto() { return productDto; } } class OldCustomerBuilder : ProductBuilder { ProductDto productDto = new ProductDto(); public override void ApplyDiscount() { productDto.Discount = productDto.UnitPrice; productDto.IsDiscount = false; } public override void GetProductData() { productDto.Id = 1; productDto.CategoryName = "Tech"; productDto.ProductName = "Computer"; productDto.UnitPrice = 100.5m; } public override ProductDto GetProductDto() { return productDto; } } class ProductDirector { public void GenerateBuilder(ProductBuilder productBuilder) { productBuilder.GetProductData(); productBuilder.ApplyDiscount(); } } } }
/* * Bungie.Net API * * These endpoints constitute the functionality exposed by Bungie.net, both for more traditional website functionality and for connectivity to Bungie video games and their related functionality. * * OpenAPI spec version: 2.1.1 * Contact: support@bungie.com * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Text.RegularExpressions; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using System.ComponentModel.DataAnnotations; using SwaggerDateConverter = BungieNetPlatform.Client.SwaggerDateConverter; namespace BungieNetPlatform.Model { /// <summary> /// The most essential summary information about a Profile (in Destiny 1, we called these \&quot;Accounts\&quot;). /// </summary> [DataContract] public partial class DestinyEntitiesProfilesDestinyProfileComponent : IEquatable<DestinyEntitiesProfilesDestinyProfileComponent>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="DestinyEntitiesProfilesDestinyProfileComponent" /> class. /// </summary> /// <param name="UserInfo">If you need to render the Profile (their platform name, icon, etc...) somewhere, this property contains that information..</param> /// <param name="DateLastPlayed">The last time the user played with any character on this Profile..</param> /// <param name="VersionsOwned">If you want to know what expansions they own, this will contain that data..</param> /// <param name="CharacterIds">A list of the character IDs, for further querying on your part..</param> public DestinyEntitiesProfilesDestinyProfileComponent(UserUserInfoCard UserInfo = default(UserUserInfoCard), DateTime? DateLastPlayed = default(DateTime?), DestinyDestinyGameVersions VersionsOwned = default(DestinyDestinyGameVersions), List<long?> CharacterIds = default(List<long?>)) { this.UserInfo = UserInfo; this.DateLastPlayed = DateLastPlayed; this.VersionsOwned = VersionsOwned; this.CharacterIds = CharacterIds; } /// <summary> /// If you need to render the Profile (their platform name, icon, etc...) somewhere, this property contains that information. /// </summary> /// <value>If you need to render the Profile (their platform name, icon, etc...) somewhere, this property contains that information.</value> [DataMember(Name="userInfo", EmitDefaultValue=false)] public UserUserInfoCard UserInfo { get; set; } /// <summary> /// The last time the user played with any character on this Profile. /// </summary> /// <value>The last time the user played with any character on this Profile.</value> [DataMember(Name="dateLastPlayed", EmitDefaultValue=false)] public DateTime? DateLastPlayed { get; set; } /// <summary> /// If you want to know what expansions they own, this will contain that data. /// </summary> /// <value>If you want to know what expansions they own, this will contain that data.</value> [DataMember(Name="versionsOwned", EmitDefaultValue=false)] public DestinyDestinyGameVersions VersionsOwned { get; set; } /// <summary> /// A list of the character IDs, for further querying on your part. /// </summary> /// <value>A list of the character IDs, for further querying on your part.</value> [DataMember(Name="characterIds", EmitDefaultValue=false)] public List<long?> CharacterIds { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class DestinyEntitiesProfilesDestinyProfileComponent {\n"); sb.Append(" UserInfo: ").Append(UserInfo).Append("\n"); sb.Append(" DateLastPlayed: ").Append(DateLastPlayed).Append("\n"); sb.Append(" VersionsOwned: ").Append(VersionsOwned).Append("\n"); sb.Append(" CharacterIds: ").Append(CharacterIds).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as DestinyEntitiesProfilesDestinyProfileComponent); } /// <summary> /// Returns true if DestinyEntitiesProfilesDestinyProfileComponent instances are equal /// </summary> /// <param name="input">Instance of DestinyEntitiesProfilesDestinyProfileComponent to be compared</param> /// <returns>Boolean</returns> public bool Equals(DestinyEntitiesProfilesDestinyProfileComponent input) { if (input == null) return false; return ( this.UserInfo == input.UserInfo || (this.UserInfo != null && this.UserInfo.Equals(input.UserInfo)) ) && ( this.DateLastPlayed == input.DateLastPlayed || (this.DateLastPlayed != null && this.DateLastPlayed.Equals(input.DateLastPlayed)) ) && ( this.VersionsOwned == input.VersionsOwned || (this.VersionsOwned != null && this.VersionsOwned.Equals(input.VersionsOwned)) ) && ( this.CharacterIds == input.CharacterIds || this.CharacterIds != null && this.CharacterIds.SequenceEqual(input.CharacterIds) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.UserInfo != null) hashCode = hashCode * 59 + this.UserInfo.GetHashCode(); if (this.DateLastPlayed != null) hashCode = hashCode * 59 + this.DateLastPlayed.GetHashCode(); if (this.VersionsOwned != null) hashCode = hashCode * 59 + this.VersionsOwned.GetHashCode(); if (this.CharacterIds != null) hashCode = hashCode * 59 + this.CharacterIds.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
/** File Created May 26th 2017 - File name = MouseLook.cs Author: Gabriel Gaudreau Project: ShootingRangeGame **This script is based on an answer found in Unity3d Forums.** */ using UnityEngine; [AddComponentMenu("Camera-Control/Mouse Look")] public class MouseLook : MonoBehaviour { public enum Axes { XANDY, X, Y} public Axes axes = Axes.XANDY; public float sensitivityX, sensitivityY; private float maxX, minX, maxY, minY, rotationY; /// <summary> /// Start function, initializes variables /// </summary> void Start() { sensitivityX = 1.2f; sensitivityY = 1.2f; minX = -360.0f; maxX = 360.0f; minY = -60.0f; maxY = 60.0f; rotationY = 0.0f; } /// <summary> /// Update function, runs every frame, handles mouse delta inputs and converts them into rotation for the camera and player gameobjects /// </summary> void Update() { if (Cursor.lockState == CursorLockMode.Locked) { //this if is only in the event that inside the inspector, I decide to only rotate one object, on both axes. if (axes == Axes.XANDY) { float rotationX = transform.localEulerAngles.y + Input.GetAxis("Mouse X") * sensitivityX; rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp(rotationY, minY, maxY); transform.localEulerAngles = new Vector3(-rotationY, rotationX, 0); } //These next 2 elses work separately, X moves the body horizontally else if (axes == Axes.X) { transform.Rotate(0, Input.GetAxis("Mouse X") * sensitivityX, 0); } //This else (Y) moves the head only, makes it feel more realistic. else { rotationY += Input.GetAxis("Mouse Y") * sensitivityY; rotationY = Mathf.Clamp(rotationY, minY, maxY); transform.localEulerAngles = new Vector3(-rotationY, transform.localEulerAngles.y, 0); } } } }
using Publicon.Core.Entities.Concrete; using System.Collections.Generic; using System.Threading.Tasks; namespace Publicon.Core.Repositories.Abstract { public interface ICategoryRepository : IGenericRepository<Category>, IRepository { //new Task<Category> GetByIdAsync(Guid id); Task<bool> ExistByNameAsync(string name); Task<IEnumerable<Category>> FilterAsync(bool? isArchived); //Task<Field> GetFieldAsync(Guid categoryId, Guid fieldId); } }
using UnityEngine; using System.Collections; public class Spawnpoint : MonoBehaviour { /* Denne klassen holder på selve spawnpointet og de forskjellige funksjonen spawnpointet har */ //Har tre objekter, flamme , varsellys og spawnpoint public GameObject flamme; public GameObject varselLys; public GameObject spawnpoint; //Alle spawninger legges til et eget spillobjekt som holder på alle fiendene private GameObject fiendeHolder; void Awake(){ fiendeHolder = GameObject.Find ("FiendeHolder"); } //Slukker flamme public void stengAv(){ flamme.SetActive(false); varselLys.SetActive(false); } //Tenner flamme public void tennLys(){ flamme.SetActive(true); varselLys.SetActive(true); } //Spawner fienden som er mottatt fra spawnmanager public void SpawnFiende(GameObject fiende){ //Lager et game objekt som skal instansieres GameObject fiendeInstance; // instantiater (spawner) fiende på plasseringen til spawnpoint fra listen med tilfeldige spawnpoints fiendeInstance = Instantiate(fiende, spawnpoint.transform.position, Quaternion.identity) as GameObject; // legger de i et annet gameobject (for orden i hierarkiet) fiendeInstance.transform.parent = fiendeHolder.transform; } }
/********************************************************************************** Simple Smart Types Lite https://github.com/dgakh/SSTypes ----------------------- The MIT License (MIT) Copyright (c) 2016 Dmitriy Gakh ( dmgakh@gmail.com ). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. **********************************************************************************/ namespace SSTypes { /// <summary> /// Class containing useful fields, methods, and properties need for other classes or /// for general internal purposes. /// </summary> internal static class HelperInternal { // https://msdn.microsoft.com/en-us/library/system.random%28v=vs.110%29.aspx private static System.Random random_generator = new System.Random(); /// <summary> /// Returns common System.Random object that can be used for general purposes. /// The method is not thread safe. /// </summary> internal static System.Random GetRandomGenerator() { return random_generator; } /// <summary> /// Creates new common instance of System.Random object. /// The method is not thread safe. /// </summary> internal static void ResetRandomGenerator() { random_generator = new System.Random(); } /// <summary> /// Creates new instance of System.Random object with specific seed. /// The method is not thread safe. /// </summary> /// <param name="seed">Seed for the new common System.Random object.</param> internal static void ResetRandomGenerator(int seed) { random_generator = new System.Random(seed); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ArticleSubmitTool.Domain; using ArticleSubmitTool.Models; using ArticleSubmitTool.Models.InstantArticles; using ArticleSubmitTool.Shared; using ArticleSubmitTool.Shared.Helpers; using ArticleSubmitTool.Web.Models.InstantArticles; using InstantArticleItemType = ArticleSubmitTool.Web.Models.InstantArticles.InstantArticleItemType; namespace ArticleSubmitTool.Code { public static class Mapper { public static void Initialize() { AutoMapper.Mapper.Initialize(cfg => { #region model to vm mappings cfg.CreateMap<User, UserModel>(); cfg.CreateMap<UserSetting, UserSettingModel>(); cfg.CreateMap<FacebookPage, FacebookPageModel>(); cfg.CreateMap<Domain.InstantArticleItemType, InstantArticleItemTypeModel>().MaxDepth(1); var attrDic = Common.ItemData.ToDictionary(data => data.Key, data => data.Value.Attributes.ToDictionary(a => a.Name, a => a)); cfg.CreateMap<InstantArticleItem, InstantArticleItemModel>().MaxDepth(2) .ForMember(dest => dest.Attributes, opt => opt.MapFrom(src => BinarySerializer.Deserialize<Dictionary<string, string>>(src.Attributes) .Select( kvp => new InstantArticleItemAttribute( attrDic[(InstantArticleItemType) src.ItemTypeId][kvp.Key]) { Value = kvp.Value }))) .ForMember(dest => dest.Children, opt => opt.MapFrom( src => src.Children.ToList())) .ForMember(dest => dest.Parent, opt => opt.MapFrom(src => src.Parent)); cfg.CreateMap<InstantArticle, InstantArticleModel>() .ForMember(dest => dest.Attributes, opt => opt.MapFrom(src => BinarySerializer.Deserialize<Dictionary<string, string>>(src.Attributes))) .ForMember(dest => dest.Items, opt => opt.MapFrom(src => src.Items.ToList())) .ForMember(dest => dest.Authors, opt => opt.MapFrom(src => BinarySerializer.Deserialize<List<string>>(src.Authors))); #endregion #region vm to model mappings cfg.CreateMap<UserModel, User>(); cfg.CreateMap<FacebookPageModel, FacebookPage>(); cfg.CreateMap<UserSettingModel, UserSetting>(); cfg.CreateMap<InstantArticleItemTypeModel, Domain.InstantArticleItemType>(); cfg.CreateMap<InstantArticleItemModel, InstantArticleItem>().MaxDepth(2) .ForMember(dest => dest.Attributes, opt => opt.MapFrom( src => BinarySerializer.Serialize<Dictionary<string, string>>( src.Attributes.ToDictionary(a => a.Name, a => a.Value)))) .ForMember(dest => dest.Children, opt => opt.MapFrom(src => src.Children.ToList())) .ForMember(dest => dest.Parent, opt => opt.MapFrom(src => src.Parent)); cfg.CreateMap<InstantArticleModel, InstantArticle>() .ForMember(dest => dest.Attributes, opt => opt.MapFrom( src => BinarySerializer.Serialize<Dictionary<string, string>>( src.Attributes.ToDictionary(a => a.Name, a => a.Value)))) .ForMember(dest => dest.Items, opt => opt.MapFrom(src => src.Items)) .ForMember(dest => dest.Authors, opt => opt.MapFrom( src => BinarySerializer.Serialize<List<string>>( src.Authors.ToList()))); #endregion }); } public static IEnumerable<M> CreateModels<VM, M>(IEnumerable<VM> vmCol) { return vmCol.Select<VM, M>(vm => CreateModel<VM, M>(vm)); } public static IEnumerable<VM> CreateViewModels<M, VM>(IEnumerable<M> mCol) { return mCol.Select<M, VM>(m => CreateViewModel<M, VM>(m)); } public static M CreateModel<VM, M>(VM vm) { var model = AutoMapper.Mapper.Map<VM, M>(vm); return model; } public static VM CreateViewModel<M, VM>(M model) { var vm = AutoMapper.Mapper.Map<M, VM>(model); return vm; } } }
using System.IO; using System.Linq; using System.Net; using System.Text; using System.Text.RegularExpressions; using CloneDeploy_ApiCalls; using CloneDeploy_Common; using CloneDeploy_Entities.DTOs; using log4net; namespace CloneDeploy_Services.Workflows { public class DefaultBootMenu { private const string NewLineChar = "\n"; private readonly Regex _alphaNumericNoSpace = new Regex("[^a-zA-Z0-9]"); private readonly Regex _alphaNumericSpace = new Regex("[^a-zA-Z0-9 ]"); private readonly BootEntryServices _bootEntryServices; private readonly BootMenuGenOptionsDTO _defaultBoot; private readonly string _globalComputerArgs = SettingServices.GetSettingValue(SettingStrings.GlobalComputerArgs); private readonly SecondaryServerServices _secondaryServerServices; private readonly string _webPath = SettingServices.GetSettingValue(SettingStrings.WebPath)+ "api/ClientImaging/"; private readonly ILog log = LogManager.GetLogger(typeof(DefaultBootMenu)); public DefaultBootMenu(BootMenuGenOptionsDTO defaultBootMenu) { _defaultBoot = defaultBootMenu; _bootEntryServices = new BootEntryServices(); _secondaryServerServices = new SecondaryServerServices(); } private string _userToken { get; set; } private void CreateGrubMenu() { var customMenuEntries = _bootEntryServices.SearchBootEntrys() .Where(x => x.Type == "grub" && x.Active == 1) .OrderBy(x => x.Order) .ThenBy(x => x.Name); var defaultCustomEntry = customMenuEntries.FirstOrDefault(x => x.Default == 1); var grubMenu = new StringBuilder(); grubMenu.Append("insmod password_pbkdf2" + NewLineChar); grubMenu.Append("insmod regexp" + NewLineChar); grubMenu.Append("set default=0" + NewLineChar); grubMenu.Append("set timeout=10" + NewLineChar); grubMenu.Append("set pager=1" + NewLineChar); if (!string.IsNullOrEmpty(_defaultBoot.GrubUserName) && !string.IsNullOrEmpty(_defaultBoot.GrubPassword)) { grubMenu.Append("set superusers=\"" + _defaultBoot.GrubUserName + "\"" + NewLineChar); string sha = null; try { sha = new WebClient().DownloadString( "http://docs.clonedeploy.org/grub-pass-gen/encrypt.php?password=" + _defaultBoot.GrubPassword); sha = sha.Replace("\n \n\n\n", ""); } catch { log.Error("Could not generate sha for grub password. Could not contact http://clonedeploy.org"); } grubMenu.Append("password_pbkdf2 " + _defaultBoot.GrubUserName + " " + sha + "" + NewLineChar); grubMenu.Append("export superusers" + NewLineChar); grubMenu.Append("" + NewLineChar); } grubMenu.Append(@"regexp -s 1:b1 '(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3})' $net_default_mac" + NewLineChar); grubMenu.Append(@"regexp -s 2:b2 '(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3})' $net_default_mac" + NewLineChar); grubMenu.Append(@"regexp -s 3:b3 '(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3})' $net_default_mac" + NewLineChar); grubMenu.Append(@"regexp -s 4:b4 '(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3})' $net_default_mac" + NewLineChar); grubMenu.Append(@"regexp -s 5:b5 '(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3})' $net_default_mac" + NewLineChar); grubMenu.Append(@"regexp -s 6:b6 '(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3}):(.{1,3})' $net_default_mac" + NewLineChar); grubMenu.Append(@"mac=01-$b1-$b2-$b3-$b4-$b5-$b6" + NewLineChar); grubMenu.Append("" + NewLineChar); if (_defaultBoot.Type == "standard") { grubMenu.Append("if [ -s /pxelinux.cfg/$mac.cfg ]; then" + NewLineChar); grubMenu.Append("configfile /pxelinux.cfg/$mac.cfg" + NewLineChar); grubMenu.Append("fi" + NewLineChar); } else { grubMenu.Append("if [ -s /proxy/efi64/pxelinux.cfg/$mac.cfg ]; then" + NewLineChar); grubMenu.Append("configfile /proxy/efi64/pxelinux.cfg/$mac.cfg" + NewLineChar); grubMenu.Append("fi" + NewLineChar); } if (defaultCustomEntry != null) { grubMenu.Append("" + NewLineChar); grubMenu.Append("menuentry \"" + _alphaNumericSpace.Replace(defaultCustomEntry.Name, "") + "\" --unrestricted {" + NewLineChar); grubMenu.Append(defaultCustomEntry.Content + NewLineChar); grubMenu.Append("}" + NewLineChar); } grubMenu.Append("" + NewLineChar); grubMenu.Append("menuentry \"Boot To Local Machine\" --unrestricted {" + NewLineChar); grubMenu.Append("exit" + NewLineChar); grubMenu.Append("}" + NewLineChar); grubMenu.Append("" + NewLineChar); grubMenu.Append("menuentry \"CloneDeploy\" --user {" + NewLineChar); grubMenu.Append("echo Please Wait While The Boot Image Is Transferred. This May Take A Few Minutes." + NewLineChar); grubMenu.Append("linux /kernels/" + _defaultBoot.Kernel + " root=/dev/ram0 rw ramdisk_size=156000 " + " web=" + _webPath + " USER_TOKEN=" + _userToken + " consoleblank=0 " + _globalComputerArgs + "" + NewLineChar); grubMenu.Append("initrd /images/" + _defaultBoot.BootImage + "" + NewLineChar); grubMenu.Append("}" + NewLineChar); grubMenu.Append("" + NewLineChar); grubMenu.Append("menuentry \"Client Console\" --user {" + NewLineChar); grubMenu.Append("echo Please Wait While The Boot Image Is Transferred. This May Take A Few Minutes." + NewLineChar); grubMenu.Append("linux /kernels/" + _defaultBoot.Kernel + " root=/dev/ram0 rw ramdisk_size=156000 " + " web=" + _webPath + " USER_TOKEN=" + _userToken + " task=debug consoleblank=0 " + _globalComputerArgs + "" + NewLineChar); grubMenu.Append("initrd /images/" + _defaultBoot.BootImage + "" + NewLineChar); grubMenu.Append("}" + NewLineChar); grubMenu.Append("" + NewLineChar); foreach (var customEntry in customMenuEntries) { if (defaultCustomEntry != null && customEntry.Id == defaultCustomEntry.Id) continue; grubMenu.Append("" + NewLineChar); grubMenu.Append("menuentry \"" + _alphaNumericSpace.Replace(customEntry.Name, "") + "\" --user {" + NewLineChar); grubMenu.Append(customEntry.Content + NewLineChar); grubMenu.Append("}" + NewLineChar); grubMenu.Append("" + NewLineChar); } var path = SettingServices.GetSettingValue(SettingStrings.TftpPath) + "grub" + Path.DirectorySeparatorChar + "grub.cfg"; if (SettingServices.ServerIsNotClustered) new FileOpsServices().WritePath(path, grubMenu.ToString()); else { if (SettingServices.TftpServerRole) new FileOpsServices().WritePath(path, grubMenu.ToString()); foreach (var tftpServer in _secondaryServerServices.GetAllWithTftpRole()) { var tftpPath = new APICall(_secondaryServerServices.GetToken(tftpServer.Name)) .SettingApi.GetSetting("Tftp Path").Value; var tftpFile = new TftpFileDTO(); tftpFile.Contents = grubMenu.ToString(); tftpFile.Path = tftpPath + "grub" + Path.DirectorySeparatorChar + "grub.cfg"; new APICall(_secondaryServerServices.GetToken(tftpServer.Name)) .ServiceAccountApi.WriteTftpFile(tftpFile); } } } private void CreateIpxeMenu() { var replacedPath = _webPath; if (SettingServices.GetSettingValue(SettingStrings.IpxeSSL).Equals("0")) { replacedPath = replacedPath.ToLower().Replace("https", "http"); } var customMenuEntries = _bootEntryServices.SearchBootEntrys() .Where(x => x.Type == "ipxe" && x.Active == 1) .OrderBy(x => x.Order) .ThenBy(x => x.Name); var defaultCustomEntry = customMenuEntries.FirstOrDefault(x => x.Default == 1); var ipxeMenu = new StringBuilder(); ipxeMenu.Append("#!ipxe" + NewLineChar); ipxeMenu.Append("chain 01-${net0/mac:hexhyp}.ipxe || chain 01-${net1/mac:hexhyp}.ipxe || goto Menu" + NewLineChar); ipxeMenu.Append("" + NewLineChar); ipxeMenu.Append(":Menu" + NewLineChar); ipxeMenu.Append("menu Boot Menu" + NewLineChar); ipxeMenu.Append("item bootLocal Boot To Local Machine" + NewLineChar); ipxeMenu.Append("item clonedeploy CloneDeploy" + NewLineChar); ipxeMenu.Append("item console Client Console" + NewLineChar); foreach (var customEntry in customMenuEntries) { ipxeMenu.Append("item " + _alphaNumericNoSpace.Replace(customEntry.Name, "") + " " + _alphaNumericSpace.Replace(customEntry.Name, "") + NewLineChar); } if (defaultCustomEntry == null) ipxeMenu.Append("choose --default bootLocal --timeout 5000 target && goto ${target}" + NewLineChar); else { ipxeMenu.Append("choose --default " + _alphaNumericNoSpace.Replace(defaultCustomEntry.Name, "") + " --timeout 5000 target && goto ${target}" + NewLineChar); } ipxeMenu.Append("" + NewLineChar); if (SettingServices.GetSettingValue(SettingStrings.IpxeRequiresLogin) == "True") { ipxeMenu.Append(":bootLocal" + NewLineChar); ipxeMenu.Append("exit" + NewLineChar); ipxeMenu.Append("" + NewLineChar); ipxeMenu.Append(":console" + NewLineChar); ipxeMenu.Append("set task debug" + NewLineChar); ipxeMenu.Append("goto login" + NewLineChar); ipxeMenu.Append("" + NewLineChar); ipxeMenu.Append(":clonedeploy" + NewLineChar); ipxeMenu.Append("set task ond" + NewLineChar); ipxeMenu.Append("goto login" + NewLineChar); ipxeMenu.Append("" + NewLineChar); ipxeMenu.Append(":login" + NewLineChar); ipxeMenu.Append("login" + NewLineChar); ipxeMenu.Append("params" + NewLineChar); ipxeMenu.Append("param uname ${username:uristring}" + NewLineChar); ipxeMenu.Append("param pwd ${password:uristring}" + NewLineChar); ipxeMenu.Append("param kernel " + _defaultBoot.Kernel + "" + NewLineChar); ipxeMenu.Append("param bootImage " + _defaultBoot.BootImage + "" + NewLineChar); ipxeMenu.Append("param task " + "${task}" + "" + NewLineChar); ipxeMenu.Append("echo Authenticating" + NewLineChar); ipxeMenu.Append("chain --timeout 15000 " + replacedPath + "IpxeLogin##params || goto Menu" + NewLineChar); } else { ipxeMenu.Append(":bootLocal" + NewLineChar); ipxeMenu.Append("exit" + NewLineChar); ipxeMenu.Append("" + NewLineChar); ipxeMenu.Append(":clonedeploy" + NewLineChar); ipxeMenu.Append("kernel " + replacedPath + "IpxeBoot?filename=" + _defaultBoot.Kernel + "&type=kernel" + " initrd=" + _defaultBoot.BootImage + " root=/dev/ram0 rw ramdisk_size=156000 " + " web=" + _webPath + " USER_TOKEN=" + _userToken + " consoleblank=0 " + _globalComputerArgs + NewLineChar); ipxeMenu.Append("imgfetch --name " + _defaultBoot.BootImage + " " + replacedPath + "IpxeBoot?filename=" + _defaultBoot.BootImage + "&type=bootimage" + NewLineChar); ipxeMenu.Append("boot" + NewLineChar); ipxeMenu.Append("" + NewLineChar); ipxeMenu.Append(":console" + NewLineChar); ipxeMenu.Append("kernel " + replacedPath + "IpxeBoot?filename=" + _defaultBoot.Kernel + "&type=kernel" + " initrd=" + _defaultBoot.BootImage + " root=/dev/ram0 rw ramdisk_size=156000 " + " web=" + _webPath + " USER_TOKEN=" + _userToken + " task=debug" + " consoleblank=0 " + _globalComputerArgs + NewLineChar); ipxeMenu.Append("imgfetch --name " + _defaultBoot.BootImage + " " + replacedPath + "IpxeBoot?filename=" + _defaultBoot.BootImage + "&type=bootimage" + NewLineChar); ipxeMenu.Append("boot" + NewLineChar); ipxeMenu.Append("" + NewLineChar); } //Set Custom Menu Entries foreach (var customEntry in customMenuEntries) { ipxeMenu.Append(":" + _alphaNumericNoSpace.Replace(customEntry.Name, "") + NewLineChar); ipxeMenu.Append(customEntry.Content + NewLineChar); } string path; if (_defaultBoot.Type == "standard") path = SettingServices.GetSettingValue(SettingStrings.TftpPath) + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default.ipxe"; else path = SettingServices.GetSettingValue(SettingStrings.TftpPath) + "proxy" + Path.DirectorySeparatorChar + _defaultBoot.Type + Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default.ipxe"; if (SettingServices.ServerIsNotClustered) new FileOpsServices().WritePath(path, ipxeMenu.ToString()); else { if (SettingServices.TftpServerRole) new FileOpsServices().WritePath(path, ipxeMenu.ToString()); foreach (var tftpServer in _secondaryServerServices.GetAllWithTftpRole()) { var tftpPath = new APICall(_secondaryServerServices.GetToken(tftpServer.Name)) .SettingApi.GetSetting("Tftp Path").Value; var tftpFile = new TftpFileDTO(); tftpFile.Contents = ipxeMenu.ToString(); if (_defaultBoot.Type == "standard") tftpFile.Path = tftpPath + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default.ipxe"; else tftpFile.Path = tftpPath + "proxy" + Path.DirectorySeparatorChar + _defaultBoot.Type + Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default.ipxe"; new APICall(_secondaryServerServices.GetToken(tftpServer.Name)) .ServiceAccountApi.WriteTftpFile(tftpFile); } } } private void CreateSyslinuxMenu() { var customMenuEntries = _bootEntryServices.SearchBootEntrys() .Where(x => x.Type == "syslinux/pxelinux" && x.Active == 1) .OrderBy(x => x.Order) .ThenBy(x => x.Name); var defaultCustomEntry = customMenuEntries.FirstOrDefault(x => x.Default == 1); var sysLinuxMenu = new StringBuilder(); sysLinuxMenu.Append("DEFAULT vesamenu.c32" + NewLineChar); sysLinuxMenu.Append("MENU TITLE Boot Menu" + NewLineChar); sysLinuxMenu.Append("MENU BACKGROUND bg.png" + NewLineChar); sysLinuxMenu.Append("menu tabmsgrow 22" + NewLineChar); sysLinuxMenu.Append("menu cmdlinerow 22" + NewLineChar); sysLinuxMenu.Append("menu endrow 24" + NewLineChar); sysLinuxMenu.Append("menu color title 1;34;49 #eea0a0ff #cc333355 std" + NewLineChar); sysLinuxMenu.Append("menu color sel 7;37;40 #ff000000 #bb9999aa all" + NewLineChar); sysLinuxMenu.Append("menu color border 30;44 #ffffffff #00000000 std" + NewLineChar); sysLinuxMenu.Append("menu color pwdheader 31;47 #eeff1010 #20ffffff std" + NewLineChar); sysLinuxMenu.Append("menu color hotkey 35;40 #90ffff00 #00000000 std" + NewLineChar); sysLinuxMenu.Append("menu color hotsel 35;40 #90000000 #bb9999aa all" + NewLineChar); sysLinuxMenu.Append("menu color timeout_msg 35;40 #90ffffff #00000000 none" + NewLineChar); sysLinuxMenu.Append("menu color timeout 31;47 #eeff1010 #00000000 none" + NewLineChar); sysLinuxMenu.Append("NOESCAPE 0" + NewLineChar); sysLinuxMenu.Append("ALLOWOPTIONS 0" + NewLineChar); sysLinuxMenu.Append("" + NewLineChar); sysLinuxMenu.Append("LABEL local" + NewLineChar); sysLinuxMenu.Append("localboot 0" + NewLineChar); if (defaultCustomEntry == null) sysLinuxMenu.Append("MENU DEFAULT" + NewLineChar); sysLinuxMenu.Append("MENU LABEL Boot To Local Machine" + NewLineChar); sysLinuxMenu.Append("" + NewLineChar); sysLinuxMenu.Append("LABEL CloneDeploy" + NewLineChar); if (!string.IsNullOrEmpty(_defaultBoot.OndPwd) && _defaultBoot.OndPwd != "Error: Empty password") sysLinuxMenu.Append("MENU PASSWD " + _defaultBoot.OndPwd + "" + NewLineChar); sysLinuxMenu.Append("kernel kernels" + Path.DirectorySeparatorChar + _defaultBoot.Kernel + "" + NewLineChar); sysLinuxMenu.Append("append initrd=images" + Path.DirectorySeparatorChar + _defaultBoot.BootImage + " root=/dev/ram0 rw ramdisk_size=156000 " + " web=" + _webPath + " USER_TOKEN=" + _userToken + " consoleblank=0 " + _globalComputerArgs + "" + NewLineChar); sysLinuxMenu.Append("MENU LABEL CloneDeploy" + NewLineChar); sysLinuxMenu.Append("" + NewLineChar); sysLinuxMenu.Append("LABEL Client Console" + NewLineChar); if (!string.IsNullOrEmpty(_defaultBoot.DebugPwd) && _defaultBoot.DebugPwd != "Error: Empty password") sysLinuxMenu.Append("MENU PASSWD " + _defaultBoot.DebugPwd + "" + NewLineChar); sysLinuxMenu.Append("kernel kernels" + Path.DirectorySeparatorChar + _defaultBoot.Kernel + "" + NewLineChar); sysLinuxMenu.Append("append initrd=images" + Path.DirectorySeparatorChar + _defaultBoot.BootImage + " root=/dev/ram0 rw ramdisk_size=156000 " + " web=" + _webPath + " USER_TOKEN=" + _userToken + " task=debug consoleblank=0 " + _globalComputerArgs + "" + NewLineChar); sysLinuxMenu.Append("MENU LABEL Client Console" + NewLineChar); sysLinuxMenu.Append("" + NewLineChar); //Insert active custom boot menu entries foreach (var customEntry in customMenuEntries) { sysLinuxMenu.Append("LABEL " + _alphaNumericSpace.Replace(customEntry.Name, "") + NewLineChar); sysLinuxMenu.Append(customEntry.Content + NewLineChar); if (defaultCustomEntry != null && customEntry.Id == defaultCustomEntry.Id) sysLinuxMenu.Append("MENU DEFAULT" + NewLineChar); sysLinuxMenu.Append("MENU LABEL " + _alphaNumericSpace.Replace(customEntry.Name, "") + NewLineChar); sysLinuxMenu.Append("" + NewLineChar); } sysLinuxMenu.Append("PROMPT 0" + NewLineChar); sysLinuxMenu.Append("TIMEOUT 50" + NewLineChar); string path; if (_defaultBoot.Type == "standard") path = SettingServices.GetSettingValue(SettingStrings.TftpPath) + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default"; else path = SettingServices.GetSettingValue(SettingStrings.TftpPath) + "proxy" + Path.DirectorySeparatorChar + _defaultBoot.Type + Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default"; if (SettingServices.ServerIsNotClustered) new FileOpsServices().WritePath(path, sysLinuxMenu.ToString()); else { if (SettingServices.TftpServerRole) new FileOpsServices().WritePath(path, sysLinuxMenu.ToString()); foreach (var tftpServer in _secondaryServerServices.GetAllWithTftpRole()) { var tftpPath = new APICall(_secondaryServerServices.GetToken(tftpServer.Name)) .SettingApi.GetSetting("Tftp Path").Value; var tftpFile = new TftpFileDTO(); tftpFile.Contents = sysLinuxMenu.ToString(); if (_defaultBoot.Type == "standard") tftpFile.Path = tftpPath + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default"; else tftpFile.Path = tftpPath + "proxy" + Path.DirectorySeparatorChar + _defaultBoot.Type + Path.DirectorySeparatorChar + "pxelinux.cfg" + Path.DirectorySeparatorChar + "default"; new APICall(_secondaryServerServices.GetToken(tftpServer.Name)) .ServiceAccountApi.WriteTftpFile(tftpFile); } } } public void Execute() { if (SettingServices.GetSettingValue(SettingStrings.DebugRequiresLogin) == "No" || SettingServices.GetSettingValue(SettingStrings.OnDemandRequiresLogin) == "No" || SettingServices.GetSettingValue(SettingStrings.RegisterRequiresLogin) == "No") _userToken = SettingServices.GetSettingValue(SettingStrings.UniversalToken); else { _userToken = ""; } var mode = SettingServices.GetSettingValue(SettingStrings.PxeMode); if (_defaultBoot.Type == "standard") { if (mode.Contains("ipxe")) CreateIpxeMenu(); else if (mode.Contains("grub")) CreateGrubMenu(); else CreateSyslinuxMenu(); } else { CreateIpxeMenu(); CreateSyslinuxMenu(); CreateGrubMenu(); } } } }
namespace StudentClass { using System; using System.Linq; using System.Text; /*Define a class Student, which contains data about a student – first, middle and last name, SSN, permanent address, mobile phone e-mail, course, specialty, university, faculty. Use an enumeration for the specialties, universities and faculties.*/ public class Student : ICloneable, IComparable { public Student() { } #region Constructors public Student(string firstName, string middleName, string lastName, ulong ssn, string address, string phone, string email) { this.FirstName = firstName; this.MiddleName = middleName; this.LastName = lastName; this.SSN = ssn; this.Address = address; this.MobilePhone = phone; this.Email = email; } public Student(string firstName, string middleName, string lastName, ulong ssn, string address, string phone, string email, int course, UniversityName university, FacultyName faculty, SpecialtyName specialty) : this(firstName, middleName, lastName, ssn, address, phone, email) { this.Course = course; this.University = university; this.Faculty = faculty; this.Specialty = specialty; } #endregion #region Properties public string FirstName { get; set; } public string MiddleName { get; set; } public string LastName { get; set; } public ulong SSN { get; set; } public string Address { get; set; } public string MobilePhone { get; set; } public string Email { get; set; } public int Course { get; set; } public SpecialtyName Specialty { get; set; } public UniversityName University { get; set; } public FacultyName Faculty { get; set; } #endregion public enum SpecialtyName { AICS, E, EE, EPE, EPSPT, ID, IM, HE, NAMT, RES, RM, SIT, SM, TEI, TET } public enum UniversityName { Technical_University_of_Sofia, Technical_University_of_Varna, Technical_University_of_Rousse } public enum FacultyName { Computer_Science_and_Information_Technology, Electronic_Engineering, Electronics_and_Automation, Marine_Sciences_and_Ecology, Mechanical_Engineering, Telecommunications, } public override bool Equals(object obj) { var student = obj as Student; if (this.FirstName == student.FirstName && this.MiddleName == student.MiddleName && this.LastName == student.LastName && this.SSN == student.SSN && this.Address == student.Address && this.MobilePhone == student.MobilePhone && this.Email == student.Email && this.Course == student.Course && this.Specialty == student.Specialty && this.Faculty == student.Faculty && this.University == student.University) return true; return false; } public override string ToString() { var sb = new StringBuilder(); var name = new StringBuilder(); name.Append(this.FirstName); name.Append(" "); name.Append(this.MiddleName); name.Append(" "); name.Append(this.LastName); name.Append(" "); sb.Append(new string('_', 45)); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", this.GetType().Name.ToUpper(), name.ToString()); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "SSN", this.SSN); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "ADDRESS", this.Address); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "PHONE", this.MobilePhone); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "E-MAIL", this.Email); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "COURSE", this.Course); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "UNIVERSITY", this.University.ToString().Replace("_", " ")); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "FACULTY", this.Faculty.ToString().Replace("_", " ")); sb.AppendLine(); sb.AppendFormat("{0,-10}: {1}", "SPECIALTY", this.Specialty); sb.AppendLine(); sb.Append(new string('_', 45)); return sb.ToString(); } public override int GetHashCode() { var sumSNN = this.SSN.ToString().Select(x => int.Parse(x.ToString())).ToArray().Sum(); sumSNN += 2; var addition = (int)(this.SSN / (ulong)sumSNN); return base.GetHashCode() + addition; } public static bool operator ==(Student studentFirst, Student studentSecond) { return studentFirst.Equals(studentSecond); } public static bool operator !=(Student studentFirst, Student studentSecond) { return !(studentFirst.Equals(studentSecond)); } public object Clone() { Student studentClone = new Student( this.FirstName, this.MiddleName, this.LastName, this.SSN, this.Address, this.MobilePhone, this.Email, this.Course, this.University, this.Faculty, this.Specialty); return studentClone; } public int CompareTo(object obj) { var student = obj as Student; if (this.FirstName.CompareTo(student.FirstName) <= 0) { return student.SSN.CompareTo(this.SSN); } return this.FirstName.CompareTo(student.FirstName); } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.IO; using System.Net.Http; using System.Threading.Tasks; using InfiniteMeals.Meals.Model; using Newtonsoft.Json.Linq; using Xamarin.Forms; using InfiniteMeals.Information; using Plugin.LatestVersion; using InfiniteMeals.PromptAddress; using Newtonsoft.Json; namespace InfiniteMeals { public partial class SelectMealOptions : ContentPage { private int mealOrdersCount = 0; public ObservableCollection<MealsModel> Meals = new ObservableCollection<MealsModel>(); private string kitchenID; private string kitchenZipcode; private string availableZipcode; public SelectMealOptions(string kitchen_id, string kitchen_name, string zipcode, string available_zipcode) { InitializeComponent(); SetBinding(TitleProperty, new Binding(kitchen_name)); kitchenID = kitchen_id; kitchenZipcode = zipcode; availableZipcode = available_zipcode; Console.WriteLine("kitchen_id = " + kitchen_id); Console.WriteLine("kitchen_name = " + kitchen_name); Console.WriteLine("zipcode = " + zipcode); Console.WriteLine("avaiable_zipcode" + available_zipcode); GetMeals(kitchenID); mealsListView.RefreshCommand = new Command(() => { GetMeals(kitchenID); mealsListView.IsRefreshing = false; }); } // GET MEALS FUNCTION UPDATED BY CARLOS protected async Task GetMeals(string kitchen_id) { // Console.WriteLine("kitchen_name: " + kitchen_name); NoMealsLabel.IsVisible = false; var request = new HttpRequestMessage(); request.RequestUri = new Uri("https://tsx3rnuidi.execute-api.us-west-1.amazonaws.com/dev/api/v2/itemsByBusiness/" + kitchen_id); request.Method = HttpMethod.Get; var client = new HttpClient(); HttpResponseMessage response = await client.SendAsync(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { HttpContent content = response.Content; var mealsString = await content.ReadAsStringAsync(); JObject meals = JObject.Parse(mealsString); String todaysDate = DateTime.Now.ToString("MM/dd/yyyy"); Console.WriteLine("This is what you see in meals" + meals); string items = await response.Content.ReadAsStringAsync(); ServingFreshBusinessItems data = new ServingFreshBusinessItems(); data = JsonConvert.DeserializeObject<ServingFreshBusinessItems>(items); if (todaysDate[0] == '0') { todaysDate = todaysDate.Substring(1); } todaysDate = todaysDate.Replace("/0", "/"); this.Meals.Clear(); NoMealsLabel.IsVisible = false; for(int i = 0; i < data.result.result.Count; i++) { NoMealsLabel.IsVisible = false; this.Meals.Add(new MealsModel() { imageString = data.result.result[i].item_photo, title = data.result.result[i].item_name, price = data.result.result[i].item_price.ToString(), description = "description", kitchen_id = data.result.result[i].itm_business_uid, id = data.result.result[i].item_uid, qty = 0 } ); } mealsListView.ItemsSource = Meals; } } // FUNCTION UPDATED BY CARLOS // THE VERSION ELSE STATEMENT WAS REMOVE FOR TESTING PURPOSES async void Handle_Clicked(object sender, System.EventArgs e) { //var isLatest = await CrossLatestVersion.Current.IsUsingLatestVersion(); if (mealOrdersCount == 0) { await DisplayAlert("Order Error", "Please make an order to continue", "Continue"); } //else if (!isLatest) //{ // await DisplayAlert("Update Required", "Please download the latest version of Serving Now from the app store", "Ok"); // await CrossLatestVersion.Current.OpenAppInStore(); //} //else //{ var secondPage = new CheckOutPage(Meals, kitchenID, kitchenZipcode, availableZipcode); await Navigation.PushAsync(secondPage); //} //var checkoutPage = new CheckOutPage(); //await Navigation.PushAsync(checkoutPage); } private void reduceOrders(object sender, System.EventArgs e) { var button = (ImageButton)sender; var mealObject = (MealsModel)button.CommandParameter; if (mealObject != null) { if (mealObject.qty > 0) { mealObject.qty -= 1; mealOrdersCount -= 1; } } } private void addOrders(object sender, System.EventArgs e) { var button = (ImageButton)sender; var mealObject = (MealsModel)button.CommandParameter; if (mealObject != null) { if (mealObject.qty < 50) { mealObject.qty += 1; mealOrdersCount += 1; } } } void NavigateToInformation(object sender, EventArgs e) { Navigation.PushAsync(new InformationPage()); } void PromptForAddress(object sender, EventArgs e) { Navigation.PushAsync(new PromptAddressPage()); } //public string createUrl() //{ // DateTime dateTime = DateTime.UtcNow.Date; // var today = dateTime.ToString("yyyyMMdd"); // string url = "https://s3-us-west-2.amazonaws.com/ordermealapp/" + today; // return url; //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.ComponentModel; namespace SKT.MES.Web.Controls { [ToolboxData("<{0}:DropDownGroup runat=server></{0}:DropDownGroup>")] public class DropDownGroup : DropDownList { /// <summary> /// 构造函数 /// </summary> public DropDownGroup() { } /// <summary> /// 将控件的内容呈现到指定的编写器中 /// </summary> /// <param name="writer"></param> protected override void RenderContents(HtmlTextWriter writer) { OptionGroupRenderContents(writer); } /// <summary> /// 呈现Option或OptionGroup /// </summary> /// <param name="writer">writer</param> private void OptionGroupRenderContents(HtmlTextWriter writer) { // 是否需要呈现OptionGroup的EndTag bool writerEndTag = false; foreach (ListItem li in this.Items) { // 如果没有optgroup属性则呈现Option if (li.Value != this.OptionGroupValue) { // 呈现Option RenderListItem(li, writer); } // 如果有optgroup属性则呈现OptionGroup else { if (writerEndTag) // 呈现OptionGroup的EndTag OptionGroupEndTag(writer); else writerEndTag = true; // 呈现OptionGroup的BeginTag OptionGroupBeginTag(li, writer); } } if (writerEndTag) // 呈现OptionGroup的EndTag OptionGroupEndTag(writer); } /// <summary> /// 呈现OptionGroup的BeginTag /// </summary> /// <param name="li">OptionGroup数据项</param> /// <param name="writer">writer</param> private void OptionGroupBeginTag(ListItem li, HtmlTextWriter writer) { writer.WriteBeginTag("optgroup"); // 写入OptionGroup的label writer.WriteAttribute("label", li.Text); foreach (string key in li.Attributes.Keys) { // 写入OptionGroup的其它属性 writer.WriteAttribute(key, li.Attributes[key]); } writer.Write(HtmlTextWriter.TagRightChar); writer.WriteLine(); } /// <summary> /// 呈现OptionGroup的EndTag /// </summary> /// <param name="writer">writer</param> private void OptionGroupEndTag(HtmlTextWriter writer) { writer.WriteEndTag("optgroup"); writer.WriteLine(); } /// <summary> /// 呈现Option /// </summary> /// <param name="li">Option数据项</param> /// <param name="writer">writer</param> private void RenderListItem(ListItem li, HtmlTextWriter writer) { writer.WriteBeginTag("option"); // 写入Option的Value writer.WriteAttribute("value", li.Value, true); if (li.Selected) { // 如果该Option被选中则写入selected writer.WriteAttribute("selected", "selected", false); } foreach (string key in li.Attributes.Keys) { // 写入Option的其它属性 writer.WriteAttribute(key, li.Attributes[key]); } writer.Write(HtmlTextWriter.TagRightChar); // 写入Option的Text HttpUtility.HtmlEncode(li.Text, writer); writer.WriteEndTag("option"); writer.WriteLine(); } /// <summary> /// 用于添加SmartDropDownList的分组项的ListItem的Value值 /// </summary> [ Browsable(true), Description("用于添加DropDownList的分组项的ListItem的Value值"), Category("扩展") ] public virtual string OptionGroupValue { get { string s = (string)ViewState["OptionGroupValue"]; return (s == null) ? "optgroup" : s; } set { ViewState["OptionGroupValue"] = value; } } } }
 namespace MFW.LALLib { public enum ErrorNumberEnum { UNKNOWN = -1, //(-1), PLCM_SAMPLE_OK, //(0), /*sample code error number representing OK*/ /*SDK error number*/ PLCM_MFW_ERR_INVALID_HANDLE, //(1), PLCM_MFW_ERR_MOREDATA, //(2), PLCM_MFW_ERR_INVALID_DEVICETYPE, //(3), PLCM_MFW_ERR_NOTIMPLEMENTED, //(4), PLCM_MFW_ERR_NOTSUPPORTED, //(5), PLCM_MFW_ERR_INVALID_MESSAGEQ, //(6), PLCM_MFW_ERR_INVALID_STREAMINFO, //(7), PLCM_MFW_ERR_INVALID_WND, //(8), PLCM_MFW_ERR_INTERNAL, //(9), PLCM_MFW_ERR_INVALIDCALL, //(10), PLCM_MFW_ERR_INVALID_PARAMETER, //(11), PLCM_MFW_ERR_WARNING_SENDING_CONTENT, //(12), PLCM_MFW_ERR_INVALID_DEVICE, //(13), PLCM_MFW_ERR_INVALID_CAPS, //(14), PLCM_MFW_ERR_INVALID_KVLIST, //(15), PLCM_MFW_ERR_UNSUPPORT_NEON, //(16), PLCM_MFW_ERR_GENERIC, //(17), PLCM_MFW_ERR_ENCRYPTION_CONFIG, //(18), PLCM_MFW_ERR_CALL_EXCEED_MAXIMUM_CALLS, //(19), PLCM_MFW_ERR_CALL_IN_REGISTERING, //(20), PLCM_MFW_ERR_CALL_INVALID_FORMAT, //(21), PLCM_MFW_ERR_CALL_NO_CONNECT, //(22), PLCM_MFW_ERR_CALL_HOST_UNKNOWN, //(23), PLCM_MFW_ERR_CALL_EXIST, //(24), PLCM_MFW_ERR_CALL_INVALID_OPERATION, //(25), PLCM_MFW_ERR_INVOKEAPI_INCALLBACK, //(26), PLCM_MFW_ERR_PLAYBACK_FILE_NON_EXIST, //(27), //MORE...add SDK error code /*sample code error number, start from 129*/ PLCM_SAMPLE_INVALID_CALLHANDLE= -1, //(0xffffffff), PLCM_SAMPLE_ERRNO_START = 128, //(128), PLCM_SAMPLE_LOADDLL_FAIL, //(PLCM_SAMPLE_ERRNO_START.getValue() + 1), PLCM_SAMPLE_LOADDLL_FUNC_FAIL, //(PLCM_SAMPLE_ERRNO_START.getValue() + 2), PLCM_SAMPLE_KVLISTINST_NULL, //(PLCM_SAMPLE_ERRNO_START.getValue() + 3), PLCM_SAMPLE_CALLBACK_NULL, //(PLCM_SAMPLE_ERRNO_START.getValue() + 4), PLCM_SAMPLE_REGISTER_FAIL, //(PLCM_SAMPLE_ERRNO_START.getValue() + 5), PLCM_SAMPLE_SHARE_CONTENT_FAIL, //(PLCM_SAMPLE_ERRNO_START.getValue() + 6), PLCM_SAMPLE_UPDATECONFIG_FAIL, //(PLCM_SAMPLE_ERRNO_START.getValue() + 7), PLCM_SAMPLE_NULL_CALLHANDLE, //(PLCM_SAMPLE_ERRNO_START.getValue() + 8), PLCM_SAMPLE_NULL_DEVICE, //(PLCM_SAMPLE_ERRNO_START.getValue() + 9), PLCM_SAMPLE_NULL_CALLEE_ADDR, //(PLCM_SAMPLE_ERRNO_START.getValue() + 10), PLCM_SAMPLE_NULL_DEVICE_NAME //(PLCM_SAMPLE_ERRNO_START.getValue() + 11); //MORE...add sample error code } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Entidade { [Serializable] public class EAssociado { public EAssociado() { tipoAssociado = new ETipoAssociado(); } public int identificador { get; set; } public string nome { get; set; } public string endereco { get; set; } public string telefone { get; set; } public ETipoAssociado tipoAssociado { get; set; } } }
using System.Collections.Generic; using Microsoft.OpenApi.Models; namespace Peppy.Swagger { public class SecurityOptions { public SecurityOptions() { Name = "Bearer"; OpenApiSecurityScheme = new OpenApiSecurityScheme { Description = "JWT Bearer 授权 \"Authorization: Bearer+空格+token\"", Name = "Authorization", In = ParameterLocation.Header, Type = SecuritySchemeType.ApiKey }; } public string Name { get; set; } public OpenApiSecurityScheme OpenApiSecurityScheme { get; set; } public IEnumerable<string> Scopes { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL_DAL { public partial class SANPHAM { private string _TENLSP; public string TENLSP { get { return _TENLSP; } set { _TENLSP = value; } } public SANPHAM(SANPHAM sp, string tenloai) { this.MASP = sp.MASP; this.TENSP = sp.TENSP; this.TRANGTHAI = sp.TRANGTHAI; this.TENLSP = tenloai; this.HINHANH = sp.HINHANH; this.GIABAN = sp.GIABAN; this.MALSP = sp.MALSP; } } }
using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace BuildingBlocks.Mvc { public static class ModelStateExtensions { public static BadRequestObjectResult GenerateBadRequestFromExceptions( this ModelStateDictionary modelState ) { var errors = modelState.Values .SelectMany(value => value.Errors) .Select(error => error.Exception.InnerException.Message) .ToArray(); return new BadRequestObjectResult(errors); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; namespace XMLSample { class MyXHandler { private string _Path; private XmlDocument XDoc = new XmlDocument(); public MyXHandler(string path) { this._Path = path; } public void Handle1() { this.XDoc.Load(this._Path); XmlElement xRoot = this.XDoc.DocumentElement; XmlNodeList childnodes = xRoot.SelectNodes("*"); foreach (XmlNode n in childnodes) Console.WriteLine(n.OuterXml); } public void Handle2() { XmlElement xRoot = this.XDoc.DocumentElement; XmlNodeList childnodes = xRoot.SelectNodes("user"); foreach (XmlNode n in childnodes) Console.WriteLine(n.SelectSingleNode("@name").Value); } public void Handle3() { XmlElement xRoot = this.XDoc.DocumentElement; XmlNode childnode = xRoot.SelectSingleNode("user[@name='Bill Gates']"); if (childnode != null) Console.WriteLine(childnode.OuterXml); } public void Handle4() { XmlElement xRoot = this.XDoc.DocumentElement; XmlNode childnode = xRoot.SelectSingleNode("user[company='Microsoft']"); if (childnode != null) Console.WriteLine(childnode.OuterXml); } public void Handle5() { XmlElement xRoot = this.XDoc.DocumentElement; XmlNodeList childnodes = xRoot.SelectNodes("//user/company"); foreach (XmlNode n in childnodes) Console.WriteLine(n.InnerText); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Business.Abstract; using Business.Service; using Domain.Entity; using PresentationMVC.Models; using Business.Common; namespace PresentationMVC.Controllers { public class StaffController : Controller { #region Actions /// <summary> /// Load the Staff main page /// </summary> /// <returns></returns> [HttpGet] public ActionResult Index() { Session.Remove(Constants.STAFF_SEARCH_SESSION); StaffDataModel model = GetStaffDataModel(); return View(model); } /// <summary> /// Load the staff in the form to update the details /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet] public ActionResult Edit(long id) { IStaffService srv = new StaffServiceImpl(); Staff staff = srv.GetStaffById(id); staff.InitialEmail = staff.Email; StaffDataModel model = GetStaffDataModel(staff); return View("Index", model); } /// <summary> /// Delete the staff /// </summary> /// <param name="id"></param> /// <returns></returns> [HttpGet] public ActionResult Delete(long id) { IStaffService srv = new StaffServiceImpl(); Staff staff = srv.GetStaffById(id); srv.DeleteStaff(staff); ViewData["DELETE_MSG"] = "Successsfully deleted the record."; this.ViewData.Model = GetStaffDataModel(); return PartialView("StaffGridPartial"); } [HttpGet] public ActionResult ReloadGrid() { StaffDataModel model = GetStaffDataModel(); this.ViewData.Model = model; return PartialView("StaffGridPartial", model); } [HttpPost] public ActionResult GridviewSearch(StaffDataModel model) { Session[Constants.STAFF_SEARCH_SESSION] = model.StaffSearch; this.ViewData.Model = GetStaffDataModel(); return PartialView("StaffGridPartial"); } /// <summary> /// Save the staff details /// </summary> /// <param name="model"></param> /// <returns></returns> [HttpPost] public ActionResult Save(StaffDataModel model) { return SaveOrUpdate(model); } [HttpGet] public JsonResult EmailAvailable(StaffDataModel model) { if (model.Staff.Email != model.Staff.InitialEmail) { IStaffService srv = new StaffServiceImpl(); Staff staff = srv.GetStaffByEmail(model.Staff.Email); if (staff == null) { return Json(true, JsonRequestBehavior.AllowGet); } else { return Json(string.Format("{0} already exist", Request.QueryString["Staff.Email"]), JsonRequestBehavior.AllowGet); } } else { return Json(true, JsonRequestBehavior.AllowGet); } } #endregion #region Private Methods private StaffDataModel GetStaffDataModel() { return GetStaffDataModel(null); } private StaffDataModel GetStaffDataModel(Staff staff) { IStaffService srv = new StaffServiceImpl(); IList<Staff> lstStaff = new List<Staff>(); if (Session[Constants.STAFF_SEARCH_SESSION] == null) { lstStaff = srv.GetAllStaffs(); } else { StaffDataModel sdm = new StaffDataModel(); sdm.StaffSearch = Session[Constants.STAFF_SEARCH_SESSION] as StaffSearchModel; lstStaff = srv.GetAllStaffs(sdm.StaffSearch.SearchBy, sdm.StaffSearch.Value); } StaffDataModel model = new StaffDataModel(); model.Staff = staff == null ? new Staff() : staff; model.AllStaff = lstStaff; return model; } /// <summary> /// Base on the staff object it create a new staff record or update already existing record. /// </summary> /// <param name="model"></param> /// <returns></returns> private ActionResult SaveOrUpdate(StaffDataModel model) { Staff staff = model.Staff; IStaffService staffSrv = new StaffServiceImpl(); if (ModelState.IsValid) { try { if (staff.ID > 0) { Staff tmpStaff = staffSrv.GetStaffById(staff.ID); tmpStaff.FirstName = staff.FirstName; tmpStaff.LastName = staff.LastName; tmpStaff.Email = staff.Email; tmpStaff.AddressLine1 = staff.AddressLine1; tmpStaff.AddressLine2 = staff.AddressLine2; tmpStaff.City = staff.City; tmpStaff.County = staff.County; tmpStaff.Country = staff.Country; tmpStaff.Postcode = staff.Postcode; tmpStaff.UpdatedDate = staff.UpdatedDate; tmpStaff.Title = staff.Title; tmpStaff.UpdatedDate = DateTime.Now; staffSrv.UpdateStaff(tmpStaff); ViewData["MSG"] = "Successfully updated the details."; } else { staffSrv.SaveStaff(staff); ViewData["MSG"] = "Successfully saved the details."; } ModelState.Clear(); staff = new Staff(); model.Staff = staff; } catch (Exception ex) { ModelState.AddModelError("", "Error" + ex.ToString()); } } IStaffService srv = new StaffServiceImpl(); model.AllStaff = srv.GetAllStaffs(); return RedirectToAction("Index"); ; } #endregion } }
using System; using System.Collections.Generic; using System.Net; using Microsoft.Win32; namespace Luminous { public static class Miscellaneous { public static string GetLocalGuid() { var location = @"SOFTWARE\Microsoft\Cryptography"; var name = "MachineGuid"; using (var localMachineX64View = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)) { using (var rk = localMachineX64View.OpenSubKey(location)) { if (rk == null) throw new KeyNotFoundException( string.Format("Key Not Found: {0}", location)); var machineGuid = rk.GetValue(name); if (machineGuid == null) throw new IndexOutOfRangeException( string.Format("Index Not Found: {0}", name)); return machineGuid.ToString(); } } } public static string getIp() { return new WebClient().DownloadString("http://program.ellis.pw/auth.php"); } public static string getDate() { return new WebClient().DownloadString("http://program.ellis.pw/date.php"); } public static string randomString( string charz = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", int length = 8) { var chars = charz; var stringChars = new char[length]; var random = new Random(); for (var i = 0; i < stringChars.Length; i++) stringChars[i] = chars[random.Next(chars.Length)]; var finalString = new string(stringChars); return finalString; } } }
using CrazyPost.Models; using System.Collections.Generic; using System.Threading.Tasks; namespace CrazyPost.Repository { public interface ICommentRepository { Task Add(Comment item); Task<IEnumerable<Comment>> GetAll(); Task<Comment> Find(int id); Task Remove(int id); Task Update(int id, Comment item); } }
using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; namespace Umbraco.Core { /// <summary> /// Utility methods for the <see cref="Guid"/> struct. /// </summary> internal static class GuidUtils { /// <summary> /// Combines two guid instances utilizing an exclusive disjunction. /// The resultant guid is not guaranteed to be unique since the number of unique bits is halved. /// </summary> /// <param name="a">The first guid.</param> /// <param name="b">The seconds guid.</param> /// <returns></returns> [MethodImpl(MethodImplOptions.AggressiveInlining)] public static Guid Combine(Guid a, Guid b) { var ad = new DecomposedGuid(a); var bd = new DecomposedGuid(b); ad.Hi ^= bd.Hi; ad.Lo ^= bd.Lo; return ad.Value; } /// <summary> /// A decomposed guid. Allows access to the high and low bits without unsafe code. /// </summary> [StructLayout(LayoutKind.Explicit)] private struct DecomposedGuid { [FieldOffset(00)] public Guid Value; [FieldOffset(00)] public long Hi; [FieldOffset(08)] public long Lo; public DecomposedGuid(Guid value) : this() => this.Value = value; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using ViewProject.ViewModels.Common; namespace ViewProject.ViewModels { public class HomeViewModel : BaseViewModel { #region Variables private ListeOffreViewModel _listeOffreViewModel = null; #endregion #region Constructeurs public HomeViewModel() { _listeOffreViewModel = new ListeOffreViewModel(); } #endregion #region Data Bindings public ListeOffreViewModel ListeOffreViewModel { get { return _listeOffreViewModel; } set { _listeOffreViewModel = value; } } #endregion } }
using System; namespace Covid_19_Arkanoid.Controlador { public class NoLivesException: Exception { public NoLivesException(string message) : base(message) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Data.SqlClient; using System.Web.Configuration; namespace CIS484Projects { public partial class WebForm1 : System.Web.UI.Page { protected void LoginBtn_Click(object sender, EventArgs e) { //Referencing ConnectionString in Web.config SqlConnection sqlConnection = new SqlConnection(WebConfigurationManager.ConnectionStrings["AUTH"].ConnectionString); sqlConnection.Open(); //Searching for inputted email in database via parameterized query String emailQuery = "SELECT email FROM Users WHERE email = @email"; SqlCommand emailCommand = new SqlCommand(emailQuery, sqlConnection); emailCommand.Parameters.AddWithValue("email", EmailForLoginTextBox.Text); String email = emailCommand.ExecuteScalar().ToString(); //Testing inputted password against associated email via parameterized query String passQuery = "SELECT password FROM Users WHERE email = @email"; SqlCommand passwordCommand = new SqlCommand(passQuery, sqlConnection); passwordCommand.Parameters.AddWithValue("email", EmailForLoginTextBox.Text); String DBpassword = passwordCommand.ExecuteScalar().ToString(); //Closing DB connection sqlConnection.Close(); if (email.Length > 0 && PasswordForLoginTextBox.Text.Equals(DBpassword)) { Session["UserName"] = EmailForLoginTextBox.Text; Response.Redirect("2-HomePage.aspx"); } else { ResultLabel.Text = "This email is not in the database or the password is incorrect."; } } protected void registrationNavButton_Click(object sender, EventArgs e) { Response.Redirect("1a-UserRegPage.aspx"); } protected void AdminLoginBtn_Click(object sender, EventArgs e) { EmailForLoginTextBox.Text = "admin"; PasswordForLoginTextBox.Text = "password"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace HangMan { public class HardCodedWordGenerator : IWordGenerator { private string[] words = new string[10]; public HardCodedWordGenerator() { words[0] = "python"; words[1] = "java"; words[2] = "mississippi"; words[3] = "car"; words[4] = "tacos"; words[5] = "time"; words[6] = "baseball"; words[7] = "watch"; words[8] = "agilethouht"; words[9] = "deloitte"; } public string GetWord() { Random r1 = new Random(); int randomNum = r1.Next(0, 10); return words[randomNum]; }//end getword } }
using Sunny.Lib; using Sunny.Lib.CustomeAttribute; using Xunit; using System; using System.Collections.Generic; using System.Linq; using System.IO; using TestCommon; namespace Sunny.Lib.Test { /// <summary> ///This is a test class for ConvertHelperTest and is intended ///to contain all ConvertHelperTest Unit Tests ///</summary> public class EnvironmentHelperTest { #region Additional test attributes // //You can use the following additional attributes as you write your tests: // //Use ClassInitialize to run code before running the first test in the class //[ClassInitialize()] //public static void MyClassInitialize(TestContext testContext) //{ //} // //Use ClassCleanup to run code after all tests in a class have run //[ClassCleanup()] //public static void MyClassCleanup() //{ //} // //Use TestInitialize to run code before running each test //[TestInitialize()] //public void MyTestInitialize() //{ //} // //Use TestCleanup to run code after each test has run //[TestCleanup()] //public void MyTestCleanup() //{ //} // #endregion [Fact] public void EnvironmentHelper_BVT() { string currentExcDir = EnvironmentHelper.CurrentExecuteDir; string currentProjectDir = EnvironmentHelper.CurrentProjectDir; string currentSolutionDir = EnvironmentHelper.CurrentSolutionDir; string path = @"%ProgramFiles%\Test\Bin"; string path1 = EnvironmentHelper.ExpandEnvironmentVariables(path); string path2 = Path.Combine(Environment.ExpandEnvironmentVariables(@"%systemdrive%\"), @"Program Files (x86)\Test\Bin"); string path3 = EnvironmentHelper.ExpandEnvironmentVariables(path2); Assert.Equal(path3, path1); } } }
using CallLogSystem.Common; using Model; using Repository.Implement; using Repository.Interface; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CallLogSystem.Controllers { public class AccountController : Controller { IAccountRepository accountRepository = new AccountRepository(); // GET: Account public ActionResult Index() { return RedirectToAction("Login"); } [HttpGet] public ActionResult Login() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Login(string username, string password) { AccountModel account = accountRepository.Login(username, password); if (account == null) { ViewBag.notify = "Login Fail!"; return View(); } else { Session.Add(CommonConstants.USER_SESSION, account); return Redirect("/CallLog/Index"); } } public ActionResult Logout() { Session.Abandon(); return RedirectToAction("Login"); } } }
using FatCat.Nes.OpCodes.AddressingModes; namespace FatCat.Nes.OpCodes.Branching { public abstract class BranchOpCode : OpCode { protected abstract CpuFlag Flag { get; } protected abstract bool FlagState { get; } protected BranchOpCode(ICpu cpu, IAddressMode addressMode) : base(cpu, addressMode) { } public override int Execute() { var cycles = 0; var flagSet = cpu.GetFlag(Flag); if (flagSet == FlagState) { cycles++; cpu.AbsoluteAddress = (ushort)(cpu.ProgramCounter + cpu.RelativeAddress); if (HasPaged()) cycles++; cpu.ProgramCounter = cpu.AbsoluteAddress; } return cycles; } private bool HasPaged() => cpu.AbsoluteAddress.ApplyHighMask() != cpu.ProgramCounter.ApplyHighMask(); } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; namespace ECommerceSite.Controllers { [Route("products")] [ApiController] public class ProductsController : ControllerBase { [HttpGet] public IEnumerable<Product> Get() { return GetProducts(); } public List<Product> GetProducts() { var products = new List<Product>(); products.Add(new Product(12, "iPhone 12", "This is the latest iPhone from Apple in 2020.", 1500, "https://store.storeimages.cdn-apple.com/8756/as-images.apple.com/is/iphone-12-pro-blue-hero?wid=940&hei=1112&fmt=png-alpha&qlt=80&.v=1601620623000")); products.Add(new Product(8, "iPhone 8", "This is the Apple iPhone 8", 799, "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQ72H1OXAN9qMk8CHPf-ad8Js7fBruZC2m0pZI9A4ev8lTQu8cTPwDdPJgBFQS30nyYvBwlKmY&usqp=CAc")); products.Add(new Product(20, "Galaxy S20", "This is the latest phone from Samsung this year.", 1400, "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcT3u-xunIVIMNvDq_ltHGm7OR-Yg-PniJcHusP52nQC9_J7luf54AYrmwGVV_ufHzGemw3JBPI&usqp=CAc")); products.Add(new Product(10, "Galaxy S10", "This is the Samsung Galaxy S10. This came out in 2019.", 899, "https://azcd.harveynorman.com.au/media/catalog/product/cache/21/image/992x558/9df78eab33525d08d6e5fb8d27136e95/s/a/samsung-galaxy-s10-128gb-green_1.jpg")); products.Add(new Product(5, "Google Pixel 5", "This is the latest phone from Google", 999, "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcRDjycIVc1560Z6QTyqyAeDdQHIzINRFcWVKHTvhx0vNd_O58YGNZPTPEsUq5-HFZxE4N9P4hBD&usqp=CAc")); products.Add(new Product(2, "iPhone 12 cover", "This is a cover for the latest iPhone 12", 20, "https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcTvAUGTP9SxZ7nFmv5Joz1BOgbGB8maXS7_vIbnvUgUONNA_RsqBhGVE8QZbK1sL2VshCMDtU4&usqp=CAc")); return products; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; using OpenQA.Selenium; using OpenQA.Selenium.Firefox; using OpenQA.Selenium.IE; using OpenQA.Selenium.Support; using OpenQA.Selenium.Chrome; namespace UnitTestSelenium { [TestClass] public class UnitTest1 { private const string IE_DRIVER_PATH = @"C:\SeleniumDriver"; private const string ScreenShotLocation = @"C:\ScreenShot"; [TestMethod] public void TestMethod1() { //IWebDriver driver = new ChromeDriver(IE_DRIVER_PATH); IWebDriver driver = new InternetExplorerDriver(IE_DRIVER_PATH); //IWebDriver driver = new FirefoxDriver(IE_DRIVER_PATH); driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(0.5)); driver.Navigate().GoToUrl("http://localhost:58893/"); IWebElement searchInput=driver.FindElement(By.Id("UserName")); searchInput.SendKeys("jperez"); IWebElement searchInput2 = driver.FindElement(By.Id("Password")); searchInput2.SendKeys("Password1"); IWebElement enter = driver.FindElement(By.Id("btnlogin")); enter.Click(); //searchInput.SendKeys(Keys.Enter); } } }
using System; using System.Net; using System.Net.Mail; using System.Windows.Forms; using EsploraPulse.Static; namespace EsploraPulse.View { /// <summary> /// This class represents a form used for sending an email. /// </summary> /// <author>Jonathan Walker</author> /// <version>11/28/2015</version> public partial class EmailForm : Form { private readonly int bpm; /// <summary> /// Initializes a new instance of the <see cref="EmailForm"/> class. /// </summary> /// <param name="bpm">The BPM or heart rate to email.</param> /// <exception cref="ArgumentOutOfRangeException">@bpm must be greater than or equal to zero</exception> public EmailForm(int bpm) { if (bpm < 0) { throw new ArgumentOutOfRangeException(nameof(bpm), @"bpm must be greater than or equal to zero"); } InitializeComponent(); this.bpm = bpm; } private void sendButton_Click(object sender, EventArgs e) { try { this.sendBPMEmail(); MessageBox.Show(@"Message Sent!", @"Success"); } catch (ArgumentException) { ErrorHandler.DisplayErrorMessage("Invalid Input", "Please enter information into every text box."); return; } catch (FormatException) { ErrorHandler.DisplayErrorMessage("Invalid Input", "Please ensure that your email addresses meet the formatting requirements of email addresses (i.e. address@host.domain)."); return; } catch (SmtpException) { ErrorHandler.DisplayErrorMessage("Authentication Error", "There was a problem authenticating your email account. Please ensure your password is correct. " + "If the password is correct, Gmail may be blocking this app from accessing your email. Please check your email for further instructions."); return; } this.Close(); } private void sendBPMEmail() { var dateAndTime = DateTime.Now; var fromAddress = new MailAddress(this.fromTextBox.Text); var toAddress = new MailAddress(this.toTextBox.Text); var fromPassword = this.passwordTextBox.Text; var subject = dateAndTime.ToString("yyyy MMMM dd") + ": Heart Rate"; var body = "My heart rate was " + this.bpm + " on " + dateAndTime.ToString("yyyy MMMM dd") + " at " + dateAndTime.ToString("hh:mm tt"); var client = new SmtpClient { Host = "smtp.gmail.com", Port = 587, DeliveryMethod = SmtpDeliveryMethod.Network, UseDefaultCredentials = false, EnableSsl = true, Credentials = new NetworkCredential(fromAddress.Address, fromPassword) }; using (var message = new MailMessage(fromAddress, toAddress) { Subject = subject, Body = body }) { client.Send(message); } client.Dispose(); } private void cancelButton_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; this.Close(); } } }
using iCopy.Model.Options; using iCopy.Web.Helper; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.IO; using System.Linq; using System.Net; using System.Security.Claims; using System.Threading.Tasks; namespace iCopy.Web.Controllers { public class UploadController : Controller { private readonly ProfilePhotoOptions profilePhotoOptions; private readonly PrintRequestFileOptions printRequestFileOptions; private readonly IHostingEnvironment hostingEnvironment; public Model.Request.ProfilePhoto FileSession { get => HttpContext.Session.Get<Model.Request.ProfilePhoto>(Session.Keys.Upload.ProfileImage); set => HttpContext.Session.Set<Model.Request.ProfilePhoto>(Session.Keys.Upload.ProfileImage, value); } public Model.Request.PrintRequestFile PrintRequestFileSession { get => HttpContext.Session.Get<Model.Request.PrintRequestFile>(Session.Keys.Upload.PrintRequestFile); set => HttpContext.Session.Set<Model.Request.PrintRequestFile>(Session.Keys.Upload.PrintRequestFile, value); } public UploadController(ProfilePhotoOptions profilePhotoOptions, PrintRequestFileOptions printRequestFileOptions, IHostingEnvironment hostingEnvironment) { this.profilePhotoOptions = profilePhotoOptions; this.printRequestFileOptions = printRequestFileOptions; this.hostingEnvironment = hostingEnvironment; } [HttpPost] public async Task<IActionResult> UploadProfileImage(IFormFile file) { if(FileSession != null && System.IO.File.Exists(FileSession.Path)) System.IO.File.Delete(FileSession.Path); if(file != null) { string filename = Guid.NewGuid().ToString(); while (System.IO.File.Exists(Path.Combine(hostingEnvironment.WebRootPath, "Uploads", profilePhotoOptions.Path, $"{filename}{Path.GetExtension(file.FileName)}"))) filename = Guid.NewGuid().ToString(); string url = Path.Combine("Uploads", profilePhotoOptions.Path, $"{filename}{Path.GetExtension(file.FileName)}"); string path = Path.Combine(hostingEnvironment.WebRootPath, "Uploads", profilePhotoOptions.Path, filename + Path.GetExtension(file.FileName)); if (file.Length > profilePhotoOptions.MaxSize) return StatusCode(StatusCodes.Status413RequestEntityTooLarge); if (!profilePhotoOptions.SupportedContentTypes.Contains(file.ContentType)) return StatusCode(StatusCodes.Status415UnsupportedMediaType); MemoryStream stream = new MemoryStream(); await file.CopyToAsync(stream); System.Drawing.Image image = System.Drawing.Image.FromStream(stream); if (image.Width > profilePhotoOptions.MaxWidth || image.Height > profilePhotoOptions.MaxHeight) image = Helper.Graphics.Image.Resize(image, profilePhotoOptions.MaxWidth, profilePhotoOptions.MaxHeight); FileSession = new Model.Request.ProfilePhoto() { Path = url, FileSystemPath = path, Extension = Path.GetExtension(file.FileName), Name = filename, XResolution = image.HorizontalResolution, YResolution = image.VerticalResolution, Height = image.Height, Width = image.Width, SizeInBytes = stream.Length, Format = image.PixelFormat.ToString(), }; try { using (var filesystemstream = new FileStream(path, FileMode.Create)) { stream.Position = 0; await stream.CopyToAsync(filesystemstream); } } catch(Exception e) { // TODO: Dodati log operaciju return StatusCode((int)HttpStatusCode.InternalServerError); } } return Ok(); } [HttpGet] public Task<OkResult> RemoveUploadedProfileImage() { if (FileSession != null && System.IO.File.Exists(hostingEnvironment.WebRootPath + "\\" + FileSession.Path)) System.IO.File.Delete(hostingEnvironment.WebRootPath + "\\" + FileSession.Path); return Task.FromResult(Ok()); } [HttpPost] public async Task<IActionResult> UploadPrintRequestFile(IFormFile file) { if (PrintRequestFileSession != null && System.IO.File.Exists(PrintRequestFileSession.Path)) System.IO.File.Delete(PrintRequestFileSession.Path); if (file != null) { string filename = Guid.NewGuid().ToString(); while (System.IO.File.Exists(Path.Combine(hostingEnvironment.WebRootPath, "Uploads", printRequestFileOptions.Path, $"{filename}{Path.GetExtension(file.FileName)}"))) filename = Guid.NewGuid().ToString(); string url = Path.Combine("Uploads", printRequestFileOptions.Path, $"{filename}{Path.GetExtension(file.FileName)}"); string path = Path.Combine(hostingEnvironment.WebRootPath, "Uploads", printRequestFileOptions.Path, filename + Path.GetExtension(file.FileName)); if (file.Length > printRequestFileOptions.MaxSize) return StatusCode(StatusCodes.Status413RequestEntityTooLarge); if (!printRequestFileOptions.SupportedContentTypes.Contains(file.ContentType)) return StatusCode(StatusCodes.Status415UnsupportedMediaType); MemoryStream stream = new MemoryStream(); await file.CopyToAsync(stream); PrintRequestFileSession = new Model.Request.PrintRequestFile() { Path = url, FileSystemPath = path, Extension = Path.GetExtension(file.FileName), Name = filename, SizeInBytes = stream.Length }; try { using (var filesystemstream = new FileStream(path, FileMode.Create)) { stream.Position = 0; await stream.CopyToAsync(filesystemstream); } } catch (Exception e) { // TODO: Dodati log operaciju return StatusCode((int)HttpStatusCode.InternalServerError); } } return Ok(); } [HttpGet] public Task<OkResult> RemoveUploadedFile() { if (PrintRequestFileSession != null && System.IO.File.Exists(hostingEnvironment.WebRootPath + "\\" + PrintRequestFileSession.Path)) System.IO.File.Delete(hostingEnvironment.WebRootPath + "\\" + PrintRequestFileSession.Path); return Task.FromResult(Ok()); } } }
using ACBr.Net.Sat; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PDV.VIEW.FRENTECAIXA.MFe.Emissao { public class RetornoMFe { public bool Enviado { get; set; } public string Resposta { get; set; } public CFe CFe { get; set; } public CFeCanc CFeCanc { get; set; } public static explicit operator Action<object>(RetornoMFe v) { throw new NotImplementedException(); } } }
using System.Web; using System.Web.Optimization; namespace App.Server { public class BundleConfig { // For more information on bundling, visit http://go.microsoft.com/fwlink/?LinkId=301862 public static void RegisterBundles(BundleCollection bundles) { bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/knockout").Include( "~/Scripts/knockout-{version}.js")); //bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include( // "~/Scripts/app/jquery.validate*")); // Use the development version of Modernizr to develop with and learn from. Then, when you're // ready for production, use the build tool at http://modernizr.com to pick only the tests you need. //bundles.Add(new ScriptBundle("~/bundles/modernizr").Include( // "~/Scripts/app/modernizr-*")); //bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include( // "~/Scripts/app/bootstrap.js", // "~/Scripts/app/respond.js")); //bundles.Add(new StyleBundle("~/Content/css").Include( // "~/Content/bootstrap.css", // "~/Content/site.css")); //bundles.Add(new ScriptBundle("~/bundles/knockout").Include( // "~/Scripts/app/knockout-{version}.js")); //bundles.Add(new ScriptBundle("~/bundles/app").IncludeDirectory("~/Scripts/app/app/", "*.js", true)); bundles.Add(new ScriptBundle("~/bundles/app").Include( "~/Scripts/app/Common/Utils.js", "~/Scripts/app/Common/Consts.js", "~/Scripts/app/Common/AppSizes.js", "~/Scripts/app/Common/Multilang.js", "~/Scripts/app/Common/HtmlProvider.js", "~/Scripts/app/Common/AppSettings.js", "~/Scripts/app/Infrastructure/WaitDispatcher.js", "~/Scripts/app/Infrastructure/ObservableObject.js", "~/Scripts/app/Infrastructure/Layer.js", "~/Scripts/app/Infrastructure/LayerFasade.js", "~/Scripts/app/Infrastructure/BusinessLayer.js", "~/Scripts/app/Infrastructure/DataLayer.js", "~/Scripts/app/Infrastructure/ViewLayer.js", "~/Scripts/app/Common/Metadata.js", "~/Scripts/app/Common/AttributeUtils.js", "~/Scripts/app/Common/EntityValidator.js", "~/Scripts/app/MsgBox/BMsgBox.js", "~/Scripts/app/MsgBox/VMsgBox.js", "~/Scripts/app/Navigation/VNavigationBar.js", "~/Scripts/app/Root/BRoot.js", "~/Scripts/app/Root/RootDataBorder.js", "~/Scripts/app/Root/RootViewBorder.js", "~/Scripts/app/Root/VRoot.js", "~/Scripts/app/Root/DRoot.js", "~/Scripts/app/LoginForm/BLoginForm.js", "~/Scripts/app/LoginForm/DLoginForm.js", "~/Scripts/app/LoginForm/VLoginForm.js", "~/Scripts/app/LoginForm/LoginFormViewBorder.js", "~/Scripts/app/Popup/BPopup.js", "~/Scripts/app/Popup/VPopup.js", "~/Scripts/app/LoginPanel/BLoginPanel.js", "~/Scripts/app/LoginPanel/VLoginPanel.js", "~/Scripts/app/Sections/BSections.js", "~/Scripts/app/Sections/VSections.js", "~/Scripts/app/Sections/SectionsViewBorder.js", "~/Scripts/app/Tree/VTree.js", "~/Scripts/app/Tree/TreeViewBorder.js", "~/Scripts/app/Tree/BTree.js", "~/Scripts/app/WorkspacePnl/BWorkspacePnl.js", "~/Scripts/app/WorkspacePnl/VWorkspacePnl.js", "~/Scripts/app/Frames/BFramesRoot.js", "~/Scripts/app/Frames/VFramesRoot.js", "~/Scripts/app/UploadDlg/VUploadDlg.js", "~/Scripts/app/UploadDlg/BUploadDlg.js", "~/Scripts/app/Frames/BaseFrame/BBaseFrame.js", "~/Scripts/app/Frames/BaseFrame/VBaseFrame.js", "~/Scripts/app/Frames/BaseFrame/BaseFrameViewBorder.js", "~/Scripts/app/Frames/BaseFrame/BaseFrameDataBorder.js", "~/Scripts/app/Frames/GridFrame/DataGrid/VDataGrid.js", "~/Scripts/app/Frames/GridFrame/DataGrid/BDataGrid.js", "~/Scripts/app/Frames/GridFrame/DataGrid/DataGridViewBorder.js", "~/Scripts/app/Frames/GridFrame/BGridFrame.js", "~/Scripts/app/Frames/GridFrame/VGridFrame.js", "~/Scripts/app/Frames/GridFrame/GridFrameViewBorder.js", "~/Scripts/app/Frames/GridFrame/GridFrameDataBorder.js", "~/Scripts/app/Frames/GridFrame/UnderConstrustionFrame/BUnderConstrustionFrame.js", "~/Scripts/app/Frames/GridFrame/UnderConstrustionFrame/VUnderConstrustionFrame.js", "~/Scripts/app/Frames/GridFrame/Filters/BFilters.js", "~/Scripts/app/Frames/GridFrame/Filters/VFilters.js", "~/Scripts/app/Frames/GridFrame/Filters/FiltersViewBorder.js", "~/Scripts/app/Frames/Commands/BCommandBar.js", "~/Scripts/app/Frames/Commands/CommandBarVBorder.js", "~/Scripts/app/Frames/Commands/VCommandBar.js", "~/Scripts/app/Frames/Commands/CommandHandler.js", "~/Scripts/app/Common/QueryParams.js", "~/Scripts/app/Frames/GridFrame/Paging/BPagingPnl.js", "~/Scripts/app/Frames/GridFrame/Paging/VPagingPnl.js", "~/Scripts/app/Frames/AutoLayoutFrame/LayoutBuilder.js", "~/Scripts/app/Frames/AutoLayoutFrame/FrameBuilder.js", "~/Scripts/app/Frames/AutoLayoutFrame/BAutoLayoutFrame.js", "~/Scripts/app/Frames/AutoLayoutFrame/VAutoLayoutFrame.js", "~/Scripts/app/Frames/AutoLayoutFrame/AutoLayoutFrameViewBorder.js", "~/Scripts/app/Frames/AutoLayoutFrame/AutoLayoutFrameDataBorder.js", "~/Scripts/app/Tracker/ItrGridFrame/BItrGridFrame.js", "~/Scripts/app/Tracker/ItrGridFrame/VItrGridFrame.js", "~/Scripts/app/HR/BGridWithExtraFind.js", "~/Scripts/app/HR/VGridWithExtraFind.js", "~/Scripts/app/Frames/LocalizationFrame/BLocalizationFrame.js", "~/Scripts/app/Frames/LocalizationFrame/VLocalizationFrame.js", "~/Scripts/app/site.js" )); #if (!DEBUG) BundleTable.EnableOptimizations = true; #endif #if (DEBUG) BundleTable.EnableOptimizations = false; #endif } } }
using System; using System.Collections.Generic; using System.Text; namespace Checkout.Payment.Gateway.Seedwork.Extensions { public interface ITryResult<T> { bool Success { get; } string Message { get; } public T Result { get; } } }
using Logic.Buildings; using Logic.Resource; using NUnit.Framework; using System; namespace UnitTest4X { [TestFixture] public class SpaceBuildingsTest { [TestCase] public void HabitatBuilderOneTurnProgress_NotEnoughResources_NoProgress() { HabitatBuilder habitatBuilder = new HabitatBuilder("a"); double resourceFactor = 0.5; Resources neededResources = new Resources( resourceFactor * habitatBuilder.CostPerTurn.Hydrogen, resourceFactor * habitatBuilder.CostPerTurn.CommonMetals, resourceFactor * habitatBuilder.CostPerTurn.RareEarthElements ); habitatBuilder.OneTurnProgress(neededResources); Assert.AreEqual(0, habitatBuilder.BuildingProgress); } [TestCase] public void HabitatBuilderOneTurnProgress_EnoughResources_ProgressMade() { HabitatBuilder habitatBuilder = new HabitatBuilder("a"); double resourceFactor = 5; Resources neededResources = new Resources(habitatBuilder.CostPerTurn); neededResources.Multiply(resourceFactor); for (int i = 0; i < resourceFactor; i++) { habitatBuilder.OneTurnProgress(neededResources); } Assert.AreEqual((int)resourceFactor, habitatBuilder.BuildingProgress); } [TestCase] public void HabitatBuilderOneTurnProgress_EnoughResources_HabitatBuilt() { HabitatBuilder habitatBuilder = new HabitatBuilder("a"); double resourceFactor = habitatBuilder.BuildingDuration * 2; Resources neededResources = new Resources(habitatBuilder.CostPerTurn); neededResources.Multiply(resourceFactor); for (int i = 0; i < resourceFactor; i++) { habitatBuilder.OneTurnProgress(neededResources); } Assert.AreEqual(habitatBuilder.BuildingDuration, habitatBuilder.BuildingProgress); } [TestCase] public void SystemBuildingsBuildNew_ObjectAddedTwice_CountIsCorrect() { HabitatBuilder habitatBuilder = new HabitatBuilder("a"); HabitatBuilder habitatBuilder2 = new HabitatBuilder("a"); SystemBuildings systemBuildings = new SystemBuildings(); systemBuildings.BuildNew(habitatBuilder); systemBuildings.BuildNew(habitatBuilder); systemBuildings.BuildNew(habitatBuilder2); habitatBuilder2.OneTurnProgress(new Resources(double.MaxValue, double.MaxValue, double.MaxValue)); systemBuildings.BuildNew(habitatBuilder2); Assert.AreEqual(2, systemBuildings.InConstructionCount); } [TestCase] public void SystemBuildingsBuildNew_ArgIsNull_ExceptionThrown() { SystemBuildings systemBuildings = new SystemBuildings(); HabitatBuilder habitatBuilder = null; Assert.Throws<ArgumentNullException>(() => { systemBuildings.BuildNew(habitatBuilder); }); } [TestCase] public void SystemBuildingsBuildNew_ArgsAreValid_Added() { SystemBuildings systemBuildings = new SystemBuildings(); int addedBuildings = 10; for (int i = 0; i < addedBuildings; i++) { systemBuildings.BuildNew(new HabitatBuilder("a")); } Assert.AreEqual(addedBuildings, systemBuildings.InConstructionCount); } [TestCase] public void SystemBuildingsNextTurn_ArgsAreValid_Built() { SystemBuildings systemBuildings = new SystemBuildings(); Resources resources = new Resources(double.MaxValue, double.MaxValue, double.MaxValue); int addedBuildings = 10_000; int turns = 30; for (int i = 0; i < addedBuildings; i++) { systemBuildings.BuildNew(new HabitatBuilder("a")); } for (int i = 0; i < turns; i++) { systemBuildings.NextTurn(resources); } Assert.AreEqual(addedBuildings, systemBuildings.ExistingCount); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FTUEManager : MonoBehaviour { public static FTUEManager Instance; public List<FTUEStep> _steps; // Start is called before the first frame update void Awake() { Instance = this; } private void Start() { InitSteps(); StartCoroutine(Execute()); } private void InitSteps() { } public IEnumerator Execute() { foreach (FTUEStep step in _steps) { step.OnStepStart(); StartCoroutine(step.OnExecute()); while (!step.IsFinished) { yield return new WaitForEndOfFrame(); } } } }
using System; namespace console_game { public class NeutralSpace : LevelSpace { public NeutralSpace(string prompt) : base(prompt) { } override public bool HasEnemies() { return false; } public override bool HasFriendlies() { return false; } } }
using System; using System.Threading.Tasks; namespace PmSoft.Caching { /// <summary> /// 缓存服务接口 /// </summary> public interface ICacheService { /// <summary> /// 添加到缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="timeSpan"></param> void Add(string cacheKey, object value, TimeSpan timeSpan); /// <summary> /// 添加到缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="timeSpan"></param> Task AddAsync(string cacheKey, object value, TimeSpan timeSpan); /// <summary> /// 添加到缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="cachingExpirationType"></param> void Add(string cacheKey, object value, CachingExpirationType cachingExpirationType); /// <summary> /// 添加到缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="cachingExpirationType"></param> Task AddAsync(string cacheKey, object value, CachingExpirationType cachingExpirationType); /// <summary> /// 清空缓存 /// </summary> void Clear(); /// <summary> /// 清空缓存 /// </summary> Task ClearAsync(); /// <summary> /// 从缓存获取 /// </summary> /// <param name="cacheKey"></param> /// <returns></returns> object Get(string cacheKey); /// <summary> /// 从缓存获取 /// </summary> /// <param name="cacheKey"></param> /// <returns></returns> Task<object> GetAsync(string cacheKey); /// <summary> /// 从缓存获取(缓存项必须是引用类型) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheKey"></param> /// <returns></returns> T Get<T>(string cacheKey) where T : class; /// <summary> /// 从缓存获取(缓存项必须是引用类型) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheKey"></param> /// <returns></returns> Task<T> GetAsync<T>(string cacheKey) where T : class; /// <summary> /// 尝试获取一个值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <returns></returns> bool TryGetValue<T>(string cacheKey, out T value); /// <summary> /// 从一层缓存获取(缓存项必须是引用类型) /// 在启用分布式缓存的情况下,指穿透二级缓存从一层缓存(分布式缓存)读取 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheKey"></param> /// <returns></returns> T GetFromFirstLevel<T>(string cacheKey) where T : class; /// <summary> /// 从一层缓存获取(缓存项必须是引用类型) /// 在启用分布式缓存的情况下,指穿透二级缓存从一层缓存(分布式缓存)读取 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cacheKey"></param> /// <returns></returns> Task<T> GetFromFirstLevelAsync<T>(string cacheKey) where T : class; /// <summary> /// 从一层缓存获取 /// 在启用分布式缓存的情况下,指穿透二级缓存从一层缓存(分布式缓存)读取 /// </summary> /// <param name="cacheKey"></param> /// <returns></returns> object GetFromFirstLevel(string cacheKey); /// <summary> /// 从一层缓存获取 /// 在启用分布式缓存的情况下,指穿透二级缓存从一层缓存(分布式缓存)读取 /// </summary> /// <param name="cacheKey"></param> /// <returns></returns> Task<object> GetFromFirstLevelAsync(string cacheKey); /// <summary> /// 标识为删除 /// </summary> /// <param name="cacheKey"></param> /// <param name="entity"></param> /// <param name="cachingExpirationType"></param> void MarkDeletion(string cacheKey, IEntity entity, CachingExpirationType cachingExpirationType); /// <summary> /// 标识为删除 /// </summary> /// <param name="cacheKey"></param> /// <param name="entity"></param> /// <param name="cachingExpirationType"></param> Task MarkDeletionAsync(string cacheKey, IEntity entity, CachingExpirationType cachingExpirationType); /// <summary> /// 移除缓存 /// </summary> /// <param name="cacheKey"></param> void Remove(string cacheKey); /// <summary> /// 移除缓存 /// </summary> /// <param name="cacheKey"></param> Task RemoveAsync(string cacheKey); /// <summary> /// 添加或更新缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="timeSpan"></param> void Set(string cacheKey, object value, TimeSpan timeSpan); /// <summary> /// 添加或更新缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="timeSpan"></param> Task SetAsync(string cacheKey, object value, TimeSpan timeSpan); /// <summary> /// 添加或更新缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="cachingExpirationType"></param> void Set(string cacheKey, object value, CachingExpirationType cachingExpirationType); /// <summary> /// 添加或更新缓存 /// </summary> /// <param name="cacheKey"></param> /// <param name="value"></param> /// <param name="cachingExpirationType"></param> Task SetAsync(string cacheKey, object value, CachingExpirationType cachingExpirationType); /// <summary> /// 是否启用分布式缓存 /// </summary> bool EnableDistributedCache { get; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data; using DAL; namespace BLL { public class BLL_CTHD { DAL_CTHD cthddal = new DAL_CTHD(); //phương thức này gọi phương thức sv_select() ở lớp CTHD_DAL (tầng DAL) public DataTable CTHD_Select() { return cthddal.CTHD_select(); } //phương thức này gọi phương thức sv_insert() ở lớp CTHD_DAL (tầng DAL) public int CTHD_Insert(string mahanghoa, string mahoadon, string sl) { return cthddal.CTHD_insert(mahanghoa, mahoadon, sl); } //phương thức này gọi phương thức sv_update() ở lớp CTHD_DAL (tầng DAL) public int CTHD_Update( string mahanghoa,string mahoadon,string sl) { return cthddal.CTHD_update(mahanghoa,mahoadon, sl); } //phương thức này gọi phương thức sv_delete() ở lớp CTHD_DAL (tầng DAL) public int CTHD_Delete(string mahanghoa, string mahoadon) { return cthddal.CTHD_delete(mahanghoa, mahoadon); } } }
using System; using System.Data; using System.Collections.Generic; using System.Text; using Npgsql; using NpgsqlTypes; using CGCN.Framework; using CGCN.DataAccess; namespace QTHT.DataAccess { /// <summary> /// Mô tả thông tin cho bảng log /// Cung cấp các hàm xử lý, thao tác với bảng log /// Người tạo (C): /// Ngày khởi tạo: 17/10/2014 /// </summary> public class log { #region Private Variables private int intid; private DateTime dtmthoigian; private string striduser; private string strthaotac; #endregion #region Public Constructor Functions public log() { intid = 0; dtmthoigian = DateTime.Now; striduser = string.Empty; strthaotac = string.Empty; } public log(int intid, DateTime dtmthoigian, string striduser, string strthaotac) { this.intid = intid; this.dtmthoigian = dtmthoigian; this.striduser = striduser; this.strthaotac = strthaotac; } #endregion #region Properties public int id { get { return intid; } set { intid = value; } } public DateTime thoigian { get { return dtmthoigian; } set { dtmthoigian = value; } } public string iduser { get { return striduser; } set { striduser = value; } } public string thaotac { get { return strthaotac; } set { strthaotac = value; } } #endregion #region Public Method private readonly DataAccessLayerBaseClass mDataAccess = new DataAccessLayerBaseClass(Data.ConnectionString); /// <summary> /// Lấy toàn bộ dữ liệu từ bảng log /// </summary> /// <returns>DataTable</returns> public DataTable GetAll() { string strFun = "fn_log_getall"; try { DataSet dslog = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure); return dslog.Tables[0]; } catch { return null; } } /// <summary> /// Hàm lấy log theo mã /// </summary> /// <returns>Trả về objlog </returns> public log GetByID(int intid) { log objlog = new log(); string strFun = "fn_log_getobjbyid"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[1]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Integer); prmArr[0].Value = intid; DataSet dslog = mDataAccess.ExecuteDataSet(strFun, CommandType.StoredProcedure, prmArr); if ((dslog != null) && (dslog.Tables.Count > 0)) { if (dslog.Tables[0].Rows.Count > 0) { DataRow dr = dslog.Tables[0].Rows[0]; try{ objlog.id = Convert.ToInt32("0" + dr["id"].ToString());} catch{ objlog.id = 0;} try { objlog.thoigian = Convert.ToDateTime(dr["thoigian"].ToString());} catch { objlog.thoigian = new DateTime(1900, 1, 1); } objlog.iduser = dr["iduser"].ToString(); objlog.thaotac = dr["thaotac"].ToString(); return objlog; } return null; } return null; } catch { return null; } } /// <summary> /// Hàm thêm mới log /// </summary> /// <param name="sUserName">Tên đăng nhập kiểu string</param> /// <param name="sTask">Thao tác kiểu string</param> /// <returns>Trả về trắng: Thêm mới thành công; Trả về khác trắng: Thêm mới không thành công</returns> public string Append(string sUserName, string sTask) { string strProc = "fn_log_appen"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[3]; prmArr[0] = new NpgsqlParameter("iduser", NpgsqlDbType.Varchar); prmArr[0].Value = sUserName; prmArr[1] = new NpgsqlParameter("thaotac", NpgsqlDbType.Varchar); prmArr[1].Value = sTask; prmArr[2] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[2].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[2].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Add".ToUpper()) == true) return ""; return "Thêm mới dữ liệu không thành công"; } catch (Exception ex) { return "Thêm mới dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Cập nhật dữ liệu vào bảng: log /// </summary> /// <param name="obj">objlog</param> /// <returns>Trả về trắng: Cập nhật thành công; Trả về khác trắng: Cập nhật không thành công</returns> public string Update(log objlog) { string strProc = "fn_log_Update"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[5]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Integer); prmArr[0].Value = objlog.intid; prmArr[1] = new NpgsqlParameter("thoigian", NpgsqlDbType.TimestampTZ); prmArr[1].Value = objlog.dtmthoigian; prmArr[2] = new NpgsqlParameter("iduser", NpgsqlDbType.Varchar); prmArr[2].Value = objlog.striduser; prmArr[3] = new NpgsqlParameter("thaotac", NpgsqlDbType.Varchar); prmArr[3].Value = objlog.strthaotac; prmArr[4] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[4].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string sKQ = prmArr[4 ].Value.ToString().Trim(); if (sKQ.ToUpper().Equals("Update".ToUpper()) == true) return ""; return "Cập nhật dữ liệu không thành công"; } catch(Exception ex) { return "Cập nhật dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Xóa dữ liệu từ bảng log /// </summary> /// <returns>Trả về trắng: xóa thành công; Trả về khác trắng: xóa không thành công</returns> public string Delete(int intid) { string strProc = "fn_log_delete"; try { NpgsqlParameter[] prmArr = new NpgsqlParameter[2]; prmArr[0] = new NpgsqlParameter("id", NpgsqlDbType.Integer); prmArr[0].Value = intid; prmArr[1] = new NpgsqlParameter("ireturn", NpgsqlDbType.Text); prmArr[1].Direction = ParameterDirection.Output; mDataAccess.ExecuteQuery(strProc, CommandType.StoredProcedure, prmArr); string KQ = prmArr[1].Value.ToString().Trim(); if (KQ.ToUpper().Equals("Del".ToUpper()) == true) return ""; return "Xóa dữ liệu không thành công"; } catch(Exception ex) { return "Xóa dữ liệu không thành công. Chi Tiết: " + ex.Message; } } /// <summary> /// Hàm tìm kiếm log sử dụng chuối truy vấn trực tiếp /// </summary> /// <param name="squery">Chuối truy vấn kiểu string</param> /// <returns>DataTable</returns> public DataTable FindLogUseQuery(string squery) { DataTable dt = new DataTable(); try { dt = mDataAccess.ExecuteDataSet(squery, CommandType.Text).Tables[0]; return dt; } catch { return null; } } #endregion } }
using System; namespace TypicalInterviewQuestions { //Write a function to print nth number in Fibonacci series? public class FibonacciPrint { public int PrintNthElementInSequence(int nthElement) { if (nthElement < 0) throw new ArgumentException("Fibonacci Element must be a positive number"); if (nthElement == 0) return 0; if (nthElement == 1) return 0; if (nthElement == 2) return 1; int result = 0; int firstNumber = 0; int secondNumber = 1; for (int i = 2; i < nthElement; i++) { result = firstNumber + secondNumber; firstNumber = secondNumber; secondNumber = result; } return result; } } }
namespace E13_CheckABitAtGivenPosition { using System; public class CheckABitAtGivenPosition { public static void Main(string[] args) { // Write a Boolean expression that returns if the bit at // position p (counting from 0, starting from the right) in // given integer number n, has value of 1. // Examples: // // n binary representation of n p bit @ p == 1 // 5 00000000 00000101 2 true // 0 00000000 00000000 9 false // 15 00000000 00001111 1 true // 5343 00010100 11011111 7 true // 62241 11110011 00100001 11 false Console.WriteLine("Return \"true\" if the bit at position p in given " + "integer number n, has value of 1."); Console.Write("Enter an integer : "); int number = int.Parse(Console.ReadLine()); Console.Write("Enter position of the bit : "); int bitPosition = int.Parse(Console.ReadLine()); int mask = 1 << bitPosition; int valueAndMask = number & mask; int bit = valueAndMask >> bitPosition; if (bit == 1) { Console.WriteLine(true); } else { Console.WriteLine(false); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public enum BoundsTest { // Center of the screen center, // On Screen onScreen, // Off Screen offScreen } public class Utilities : MonoBehaviour { //============================= Bounds Functions =============================\\ // Creates Bounds that encapsulate the two Bounds passed in public static Bounds BoundsUnion(Bounds b0, Bounds b1) { if (b0.size == Vector3.zero && b1.size != Vector3.zero) { return (b1); } else if (b0.size != Vector3.zero && b1.size == Vector3.zero) { return (b0); } else if (b0.size == Vector3.zero && b1.size == Vector3.zero) { return (b0); } // Stretch b0 to include the b1.min and b1.max b0.Encapsulate(b1.min); b1.Encapsulate(b1.max); return (b0); } public static Bounds CombineBoundsOfChildren(GameObject go) { // Create an empty Bounds b Bounds b = new Bounds(Vector3.zero, Vector3.zero); // If this GameObject has a Renderer Component... if (go.GetComponent<Renderer>() != null) { // Expand b to contain the Renderer's Bounds b = BoundsUnion(b, go.GetComponent<Renderer>().bounds); } // If this GameObject has a Collider Component... if (go.GetComponent<Collider>() != null) { // Expand b to contain the Collider's Bounds b = BoundsUnion(b, go.GetComponent<Collider>().bounds); } // Recursively iterate through each child of this gameObject.transform foreach (Transform t in go.transform) { // Expand b to contain their Bounds as well b = BoundsUnion(b, CombineBoundsOfChildren(t.gameObject)); } return (b); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
using Particles.Engine.Controls; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Media.Animation; namespace Particles.Engine.Emitters { public abstract class Emitter : Control { #region DependencyProperties public int MaxParticles { get { return (int)GetValue(MaxParticlesProperty); } set { SetValue(MaxParticlesProperty, value); } } // Using a DependencyProperty as the backing store for MaxParticles. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxParticlesProperty = DependencyProperty.Register("MaxParticles", typeof(int), typeof(Emitter), new PropertyMetadata(0)); public int MinParticles { get { return (int)GetValue(MinParticlesProperty); } set { SetValue(MinParticlesProperty, value); } } // Using a DependencyProperty as the backing store for MinParticles. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinParticlesProperty = DependencyProperty.Register("MinParticles", typeof(int), typeof(Emitter), new PropertyMetadata(0)); public double MaxHorizontalVelocity { get { return (double)GetValue(MaxHorizontalVelocityProperty); } set { SetValue(MaxHorizontalVelocityProperty, value); } } // Using a DependencyProperty as the backing store for MaxHorizontalVelocity. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxHorizontalVelocityProperty = DependencyProperty.Register("MaxHorizontalVelocity", typeof(double), typeof(Emitter), new PropertyMetadata(0d)); public double MinHorizontalVelocity { get { return (double)GetValue(MinHorizontalVelocityProperty); } set { SetValue(MinHorizontalVelocityProperty, value); } } // Using a DependencyProperty as the backing store for MinHorizontalVelocity. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinHorizontalVelocityProperty = DependencyProperty.Register("MinHorizontalVelocity", typeof(double), typeof(Emitter), new PropertyMetadata(0d)); public double MaxVerticalVelocity { get { return (double)GetValue(MaxVerticalVelocityProperty); } set { SetValue(MaxVerticalVelocityProperty, value); } } // Using a DependencyProperty as the backing store for MaxVerticalVelocity. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxVerticalVelocityProperty = DependencyProperty.Register("MaxVerticalVelocity", typeof(double), typeof(Emitter), new PropertyMetadata(0d)); public double MinVerticalVelocity { get { return (double)GetValue(MinVerticalVelocityProperty); } set { SetValue(MinVerticalVelocityProperty, value); } } // Using a DependencyProperty as the backing store for MinVerticalVelocity. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinVerticalVelocityProperty = DependencyProperty.Register("MinVerticalVelocity", typeof(double), typeof(Emitter), new PropertyMetadata(0d)); public double MaxLifeSpan { get { return (double)GetValue(MaxLifeSpanProperty); } set { SetValue(MaxLifeSpanProperty, value); } } // Using a DependencyProperty as the backing store for MaxLifeSpan. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxLifeSpanProperty = DependencyProperty.Register("MaxLifeSpan", typeof(double), typeof(Emitter), new PropertyMetadata(double.MaxValue)); public double MinLifeSpan { get { return (double)GetValue(MinLifeSpanProperty); } set { SetValue(MinLifeSpanProperty, value); } } // Using a DependencyProperty as the backing store for MinLifeSpan. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinLifeSpanProperty = DependencyProperty.Register("MinLifeSpan", typeof(double), typeof(Emitter), new PropertyMetadata(double.MaxValue)); public double MaxMass { get { return (double)GetValue(MaxMassProperty); } set { SetValue(MaxMassProperty, value); } } // Using a DependencyProperty as the backing store for MaxMass. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxMassProperty = DependencyProperty.Register("MaxMass", typeof(double), typeof(Emitter), new PropertyMetadata(2.0d)); public double MinMass { get { return (double)GetValue(MinMassProperty); } set { SetValue(MinMassProperty, value); } } // Using a DependencyProperty as the backing store for MinMass. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinMassProperty = DependencyProperty.Register("MinMass", typeof(double), typeof(Emitter), new PropertyMetadata(2.0d)); public double MaxParticleWidth { get { return (double)GetValue(MaxParticleWidthProperty); } set { SetValue(MaxParticleWidthProperty, value); } } // Using a DependencyProperty as the backing store for MaxParticleWidth. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxParticleWidthProperty = DependencyProperty.Register("MaxParticleWidth", typeof(double), typeof(Emitter), new PropertyMetadata(10.0d)); public double MinParticleWidth { get { return (double)GetValue(MinParticleWidthProperty); } set { SetValue(MinParticleWidthProperty, value); } } // Using a DependencyProperty as the backing store for MinParticleWidth. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinParticleWidthProperty = DependencyProperty.Register("MinParticleWidth", typeof(double), typeof(Emitter), new PropertyMetadata(4.0d)); public double MaxParticleHeight { get { return (double)GetValue(MaxParticleHeightProperty); } set { SetValue(MaxParticleHeightProperty, value); } } // Using a DependencyProperty as the backing store for MaxParticleHeight. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxParticleHeightProperty = DependencyProperty.Register("MaxParticleHeight", typeof(double), typeof(Emitter), new PropertyMetadata(10.0d)); public double MinParticleHeight { get { return (double)GetValue(MinParticleHeightProperty); } set { SetValue(MinParticleHeightProperty, value); } } // Using a DependencyProperty as the backing store for MinParticleHeight. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinParticleHeightProperty = DependencyProperty.Register("MinParticleHeight", typeof(double), typeof(Emitter), new PropertyMetadata(4.0d)); public double MaxPositionOffset { get { return (double)GetValue(MaxPositionOffsetProperty); } set { SetValue(MaxPositionOffsetProperty, value); } } // Using a DependencyProperty as the backing store for MaxPositionOffset. This enables animation, styling, binding, etc... public static readonly DependencyProperty MaxPositionOffsetProperty = DependencyProperty.Register("MaxPositionOffset", typeof(double), typeof(Emitter), new PropertyMetadata(0.01d)); public double MinPositionOffset { get { return (double)GetValue(MinPositionOffsetProperty); } set { SetValue(MinPositionOffsetProperty, value); } } // Using a DependencyProperty as the backing store for MinPositionOffset. This enables animation, styling, binding, etc... public static readonly DependencyProperty MinPositionOffsetProperty = DependencyProperty.Register("MinPositionOffset", typeof(double), typeof(Emitter), new PropertyMetadata(-0.01d)); public double StartOpacity { get { return (double)GetValue(StartOpacityProperty); } set { SetValue(StartOpacityProperty, value); } } // Using a DependencyProperty as the backing store for StartOpacity. This enables animation, styling, binding, etc... public static readonly DependencyProperty StartOpacityProperty = DependencyProperty.Register("StartOpacity", typeof(double), typeof(Emitter), new PropertyMetadata(0.3d)); public double EndOpacity { get { return (double)GetValue(EndOpacityProperty); } set { SetValue(EndOpacityProperty, value); } } // Using a DependencyProperty as the backing store for EndOpacity. This enables animation, styling, binding, etc... public static readonly DependencyProperty EndOpacityProperty = DependencyProperty.Register("EndOpacity", typeof(double), typeof(Emitter), new PropertyMetadata(0d)); public ColorKeyFrameCollection ColorKeyFrames { get { return (ColorKeyFrameCollection)GetValue(ColorKeyFramesProperty); } set { SetValue(ColorKeyFramesProperty, value); } } // Using a DependencyProperty as the backing store for ColorKeyFrames. This enables animation, styling, binding, etc... public static readonly DependencyProperty ColorKeyFramesProperty = DependencyProperty.Register("ColorKeyFrames", typeof(ColorKeyFrameCollection), typeof(Emitter), new PropertyMetadata(new ColorKeyFrameCollection())); #endregion #region Virtual Methods /// <summary> /// Generates the particles for an emitter, called once at creation by the Particle System. /// </summary> /// <param name="system"></param> virtual public void GenerateParticles(ParticleSystem system) { // Init the particles for the emitter for (int i = 0; i < MaxParticles; i++) { Particle mParticle = new Particle(); UpdateParticle(mParticle); this.AddParticle(system, mParticle); system.Particles.Add(mParticle); } } /// <summary> /// Method which is used to perform additional processing when adding a particle to the system for the /// first time. /// </summary> /// <param name="system"></param> /// <param name="particle"></param> virtual public void AddParticle(ParticleSystem system, Particle particle) { } /// <summary> /// Updates the particle by reinitializing its parameters. Used when a particle is first created and /// when a particle is resurrected. /// </summary> /// <param name="particle"></param> virtual public void UpdateParticle(Particle particle) { particle.Owner = this; particle.Mass = Helpers.RandomNumberGenerator.Instance.NextDouble(MinMass, MaxMass); particle.StartOpacity = this.StartOpacity; particle.EndOpacity = this.EndOpacity; particle.Force = new Vector(0, 0); particle.Velocity = new Vector( Helpers.RandomNumberGenerator.Instance.NextDouble(MinHorizontalVelocity, MaxHorizontalVelocity), Helpers.RandomNumberGenerator.Instance.NextDouble(MinVerticalVelocity, MaxVerticalVelocity)); particle.LifeSpan = Helpers.RandomNumberGenerator.Instance.NextDouble(MinLifeSpan, MaxLifeSpan); particle.BackgroundColors = this.ColorKeyFrames; } #endregion } }
using Moq; using MvcTurbine.GoogleSiteMap.Models; using MvcTurbine.GoogleSiteMap.Serialization; using NUnit.Framework; using Should; namespace MvcTurbine.GoogleSiteMap.Tests.Serialization { [TestFixture] public class GoogleUrlSetSerializerTests { [Test] public void Result_should_start_with_standard_google_site_map_xml() { var expected = @"<?xml version=""1.0"" encoding=""UTF-8""?> <urlset xmlns=""http://www.google.com/schemas/sitemap/0.90"">"; var serializer = new GoogleUrlSetSerializer(new Mock<IGoogleUrlSerializer>().Object); var result = serializer.Serialize(new GoogleUrl[] {}); result.StartsWith(expected).ShouldBeTrue(); } [Test] public void Result_ends_with_close_tag() { var expected = @"</urlset>"; var serializer = new GoogleUrlSetSerializer(new Mock<IGoogleUrlSerializer>().Object); var result = serializer.Serialize(new GoogleUrl[] {}); result.EndsWith(expected).ShouldBeTrue(); } [Test] public void When_passed_one_url_then_include_xml_for_that_url() { var googleUrl = new GoogleUrl(); var singleUrlSerializerFake = new Mock<IGoogleUrlSerializer>(); singleUrlSerializerFake .Setup(x => x.Serialize(googleUrl)) .Returns("RESULTONE"); var serializer = new GoogleUrlSetSerializer(singleUrlSerializerFake.Object); var result = serializer.Serialize(new[] {googleUrl}); result.Contains("RESULTONE").ShouldBeTrue(); } [Test] public void When_passed_two_urls_then_include_xml_for_those_urls() { var firstUrl = new GoogleUrl(); var secondUrl = new GoogleUrl(); var singleUrlSerializerFake = new Mock<IGoogleUrlSerializer>(); singleUrlSerializerFake .Setup(x => x.Serialize(firstUrl)) .Returns("RESULTONE"); singleUrlSerializerFake .Setup(x => x.Serialize(secondUrl)) .Returns("RESULTTWO"); var serializer = new GoogleUrlSetSerializer(singleUrlSerializerFake.Object); var result = serializer.Serialize(new[] {firstUrl, secondUrl}); result.Contains("RESULTONERESULTTWO").ShouldBeTrue(); } } }
using System; using System.Runtime.InteropServices; namespace OverCR.StatX.Hooks.WinAPI { class Kernel32 { [DllImport("kernel32.dll")] internal static extern IntPtr GetModuleHandle(string moduleName); } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // // ReSharper disable once CheckNamespace using System; using System.Web.UI; using DotNetNuke.Entities.Users; using DotNetNuke.Web.Client; using DotNetNuke.Web.Client.ClientResourceManagement; using Newtonsoft.Json; // ReSharper disable once CheckNamespace namespace DotNetNuke.Services.Tokens { public class StylesheetDto { [JsonProperty("path")] public string Path { get; set; } [JsonProperty("priority")] public int Priority { get; set; } [JsonProperty("provider")] public string Provider { get; set; } } public class CssPropertyAccess : JsonPropertyAccess<StylesheetDto> { private readonly Page _page; public CssPropertyAccess(Page page) { _page = page; } protected override string ProcessToken(StylesheetDto model, UserInfo accessingUser, Scope accessLevel) { if (String.IsNullOrEmpty(model.Path)) { throw new ArgumentException("The Css token must specify a path or property."); } if (model.Priority == 0) { model.Priority = (int)FileOrder.Css.DefaultPriority; } if (String.IsNullOrEmpty(model.Provider)) { ClientResourceManager.RegisterStyleSheet(_page, model.Path, model.Priority); } else { ClientResourceManager.RegisterStyleSheet(_page, model.Path, model.Priority, model.Provider); } return String.Empty; } } }
namespace TipsAndTricksLibrary.Tests.Extensions { using System.Collections.Generic; using JetBrains.Annotations; using TipsAndTricksLibrary.Extensions; using Xunit; public class ArrayExtensionsTests { [UsedImplicitly] public static IEnumerable<object[]> UpperBoundTestsData; [UsedImplicitly] public static IEnumerable<object[]> LowerBoundTestsData; static ArrayExtensionsTests() { UpperBoundTestsData = new[] { new object[] {new[] {1, 2, 3}, 2, null, null, 2}, new object[] {new[] {1, 2, 3}, 0, null, null, 0}, new object[] {new[] {1, 2, 5}, 5, null, null, null}, new object[] {new[] {1, 2, 3}, 2, null, 1, null}, new object[] {new[] {1, 2, 3}, 0, 1, null, 1}, }; LowerBoundTestsData = new[] { new object[] {new[] {1, 2, 3}, 2, null, null, 1}, new object[] {new[] {1, 2, 3}, 0, null, null, 0}, new object[] {new[] {1, 2, 5}, 5, null, null, 2}, new object[] {new[] {1, 2, 5}, 6, null, null, null}, new object[] {new[] {1, 2, 3}, 2, null, 1, 1}, new object[] {new[] {1, 2, 3}, 3, null, 1, null}, new object[] {new[] {1, 2, 3}, 0, 1, null, 1}, }; } [Theory] [MemberData(nameof(UpperBoundTestsData))] public void ShouldFindUpperBound(int[] source, int value, int? startIndex, int? endIndex, int? expectedResult) { Assert.Equal(expectedResult, source.UpperBound(value, startIndex: startIndex, endIndex: endIndex)); } [Theory] [MemberData(nameof(LowerBoundTestsData))] public void ShouldFindLowerBound(int[] source, int value, int? startIndex, int? endIndex, int? expectedResult) { Assert.Equal(expectedResult, source.LowerBound(value, startIndex: startIndex, endIndex: endIndex)); } } }
using System.Security.Cryptography; using Microsoft.Extensions.DependencyInjection; using Services; namespace ConsoleApp { class Program { static void Main(string[] args) { var services = new ServiceCollection(); RegisterServices(services); var serviceProvider = services.BuildServiceProvider(); var serviceScope = serviceProvider.CreateScope(); var application = serviceScope.ServiceProvider.GetService<MyConsoleApplication>(); application.Start(); DisposeServices(serviceProvider); } private static void RegisterServices(IServiceCollection services) { var sha512Managed = new SHA512Managed(); services.AddSingleton<RandomStringGenerator>(new SHARandomStringGenerator(sha512Managed)); services.AddSingleton<MyConsoleApplication>(); } private static void DisposeServices(ServiceProvider serviceProvider) { serviceProvider?.Dispose(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; public class FlashText : MonoBehaviour { TextMeshProUGUI text; private void Awake() { text = GetComponent<TextMeshProUGUI>(); StartCoroutine(TextFlash()); } private IEnumerator TextFlash() { while (true) { // Opaque to Transparent for (float i = 1; i >= 0; i -= Time.unscaledDeltaTime) { text.color = new Color(text.color.r, text.color.g, text.color.b, i); yield return null; } // Transparent to Opaque for (float i = 0; i <= 1; i += Time.unscaledDeltaTime) { text.color = new Color(text.color.r, text.color.g, text.color.b, i); yield return null; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class UIController : MonoBehaviour { [SerializeField] private GameObject killButton = null; [SerializeField] private GameObject makeBestButton = null; [SerializeField] private GameObject selectedAgentIcon = null; [SerializeField] private Agent selectedAgent = null; private bool paused = false; //create singleton - This means that there can only be one of this in the scene at any given time public static UIController instance; private static UIController _instance; public static UIController Instance { get { if (_instance == null) { _instance = GameObject.FindObjectOfType<UIController>(); } return _instance; } } public void SelectAgent(Agent agent) { if (agent == null || selectedAgent != agent) { selectedAgent = agent; killButton.SetActive(true); makeBestButton.SetActive(true); } else if(selectedAgent == agent) { selectedAgent = null; selectedAgentIcon.transform.GetComponent<RectTransform>().position = new Vector3(-9999, -9999, -9999); killButton.SetActive(false); makeBestButton.SetActive(false); } } public void KillAgent() { if(selectedAgent != null) selectedAgent.KillAgent(); } public void KillAllAgents() { foreach(Runner runner in FindObjectsOfType<Runner>()) { runner.KillAgent(); } } public void MakeAgentBest() { PopulationController.Instance.SetBest(selectedAgent._net); } public void PauseTime() { paused = !paused; if (paused == true) { Time.timeScale = 0; } else { Time.timeScale = 1; } } public void Update() { if (selectedAgent != null) { selectedAgentIcon.transform.GetComponent<RectTransform>().position = Camera.main.WorldToScreenPoint(selectedAgent.transform.position); } } }
using UnityEngine; using System.Collections; public class DropMovement : MonoBehaviour{ ParticleSystem drops; ParticleSystem.Particle[] particles; //ParticleSystem.VelocityOverLifetimeModule velocity; //ParticleSystem.ForceOverLifetimeModule force; //public Transform receiver; void Awake(){ drops = GetComponent<ParticleSystem> (); } /*void Update(){ if(Input.GetKeyDown(KeyCode.R)){ GameObject zero = new GameObject (); SendDrop (zero.transform); Destroy (zero); } }*/ //create and launch the partical public void SendDrop(Transform receiver){ float dist = Vector3.Distance (transform.position,receiver.position) / 2f; if(dist != 0 && transform != receiver){ float z = (receiver.position.z - transform.position.z) / dist; float y = dist; float x = (receiver.position.x - transform.position.x) / dist; drops.Emit (1); if(particles == null || particles.Length < drops.main.maxParticles){ particles = new ParticleSystem.Particle[drops.main.maxParticles]; } int numParticles = drops.GetParticles (particles); if(numParticles != 0){ particles [numParticles - 1].velocity = new Vector3(x,y,z); drops.SetParticles (particles, numParticles); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AsyncDelegates { public enum ExamplesEnumeration { AsyncAction, EndInvoke, FuncAsync, WaitForAsync, IsComplited, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace XmlCitac.Class { public class Osobe { public string email { get; set; } public string prezimeime { get; set; } public string adresa { get; set; } public string datumrodjenja { get; set; } public string brojtelefona { get; set; } } }
using System; using Server.Items; namespace Server.Items { public class CosmicOil : Item, ICommodity { int ICommodity.DescriptionNumber { get { return LabelNumber; } } bool ICommodity.IsDeedable { get { return true; } } [Constructable] public CosmicOil() : this( 1 ) { } [Constructable] public CosmicOil( int amount ) : base( 0x2DB6 ) { Name = "cosmic oil"; Hue = 1462; Stackable = true; Amount = amount; Weight = 1.0; ItemValue = ItemValue.Epic; } public CosmicOil( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
using System; using UIKit; using CoreImage; using CoreGraphics; using System.Drawing; using Ts.Core.iOS; namespace Ts.Core.Utilities { public static class BlurViewUtil { private static float _blurRadius = 5f; public static UIImage _imgBlur1; public static UIImage _imgBlur2; public static float BlurRadius { get { return _blurRadius;} set { _blurRadius = value;} } public static UIImage BlurView (UIView view, float radius = 5f) { if (_imgBlur1 == null) { _imgBlur1 = BlurImage (Snapshot (view), radius); } return _imgBlur1; } public static UIImage BlurImage (UIImage image, float radius = 5f) { BlurRadius = radius; if (_imgBlur2 != null) { return _imgBlur2; } using (var blur = new CIGaussianBlur ()) { blur.Image = new CIImage (image); blur.Radius = BlurRadius; float width = (float)image.Size.Width; float height = (float)image.Size.Height; using (CIImage output = blur.OutputImage) using (CIContext context = CIContext.FromOptions (null)) using (CGImage cgimage = context.CreateCGImage (output, new RectangleF (0, 0, width, height))) { UIImage cropImage = UIImage.FromImage (Crop (CIImage.FromCGImage (cgimage), width, height)); _imgBlur2 = FileUtil.Resize (cropImage, width, height); return _imgBlur2; } } } private static CIImage Crop (CIImage image, float width, float height) { var crop = new CICrop { Image = image, Rectangle = new CIVector (10, 10, width - 20, height - 20) }; return crop.OutputImage; } private static UIImage Snapshot (UIView View) { UIImage image; UIGraphics.BeginImageContext (View.Bounds.Size); //pre-iOS 7 using layer to snapshot if (DeviceUtil.OSVersion < 7) { View.Layer.RenderInContext (UIGraphics.GetCurrentContext ()); } else { View.DrawViewHierarchy (View.Bounds, true); } image = UIGraphics.GetImageFromCurrentImageContext (); UIGraphics.EndImageContext (); return image; } } }
using innovation4austria.dataaccess; using log4net; using System; using System.Data; using System.Diagnostics; using System.Linq; namespace innovation4austria.logic { public class RollenVerwaltung { private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Lädt alle Rollen aus der Datenbank /// </summary> /// <returns></returns> public static string[] LadeAlleRollenNamen() { log.Debug("LadeAlle()"); string[] alleRollenNamen= null; using (var context = new InnovationContext()) { try { alleRollenNamen = context.AlleRollen.Select(x=> x.bezeichnung).ToArray(); } catch (Exception ex) { log.Error("Exception bei LadeAlle aufgetreten",ex); if (ex.InnerException != null) { log.Error(ex.InnerException); } #if DEBUG Debugger.Break(); #endif } return alleRollenNamen; } } /// <summary> /// Lädt alle Benutzer die einer Rolle angehören /// </summary> /// <returns></returns> public static string[] LadeRollenBenutzerNamen(string rollenName) { if (string.IsNullOrEmpty(rollenName)) { throw new ArgumentException("rollenName darf nicht leer sein"); } string[] benutzerNamen = null; using (var context = new InnovationContext()) { try { int rollenId = context.AlleRollen.FirstOrDefault(x => x.bezeichnung == rollenName).id; benutzerNamen = context.AlleBenutzer.Where(x => x.rolle_id == rollenId && x.aktiv).Select(x => x.benutzername).ToArray(); } catch (Exception ex) { log.Error("Exception bei LadeRollenBenutzerNamen aufgetreten", ex); if (ex.InnerException != null) { log.Error(ex.InnerException); } #if DEBUG Debugger.Break(); #endif } } return benutzerNamen; } /// <summary> /// Findet alle BenutzerNamen in einer Rolle deren BenutzerNamen den suchNamen enthalten /// </summary> /// <param name="rollenName">die Rolle die durchsucht wird</param> /// <param name="suchName">der Begriff anch dem gesucht wird</param> /// <returns>ein Array von Benutzernamen oder null</returns> public static string[] FindePassendeBenutzerInRolle(string rollenName, string suchName) { string[] benutzerNamen = null; if (string.IsNullOrEmpty(rollenName)) { throw new ArgumentException("rollenName darf nicht leer sein"); } if (string.IsNullOrEmpty(suchName)) { throw new ArgumentException("suchName darf nicht leer sein"); } using (var context = new InnovationContext()) { try { Rolle rolle = context.AlleRollen.FirstOrDefault(x => x.bezeichnung == rollenName); if (rolle == null) { throw new ObjectNotFoundException("Rolle wurde nicht gefunden"); } if (rolle.Benutzer == null) { throw new ObjectNotFoundException("Es wurden keine Benutzer für diese Rolle gefunden"); } benutzerNamen = rolle.Benutzer.Where(x => x.benutzername.Contains(suchName)&& x.aktiv).Select(x => x.benutzername).ToArray(); } catch (Exception ex) { log.Error("Exception bei FindePassendeBenutzerInRolle aufgetreten", ex); if (ex.InnerException != null) { log.Error(ex.InnerException); } #if DEBUG Debugger.Break(); #endif } return benutzerNamen; } } /// <summary> /// Lädt alle Rollen des Benutzers /// </summary> /// <param name="benutzerName">der übergebene Benutzer</param> /// <returns></returns> public static string[] LadeRolleBenutzer(string benutzerName) { string[] rollenName = null; if (string.IsNullOrEmpty(benutzerName)) { throw new ArgumentException("benutzerName darf nicht leer sein"); } using (var context = new InnovationContext()) { try { Benutzer benutzer = context.AlleBenutzer.FirstOrDefault(x => x.benutzername == benutzerName && x.aktiv); if (benutzer == null) { throw new ObjectNotFoundException("Benutzer wurde nicht gefunden"); } if (benutzer.Rolle == null) { throw new ObjectNotFoundException("Rolle des Benutzers wurde nicht gefunden"); } rollenName = new string[] { benutzer.Rolle.bezeichnung }; } catch (Exception ex) { log.Error("Exception bei LadeRolleBenutzer aufgetreten", ex); if (ex.InnerException != null) { log.Error(ex.InnerException); } #if DEBUG Debugger.Break(); #endif } return rollenName; } } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="HttpNotFoundException.cs" company=""> // // </copyright> // <summary> // The http not found exception. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace ConsoleWebServer.Framework.Exceptions { using System; /// <summary> /// The http not found exception. /// </summary> public class HttpNotFoundException : Exception { /// <summary> /// Initializes a new instance of the <see cref="HttpNotFoundException"/> class. /// </summary> /// <param name="message"> /// The message. /// </param> public HttpNotFoundException(string message) : base(message) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UIKit; using Xamarin.Forms; namespace OMIKAS { public partial class MainForm : ContentPage { /// <summary> /// Konstruktor klasy, tworzy okno z użytkownikiem oraz iloscia jego danych /// </summary> /// <param name="usr">Nazwa uzytkownika uruchamiajacego okno</param> public MainForm(string usr) { InitializeComponent(); //Uzupelnij tekst etykiet lbl_welcome.Text = "Witaj " + App.DAUtil.GetUser().ElementAt(0).user_name; lbl_all_stat.Text = "Masz "+App.alloymetals.Count.ToString()+" stworzonych składników stopowych."; lbl_smel_stat.Text = "Masz "+App.smeltals.Count.ToString()+" stworzonych wytopów."; } /// <summary> /// Odswieza dane po pokazaniu okna /// </summary> protected override void OnAppearing() { base.OnAppearing(); //Uzupelnij tekst etykiet lbl_welcome.Text = "Witaj " + App.DAUtil.GetUser().ElementAt(0).user_name; lbl_all_stat.Text = "Masz " + App.alloymetals.Count.ToString() + " stworzonych składników stopowych."; lbl_smel_stat.Text = "Masz " + App.smeltals.Count.ToString() + " stworzonych wytopów."; } } }
using System; using System.Globalization; using Xamarin.Forms; namespace Workout.Converters { /// <summary> /// Class that converts bpm values which are lower than or equal to 0 to "--" string. /// </summary> public class BpmValueConverter : IValueConverter { #region methods /// <summary> /// Converts values which are lower than or equal to 0 to "--" string. /// </summary> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>Converted value.</returns> public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return System.Convert.ToInt32(value) <= 0 ? "--" : value; } /// <summary> /// Does nothing, but it must be defined, because it is in "IValueConverter" interface. /// </summary> /// <param name="value">The value produced by the binding source.</param> /// <param name="targetType">The type of the binding target property.</param> /// <param name="parameter">The converter parameter to use.</param> /// <param name="culture">The culture to use in the converter.</param> /// <returns>Converted value.</returns> public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } #endregion } }
using System; using System.ComponentModel; using System.Drawing; using System.IO; using System.Management; using System.Net; using System.Windows.Forms; namespace Image_RGB { // Token: 0x02000003 RID: 3 public partial class Form2 : Form { // Token: 0x06000002 RID: 2 RVA: 0x000020DC File Offset: 0x000002DC public Form2() { WebRequest webRequest = WebRequest.Create("https://pastebin.com/raw/u00Fgvc1"); WebResponse response = webRequest.GetResponse(); Stream responseStream = response.GetResponseStream(); string text = string.Empty; using (StreamReader streamReader = new StreamReader(responseStream)) { text = streamReader.ReadToEnd(); } bool flag = text.Contains(Form2.GetProcessorID()); this.InitializeComponent(); } // Token: 0x06000003 RID: 3 RVA: 0x00002188 File Offset: 0x00000388 private void button1_Click(object sender, EventArgs e) { this.dialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;..."; this.dialog.Title = "Select a picture to convert."; bool flag = this.dialog.ShowDialog() == DialogResult.OK; if (flag) { this.pictureBox1.ImageLocation = this.dialog.FileName; } } // Token: 0x06000004 RID: 4 RVA: 0x000021E4 File Offset: 0x000003E4 private void button2_Click(object sender, EventArgs e) { this.textBox1.Text = ""; this.str = "local imageBytes = {"; this.pictureBox1.BackColor = Color.Transparent; Bitmap bitmap = new Bitmap(this.dialog.FileName); int num = int.Parse(this.textBox2.Text); for (int i = 0; i < bitmap.Width; i++) { for (int j = 0; j < bitmap.Height; j++) { bool flag = i % num == 0 && j % num == 0; if (flag) { Color pixel = bitmap.GetPixel(i, j); this.str = string.Concat(new object[] { this.str, "\n {x = ", i, ", y = ", j, ", r = ", pixel.R, ", g = ", pixel.G, " , b = ", pixel.B, "}, " }); } } } this.str = string.Concat(new object[] { this.str, "}\r\nlocal X = ", this.pictureBox1.Width, " local Y = ", this.pictureBox1.Height }); this.str += " local P = Instance.new('Part')\r\nP.Name = 'Bitmap'\r\nP.Anchored = true\r\nP.Transparency = 1\r\nP.Position = Vector3.new(0, 0, 0)\r\nP.Parent = game.Workspace\r\n\r\nlocal B = Instance.new('BillboardGui')\r\nB.Name = 'Image'\r\nB.AlwaysOnTop = true\r\nB.Size = UDim2.new(0, X, 0, Y)\r\nB.Parent = P\r\nlocal F = Instance.new('Frame')\r\nF.Name = 'Holder'\r\nF.Size = UDim2.new(1, 0, 1, 0)\r\nF.BackgroundTransparency = 1\r\nF.Parent = B"; this.str = this.str + "\r\nlocal res = " + this.textBox2.Text; this.str += " local current = 1\r\n\r\nlocal cooldown = false\r\n\r\nlocal cooldowncount = 0\r\n\r\nfor _,v in pairs(imageBytes) do\r\n\tlocal frame = Instance.new('Frame')\r\n\tframe.BackgroundColor3 = Color3.new(v.r/255, v.g/255, v.b/255)\r\n\tframe.Size = UDim2.new(0, 1, 0, 1)\r\n\tframe.BorderSizePixel = 0\r\n\tframe.Position = UDim2.new(0, math.floor(v.x/res), 0, math.floor(v.y/res))\r\n\tframe.Parent = F\r\n\tif frame.BackgroundColor3 == Color3.new(0, 0, 0) then\r\n\t\tframe:Destroy()\r\n\tend\r\n\tcurrent = current+1\r\n\tif current % 2 == 0 and not cooldown then\r\n\t\tcooldown = true\r\n\t\twait()\r\n\telseif current % 2 == 0 and cooldown then\r\n\t\tcooldowncount = cooldowncount+1\r\n\t\tif cooldowncount == 25 then\r\n\t\t\tcooldowncount = 0\r\n\t\t\tcooldown = false\r\n\t\tend\r\n\tend\r\nend"; this.textBox1.Text = this.str; } // Token: 0x06000007 RID: 7 RVA: 0x0000206B File Offset: 0x0000026B private void Form1_Load(object sender, EventArgs e) { } // Token: 0x06000008 RID: 8 RVA: 0x0000206B File Offset: 0x0000026B private void pictureBox1_Click(object sender, EventArgs e) { } // Token: 0x06000009 RID: 9 RVA: 0x0000206B File Offset: 0x0000026B private void textBox1_TextChanged(object sender, EventArgs e) { } // Token: 0x0600000A RID: 10 RVA: 0x0000206E File Offset: 0x0000026E private void button3_Click(object sender, EventArgs e) { Clipboard.SetDataObject(this.textBox1.SelectedText, true); } // Token: 0x0600000B RID: 11 RVA: 0x0000206B File Offset: 0x0000026B private void textBox2_TextChanged(object sender, EventArgs e) { } // Token: 0x0600000C RID: 12 RVA: 0x0000206B File Offset: 0x0000026B private void label1_Click(object sender, EventArgs e) { } // Token: 0x0600000D RID: 13 RVA: 0x00002083 File Offset: 0x00000283 private void button3_Click_1(object sender, EventArgs e) { MessageBox.Show("Saved to decal.lua"); File.WriteAllText("decal.lua", this.textBox1.Text); } // Token: 0x0600000E RID: 14 RVA: 0x00002BC8 File Offset: 0x00000DC8 public static string GetProcessorID() { string str = "C"; ManagementObject managementObject = new ManagementObject("win32_logicaldisk.deviceid=\"" + str + ":\""); managementObject.Get(); return managementObject["VolumeSerialNumber"].ToString(); } // Token: 0x04000001 RID: 1 private OpenFileDialog dialog = new OpenFileDialog(); // Token: 0x04000002 RID: 2 private string str = ""; } }
using System; using System.Collections.Generic; namespace OmniSharp.Extensions.JsonRpc { public interface IHandlersManager { IDisposable Add(IJsonRpcHandler handler, JsonRpcHandlerOptions? options = null); IDisposable Add(string method, IJsonRpcHandler handler, JsonRpcHandlerOptions? options = null); IDisposable Add(JsonRpcHandlerFactory factory, JsonRpcHandlerOptions? options = null); IDisposable Add(string method, JsonRpcHandlerFactory factory, JsonRpcHandlerOptions? options = null); IDisposable Add(Type handlerType, JsonRpcHandlerOptions? options = null); IDisposable Add(string method, Type handlerType, JsonRpcHandlerOptions? options = null); IDisposable AddLink(string fromMethod, string toMethod); IEnumerable<IHandlerDescriptor> Descriptors { get; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace Game { /// <summary> /// Used as a container to hold the board tile and shogi piece GameObjects /// </summary> public class BoardTile { /** * Data members for tile and piece and the Member properties for said * data. They are separeted for consistency and accessibility, where * Tile should be readonly while Piece can be changed. */ private Vector3Int m_position; private GameObject m_tile; private Piece m_piece; public Vector3Int Position { get { return m_position; } } public GameObject Tile { get { return m_tile; } } public Piece Piece { get { return m_piece; } set { m_piece = value; } } /** * Basic constructors for the class */ public BoardTile() { m_position = new Vector3Int(); m_tile = null; m_piece = null; } public BoardTile(Vector3Int position, GameObject tile, Piece piece) { m_position = position; m_tile = tile; m_piece = piece; } } /// <summary> /// Categories of console logging actions /// </summary> public enum LogType { Move = 0x00, Take = 0x01, Promote = 0x02, Win = 0x03 } /// <summary> /// Container to hold all logging information for easy printing /// </summary> struct LogEntry { public string description; public string initiator; public string receiver; public string piece; public Vector3 initiatorLocation; public Vector3 receiverLocation; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace QuickCollab.Models { public class SessionRegistration { public string SessionId { get; set; } public string Password { get; set; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Boarding.cs" company="CGI"> // Copyright (c) CGI. All rights reserved. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; using CGI.Reflex.Core; using CGI.Reflex.Core.Utilities; namespace CGI.Reflex.Web.Models.UserSessions { public class Boarding : IValidatableObject { [HiddenInput(DisplayValue = false)] public string SingleAccessToken { get; set; } public string UserName { get; set; } [Required(ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "Required")] [StringLength(50, ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "StringLength")] [Display(ResourceType = typeof(CoreResources), Name = "Password")] [DataType(DataType.Password)] public string Password { get; set; } [Required(ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "Required")] [StringLength(50, ErrorMessageResourceType = typeof(CoreResources), ErrorMessageResourceName = "StringLength")] [Display(ResourceType = typeof(WebResources), Name = "PasswordConfirm")] [DataType(DataType.Password)] public string PasswordConfirm { get; set; } public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) { if (!string.IsNullOrEmpty(Password)) { if (!PasswordPolicy.Validate(Password)) { yield return new ValidationResult("Le mot de passe n'est pas valide. Il doit faire 6 caractères minimum, et contenir au moins une minusucle, une majuscule et un chiffre.", new[] { "Password" }); } if (!Password.Equals(PasswordConfirm)) { yield return new ValidationResult("Les mots de passe ne correspondent pas.", new[] { "PasswordConfirm" }); } } } } }
using System.Linq; namespace CS.Data { public static class CategoryFilter { public static IQueryable<Category> WithCategoryId (this IQueryable<Category> qry, int id) { return qry.Where(c => c.CategoryId == id); } public static IQueryable<Category> WithCategoryName (this IQueryable<Category> qry, string categoryname) { return qry.Where(c => c.CategoryName.ToLower() == categoryname.ToLower()); } } }
using System; namespace AgentStoryComponents { public static class config { // LOCAL - DEV public static string db = "AgentStoryEvolution"; public static string dbUser = "AgentStorydbo"; public static string dbPwd = "jy1met2"; public static string dbIP = "127.0.0.1"; public static string protocol = "http"; public static string host = "localhost:8181"; public static string app = ""; //virtual dir ... public static int startStoryID = 7; public static int startStoryPage = 0; public static string aspNetEmailLicensePath = @"C:\Users\Admin2\Documents\Visual Studio 2008\Projects\GameStory\AgentStoryEvolution\AgentStoryHTTP\AgentStoryHTTP\bin\aspNetEmail.xml.lic"; public static int helpStoryID = 69; // PRODUCTION //public static string db = "AgentStoryEvolution"; //public static string dbUser = "AgentStorydbo"; //public static string dbPwd = "jy1met2"; //public static string dbIP = "127.0.0.1"; //public static string protocol = "http"; //public static string host = "hosting.smartorg.com"; //public static string app = "GameStory"; //public static int startStoryID = 6; //public static int startStoryPage = 0; //public static string aspNetEmailLicensePath = @"C:\Inetpub\wwwroot\hosting.smartorg.com\GameStory\bin\aspNetEmail.xml.lic"; //public static int helpStoryID = 69; public static string startEditor = "./screens/SlideNavigator.aspx"; public static string extraClassID = "AgentStoryComponents.extAPI.commands."; //plugin - extensibility class loader class ID public static string startStoryToolBR = "BASIC"; public static string defaultStoryToolBR = "BASIC"; //platform public static string storyToolbarStartMode = "BASIC"; //NONE NAV MIN ALL NOCHAT public static string includeMasterURL = "./includes/YUI"; public static bool editorsElementsExclusive = false; // true - story editors can only edit their own elements OR false - any editor can edit any elements in story public static bool ownerOfStoryCanModerate = true; public static string logoText = "SmartOrg"; public static string Orginization = "SmartOrg"; public static string storyUnavailible = "story unavailable"; public static string defaultLoginMessage = "Login "; public static bool bRequireVerificationForUserReg = false; public static bool bDebug = false; // public static bool allowMulipleWebmasterAliases = true; public static string auditMode = "FULL"; // FULL / NONE public static int numPEperUser = 15; // MAX number page elements returned in library call / lib page public static int changed = 1; public static string YouTubeDeveloperID = "BQOPXj9u7UE"; public static string defaultPassword = "pwd"; public static string smtpServer = "mail.agentidea.com"; public static string smtpUser = "mail-daemon@agentidea.com"; public static string smtpPwd = "jy1met2"; public static string allEmailFrom = "mail-daemon@agentidea.com"; public static string HomePageTitle = "Welcome to " + logoText; public static string webMasterEmail = "g@agentidea.com"; public static string welcomeTo = "welcome"; public static string publicUserEmail = "joepublic@bukanator.com"; public static int publicUserID = 4; /// <summary> /// oledb connection string /// </summary> public static string conn { get { return string.Format("Provider=sqloledb;Data Source={3};Initial Catalog={0};User Id={1};Password={2};", db, dbUser, dbPwd, dbIP); } } /// <summary> /// sqlclient connection string /// </summary> public static string sqlConn { get { return string.Format("server={3};database={0};UID={1};PWD={2};", db, dbUser, dbPwd, dbIP); } } public static string anonEmailReplyTo = "anon-relay@agentidea.com"; public static string AnonEmailBodyFooter= @" The sender of this message has indicated that their email address be kept private. "; public static string HelpEmailBodyFooter = @" Problems with this email? Visit http://www.agentidea.com/EmailHelp"; public static string GeneralEmailBodyFooter = @" __________________________________________ Share Stories at http://www.agentidea.com "; public static string defaultPEtext= @"<div style='width:400px;'> <b>This is an example page element</b> <br> <br> to EDIT: <ul> <li>click the 'edit' button, which will allow you to edit the source code / HTML</li> <li>to add a new page element, double click anywhere on a page</li> </ul> </div>"; public static string TOS = @" TOS removed!"; } }
using System; using System.Text.RegularExpressions; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CTDLGT.Stack___Queue { public class StackNode<T> { class Node { // Định nghĩa phần tử của danh sách là Node T data; // phần dữ liệu của Node Node next; // next trỏ đến Node tiếp theo // Contructor Node với dữ liệu t public Node(T t) { next = null; data = t; } // Định nghĩa các thuộc tính (Propeties) public T Data { get { return data; } set { data = value; } } public Node Next { get { return next; } set { next = value; } } } Node head; public void Push(T x) //Thêm phần tử { Node n = new Node(x); n.Next = head; head = n; } public T Pop() //Lấy phần tử { Node n = head; head = n.Next; return n.Data; } public T Top() //Lấy phần tử đầu { Node n = head; return n.Data; } public bool IsEmpty() { if (head == null) { return true; } return false; } public void PrintStack() { Node p = head; while (p != null) { Console.Write(" " + p.Data); p = p.Next; } } } public partial class Infixtopostfix { public Infixtopostfix() { } public string InfixtoPosfix(string nhap) { var a = new StackNode<string>(); var ketQuahauto = ""; string tk; nhap = nhap.Trim(); //Cắt hết khoảng trắng ở đầu và cuối chuỗi var s = ""; for (int i = 0; i < nhap.Length; i++) { if (nhap[i] != ' ') { s += nhap[i]; } } var demMoNgoac = 0; var demDongNgoac = 0; var demToanTu = 0; var demToanHang = 0; for (int i = 0; i < s.Length;) { GetTokken(s, out tk, ref i); if (tk[0] == '(') { demMoNgoac++; } else if (tk[0] == ')') { demDongNgoac++; } else if (LaToanTu(tk[0])) { demToanTu++; } else { demToanHang++; } } if (demDongNgoac == demMoNgoac && demToanHang - 1 == demToanTu) { for (int i = 0; i < s.Length;) { GetTokken(s, out tk, ref i); if (!LaToanTu(tk[0])) { ketQuahauto += tk + " "; } else { if (tk[0] == '(') { a.Push(tk); } else if (tk[0] == ')') { while (a.Top()[0] != '(') { ketQuahauto += a.Top() + " "; a.Pop(); } if (a.Top()[0] == '(') { a.Pop(); } } else { if (!a.IsEmpty() && DoUuTien(a.Top()[0]) < DoUuTien(tk[0])) { a.Push(tk); continue; } else if (a.IsEmpty()) { a.Push(tk); continue; } while (!a.IsEmpty() && DoUuTien(a.Top()[0]) >= DoUuTien(tk[0])) { ketQuahauto += a.Top() + " "; a.Pop(); } a.Push(tk); } } } while (!a.IsEmpty()) { if (a.Top()[0] == '(') { a.Pop(); continue; } ketQuahauto += a.Top() + " "; a.Pop(); } return ketQuahauto; } else { return "\nBieu thuc sai"; } } public void GetTokken(string chuoiNhap, out string tokken, ref int start) { tokken = ""; for (; start < chuoiNhap.Length; start++) { if (LaToanTu(chuoiNhap[start])) { if (tokken == "") { tokken += chuoiNhap[start]; start++; return; } else { return; } } else { tokken += chuoiNhap[start]; } } } public double TinhBieuThuc(string posfix) { string[] tt = posfix.Split(' '); var kq = new StackNode<string>(); for (int i = 0; i < tt.Length - 1; i++) { if (!LaToanTu(tt[i][0])) { kq.Push(tt[i]); } else { string a = kq.Top(); kq.Pop(); string b = kq.Top(); kq.Pop(); kq.Push(TinhToan(tt[i], b, a)); } } double ketqua = Convert.ToDouble(kq.Top()); return ketqua; } public string TinhToan(string toanTu, string soHang1, string soHang2) { double a = Convert.ToDouble(soHang1); double b = Convert.ToDouble(soHang2); if (toanTu[0] == '+') { return Convert.ToString(a + b); } else if (toanTu[0] == '-') { return Convert.ToString(a - b); } else if (toanTu[0] == '*') { return Convert.ToString(a * b); } else if (toanTu[0] == '/' && b != 0) { return Convert.ToString(a / b); } return ""; } public bool LaToanTu(char a) { if (a == '+' || a == '-' || a == '*' || a == '/' || a == '(' || a == ')') { return true; } return false; } public int DoUuTien(char a) { if (a == '+' || a == '-') { return 1; } else if (a == '*' || a == '/') { return 2; } return 0; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CanvasController : MonoBehaviour { public List<GameObject> UIitems; void OnEnable(){ foreach(GameObject item in UIitems){ item.SetActive(true); } } void OnDisable(){ foreach(GameObject item in UIitems){ item.SetActive(false); } } }
using System; using System.Runtime.Caching; namespace Yeasca.Metier { public static class CacheUtilisateur { private const string _cléSessions = Sessions<SessionUtilisateur>.INDEX_SESSION_CACHE; public static void initialiserLeCacheUtilisateur() { if (!MemoryCache.Default.Contains(_cléSessions)) réinitialiserLeCacheUtilisateur(); } public static void réinitialiserLeCacheUtilisateur() { if (MemoryCache.Default.Contains(_cléSessions)) MemoryCache.Default.Remove(_cléSessions); CacheItemPolicy paramètres = new CacheItemPolicy(); MemoryCache.Default.Set(_cléSessions, new Sessions<SessionUtilisateur>(), paramètres); } public static Sessions<SessionUtilisateur> Sessions { get { return MemoryCache.Default[_cléSessions] as Sessions<SessionUtilisateur>; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace quadratic_eqn { class Program { static void Main(string[] args) { double a; double b; double c; double square_b; double neg_b; double two_a; double neg_four_a_c; double square_b_minus_4ac; double root_of_square_b_4ac; double upper_calc_one; double upper_calc_two; double x_one; double x_two; a = Convert.ToDouble(Console.ReadLine()); b = Convert.ToDouble(Console.ReadLine()); c = Convert.ToDouble(Console.ReadLine()); square_b = b * b; neg_b = b * (-1); two_a = 2 * a; neg_four_a_c = 4 * a * c * (-1); square_b_minus_4ac = square_b - neg_four_a_c; if (square_b_minus_4ac < 0) Console.WriteLine(" quadratic equation has no solution"); else { root_of_square_b_4ac = Math.Sqrt(square_b_minus_4ac); upper_calc_one = neg_b + root_of_square_b_4ac; upper_calc_two = neg_b - root_of_square_b_4ac; x_one = upper_calc_one / two_a; x_two = upper_calc_two / two_a; Console.WriteLine("x1= {0}", x_one); Console.WriteLine("x2= {0}", x_two); Console.ReadLine(); } } } } }