text
stringlengths
13
6.01M
// <copyright file="IGsLiveProvider.cs" company="Firoozeh Technology LTD"> // Copyright (C) 2021 Firoozeh Technology LTD. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> /** * @author Alireza Ghodrati */ using FiroozehGameService.Core.GSLive; using FiroozehGameService.Models.Enums; namespace FiroozehGameService.Models.GSLive.Providers { /// <summary> /// Represents Game Service Multiplayer Provider (GSLive) /// </summary> public abstract class GsLiveRealTimeProvider { /// <summary> /// Create Room With Option Like : Name , Max , Role , IsPrivate /// </summary> /// <param name="option">(NOTNULL)Create Room Option</param> public abstract void CreateRoom(GSLiveOption.CreateRoomOption option); /// <summary> /// Create AutoMatch With Option Like : Min , Max , Role /// </summary> /// <param name="option">(NOTNULL)AutoMatch Option</param> public abstract void AutoMatch(GSLiveOption.AutoMatchOption option); /// <summary> /// Cancel Current AutoMatch /// </summary> public abstract void CancelAutoMatch(); /// <summary> /// Join In Room With RoomID /// </summary> /// <param name="roomId">(NOTNULL)Room's id You Want To Join</param> /// <param name="extra">Specifies the Extra Data To Send to Other Clients</param> /// <param name="password">(NULLABLE)Specifies the Password if Room is Private</param> public abstract void JoinRoom(string roomId, string extra = null, string password = null); /// <summary> /// Edit Current Room With Option Like : Name , Min , IsPrivate , ... /// NOTE : You Must Joined To a Room to Edit it /// </summary> /// <param name="option">(NOTNULL)Edit Room Option</param> public abstract void EditCurrentRoom(GSLiveOption.EditRoomOption option); /// <summary> /// Leave The Current Room /// </summary> public abstract void LeaveRoom(); /// <summary> /// Get Available Rooms According To Room's Role /// </summary> /// <param name="role">(NOTNULL)Room's Role </param> public abstract void GetAvailableRooms(string role); /// <summary> /// Send A Data To All Players in Room. /// </summary> /// <param name="data">(NOTNULL) Data To BroadCast </param> /// <param name="sendType">Send Type </param> public abstract void SendPublicMessage(byte[] data, GProtocolSendType sendType); /// <summary> /// Send A Data To Specific Player in Room. /// </summary> /// <param name="receiverMemberId">(NOTNULL) (Type : MemberID)Player's ID</param> /// <param name="data">(NOTNULL) Data for Send</param> public abstract void SendPrivateMessage(string receiverMemberId, byte[] data); /// <summary> /// Get Room Members Details /// </summary> public abstract void GetRoomMembersDetail(); /// <summary> /// Get Current Room Info /// </summary> public abstract void GetCurrentRoomInfo(); /// <summary> /// Get Your Invite Inbox /// </summary> public abstract void GetInviteInbox(); /// <summary> /// Invite a Specific Player To Specific Room /// </summary> /// <param name="roomId">(NOTNULL) (Type : RoomID)Room's ID</param> /// <param name="userId">(NOTNULL) (Type : UserID)User's ID</param> public abstract void InviteUser(string roomId, string userId); /// <summary> /// Accept a Specific Invite With Invite ID /// Note: After accepting the invitation, you will be automatically entered into the game room /// </summary> /// <param name="inviteId">(NOTNULL) (Type : InviteID) Invite's ID</param> /// <param name="extra">Specifies the Extra Data To Send to Other Clients</param> public abstract void AcceptInvite(string inviteId, string extra = null); /// <summary> /// Find All Member With Specific Query /// </summary> /// <param name="query">(NOTNULL) Query </param> /// <param name="limit">(Max = 15) The Result Limits</param> public abstract void FindMember(string query, int limit = 10); /// <summary> /// Get Current RoundTripTime(RTT) /// NOTE : You Must Join To RealTime Servers To Get Valid Data, Otherwise Return -1 /// </summary> public abstract int GetRoundTripTime(); /// <summary> /// Get Current PacketLost /// NOTE : You Must Join To RealTime Servers To Get Valid Data, Otherwise Return -1 /// </summary> public abstract long GetPacketLost(); /// <summary> /// Get Rooms Info According To Room's Role /// </summary> /// <param name="role">(NOTNULL)Room's Role </param> public abstract void GetRoomsInfo(string role); internal abstract void SendEvent(byte[] caller, byte[] data, GProtocolSendType sendType); internal abstract void SendObserver(byte[] caller, byte[] data); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class ShaderGlow : MonoBehaviour { Plane p; Vector2 mousePos; new Camera camera; Ray ray; // Start is called before the first frame update void Start() { p = new Plane(Vector3.up, Vector3.zero); //plane on xz plane camera = gameObject.GetComponent<Camera>(); } // Update is called once per frame void Update() { mousePos = Input.mousePosition; ray = camera.ScreenPointToRay(mousePos); if (p.Raycast(ray, out float enterDist)) { Vector3 worldMousePos = ray.GetPoint(enterDist); Shader.SetGlobalVector("_MousePos", worldMousePos); } } }
using System; class CountSubstringOccurrences { static void Main() { string inputStr = Console.ReadLine().ToLower(); string searchStr = Console.ReadLine().ToLower(); int indx = inputStr.IndexOf(searchStr); int counter = 0; while (indx >= 0 && indx <= inputStr.Length) { counter++; indx = inputStr.IndexOf(searchStr, indx + 1); } Console.WriteLine(counter); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BuyToolsArgs { private ItemKind m_itemKind; public ItemKind M_ItemKind { get { return m_itemKind; } set { m_itemKind = value; } } private int m_coin; public int M_Coin { get { return m_coin; } set { m_coin = value; } } }
namespace MobilePhone { using System; using System.Text; using System.Collections.Generic; public class GSM { public static GSM Iphone4s = new GSM("4s", "Apple", 300, "Ivan", new Battery(BatteryType.LiIon, 250, 145), new Display(3.5, 16000000)); public const double CallPrice = 0.35; private string model; private string manufacturer; private double price; private string owner; private Battery battery; private Display display; private List<Call> callHistory = new List<Call>(); public GSM(string model, string manufacturer, double price, string owner, Battery battery, Display display) { this.Model = model; this.Manufacturer = manufacturer; this.Price = price; this.Owner = owner; this.battery = battery; this.display = display; } public GSM(string model, string manufacturer) { this.Model = model; this.Manufacturer = manufacturer; } public void DisplayInfo() { Console.WriteLine(" Model: {0} \n Manufacturer: {1} \n\r Price: {2} \n Owner: {3} \n Battery: [Type: {4}] [Idle: {5}h] [Talk: {6}h] \n Display:[Number of colors: {7}] [Size: {8} inch] \n\n ", Model, Manufacturer, Price, Owner, battery.BatteryModel, battery.HoursIdle, battery.HoursTalk, display.NumberOfColors, display.Size); } public string CallHistoryInfo() { var callHistoryInfo = new StringBuilder(); if (this.callHistory.Count == 0) { return "Call history is empty!"; } callHistoryInfo.Append("Date\t\tTime\t\tDailed number\tDuration seconds\n"); for (int i = 0; i < this.callHistory.Count; i++) { callHistoryInfo.Append(this.callHistory[i].ToString()); callHistoryInfo.Append("\n"); } return callHistoryInfo.ToString(); } public void AddCall(Call calling) { this.callHistory.Add(calling); } public void ClearHistory() { this.callHistory.Clear(); } public List<Call> CallHistory { get { return this.callHistory; } set { this.callHistory = value; } } public string Model { get { return this.model; } set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("You must set the model"); } this.model = value; } } public string Manufacturer { get { return this.manufacturer; } set { if (string.IsNullOrWhiteSpace(value)) { throw new ArgumentException("You must set the manufacturer"); } this.manufacturer = value; } } public double Price { get { return this.price; } set { if (price < 0) { throw new ArgumentException("Price cannot be negative number"); } this.price = value; } } public string Owner { get { return this.owner; } set { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("You should insert Owner's name"); } this.owner = value; } } public Display Display { get { return this.display; } set { this.display = value; } } public Battery Battery { get { return this.battery; } set { this.battery = value; } } } }
using KRPC.Client; using System; using System.Threading; using kRPCUtilities; using KRPC.Client.Services.SpaceCenter; namespace kRPC.Programs { public class FlightControls { public FlightControls(Connection Connection, VesselProperty VesselProperty, FlightParameters FlightParams, CraftControls CraftControls) { connection = Connection; vesselProperty = VesselProperty; flightParams = FlightParams; craftControls = CraftControls; var spaceCenter = connection.SpaceCenter(); vessel = spaceCenter.ActiveVessel; var flight = vessel.Flight(); altitudeASL = connection.AddStream(() => flight.MeanAltitude); } private Connection connection; private Vessel vessel; private FlightParameters flightParams; private VesselProperty vesselProperty; private CraftControls craftControls; private Stream<double> altitudeASL; public bool RollProgramComplete { get; private set; } = false; public void RollProgram() { var flight = vessel.Flight(); var altitude = connection.AddStream(() => flight.SurfaceAltitude); Thread.Sleep(5000); vessel.AutoPilot.SAS = true; vessel.AutoPilot.RollThreshold = 2.5; vessel.AutoPilot.TargetRoll = 90f; vessel.AutoPilot.Engage(); Message.SendMessage("Beginning Roll Program", connection); while (!RollProgramComplete) { if (altitude.Get() >= flightParams.TurnStartAltitude) { RollProgramComplete = true; break; } } } public void GravityTurn() { var logicSwitch = false; Message.SendMessage("Beginning Gravity Turn", connection); while (true) { if (craftControls.SolidsJettisoned && !logicSwitch) { vessel.Control.Throttle = 1; logicSwitch = true; } if (altitudeASL.Get() >= flightParams.TurnStartAltitude && RollProgramComplete) { craftControls.MaxQThrottleSegment(); craftControls.JettisonSRBs(); vessel.AutoPilot.TargetPitch = Convert.ToSingle(90 - Math.Abs(flightParams.GravityTurnPitchPerMeter * altitudeASL.Get())); if (altitudeASL.Get() >= flightParams.TurnEndAltitude) { break; } } } } public void AscentToApoapsis() { var vesselApoapsis = connection.AddStream(() => vessel.Orbit.ApoapsisAltitude); var resourcesFirstStage = vessel.ResourcesInDecoupleStage(6, false); var firstStageFuel = connection.AddStream(() => resourcesFirstStage.Amount("LiquidFuel")); Message.SendMessage("Continuing Ascent To Apoapsis", connection); while (!craftControls.TargetApoapsisMet) { vessel.AutoPilot.TargetPitch = Convert.ToSingle(45 - Math.Abs(flightParams.AscentPitchPerMeter * altitudeASL.Get())); if (firstStageFuel.Get() / vesselProperty.MaxFuelFirstStage <= 0.12 && !craftControls.HasMECO) { //vessel.AutoPilot.Disengage(); //vessel.Control.SAS = true; //vessel.Control.SASMode = SASMode.Prograde; while (!craftControls.HasMECO) { craftControls.MECO(vesselProperty.FuelNeededForCoreRecovery, firstStageFuel); } } craftControls.SecondStageIgnition(); craftControls.ExtendSolarPanels(altitudeASL); craftControls.ReachingTargetApoapsis(vesselApoapsis); } } public void OrbitalInsertion() { var ut = connection.AddStream(() => connection.SpaceCenter().UT); #region Vis-Viva Equation double mu = vessel.Orbit.Body.GravitationalParameter; var r = vessel.Orbit.Apoapsis; var a1 = vessel.Orbit.SemiMajorAxis; var a2 = r; var v1 = Math.Sqrt(mu * ((2.0 / r) - (1.0 / a1))); var v2 = Math.Sqrt(mu * ((2.0 / r) - (1.0 / a2))); var deltaV = v2 - v1; #endregion var node = vessel.Control.AddNode(ut.Get() + vessel.Orbit.TimeToApoapsis, (float)deltaV); #region Calculate Burn Time var F = vessel.AvailableThrust; var Isp = vessel.SpecificImpulse * 9.82; var m0 = vessel.Mass; var m1 = m0 / Math.Exp(deltaV / Isp); var flowRate = F / Isp; var burnTime = (m0 - m1) / flowRate; #endregion OrientingShip(node); WaitUntilNode(ut, burnTime); ExecuteBurn(node, burnTime); } private void OrientingShip(Node node) { Message.SendMessage("Orienting Ship For Circularization Burn", connection); /* vessel.AutoPilot.ReferenceFrame = node.ReferenceFrame; vessel.AutoPilot.TargetDirection = Tuple.Create(0.0, 1.0, 0.0); vessel.AutoPilot.Wait(); */ vessel.AutoPilot.Disengage(); vessel.AutoPilot.SAS = true; Thread.Sleep(1000); vessel.AutoPilot.SASMode = SASMode.Maneuver; Thread.Sleep(25000); } private void WaitUntilNode(Stream<double> ut, double burnTime) { Message.SendMessage("Warping To Circularization Burn", connection); var burnUT = ut.Get() + vessel.Orbit.TimeToApoapsis - (burnTime / 2.0); var leadTime = 10; connection.SpaceCenter().WarpTo(burnUT - leadTime); ut.Remove(); } private void ExecuteBurn(Node node, double burnTime) { var remainingDeltaV = connection.AddStream(() => node.RemainingDeltaV); var timeToApoapsis = connection.AddStream(() => vessel.Orbit.TimeToApoapsis); while (timeToApoapsis.Get() - (burnTime / 2.0) > 0) { } Message.SendMessage("Executing Burn", connection); vessel.Control.Throttle = 1; while (remainingDeltaV.Get() >= 25) { } vessel.Control.Throttle = 0.5f; while (remainingDeltaV.Get() >= 3) { } vessel.Control.Throttle = 0; Message.SendMessage("SECO 2", connection); node.Remove(); craftControls.ExtendSolarPanels(altitudeASL); Message.SendMessage("Orbit Achieved", connection); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnManager : MonoBehaviour { public GameObject[] FishsMesopelagicaZone; public GameObject[] FishLvl2; public GameObject[] FishLvl3; public GameObject[] FishLvl4; public GameObject[] Energy; private LevelManager LvlManager; public float randomRangeX; public Transform target; private float startDelay = 1; private float spawnInterval = 3; private float timer = 0.0f; private float timelapse = 3.0f; // Start is called before the first frame updateS void Start() { LvlManager = FindObjectOfType<LevelManager>(); } // Update is called once per frame void FixedUpdate() { timer += Time.deltaTime; if (timer > timelapse) { timer -= timelapse; if (LvlManager.depth <= 2000 && LvlManager.depth >=1600) { Invoke("spawnFishMesopelagicaZone", startDelay); Invoke ("spawnEnergy", startDelay); } else if (LvlManager.depth <= 1599 && LvlManager.depth >= 1200) { Invoke("spawnLvl2Zone", startDelay); Invoke("spawnEnergy", startDelay); timelapse = 2.7f; } else if (LvlManager.depth <= 1199 && LvlManager.depth >= 800) { Invoke("spawnLvl3Zone", startDelay); timelapse = 2f; } else if (LvlManager.depth <= 799 && LvlManager.depth >= 400) { Invoke("spawnLvl4Zone", startDelay); timelapse = 1f; } } } public void spawnFishMesopelagicaZone() { UnityEngine.Vector3 spawnPos = new UnityEngine.Vector3(UnityEngine.Random.Range(-randomRangeX, randomRangeX), target.transform.position.y + 20, 0); int animalIndex = UnityEngine.Random.Range(0, FishsMesopelagicaZone.Length); Instantiate(FishsMesopelagicaZone[animalIndex], spawnPos, FishsMesopelagicaZone[animalIndex].transform.rotation); } public void spawnEnergy() { UnityEngine.Vector3 spawnPos = new UnityEngine.Vector3(UnityEngine.Random.Range(-randomRangeX, randomRangeX), target.transform.position.y + 20, 0); int energyIndex = UnityEngine.Random.Range(0, Energy.Length); Instantiate(Energy[energyIndex], spawnPos, Energy[energyIndex].transform.rotation); } public void spawnLvl2Zone() { UnityEngine.Vector3 spawnPos = new UnityEngine.Vector3(UnityEngine.Random.Range(-randomRangeX, randomRangeX), target.transform.position.y + 20, 0); int animalIndex = UnityEngine.Random.Range(0, FishLvl2.Length); Instantiate(FishLvl2[animalIndex], spawnPos, FishLvl2[animalIndex].transform.rotation); } public void spawnLvl3Zone() { UnityEngine.Vector3 spawnPos = new UnityEngine.Vector3(UnityEngine.Random.Range(-randomRangeX, randomRangeX), target.transform.position.y + 20, 0); int animalIndex = UnityEngine.Random.Range(0, FishLvl3.Length); Instantiate(FishLvl3[animalIndex], spawnPos, FishLvl3[animalIndex].transform.rotation); } public void spawnLvl4Zone() { UnityEngine.Vector3 spawnPos = new UnityEngine.Vector3(UnityEngine.Random.Range(-randomRangeX, randomRangeX), target.transform.position.y + 20, 0); int animalIndex = UnityEngine.Random.Range(0, FishLvl4.Length); Instantiate(FishLvl4[animalIndex], spawnPos, FishLvl4[animalIndex].transform.rotation); } }
using Project.Interface; using Project.Object; using Project.Presenter; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Timers; using System.Windows.Forms; namespace Project.View { public partial class MainPage : Form,IMainPage { SubjectEventScheduler schedule; UserInfObject _userInfObject; int _minuteRange =1; int _minuteNotifyEvery = 1; MainPagePresenter presenter; System.Timers.Timer timer; public MainPage(UserInfObject _userInfObject) { InitializeComponent(); this.presenter = new MainPagePresenter(this); this._userInfObject = _userInfObject; presenter.loadSubjectsAsync(); presenter.scheduledSubjectToday(); } public MainPage MainPage1 { get { return this;} } public UserInfObject userInfo { get { return _userInfObject; } set { _userInfObject = value; lblName.Text = _userInfObject.getName(); } } public DataGridView subjectList { get { return dataGridView1; } set { dataGridView1 = value; } } public DataGridView eventList { get { return dataGridView2; } set { dataGridView2 = value; } } public int minuteRange { get { return _minuteRange; } set { _minuteRange = value; } } public int minuteNotifyEvery { get { return _minuteNotifyEvery; } set { _minuteNotifyEvery = value; } } public NotifyIcon notifyIcon { get { return notifyIcon2; } set { notifyIcon2 = value; } } public Form mainpageForm { get { return this; } } Label IMainPage.lblSubjectsEnrolled { get { return this.lblSubjectsEnrolled; } set { this.lblSubjectsEnrolled = value; } } public ContextMenuStrip contextMenu { get { return this.contextMenuStrip1; } set { this.contextMenuStrip1 = value; } } private void button1_Click(object sender, EventArgs e) { presenter.showAddSubjects(); } private void button2_Click(object sender, EventArgs e) { presenter.ShowScheduleTime(); } private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e) { this.Show(); } private void dataGridView2_CellDoubleClick_1(object sender, DataGridViewCellEventArgs e) { } private void button5_Click(object sender, EventArgs e) { if (eventList.Rows.Count > 0) { presenter.ShowAllProgress(eventList.SelectedRows[0].Index); } else { MessageBox.Show("Nothing to Show"); } } private Form activeForm = null; private void openChildForm(Form childForm) { if (activeForm != null) activeForm.Close(); activeForm = childForm; childForm.TopLevel = false; childForm.FormBorderStyle = FormBorderStyle.None; childForm.Dock = DockStyle.Fill; currentPanel.Show(); currentPanel.BringToFront(); currentPanel.Controls.Add(childForm); currentPanel.Tag = childForm; childForm.BringToFront(); childForm.Show(); } private void edit_subject_btn_Click(object sender, EventArgs e) { Adding_Subject Adding_Subject = new Adding_Subject(_userInfObject); openChildForm(Adding_Subject); edit_subject_btn.BackColor = Color.FromArgb(15, 39, 63); //Schedule_btn.BackColor = Color.FromArgb(11, 17, 31); addAcitivty_btn.BackColor = Color.FromArgb(11, 17, 31); Setting_btn.BackColor = Color.FromArgb(11, 17, 31); } private void addAcitivty_btn_Click(object sender, EventArgs e) { ActSched ActSched = new ActSched(_userInfObject); openChildForm(ActSched); edit_subject_btn.BackColor = Color.FromArgb(11, 17, 31); //Schedule_btn.BackColor = Color.FromArgb(11, 17, 31); addAcitivty_btn.BackColor = Color.FromArgb(15, 39, 63); Setting_btn.BackColor = Color.FromArgb(11, 17, 31); } private void Schedule_btn_Click(object sender, EventArgs e) { } private void minmize_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; } private void clse_Click(object sender, EventArgs e) { this.Close(); } private void pictureBox2_Click(object sender, EventArgs e) { currentPanel.Hide(); currentPanel.SendToBack(); } private void Setting_btn_Click(object sender, EventArgs e) { Setting Setting = new Setting(userInfo,this); openChildForm(Setting); Setting_btn.BackColor = Color.FromArgb(15, 39, 63); edit_subject_btn.BackColor = Color.FromArgb(11, 17, 31); //Schedule_btn.BackColor = Color.FromArgb(11, 17, 31); addAcitivty_btn.BackColor = Color.FromArgb(11, 17, 31); } private void help_btn_Click(object sender, EventArgs e) { Help Help = new Help(); openChildForm(Help); help_btn.BackColor = Color.FromArgb(15, 39, 63); Setting_btn.BackColor = Color.FromArgb(11, 17, 31); edit_subject_btn.BackColor = Color.FromArgb(11, 17, 31); //Schedule_btn.BackColor = Color.FromArgb(11, 17, 31); addAcitivty_btn.BackColor = Color.FromArgb(11, 17, 31); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Xml; using DevExpress.XtraEditors; namespace IRAP.PLC.Collection { internal class DC_CPPlating_NB : CustomDataCollection { private string operationCode = "120101M1"; public DC_CPPlating_NB(MemoEdit mmoLog):base(mmoLog) { } protected override void GetDataAndSendToESB(DateTime beginDT, DateTime endDT) { WriteLogInThread( string.Format( "获取电镀[{0}]【{1}】-【{2}】的数据", SystemParams.Instance.DeviceCode, beginDT, endDT)); string sql = string.Format( "SELECT * FROM 入线表 " + "WHERE CDATE(出线时间) BETWEEN #{0}# AND #{1}#", beginDT, endDT); if (SystemParams.Instance.T216Code != "") operationCode = SystemParams.Instance.T216Code; DataTable dt = GetData(sql); XmlDocument xml = new XmlDocument(); XmlNode node = xml.CreateXmlDeclaration("1.0", "utf-8", ""); xml.AppendChild(node); if (dt != null && dt.Rows.Count > 0) { WriteLogInThread( string.Format( "共处理 {0} 条记录;", dt.Rows.Count)); XmlNode root = xml.SelectSingleNode("ROOT"); if (root == null) { root = xml.CreateElement("ROOT"); xml.AppendChild(root); } foreach (DataRow dr in dt.Rows) { if (dr["零件号码"].ToString().Trim() == "12345678") continue; root.RemoveAll(); sql = string.Format( "SELECT * FROM 线状态历史 " + "WHERE (CDATE(时间) BETWEEN #{0}# AND #{1}#) " + "AND 零件号码='{2}' AND 飞巴号='{3}'", dr["入线时间"].ToString(), dr["出线时间"].ToString(), dr["零件号码"].ToString(), dr["飞巴号"].ToString()); DataTable dtDetail = GetData(sql); if (dtDetail.Rows.Count > 0) { foreach (DataRow drd in dtDetail.Rows) { string remark = string.Format( "运行工步={0}|槽位名称={1}|设定时间={2}|入槽时间={3}", drd["运行工步"].ToString().Trim(), drd["槽位名称"].ToString().Trim(), drd["设定时间"].ToString().Trim(), drd["入槽时间"].ToString().Trim()); if (drd["设定温度波形"].ToString().Trim() != "") root.AppendChild( CreateDataRow( xml, drd, "", "温度", string.Format( "{0}|设定波形={1}|实际波形={2}", remark, drd["设定温度波形"].ToString().Trim(), drd["实际温度波形"].ToString().Trim()))); if (drd["设定电流波形"].ToString().Trim() != "") root.AppendChild( CreateDataRow( xml, drd, "", "电流", string.Format( "{0}|设定波形={1}|实际波形={2}", remark, drd["设定电流波形"].ToString().Trim(), drd["实际电流波形"].ToString().Trim()))); if (drd["实际电压波形"].ToString().Trim() != "") root.AppendChild( CreateDataRow( xml, drd, "", "电压", string.Format( "{0}|设定波形=|实际波形={1}", remark, drd["实际电压波形"].ToString().Trim()))); } } if (root.HasChildNodes) SendToESB(xml); } WriteLogInThread("处理完毕......"); } else { WriteLogInThread("无需处理......"); } } private XmlNode CreateDataRow( XmlDocument xml, DataRow dr, string paramCode, string paramName, string remark) { XmlNode node = xml.CreateElement("Row"); node.Attributes.Append( CreateAttr( xml, "CollectingTime", StrDateTimeToUnitTime(dr["时间"].ToString().Trim()))); node.Attributes.Append(CreateAttr(xml, "EquipmentCode", SystemParams.Instance.DeviceCode)); node.Attributes.Append(CreateAttr(xml, "OperationCode", operationCode)); node.Attributes.Append(CreateAttr(xml, "StepNo", "")); node.Attributes.Append(CreateAttr(xml, "ProductNo", dr["零件号码"].ToString().Trim())); node.Attributes.Append(CreateAttr(xml, "LotNumber", "")); node.Attributes.Append(CreateAttr(xml, "SerialNumber", "")); node.Attributes.Append(CreateAttr(xml, "Ordinal", "")); node.Attributes.Append(CreateAttr(xml, "ParamCode", paramCode)); node.Attributes.Append(CreateAttr(xml, "ParamName", paramName)); node.Attributes.Append(CreateAttr(xml, "LowLimit", "0")); node.Attributes.Append(CreateAttr(xml, "Criterion", "GELE")); node.Attributes.Append(CreateAttr(xml, "HighLimit", "0")); node.Attributes.Append(CreateAttr(xml, "Scale", "0")); node.Attributes.Append(CreateAttr(xml, "UnitOfMeasure", "")); node.Attributes.Append(CreateAttr(xml, "Conclusion", "")); node.Attributes.Append(CreateAttr(xml, "Metric01", "0")); node.Attributes.Append(CreateAttr(xml, "Metric02", "0")); node.Attributes.Append(CreateAttr(xml, "Metric03", "0")); node.Attributes.Append(CreateAttr(xml, "Metric04", "0")); node.Attributes.Append(CreateAttr(xml, "Metric05", "0")); node.Attributes.Append(CreateAttr(xml, "Remark", remark)); return node; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Boilerplate.Web.App.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; // For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860 namespace Boilerplate.Web.App.Controllers.Api { [Route("api/[controller]")] [ApiController] public class StoresController : ControllerBase { private readonly SalesDBContext _context; public StoresController(SalesDBContext context) { _context = context; if (_context.Store.Count() == 0) { // Create a new TodoItem if collection is empty, // which means you can't delete all TodoItems. _context.Store.Add(new Store { Name = "Item1", Address = "main" }); _context.SaveChanges(); } } // GET: api/Stores [HttpGet] public async Task<ActionResult<IEnumerable<Store>>> GetStores(int page, int numPerPage) { if (page == -1 & numPerPage == -1) { return await _context.Store.ToListAsync(); } var store = await _context.Store.ToListAsync(); var result = store.Skip((page - 1) * numPerPage).Take(numPerPage); return Ok(result); } // GET: api/Stores/5 [HttpGet("{id}")] public async Task<ActionResult<Store>> GetStore(int id) { var store = await _context.Store.FindAsync(id); if (store == null) { return NotFound(); } return store; } // POST: api/Stores [HttpPost] public async Task<ActionResult<Store>> PostTodoItem(Store store) { _context.Store.Add(store); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(GetStore), new { id = store.Id }, store); } // PUT: api/Stores/ [HttpPut("{id}")] public async Task<IActionResult> PutStore(int id, Store item) { if (id != item.Id)//fix this one to query the db { return BadRequest(); } _context.Entry(item).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); } // DELETE: api/Stores [HttpDelete("{id}")] public async Task<IActionResult> DeleteStore(int id) { var item = await _context.Store.FindAsync(id); if (item == null) { return NotFound(); } _context.Store.Remove(item); await _context.SaveChangesAsync(); return NoContent(); } } }
using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2019Gamejam { class Flag { public Vector2 pos; private bool endFlag; private Player p; public Flag(Player p) { this.p = p; endFlag = false; pos = new Vector2(620, 300); } public void Draw(Render render) { render.DrawTexture("Goal", pos); } public void Update() { } public void Hit() { endFlag = true; } public bool IsEnd() { return endFlag; } public Vector2 GetGPos() { return pos; } } }
using Controller.ExaminationAndPatientCard; using Controller.UsersAndWorkingTime; using Model.Doctor; using Model.Manager; using Model.Secretary; using Model.Users; using Repository; using Syncfusion.Windows.Shared; using System; using System.Collections.Generic; using System.Configuration; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using ZdravoKorporacija.DTO; using ZdravoKorporacija.View; namespace ZdravoKorporacija { /// <summary> /// Interaction logic for MakeAppointmentWindow.xaml /// </summary> public partial class MakeAppointmentWindow : Window { private ExaminationController examinationController = new ExaminationController(); private List<Doctor> doctors = new List<Doctor>(); private WorkingTimeController workingTimeController = new WorkingTimeController(); private PatientCardController patientCardController = new PatientCardController(); private List<Doctor> doctorsFirstShift = new List<Doctor>(); private List<Doctor> doctorsSecondShift = new List<Doctor>(); private bool doctorWorkInFirstShift; private Doctor doctor = new Doctor(); private PatientCard patientCard = new PatientCard(); public MakeAppointmentWindow() { InitializeComponent(); datePickerExamination.SelectedDate = DateTime.Now.AddDays(1); datePickerExamination.DisplayDateStart = DateTime.Now.AddDays(1); DateTime endDateInYear = new DateTime(2020, 12, 31); datePickerExamination.DisplayDateEnd = endDateInYear; patientCard = patientCardController.ViewPatientCard(MainWindow.patient.Jmbg); } private void datePickerExamination_SelectedDateChanged(object sender, SelectionChangedEventArgs e) { doctorsFirstShift = workingTimeController.ViewDoctorsWhoWork((DateTime)datePickerExamination.SelectedDate, WorkShifts.FIRST); doctorsSecondShift = workingTimeController.ViewDoctorsWhoWork((DateTime)datePickerExamination.SelectedDate, WorkShifts.SECOND); if (doctorsFirstShift.Count() == 0 && doctorsSecondShift.Count() == 0) { AppointmentMessageWindow appointmentMessageWindow = new AppointmentMessageWindow(); appointmentMessageWindow.Show(); } else if (doctorsFirstShift.Count() == 0) { doctors = doctorsSecondShift; } else if (doctorsSecondShift.Count() == 0) { doctors = doctorsFirstShift; } else { doctors = doctorsSecondShift; doctors.AddRange(doctorsFirstShift); } comboBoxDoctor.DataContext = doctors; comboBoxDoctor.SelectedItem = doctors[0]; } private void comboBoxDoctor_SelectionChanged(object sender, SelectionChangedEventArgs e) { doctor = (Doctor)comboBoxDoctor.SelectedItem; doctorWorkInFirstShift = isDoctorWorkInFirstShift(doctor); if (doctorWorkInFirstShift == true) { comboBoxAppointemtTime.DataContext = firstShift; } else { comboBoxAppointemtTime.DataContext = secondShift; } } private bool isDoctorWorkInFirstShift(Doctor doctor) { if (doctor == null) return false; WorkShifts workShifts = workingTimeController.getShiftForDoctor(doctor.Jmbg); if (workShifts == WorkShifts.FIRST) { return true; } else { return false; } } private void buttonViewProfile_Click(object sender, RoutedEventArgs e) { ProfileWindow profileWindow = new ProfileWindow(); profileWindow.Show(); this.Close(); } private void buttonHomePage_Click(object sender, RoutedEventArgs e) { HomePageWindow homePageWindow = new HomePageWindow(); homePageWindow.Show(); this.Close(); } private void buttonLogOut_Click(object sender, RoutedEventArgs e) { MainWindow mainWindow = new MainWindow(); mainWindow.Show(); this.Close(); } private void buttonMakeAppointment_Click(object sender, RoutedEventArgs e) { if (comboBoxDoctor.Text.Equals("") || datePickerExamination.Text.Equals("") || comboBoxAppointemtTime.Text.Equals("")) { ValidationMessageWindow validationWindow = new ValidationMessageWindow(); validationWindow.Show(); } else { patientCard = patientCardController.ViewPatientCard(MainWindow.patient.Jmbg); int lastId = examinationController.getLastId(); DateTime dateAndTime = (DateTime)datePickerExamination.SelectedDate; string date = dateAndTime.ToShortDateString(); string time = comboBoxAppointemtTime.Text; DateTime dateAndTimeExamination = Convert.ToDateTime(date + " " + time, CultureInfo.InvariantCulture); TypeOfExamination general = TypeOfExamination.Opsti; doctor = (Doctor)comboBoxDoctor.SelectedItem; Examination examination = examinationController.ScheduleExamination(new Examination(++lastId, general, dateAndTimeExamination, doctor, doctor.DoctorsOffice, patientCard)); if (examination == null) { BusyTermWindow busyTermWindow = new BusyTermWindow(); busyTermWindow.caption.Text = "Termin koji ste izabrali " + date +" " + time + " " + "je već zauzet kod doktora " + doctor.Name + " " + doctor.Surname + " " + doctor.Jmbg; busyTermWindow.Show(); } else { ReviewExaminationsWindow reviewExaminationsWindow = new ReviewExaminationsWindow(); reviewExaminationsWindow.Show(); this.Close(); } } } private void doctor_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.F1) { comboBoxDoctor.IsDropDownOpen = true; } } private void examinationDate_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.F1) { datePickerExamination.IsDropDownOpen = true; } } private void appointemtTime_KeyUp(object sender, KeyEventArgs e) { if (e.Key == Key.F1) { comboBoxAppointemtTime.IsDropDownOpen = true; } } public string[] firstShift = new string[] { "8:00 AM", "8:30 AM", "9:00 AM", "9:30 AM", "10:00 AM", "10:30 AM", "11:00 AM", "11:30 AM", "12:00 PM", "12:30 PM", "1:00 PM", "1:30 PM", "2:00 PM", "2:30 PM", "3:00 PM", "3:30 PM" }; public string[] secondShift = new string[] { "4:00 PM", "4:30 PM", "5:00 PM", "5:30 PM", "6:00 PM", "6:30 PM", "7:00 PM", "7:30 PM", "8:00 PM", "8:30 PM", "9:00 PM", "9:30 PM", "10:00 PM", "10:30 PM", "11:00 PM", "11:30 PM" }; } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEngine; [RequireComponent ( typeof ( Rigidbody ) )] [RequireComponent ( typeof ( CharacterMovement ) )] public class Character : MonoBehaviour { public enum State { Standing, Falling, Driving } public State currentState { get; protected set; } = State.Standing; [SerializeField] private float standingDrag = 6.0f; [SerializeField] private float fallingDrag = 0.0f; private bool canAim = true; private bool isAiming = false; public bool IsAiming { get { if (!canAim) { if (isAiming) { isAiming = false; OnAimChanged (); } } else { if (cInput.isAimInput || cWeapon.ShouldAim) { if (!isAiming) { isAiming = true; OnAimChanged (); } } else if(!cInput.isAimInput && !cWeapon.ShouldAim) { if (isAiming) { isAiming = false; OnAimChanged (); } } } return isAiming; } } public bool isCrouching { get { if (isCrouchingInput) { return true; } if (!isCrouchingInput && !canStand) { return true; } return false; } } public bool isRunning { get; set; } public bool shouldJump { get; set; } public bool canStand { get; set; } public bool isCrouchingInput { get; set; } public System.Action OnAimChanged; public new Rigidbody rigidbody { get; protected set; } public CharacterMovement cMovement { get; protected set; } public CharacterIK cIK { get; protected set; } public CharacterDrag cDrag { get; protected set; } public CharacterPhysics cPhysics { get; protected set; } public CharacterInput cInput { get; protected set; } public CharacterWeapon cWeapon { get; protected set; } public CharacterTargetMatch cTargetMatch { get; protected set; } public PlayerCameraController cCameraController { get; protected set; } public bool isGrounded { get; set; } = false; public new Collider collider; [SerializeField] private LayerMask walkableLayers; [SerializeField] private float stepHeight = 0.6f; [SerializeField] private float standHeight = 0.6f; [SerializeField] private bool isAI = false; [SerializeField] private GameObject cameraPrefab; public bool IsAI { get { return isAI; } } private void Awake () { rigidbody = GetComponent<Rigidbody> (); cMovement = GetComponent<CharacterMovement> (); cPhysics = GetComponent<CharacterPhysics> (); cIK = GetComponent<CharacterIK> (); cDrag = GetComponent<CharacterDrag> (); cInput = GetComponent<CharacterInput> (); cWeapon = GetComponent<CharacterWeapon> (); cTargetMatch = GetComponent<CharacterTargetMatch> (); if (FindObjectOfType<PlayerCameraController> () == null) cCameraController = Instantiate ( cameraPrefab ).GetComponent<PlayerCameraController> ().SetTarget ( this.transform ); else cCameraController = FindObjectOfType<PlayerCameraController> ().SetTarget ( this.transform ); } private void Update () { CheckStateUpdate (); if (isAI) return; if (IsAiming) { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } else { if (Input.GetKeyDown ( KeyCode.L )) { if (Cursor.lockState == CursorLockMode.Locked) { Cursor.lockState = CursorLockMode.None; Cursor.visible = true; } else { Cursor.lockState = CursorLockMode.Locked; Cursor.visible = false; } } } if (isCrouching) { GetComponent<CapsuleCollider> ().center = new Vector3 ( 0.0f, 0.75f, 0.0f ); GetComponent<CapsuleCollider> ().height = 1.0f; } else { GetComponent<CapsuleCollider> ().center = new Vector3 ( 0.0f, 1.1f, 0.0f ); GetComponent<CapsuleCollider> ().height = 1.4f; } } private void FixedUpdate () { CheckStateFixed (); } private void CheckStateUpdate () { switch (currentState) { case State.Standing: cMovement.OnUpdate (); cDrag.OnUpdate (); isGrounded = CheckIsGrounded (); CheckCanStand (); rigidbody.drag = standingDrag; break; case State.Falling: cMovement.OnUpdate (); isGrounded = CheckIsGrounded (); rigidbody.drag = fallingDrag; break; case State.Driving: break; default: break; } } private void CheckStateFixed () { switch (currentState) { case State.Standing: cMovement.OnFixedUpdate (); cDrag.OnFixedUpdate (); break; case State.Falling: cMovement.OnFixedUpdate (); break; case State.Driving: break; default: break; } } public void SetInput (Vector2 value) { cInput.input = value; cInput.rawInput = value; } public void SetCurrentState (State state) { currentState = state; OnStateChanged (); } private void OnStateChanged () { switch (currentState) { case State.Standing: canAim = true; break; case State.Falling: canAim = false; break; case State.Driving: canAim = false; if (!cWeapon.isHolstered) cWeapon.SetHolsterState (); break; } } private bool CheckIsGrounded () { Vector3 origin = transform.position; Vector3[] origins = new Vector3[5] { transform.position, transform.position + transform.forward * 0.25f, transform.position + transform.right * 0.25f, transform.position - transform.forward * 0.25f, transform.position - transform.right * 0.25f }; origin.y += stepHeight; Vector3 dir = -Vector3.up; float dist = stepHeight + 0.1f; RaycastHit hit; for (int i = 0; i < origins.Length; i++) { origins[i].y += stepHeight; Debug.DrawRay ( origins[i], dir * dist, Color.red ); if (Physics.Raycast ( origins[i], dir, out hit, dist, walkableLayers )) { Vector3 targetPosition = hit.point; transform.position = new Vector3 ( transform.position.x, targetPosition.y, transform.position.z ); SetCurrentState ( Character.State.Standing ); if (GetComponent<Animator> ().GetBool ( "falling" )) GetComponent<Animator> ().SetBool ( "falling", false ); return true; } } if (Physics.Raycast ( transform.position, dir, out hit, Mathf.Infinity, walkableLayers )) { float distanceToGround = Vector3.Distance ( transform.position, hit.point ); if (distanceToGround > 1.0f) { if (!GetComponent<Animator> ().GetBool ( "falling" )) GetComponent<Animator> ().SetBool ( "falling", true ); } if (distanceToGround < 1.0f) { if (rigidbody.velocity.magnitude > 7.5f) GetComponent<Animator> ().SetTrigger ( "softLand" ); } } if (cDrag.isDragging) cDrag.OnEndDrag (); if (cDrag.isBeingDragged) cDrag.OnEndDragged (); SetCurrentState ( Character.State.Falling ); Debug.Log ( "is NOT grounded" ); return false; } private bool CheckCanStand () { Vector3 origin = transform.position; Vector2 inputDir = cInput.rawInput; //origin += transform.forward * inputDir.y; //origin += transform.right * inputDir.x; if (canStand) { } else { //origin -= transform.forward * inputDir.y; //origin -= transform.right * inputDir.x; } origin.y += 0.5f; Vector3 dir = Vector3.up; Ray ray = new Ray ( origin, dir ); RaycastHit hit; if (Physics.Raycast ( ray, out hit, standHeight - 0.5f, walkableLayers )) { if (canStand) { //isCrouching = true; } if (hit.distance > 1.5f - 0.5f) canStand = false; else { canStand = true; } } else { if (!canStand) { //isCrouching = false; //Debug.Log ( "hello" ); } canStand = true; } return canStand; } }
using System.Text.RegularExpressions; namespace DaDo.Command { class WildcardPattern : Regex { public WildcardPattern(string wildCardPattern) : base(ConvertPatternToRegex(wildCardPattern), RegexOptions.IgnoreCase) { } public WildcardPattern(string wildcardPattern, RegexOptions regexOptions) : base(ConvertPatternToRegex(wildcardPattern), regexOptions) { } private static string ConvertPatternToRegex(string wildcardPattern) { string patternWithWildcards = Regex.Escape(wildcardPattern).Replace("\\*", ".*"); patternWithWildcards = string.Concat("^", patternWithWildcards.Replace("\\?", "."), "$"); return patternWithWildcards; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using DLMotion; using System.Security.Cryptography; using System.Text; using System; public class MainCore : MonoBehaviour { public bool IsMachineDisabled; private static MainCore _instance; private bool _isGaming; GameCore gameCore; public static int FirstWarningNum = 350000; public static int SecondWarningNum = 450000; internal int MovementCount; public static MainCore Instance { get { if (_instance == null) { _instance = FindObjectOfType(typeof(MainCore)) as MainCore; //if (_instance == null) //{ // GameObject obj =Instantiate(Resources.Load("MainCore") as GameObject); // //obj.hideFlags = HideFlags.HideAndDontSave; // _instance=obj.AddComponent<MainCore>(); //} } return _instance; } } public bool IsFinished; public bool IsGaming { get { return _isGaming; } set { if (_isGaming != value) { _isGaming = value; if (_isGaming) { gameCore.Reset(); gameCore.enabled = true; } else { gameCore.enabled = false; } } } } void Awake() { IsFinished = true; if (!IsMachineDisabled) { IsFinished = false; StartCoroutine(InitializeConnection()); } else { DetectionManage.Instance.ActionReConnect += OnReConnect; DetectionManage.Instance.ActionEmrgencyStop += OnEmrgencyStop; } gameCore = this.GetComponent<GameCore>(); if (gameCore != null) { gameCore.enabled = false; } else { gameCore = this.gameObject.AddComponent<GameCore>(); gameCore.enabled = false; } } // Update is called once per frame void Update () { if (!IsMachineDisabled) { if (!DynaLinkHS.ServerLinkActBit) { //Debug.Log("DynaLinkHS.ServerLinkActBit=========" + DynaLinkHS.ServerLinkActBit); } //获取机器连接的标志位 DetectionManage.Instance.Connected = DynaLinkHS.ServerLinkActBit; //获取机器急停的标志位(只有在机器连接状态下) if (CommandFunctions.IsConnected)//DetectionManage.Instance.Connected { DetectionManage.Instance.EMstopBit = DiagnosticStatus.MotStatus.EMstopBit; } } } /// <summary> /// 机器连接状态监听 /// </summary> /// <param name="IsConnected"></param> void OnReConnect(bool IsConnected) { if (!IsConnected) { CommandFunctions.IsConnected = false; } else { //CommandFunctions.IsConnected = true; } } /// <summary> /// 机器急停监听 /// </summary> /// <param name="IsEmrgencyStop"></param> void OnEmrgencyStop(bool IsEmrgencyStop) { if (IsEmrgencyStop) { CommandFunctions.IsEmrgencyStop = true; } else { CommandFunctions.IsEmrgencyStop = false; } } public void AddMovementCount() { MovementCount++; } void OnDestroy() { DetectionManage.Instance.ActionReConnect -= OnReConnect; DetectionManage.Instance.ActionEmrgencyStop -= OnEmrgencyStop; } void OnApplicationQuit() { DynaLinkCore.StopSocket(); UdpBasicClass.UdpSocketClient.SocketQuit(); } /// <summary> /// 开机连接到机器 /// </summary> /// <returns></returns> IEnumerator InitializeConnection() { //如果机器还未连接,发送连接命名 if (!DetectionManage.Instance.Connected) { Debug.Log("Begin Connect"); DynaLinkCore.ConnectClick(); } //三秒等待连接 float initialTimeOut = 0; while (!DetectionManage.Instance.Connected) { if (initialTimeOut >= 3f) { //超过三秒,连接超时,断开连接准备重连 DynaLinkCore.StopSocket(); Debug.Log("Initialize connection Time-out!"); Debug.Log("Disconnected!"); //断开连接有一定的延迟 yield return new WaitForSeconds(1f); //开始监听连接和急停的事件 DetectionManage.Instance.ActionReConnect += OnReConnect; DetectionManage.Instance.ActionEmrgencyStop += OnEmrgencyStop; //由于未连接上执行断开连接的事件一次 OnReConnect(false); IsFinished = true; yield break; } yield return new WaitForSeconds(1f); initialTimeOut += 1f; } CommandFunctions.IsConnected = true; //如果连接上了,开始监听连接事件 DetectionManage.Instance.ActionReConnect += OnReConnect; //判断机器是否有急停情况 if (DetectionManage.Instance.EMstopBit) { OnEmrgencyStop(true); } //开始监听急停事件 DetectionManage.Instance.ActionEmrgencyStop += OnEmrgencyStop; IsFinished = true; } }
using System.Collections.Generic; using System.Net.Http; namespace Yaringa.Models.Token { #pragma warning disable // Disable all warnings [System.CodeDom.Compiler.GeneratedCode("NSwag", "11.19.0.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")] public partial interface ITokensClient { /// <exception cref="SwaggerException">A server side error occurred.</exception> System.Threading.Tasks.Task<TokenDTO> CreateAsync(TokenCreationDTO dto); /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> System.Threading.Tasks.Task<TokenDTO> CreateAsync(TokenCreationDTO dto, System.Threading.CancellationToken cancellationToken); /// <exception cref="SwaggerException">A server side error occurred.</exception> System.Threading.Tasks.Task<TokenDTO> RefreshAsync(TokenRefreshDTO dto); /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> System.Threading.Tasks.Task<TokenDTO> RefreshAsync(TokenRefreshDTO dto, System.Threading.CancellationToken cancellationToken); } [System.CodeDom.Compiler.GeneratedCode("NSwag", "11.19.0.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")] public partial class TokensClient : ITokensClient { private string _baseUrl = ""; private System.Lazy<Newtonsoft.Json.JsonSerializerSettings> _settings; public TokensClient(string baseUrl) { BaseUrl = baseUrl; _settings = new System.Lazy<Newtonsoft.Json.JsonSerializerSettings>(() => { var settings = new Newtonsoft.Json.JsonSerializerSettings(); UpdateJsonSerializerSettings(settings); return settings; }); } public string BaseUrl { get { return _baseUrl; } set { _baseUrl = value; } } protected Newtonsoft.Json.JsonSerializerSettings JsonSerializerSettings { get { return _settings.Value; } } partial void UpdateJsonSerializerSettings(Newtonsoft.Json.JsonSerializerSettings settings); partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, string url); partial void PrepareRequest(System.Net.Http.HttpClient client, System.Net.Http.HttpRequestMessage request, System.Text.StringBuilder urlBuilder); partial void ProcessResponse(System.Net.Http.HttpClient client, System.Net.Http.HttpResponseMessage response); /// <exception cref="SwaggerException">A server side error occurred.</exception> public System.Threading.Tasks.Task<TokenDTO> CreateAsync(TokenCreationDTO dto) { return CreateAsync(dto, System.Threading.CancellationToken.None); } /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task<TokenDTO> CreateAsync(TokenCreationDTO dto, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/token"); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var formDataDictionary = new Dictionary<string, string>() { {"client_id", dto.Client_id }, {"username", dto.Username }, {"password", dto.Password }, {"grant_type", "password" } }; var formData = new FormUrlEncodedContent(formDataDictionary); //var content_ = new System.Net.Http.StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(dto, _settings.Value)); var content_ = formData; content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(TokenDTO); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenDTO>(responseData_, _settings.Value); return result_; } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return default(TokenDTO); } finally { if (response_ != null) response_.Dispose(); } } } finally { if (client_ != null) client_.Dispose(); } } /// <exception cref="SwaggerException">A server side error occurred.</exception> public System.Threading.Tasks.Task<TokenDTO> RefreshAsync(TokenRefreshDTO dto) { return RefreshAsync(dto, System.Threading.CancellationToken.None); } /// <exception cref="SwaggerException">A server side error occurred.</exception> /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param> public async System.Threading.Tasks.Task<TokenDTO> RefreshAsync(TokenRefreshDTO dto, System.Threading.CancellationToken cancellationToken) { var urlBuilder_ = new System.Text.StringBuilder(); urlBuilder_.Append(BaseUrl != null ? BaseUrl.TrimEnd('/') : "").Append("/api/token"); var client_ = new System.Net.Http.HttpClient(); try { using (var request_ = new System.Net.Http.HttpRequestMessage()) { var formDataDictionary = new Dictionary<string, string>() { {"client_id", dto.Client_id }, {"grant_type", "refresh_token" }, {"refresh_token", dto.Refresh_token } }; var formData = new FormUrlEncodedContent(formDataDictionary); var content_ = formData; content_.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/x-www-form-urlencoded"); request_.Content = content_; request_.Method = new System.Net.Http.HttpMethod("POST"); request_.Headers.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); PrepareRequest(client_, request_, urlBuilder_); var url_ = urlBuilder_.ToString(); request_.RequestUri = new System.Uri(url_, System.UriKind.RelativeOrAbsolute); PrepareRequest(client_, request_, url_); var response_ = await client_.SendAsync(request_, System.Net.Http.HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); try { var headers_ = System.Linq.Enumerable.ToDictionary(response_.Headers, h_ => h_.Key, h_ => h_.Value); if (response_.Content != null && response_.Content.Headers != null) { foreach (var item_ in response_.Content.Headers) headers_[item_.Key] = item_.Value; } ProcessResponse(client_, response_); var status_ = ((int)response_.StatusCode).ToString(); if (status_ == "200") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); var result_ = default(TokenDTO); try { result_ = Newtonsoft.Json.JsonConvert.DeserializeObject<TokenDTO>(responseData_, _settings.Value); return result_; } catch (System.Exception exception_) { throw new SwaggerException("Could not deserialize the response body.", (int)response_.StatusCode, responseData_, headers_, exception_); } } else if (status_ != "200" && status_ != "204") { var responseData_ = response_.Content == null ? null : await response_.Content.ReadAsStringAsync().ConfigureAwait(false); throw new SwaggerException("The HTTP status code of the response was not expected (" + (int)response_.StatusCode + ").", (int)response_.StatusCode, responseData_, headers_, null); } return default(TokenDTO); } finally { if (response_ != null) response_.Dispose(); } } } finally { if (client_ != null) client_.Dispose(); } } private string ConvertToString(object value, System.Globalization.CultureInfo cultureInfo) { if (value is System.Enum) { string name = System.Enum.GetName(value.GetType(), value); if (name != null) { var field = System.Reflection.IntrospectionExtensions.GetTypeInfo(value.GetType()).GetDeclaredField(name); if (field != null) { var attribute = System.Reflection.CustomAttributeExtensions.GetCustomAttribute(field, typeof(System.Runtime.Serialization.EnumMemberAttribute)) as System.Runtime.Serialization.EnumMemberAttribute; if (attribute != null) { return attribute.Value; } } } } else if (value is byte[]) { return System.Convert.ToBase64String((byte[]) value); } else if (value != null && value.GetType().IsArray) { var array = System.Linq.Enumerable.OfType<object>((System.Array) value); return string.Join(",", System.Linq.Enumerable.Select(array, o => ConvertToString(o, cultureInfo))); } return System.Convert.ToString(value, cultureInfo); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.72.0 (Newtonsoft.Json v9.0.0.0)")] public partial class TokenCreationDTO : System.ComponentModel.INotifyPropertyChanged { private string _grant_type; private string _username; private string _password; private string _client_id; [Newtonsoft.Json.JsonProperty("grant_type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Grant_type { get { return _grant_type; } set { if (_grant_type != value) { _grant_type = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("username", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Username { get { return _username; } set { if (_username != value) { _username = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("password", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Password { get { return _password; } set { if (_password != value) { _password = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("client_id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Client_id { get { return _client_id; } set { if (_client_id != value) { _client_id = value; RaisePropertyChanged(); } } } public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this); } public static TokenCreationDTO FromJson(string data) { return Newtonsoft.Json.JsonConvert.DeserializeObject<TokenCreationDTO>(data); } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.72.0 (Newtonsoft.Json v9.0.0.0)")] public partial class TokenRefreshDTO : System.ComponentModel.INotifyPropertyChanged { private string _grant_type; private string _client_id; private string _refresh_token; [Newtonsoft.Json.JsonProperty("grant_type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Grant_type { get { return _grant_type; } set { if (_grant_type != value) { _grant_type = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("client_id", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Client_id { get { return _client_id; } set { if (_client_id != value) { _client_id = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("refresh_token", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Refresh_token { get { return _refresh_token; } set { if (_refresh_token != value) { _refresh_token = value; RaisePropertyChanged(); } } } public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this); } public static TokenRefreshDTO FromJson(string data) { return Newtonsoft.Json.JsonConvert.DeserializeObject<TokenRefreshDTO>(data); } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.CodeDom.Compiler.GeneratedCode("NJsonSchema", "9.10.72.0 (Newtonsoft.Json v9.0.0.0)")] public partial class TokenDTO : System.ComponentModel.INotifyPropertyChanged { private string _access_token; private string _token_type; private long _expires_in; private string _refresh_token; [Newtonsoft.Json.JsonProperty("access_token", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Access_token { get { return _access_token; } set { if (_access_token != value) { _access_token = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("token_type", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Token_type { get { return _token_type; } set { if (_token_type != value) { _token_type = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("expires_in", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public long Expires_in { get { return _expires_in; } set { if (_expires_in != value) { _expires_in = value; RaisePropertyChanged(); } } } [Newtonsoft.Json.JsonProperty("refresh_token", Required = Newtonsoft.Json.Required.Default, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore)] public string Refresh_token { get { return _refresh_token; } set { if (_refresh_token != value) { _refresh_token = value; RaisePropertyChanged(); } } } public string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this); } public static TokenDTO FromJson(string data) { return Newtonsoft.Json.JsonConvert.DeserializeObject<TokenDTO>(data); } public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; protected virtual void RaisePropertyChanged([System.Runtime.CompilerServices.CallerMemberName] string propertyName = null) { var handler = PropertyChanged; if (handler != null) handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); } } [System.CodeDom.Compiler.GeneratedCode("NSwag", "11.19.0.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")] public partial class SwaggerException : System.Exception { public int StatusCode { get; private set; } public string Response { get; private set; } public System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> Headers { get; private set; } public SwaggerException(string message, int statusCode, string response, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers, System.Exception innerException) : base(message, innerException) { StatusCode = statusCode; Response = response; Headers = headers; } public override string ToString() { return string.Format("HTTP Response: \n\n{0}\n\n{1}", Response, base.ToString()); } } [System.CodeDom.Compiler.GeneratedCode("NSwag", "11.19.0.0 (NJsonSchema v9.10.72.0 (Newtonsoft.Json v9.0.0.0))")] public partial class SwaggerException<TResult> : SwaggerException { public TResult Result { get; private set; } public SwaggerException(string message, int statusCode, string response, System.Collections.Generic.Dictionary<string, System.Collections.Generic.IEnumerable<string>> headers, TResult result, System.Exception innerException) : base(message, statusCode, response, headers, innerException) { Result = result; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CarriageMenu : MonoBehaviour { public void Init() { for (int i = 0; i < transform.childCount; i++) { RectTransform child = transform.GetChild(i).GetComponent<RectTransform>(); if (child == null) { continue; } child.Rotate(0, 0, (360 / transform.childCount * i) + 180); child.localScale = Vector3.one; } } public void Reset() { foreach (Transform child in gameObject.transform) { Destroy(child.gameObject); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Observer { abstract class AlgoObservable { protected List<ObservadorDeContainers> _observers = new List<ObservadorDeContainers>(); public void AgregarObservador(ObservadorDeContainers o) { _observers.Add(o); } public void QuitarObservador(ObservadorDeContainers o) { _observers.Remove(o); } protected void Notificar() { foreach (var observador in _observers) { observador.AnalizarContainer(this); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; //.. using ETS.logic.Domain; using ETS.logic; using System.Data; using System.Data.SqlClient; namespace ETS.data { public class EmployeeDao { public static List<Employee> GetEmpList() { List<Employee> empList = new List<Employee>(); myConnection.Open(); SqlCommand get = new SqlCommand("dbo.sp_Employee_SelectAll", myConnection); get.CommandType = CommandType.StoredProcedure; SqlDataReader myReader = get.ExecuteReader(); // Check myReader has hours info if (myReader.HasRows) { while (myReader.Read()) { // Create new Employee object Employee emp = new Employee(); // Add properties emp.EmpID = (int)(myReader["EmpID"]); emp.FirstName = (myReader["FirstName"]).ToString(); emp.LastName = (myReader["LastName"]).ToString(); emp.Email = (myReader["Email"]).ToString(); emp.DOB = (DateTime)(myReader["DOB"]); emp.Phone = (myReader["Phone"]).ToString(); // Add to empList empList.Add(emp); } } myConnection.Close(); return empList; } // Set connection string private static SqlConnection myConnection = new SqlConnection(); public static void SetCon(string conn) { myConnection = new SqlConnection(conn); } public static DataSet GetDBInfo() { // Method to open database, retrieve all Employees, store it in a DataSet, // and the pass it back to MainForm myConnection.Open(); DataSet ds = new DataSet(); SqlDataAdapter adapter = new SqlDataAdapter(); adapter.SelectCommand = new SqlCommand("dbo.sp_Employee_SelectAll", myConnection); adapter.Fill(ds); myConnection.Close(); return ds; } // Get EmpHours by EmpID public static List<EmpHours> GetEmpHours(Employee emp) { List<EmpHours> empHoursList = new List<EmpHours>(); // Open the SQL connection myConnection.Open(); // Create a new SQL command using the stored procedure SqlCommand get = new SqlCommand("dbo.sp_EmpHours_GetEmpHours", myConnection); // Set commandtype to store procedure get.CommandType = CommandType.StoredProcedure; // Add parameters to command get.Parameters.AddWithValue("@empID", emp.EmpID); // Execture store procedure SqlDataReader myReader = get.ExecuteReader(); // Check myReader has hours info if (myReader.HasRows) { while (myReader.Read()) { // Create new EmpHours EmpHours empHours = new EmpHours(emp); empHours.EmpHoursID = (int)(myReader["EmpHoursID"]); empHours.Emp.EmpID = (int)(myReader["EmpID"]); empHours.Date = (DateTime)(myReader["WorkDate"]); empHours.Hours = (myReader["Hours"]).ToString(); // Add to List empHoursList.Add(empHours); } } // Close the connection (VERY important!) myConnection.Close(); return empHoursList; } public static int InsertEmployee(Employee emp) { // Open the SQL connection myConnection.Open(); // Create a new SQL command using the stored procedure SqlCommand add = new SqlCommand("dbo.sp_Employee_InsertEmployee", myConnection); // Set commandtype to store procedure add.CommandType = CommandType.StoredProcedure; // Add parameters to command add.Parameters.AddWithValue("@firstName", emp.FirstName); add.Parameters.AddWithValue("@lastName", emp.LastName); add.Parameters.AddWithValue("@email", emp.Email); add.Parameters.AddWithValue("@dob", emp.DOB); add.Parameters.AddWithValue("@phone", emp.Phone); // Execture store procedure add.ExecuteNonQuery(); // Close the connection (VERY important!) myConnection.Close(); return (int)SuccessEnum.Success; } public static int UpdateEmployee(Employee emp) { // Open the SQL connection myConnection.Open(); // Create a new SQL command using the stored procedure SqlCommand update = new SqlCommand("dbo.sp_Employee_UpdateEmployee", myConnection); // Set commandtype to store procedure update.CommandType = CommandType.StoredProcedure; // Add parameters to command update.Parameters.AddWithValue("@empID", emp.EmpID); update.Parameters.AddWithValue("@firstName", emp.FirstName); update.Parameters.AddWithValue("@lastName", emp.LastName); update.Parameters.AddWithValue("@email", emp.Email); update.Parameters.AddWithValue("@dob", emp.DOB); update.Parameters.AddWithValue("@phone", emp.Phone); // Execture store procedure update.ExecuteNonQuery(); // Close the connection (VERY important!) myConnection.Close(); return (int)SuccessEnum.Success; } private static Employee SearchById(int empId) { Employee emp = new Employee(); // Open the SQL connection myConnection.Open(); // Create a new SQL command using the stored procedure SqlCommand search = new SqlCommand("dbo.sp_Employee_SearchByID", myConnection); // Set commandtype to store procedure search.CommandType = CommandType.StoredProcedure; // Add parameters to command search.Parameters.AddWithValue("@empID", empId); // Execture store procedure SqlDataReader myReader = search.ExecuteReader(); // Check myReader has employee info if (myReader.HasRows) { while (myReader.Read()) { emp.EmpID = (int)(myReader["EmpID"]); emp.FirstName = (myReader["FirstName"]).ToString(); emp.LastName = (myReader["LastName"]).ToString(); emp.Email = (myReader["Email"]).ToString(); emp.DOB = (DateTime)(myReader["DOB"]); emp.Phone = (myReader["Phone"]).ToString(); } } // Close the connection (VERY important!) myConnection.Close(); return emp; } public static int InsertHours(EmpHours empHours) { // Format date so we can split it using (null) [whitespaces] //string date = emp.Date.Replace("/", " "); //date = date.Replace("-", " "); //string[] dateFormat = date.Split(null); //date = dateFormat[2] + dateFormat[1] + dateFormat[0]; // Open the SQL connection myConnection.Open(); // Create a new SQL command using the stored procedure SqlCommand add = new SqlCommand("dbo.sp_EmpHours_InsertEmployeeHours", myConnection); // Set commandtype to store procedure add.CommandType = CommandType.StoredProcedure; // Add parameters to command add.Parameters.AddWithValue("@empID", empHours.Emp.EmpID); add.Parameters.AddWithValue("@workDate", empHours.Date); add.Parameters.AddWithValue("@hours", empHours.Hours); // Execture store procedure add.ExecuteNonQuery(); // Close the connection (VERY important!) myConnection.Close(); return (int)SuccessEnum.Success; } //public static int SelectHoursById(Employee emp) //{ // string empInfo = ""; // // Open the SQL connection // myConnection.Open(); // // Create a new SQL command using the stored procedure // SqlCommand search = new SqlCommand("dbo.sp_EmpHours_SelectHours", myConnection); // // Set commandtype to store procedure // search.CommandType = CommandType.StoredProcedure; // // Add parameters to command // search.Parameters.AddWithValue("@empID", emp.EmpID); // // Execture store procedure // SqlDataReader myReader = search.ExecuteReader(); // // Check myReader has employee info // if (myReader.HasRows) // { // while (myReader.Read()) // { // string date = (myReader["WorkDate"]).ToString(); // string[] dateArr = date.Split(null); // empInfo += "Hours ID: " + (myReader["EmpHoursID"]).ToString() + "\n" // + "Work Date: " + dateArr[0] + "\n" // + "Hours: " + (myReader["Hours"]).ToString() + "\n\n"; // } // } // // Doesn't send a string now, so I have to work out antoher way // // to return the info. // else // { // myConnection.Close(); // return (int)SuccessEnum.Fail; // } // // Close the connection (VERY important!) // myConnection.Close(); // return (int)SuccessEnum.Success; //} } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Web; using CommonUtil; using Huawei.SCOM.ESightPlugin.LogUtil; using Huawei.SCOM.ESightPlugin.Models; using Huawei.SCOM.ESightPlugin.RESTeSightLib.Helper; using Huawei.SCOM.ESightPlugin.WebServer.Helper; namespace Huawei.SCOM.ESightPlugin.WebServer { /// <summary> /// SystemKeepAlive 的摘要说明 /// </summary> public class SystemKeepAlive : IHttpHandler { public void ProcessRequest(HttpContext context) { context.Response.ContentType = "text/plain"; var url = context.Request.Url; var formData = context.Request.Form; try { // todo 校验header中的OpenId var subscribeId = context.Request.QueryString["subscribeID"]; var msgType = context.Request.Form["msgType"]; var data = context.Request.Form["data"]; var datas = JsonUtil.DeserializeObject<List<KeepAliveData>>(data); if (!datas.Any()) { throw new Exception($"The message do not contain \"data\" param ."); } HWLogger.NotifyRecv.Info($"url :{url},[msgType:{msgType}], data:{JsonUtil.SerializeObject(datas)}"); var eSight = ESightDal.Instance.GetEntityBySubscribeId(subscribeId); if (eSight == null) { HWLogger.NotifyRecv.Warn($"can not find the eSight,subscribeID:{subscribeId}"); } else { Task.Run(() => { var aliveData = new NotifyModel<KeepAliveData> { SubscribeId = subscribeId, MsgType = Convert.ToInt32(msgType), ResourceURI = context.Request.Form["resourceURI"], Timestamp = context.Request.Form["timestamp"], Description = context.Request.Form["description"], ExtendedData = context.Request.Form["extendedData"], Data = datas.FirstOrDefault() }; var message = new TcpMessage<NotifyModel<KeepAliveData>>(eSight.HostIP, TcpMessageType.KeepAlive, aliveData); NotifyClient.Instance.SendMsg(message); }); } } catch (Exception ex) { HWLogger.NotifyRecv.Error($"SystemKeepAlive Notification Error:{url} formData:{formData}", ex); context.Response.Write($"SystemKeepAlive Notification Error:{ ex } "); } context.Response.End(); } public bool IsReusable { get { return false; } } } }
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace Fireasy.Web.Sockets { public class DefaultLifetimeManager : ILifetimeManager { private static ConcurrentDictionary<Type, ClientManager> managers = new ConcurrentDictionary<Type, ClientManager>(); private ConcurrentDictionary<string, IClientProxy> clients = new ConcurrentDictionary<string, IClientProxy>(); private ConcurrentDictionary<string, List<string>> groups = new ConcurrentDictionary<string, List<string>>(); private WebSocketAcceptContext context; public DefaultLifetimeManager(WebSocketAcceptContext context, ClientManager d) { this.context = context; } public void AddUser() { throw new NotImplementedException(); } public Task LisitenAsync() { throw new NotImplementedException(); } public async Task SendAsync(InvokeMessage message) { var json = context.Option.Formatter.FormatMessage(message); var bytes = context.Option.Encoding.GetBytes(json); await context.WebSocket.SendAsync(new ArraySegment<byte>(bytes, 0, bytes.Length), WebSocketMessageType.Text, true, CancellationToken.None); } public Task SendToGroup(InvokeMessage message) { throw new NotImplementedException(); } public Task SendToUser(InvokeMessage message) { throw new NotImplementedException(); } public Task SendToUsers(InvokeMessage message) { throw new NotImplementedException(); } } }
using PaperPlane.TLTranslator.Compiler.Model; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace PaperPlane.TLTranslator.Compiler { internal class TLDocParser { public List<TLCombinator> ParseCurrentSchema(string schemaPath) { var combinators = new List<TLCombinator>(); using (var sr = new StreamReader(schemaPath)) { bool isFunctionsDecl = false; while (!sr.EndOfStream) { var line = sr.ReadLine(); if (line.StartsWith("//")) continue; if (line.StartsWith("---types---")) { isFunctionsDecl = false; continue; } if (line.StartsWith("---functions---")) { isFunctionsDecl = true; continue; } if (string.IsNullOrWhiteSpace(line)) continue; if (line.StartsWith("vector#1cb5c415")) continue; TLCombinator tLCombinator = null; try { if (isFunctionsDecl) tLCombinator = new FunctionCombinator(line); else tLCombinator = new TypeCombinator(line); } catch (System.Exception ex) { throw new System.Exception($"Error at line {line}", ex); } combinators.Add(tLCombinator); } } return combinators; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class AppandroidCallback4FDPlayer : MonoBehaviour { public MediaPlayerCtrl _mpc; public int videoWidth; public int videoHeight; public long duration; public int prevChannel; public int channel; public int frame; public int frame_cycle; public long time; public string utc; public int max_channel; public bool isErrorPopup; public bool isZoomMoveR; public bool isChangeChannel; public enum FDLIVE_ERROR { STREAM_RECIVING_FAILURE_DICONNECTION = 2300, STREAM_RECIVING_FAILURE_WAITING_TIME_OUT = 2301 } // Start is called before the first frame update void Start() { duration = 999999; isErrorPopup = false; isZoomMoveR = true; } /* * Scene GameObject Default Name : _UNITY_ANDROID_ */ public void call_SetUnityGameObjectName4NativeMessage(string _reName) { #if UNITY_ANDROID try { using (AndroidJavaClass jc = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) { using (AndroidJavaObject jo = jc.GetStatic<AndroidJavaObject>("currentActivity")) { Debug.Log("CallAndroid : getContactList"); jo.Call("SetUnityGameObjectName4NativeMessage", new object[] { _reName }); } } } catch (Exception e) { Debug.Log(e.StackTrace); } #endif } void CallBackFromFDPlayer(string _value) { getError(_value); } void getError(string _value) { //final String str = "getError," + code + "," + msg + "," + ls_ip; string[] _tmp = _value.Split(","[0]); int code = Convert.ToInt32(_tmp[1]); switch((FDLIVE_ERROR)code) { case FDLIVE_ERROR.STREAM_RECIVING_FAILURE_DICONNECTION: case FDLIVE_ERROR.STREAM_RECIVING_FAILURE_WAITING_TIME_OUT: //_mpc.setStreamOpenStartTS((int)time); //_mpc.Load(_mpc.m_strFileName); break; } } void getVideoStreamInfo(string _value) { string[] _tmp = _value.Split(","[0]); videoWidth = int.Parse(_tmp[1]); videoHeight = int.Parse(_tmp[2]); duration = long.Parse(_tmp[3]); } void getCurrentPlayInfo(string _value) { string[] _tmp = _value.Split(","[0]); #if !UNITY_EDITOR isChangeChannel = (prevChannel != channel); prevChannel = channel; channel = int.Parse(_tmp[1]); #endif frame = int.Parse(_tmp[2]); frame_cycle = int.Parse(_tmp[3]); time = long.Parse(_tmp[4]); utc = _tmp[5]; //Debug.Log("### :: " + _value); Appmain.appnet.__WEB_CONNECT_AND_SEND_RECV_4_FAST_JSON_EXTRA(Appmain.appimg._nowFullCtl._videoInfo.id, frame, channel); } }
using Chess.v4.Engine.Extensions; using Chess.v4.Engine.Factory; using Chess.v4.Engine.Interfaces; using Chess.v4.Engine.Reference; using Chess.v4.Engine.Utility; using Chess.v4.Models; using Chess.v4.Models.Enums; using Common.Extensions; using Common.Responses; using System.Linq; namespace Chess.v4.Engine.Service { /// <summary> /// There is a guiding principle here. Don't edit the GameState object anywhere but here. /// It gets confusing. /// Go ahead and calculate things elsewhere, but bring the results back here to apply them. /// </summary> public class GameStateService : IGameStateService { private readonly IAttackService _attackService; private readonly IMoveService _moveService; private readonly INotationService _notationService; private readonly IPGNService _pgnService; public GameStateService(INotationService notationService, IPGNService pgnService, IMoveService moveService, IAttackService attackService) { _notationService = notationService; _pgnService = pgnService; _moveService = moveService; _attackService = attackService; } public OperationResult<GameState> Initialize(string fen) { if (string.IsNullOrEmpty(fen)) { fen = GeneralReference.Starting_FEN_Position; } var fenRecord = FenFactory.Create(fen); if (fenRecord == null) { OperationResult<GameState>.Fail("Bad fen."); } var gameState = new GameState(fenRecord); gameState.Squares = _notationService.GetSquares(gameState); gameState.Attacks = _attackService.GetAttacks(gameState).ToList(); gameState.StateInfo = _moveService.GetStateInfo(gameState); return OperationResult<GameState>.Ok(gameState); } /// <summary> /// Examine the move for validity return game state with error if invalid. /// Copy the game state. /// Apply the move to new game state. /// Examine the move for issues such as king check return old game state with error if invalid. /// If no issues, return new game state. /// </summary> /// <param name="gameState"></param> /// <param name="piecePosition">Positions should be numbered 0-63 where a1 is 0</param> /// <param name="newPiecePosition">Positions should be numbered 0-63 where a1 is 0</param> /// <returns></returns> public OperationResult<GameState> MakeMove(GameState gameState, int piecePosition, int newPiecePosition, PieceType? piecePromotionType = null) { var stateInfo = this.getStateInfo(gameState, piecePosition, newPiecePosition, piecePromotionType); if (stateInfo.Failure) { return OperationResult<GameState>.Fail(stateInfo.Message); } return this.makeMove(gameState, piecePosition, stateInfo.Result, newPiecePosition); } public OperationResult<GameState> MakeMove(GameState gameState, string beginning, string destination, PieceType? piecePromotionType = null) { var pos1 = NotationEngine.CoordinateToPosition(beginning); var pos2 = NotationEngine.CoordinateToPosition(destination); return this.MakeMove(gameState, pos1, pos2, piecePromotionType); } public OperationResult<GameState> MakeMove(GameState gameState, string pgnMove) { var pair = _pgnService.PGNMoveToSquarePair(gameState, pgnMove); if (pair.promotedPiece != '-') { // todo: what about piece promotion? var promotedPieceType = NotationEngine.GetPieceTypeFromCharacter(pair.promotedPiece); return this.MakeMove(gameState, pair.piecePosition, pair.newPiecePosition, promotedPieceType); } return this.MakeMove(gameState, pair.piecePosition, pair.newPiecePosition); } private static GameState manageSquares(GameState gameState, StateInfo stateInfo, int piecePosition, int newPiecePosition) { var movingGameState = gameState.DeepCopy(); var oldSquare = movingGameState.Squares.GetSquare(piecePosition); var oldSquareCopy = oldSquare.DeepCopy(); oldSquareCopy.Piece = null; var newSquare = movingGameState.Squares.GetSquare(newPiecePosition); var newSquareCopy = newSquare.DeepCopy(); newSquareCopy.Piece = stateInfo.IsPawnPromotion ? new Piece(stateInfo.PawnPromotedTo, gameState.ActiveColor) : oldSquare.Piece.DeepCopy(); movingGameState.Squares.Remove(oldSquare); movingGameState.Squares.Remove(newSquare); movingGameState.Squares.Add(oldSquareCopy); movingGameState.Squares.Add(newSquareCopy); movingGameState.Squares = movingGameState.Squares.OrderBy(a => a.Index).ToList(); return movingGameState; } private OperationResult<StateInfo> getStateInfo(GameState gameState, int piecePosition, int newPiecePosition, PieceType? piecePromotionType) { var square = gameState.Squares.GetSquare(piecePosition); if (!square.Occupied) { return OperationResult<StateInfo>.Fail("Square was empty."); } if (square.Piece.Color != gameState.ActiveColor) { return OperationResult<StateInfo>.Fail("Wrong team."); } var moveInfoResult = _moveService.GetStateInfo(gameState, piecePosition, newPiecePosition); if (moveInfoResult.Failure) { return OperationResult<StateInfo>.Fail(moveInfoResult.Message); } var moveInfo = moveInfoResult.Result; if (moveInfo.IsPawnPromotion) { if (!piecePromotionType.HasValue) { return OperationResult<StateInfo>.Fail("Must provide pawn promotion piece type in order to promote a pawn."); } moveInfo.PawnPromotedTo = piecePromotionType.Value; } //var putsOwnKingInCheck = false; if (moveInfo.IsCheck) { return OperationResult<StateInfo>.Fail("Must move out of check. Must not move into check."); } return OperationResult<StateInfo>.Ok(moveInfo); } private OperationResult<GameState> makeMove(GameState gameState, int piecePosition, StateInfo stateInfo, int newPiecePosition) { //verify that the move can be made var verifiedMove = verifyMove(gameState, piecePosition, newPiecePosition); if (verifiedMove.Failure) { return OperationResult<GameState>.Fail(verifiedMove.Message); } //make the move var newGameState = GetNewGameState(gameState, piecePosition, stateInfo, newPiecePosition); //make sure we moved out of check. if (gameState.StateInfo.IsCheck || newGameState.StateInfo.IsCheck) { if (gameState.ActiveColor == Color.White) { if (newGameState.StateInfo.IsWhiteCheck) { return OperationResult<GameState>.Fail("King must move out of check."); } } else { if (newGameState.StateInfo.IsBlackCheck) { return OperationResult<GameState>.Fail("King must move out of check."); } } } return OperationResult<GameState>.Ok(newGameState); } private OperationResult verifyMove(GameState gameState, int piecePosition, int newPiecePosition) { var oldSquare = gameState.Squares.GetSquare(piecePosition); var attacks = gameState.Attacks.GetPositionAttacksOnPosition(piecePosition, newPiecePosition); if (!attacks.Any()) { return OperationResult.Fail($"Can't find an attack by this piece ({oldSquare.Index} : {oldSquare.Piece.PieceType}) on this position ({newPiecePosition})."); } var badPawnAttacks = attacks.Where(a => a.AttackingSquare.Index == piecePosition && a.Index == newPiecePosition && a.Piece == null && a.MayOnlyMoveHereIfOccupiedByEnemy ); if (badPawnAttacks.Any()) { if ( badPawnAttacks.Count() > 1 || gameState.EnPassantTargetSquare == "-" || newPiecePosition != NotationEngine.CoordinateToPosition(gameState.EnPassantTargetSquare) ) { return OperationResult.Fail($"This piece can only move here if the new square is occupied. ({oldSquare.Index} : {oldSquare.Piece.PieceType}) on this position ({newPiecePosition})."); } } return OperationResult.Ok(); } private GameState GetNewGameState(GameState gameState, int piecePosition, StateInfo stateInfo, int newPiecePosition) { var transitionGameState = manageSquares(gameState, stateInfo, piecePosition, newPiecePosition); if (stateInfo.IsCastle) { var rookPositions = CastlingEngine.GetRookPositionsForCastle(gameState.ActiveColor, piecePosition, newPiecePosition); transitionGameState = manageSquares(transitionGameState, stateInfo, rookPositions.RookPos, rookPositions.NewRookPos); } if (stateInfo.IsEnPassant) { //remove the attacked pawn var enPassantAttackedPawnPosition = gameState.ActiveColor == Color.White ? newPiecePosition - 8 : newPiecePosition + 8; var enPassantAttackedPawnSquare = transitionGameState.Squares.GetSquare(enPassantAttackedPawnPosition); enPassantAttackedPawnSquare.Piece = null; } _notationService.SetGameStateSnapshot(gameState, transitionGameState, stateInfo, piecePosition, newPiecePosition); transitionGameState.Squares = _notationService.GetSquares(transitionGameState); transitionGameState.Attacks = _attackService.GetAttacks(transitionGameState).ToList(); transitionGameState.StateInfo = _moveService.GetStateInfo(transitionGameState); if ( transitionGameState.StateInfo.IsCheckmate || transitionGameState.StateInfo.IsDraw ) { if (transitionGameState.StateInfo.IsDraw) { transitionGameState.PGN += " 1/2-1/2"; } if (transitionGameState.StateInfo.IsCheckmate) { // todo: verify if (gameState.ActiveColor == Color.White) { transitionGameState.PGN += " 1-0"; } else { transitionGameState.PGN += " 0-1"; } } } var fenRecords = gameState.History.DeepCopy(); var previousStateFEN = gameState.ToString(); fenRecords.Add(FenFactory.Create(previousStateFEN)); transitionGameState.History = fenRecords; return transitionGameState; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace wolfgraphicsLLC_Employee_login_Register_Information_Bonus_System { public partial class wolfgraphicsLLC_Employee_Information : Form { public wolfgraphicsLLC_Employee_Information(string id) { InitializeComponent(); EmployeeIDOutput_label.Text = id; } private void Exit_button_Click(object sender, EventArgs e) { this.Close(); } private void EmployeeInfoBack_Click(object sender, EventArgs e) { this.Hide(); Login_Form ss = new Login_Form(); ss.Show(); } private void ResetBonus_Click(object sender, EventArgs e) { this.Hide(); BonusTabulator ss = new BonusTabulator(EmployeeIDOutput_label.Text); ss.Show(); } private void PassworReset_button_Click(object sender, EventArgs e) { this.Hide(); Password_Reset ss = new Password_Reset(EmployeeIDOutput_label.Text); ss.Show(); } } }
using System.Collections.Generic; using Welic.Dominio.Models.Marketplaces.Entityes; using WebApi.Models.Grids; namespace WebApi.Models { public class ListingModel { public ListingsGrid Grid { get; set; } public List<ListingItemModel> Listings { get; set; } public List<Category> Categories { get; set; } } }
using Allyn.Domain.Models.Basic; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Allyn.Domain.Models.Front { /// <summary> /// 表示"产品"聚合根类型. /// </summary> public class Product : AggregateRoot { /// <summary> /// 获取或设置产品所属店铺. /// </summary> public Shop Shop { get; set; } /// <summary> /// 产品所属类别. /// </summary> public Category Category { get; set; } /// <summary> /// 获取或设置产品标题. /// </summary> public string Title { get; set; } /// <summary> /// 获取或设置产品价格. /// </summary> public decimal Price { get; set; } /// <summary> /// 获取或设置产品图片. /// </summary> public string ImgUrl { get; set; } /// <summary> /// 获取或设置产品单位. /// </summary> public string Unit { get; set; } /// <summary> /// 获取或设置排序. /// </summary> public int Sort { get; set; } /// <summary> /// 获取或设置库存 /// </summary> public int Stock { get; set; } /// <summary> /// 获取或设置产品简介. /// </summary> public string Summary { get; set; } /// <summary> /// 获取或设置产品详情. /// </summary> public string Details { get; set; } /// <summary> /// 获取或设置是否上线. /// </summary> public bool Online { get; set; } /// <summary> /// 获取或设置创建人. /// </summary> public Guid Creater { get; set; } /// <summary> /// 获取或设置创建时间. /// </summary> public DateTime CreateDate { get; set; } /// <summary> /// 获取或设置修改者. /// </summary> public Guid? Modifier { get; set; } /// <summary> /// 获取或设置更新时间. /// </summary> public DateTime? UpdateDate { get; set; } /// <summary> /// 获取或者设置是否推荐. /// </summary> public bool IsRed { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BO { class BabyWarrior : Warrior { //var babyWarrior = new BabyWarrior(); public int lvl{ get; set; } } }
using System; using TraceWizard.Entities; namespace TraceWizard.Analyzers { public interface Analyzer { string GetName(); string GetDescription(); } public abstract class AdapterFactory { public abstract Adapter GetAdapter(string dataSource); } public interface Adapter { } }
using Microsoft.EntityFrameworkCore; namespace ActivityTracker.Models { public class ActivityTrackerContext : DbContext { public ActivityTrackerContext(DbContextOptions<ActivityTrackerContext> options) : base(options) { } public DbSet<Activity> Activities { get; set; } public DbSet<Day> Days { get; set; } public DbSet<Measurement> Measuerments { get; set; } } }
namespace ChallengeTechAndSolve.Common.Enum { public enum Restrictions { Zero = 0, One = 1, Fifty = 50, OneHundred = 100, FiveHundred = 500, } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Salle.Model.Salle; using Salle.Model.Commun; namespace Salle.Controler { class SalleCreationController { Carre Carre1; Carre Carre2; ChefRang ChefRangCarre1; ChefRang ChefRangCarre2; Carte Carte1; public MaitreHotel monMaitre; public SalleCreationController() { this.CreationChefsRang(); this.CreationTable(); this.CreationMaitreHotel(); this.CreationServeur(); this.CreationCarte(); } private void CreationTable() { /********************CREER TABLEAU POUR PREMIER CARRE******************************/ int[][] TablesCarre1 = new int[3][]; TablesCarre1[0] = new int[5]; TablesCarre1[0][0] = 2; TablesCarre1[0][1] = 4; TablesCarre1[0][2] = 6; TablesCarre1[0][3] = 8; TablesCarre1[0][4] = 4; TablesCarre1[1] = new int[5]; TablesCarre1[1][0] = 2; TablesCarre1[1][1] = 4; TablesCarre1[1][2] = 6; TablesCarre1[1][3] = 8; TablesCarre1[1][4] = 4; TablesCarre1[2] = new int[6]; TablesCarre1[2][0] = 2; TablesCarre1[2][1] = 4; TablesCarre1[2][2] = 6; TablesCarre1[2][3] = 2; TablesCarre1[2][4] = 2; TablesCarre1[2][5] = 10; /********************DEUXIEME CARRE******************************/ int[][] TablesCarre2 = new int[3][]; TablesCarre2[0] = new int[6]; TablesCarre2[0][0] = 2; TablesCarre2[0][1] = 4; TablesCarre2[0][2] = 8; TablesCarre2[0][3] = 6; TablesCarre2[0][4] = 4; TablesCarre2[0][5] = 2; TablesCarre2[1] = new int[6]; TablesCarre2[1][0] = 2; TablesCarre2[1][1] = 4; TablesCarre2[1][2] = 8; TablesCarre2[1][3] = 6; TablesCarre2[1][4] = 4; TablesCarre2[1][5] = 2; TablesCarre2[2] = new int[4]; TablesCarre2[2][0] = 2; TablesCarre2[2][1] = 4; TablesCarre2[2][2] = 8; TablesCarre2[2][3] = 10; Carre1 = new Carre(TablesCarre1, ChefRangCarre1); Carre2 = new Carre(TablesCarre2, ChefRangCarre2); } private void CreationMaitreHotel() { monMaitre = new MaitreHotel(Carre1, Carre2); } private void CreationChefsRang() { ChefRangCarre1 = new ChefRang(); ChefRangCarre2 = new ChefRang(); } private void CreationServeur() { } private void CreationCarte() { Carte1 = new Carte(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace ApplicationRunOrFormShowDialogTest { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 MainForm1 = new Form1("Form1.Show()로 생성"); Form1 MainForm2 = new Form1("Application.Run()으로 생성"); MainForm1.Show(); // Main UI Thread의 Message Loop 사용 Application.Run(MainForm2); // Main UI Thread의 Message Loop 사용 // Application.Run 에서 Message Loop를 잡고 있음. // 따라서 Form.ShowDialog 처럼 밑에 줄 코드로 내려가지 않음. // Application.Run으로 실행된 Form이 종료되거나 Application.Exit()가 호출되면 ApplicationExit 이벤트핸들러가 동작. // 이후 MessageLoop 종료되고 밑에 Form.Show는 예외가 발생함. 왜냐하면, // Show는 Show를 호출한 Thread의 MessageLoop를 공유하는데 ApplicationExit의 호출로 Main Thread의 MessageLoop가 종료되었기 때문 MainForm1 = new Form1("Exception 폼"); // Exception 발생 MainForm1.Show(); // Main UI Thread의 Message Loop 사용 // 여담으로.. Main 함수에서 Application.Run을 사용하지 않고 Form1의 인스턴스를 할당하여 ShowDialog로 띄우고, // Form1에서 Application.Run을 해도 예외가 발생한다. 두번째 메세지 루프를 사용할 수 없다는 것인데, // Main Thread의 메세지 루프가 실행되지도 않았는데 Application.Run이 동작을 안한다는 것은 이해가 안된다. } } }
using System; using EPI.HashTables; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace EPI.UnitTests.HashTables { [TestClass] public class NearestRepeatedWordsUnitTest { [TestMethod] public void FindNearestRepeatedWords() { NearestRepeatedWords.FindNearestRepeatedEntries(new[] {"All", "work", "and", "no", "play", "makes", "for", "no", "work", "no", "fun", "and", "no", "results" } ).ShouldBeEquivalentTo(new Tuple<int, int>(7, 9)); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; [RequireComponent(typeof(ButtonParameter))] public class ButtonOverride : Button { private AudioSourceController m_AudioSourceController; public void Init() { Text text = transform.GetComponentInChildren<Text>(); if (text) { text.fontSize = GetComponent<ButtonParameter>().fontNormalSize; text.color = GetComponent<ButtonParameter>().fontNormalColor; } } public override void OnSelect(BaseEventData eventData) { base.OnSelect(eventData); } public override void OnPointerEnter(PointerEventData eventData) { //音效 if (m_AudioSourceController == null) m_AudioSourceController = AudioSourcesManager.ApplyAudioSourceController(); m_AudioSourceController.Play("按钮悬浮", transform); base.OnPointerEnter(eventData); Text text = transform.GetComponentInChildren<Text>(); if (text) { text.fontSize = GetComponent<ButtonParameter>().fonthighlightSize; text.color = GetComponent<ButtonParameter>().fontHighlightedColor; } } public override void OnPointerExit(PointerEventData eventData) { base.OnPointerExit(eventData); Text text = transform.GetComponentInChildren<Text>(); if (text) { text.fontSize = GetComponent<ButtonParameter>().fontNormalSize; text.color = GetComponent<ButtonParameter>().fontNormalColor; } } public override void OnPointerDown(PointerEventData eventData) { base.OnPointerDown(eventData); Text text = transform.GetComponentInChildren<Text>(); if (text) { text.fontSize = GetComponent<ButtonParameter>().fontNormalSize; text.color = GetComponent<ButtonParameter>().fontNormalColor; } } }
using System.IO; using System.IO.Compression; using System.Threading.Tasks; namespace IcecatSharp { public static class GZipUtils { public static async Task<string> DecompressAsync(FileInfo fileToDecompress, string newFileName = null) { var currentFileName = fileToDecompress.FullName; if (string.IsNullOrEmpty(newFileName)) newFileName = currentFileName.Remove(currentFileName.Length - fileToDecompress.Extension.Length); using (var originalFileStream = fileToDecompress.OpenRead()) using (var decompressedFileStream = File.Create(newFileName)) using (var decompressionStream = new GZipStream(originalFileStream, CompressionMode.Decompress)) { await decompressionStream.CopyToAsync(decompressedFileStream); //Console.WriteLine("Decompressed: {0}", fileToDecompress.Name); } return newFileName; } } }
using UnityEngine; namespace Assets.Scripts.PlayerFolder { public class CharacterComponent:MonoBehaviour { private Player _player; void Start() { _player = new Player(name,100,100); } void Update() { _player.Moving(transform); _player.Run(); } void FixedUpdate() { _player.EnergyRegeneration(); _player.AddBroadcasts(name); } } }
using CollectionsWorkAngular.Data.Comments; using CollectionsWorkAngular.Data.Persons; using CollectionsWorkAngular.Data.Users; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata; namespace CollectionsWorkAngular.Data { /// <summary> /// Контекст данных - объект, необходимый для работы с базой данных(Добавление, удаление, обновление, просмотр данных) /// Позволяет определить отношения между сущностями и также их отражение на базу данных /// </summary> public class ApplicationDbContext : IdentityDbContext<ApplicationUser> { #region Конструктор /// <summary> /// Конструктор /// </summary> /// <param name="options">Параметры объекта DbContext. В основном используются для передачи строки подключения /// к базе данных</param> public ApplicationDbContext(DbContextOptions options) : base(options) { } #endregion #region Методы /// <summary> /// Вручную настраиваем отношения между моделями, переопределяя базовый метод Entity Framework /// </summary> /// <param name="modelBuilder">Объект, который определяет отношение между сущностями, то как они отображаются в базе данных</param> protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); //Указываем билдеру, что для данной сущности нужно создать таблицу с именем Users modelBuilder.Entity<ApplicationUser>().ToTable("Users"); //Указываем билдеру, что у сущности ApplicationUser может быть много пёрсонов, но каждый из этих пёрсонов имеет одного ApplicationUser`а //Тем самым создаём связь один ко многим modelBuilder.Entity<ApplicationUser>().HasMany(u => u.Persons).WithOne(p => p.Author); modelBuilder.Entity<ApplicationUser>().HasMany(u => u.Comments).WithOne(c => c.Author).HasPrincipalKey(u => u.Id); modelBuilder.Entity<Person>().ToTable("People"); //Указываем билдеру, что свойство Id у сущности Person должно генерироваться автоматически базой или клиентской стороной, когда добавляется новая запись с Person modelBuilder.Entity<Person>().Property(p => p.Id).ValueGeneratedOnAdd(); modelBuilder.Entity<Person>().HasMany(p => p.Comments).WithOne(c => c.Person); modelBuilder.Entity<Person>().HasOne(p => p.Author).WithMany(u => u.Persons); modelBuilder.Entity<Comment>().ToTable("Comments"); modelBuilder.Entity<Comment>().HasOne(c => c.Person).WithMany(p => p.Comments); modelBuilder.Entity<Comment>().HasOne(c => c.Parent).WithMany(c => c.Children); modelBuilder.Entity<Comment>().HasMany(c => c.Children).WithOne(c => c.Parent); //Указываем билдеру, что : 1) У каждого автора комментария может много комментариев(устанавливаем связь один ко многим) //2) Свойство UserId у сущности Comment, которое будет использоваться в качестве внешнего ключа для связи с автором(ApplicationUser) //3) При удалении ApplicationUser, комментарии связанные с данной сущностью не будут удалены modelBuilder.Entity<Comment>().HasOne(c => c.Author).WithMany(u => u.Comments).HasForeignKey(c => c.UserId).OnDelete(DeleteBehavior.Restrict); } #endregion #region Свойства //DbSet - объект, представляющий набор сущностей. С помощью данного свойство мы можем производить CRUD операции, а также LINQ запросы public DbSet<Person> People { get; set; } public DbSet<Comment> Comments { get; set; } //public DbSet<ApplicationUser> Users { get; set; } #endregion } }
using System; using System.Linq; using System.Text; using FluentAssertions; using Xunit; namespace Thinktecture.Extensions.Configuration.Legacy.LegacyConfigurationProviderTests { public class Load : LoadTestsBase { [Fact] public void Should_ignore_xml_declaration() { Parse(@"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""no"" ?> <configuration/>"); SUT.GetChildKeys(Enumerable.Empty<string>(), null).Should().BeEmpty(); } [Fact] public void Should_ignore_processing_instruction() { Parse(@"<?xml-stylesheet type=""text/xsl"" href=""style.xsl""?> <configuration/>"); SUT.GetChildKeys(Enumerable.Empty<string>(), null).Should().BeEmpty(); } [Fact] public void Should_ignore_comment() { Parse(@"<!-- comment --> <configuration/>"); SUT.GetChildKeys(Enumerable.Empty<string>(), null).Should().BeEmpty(); } [Fact] public void Should_not_emit_any_values_having_self_closing_root_only() { Parse(@"<configuration/>"); SUT.GetChildKeys(Enumerable.Empty<string>(), null).Should().BeEmpty(); } [Fact] public void Should_not_emit_any_values_having_root_only() { Parse(@"<configuration></configuration>"); SUT.GetChildKeys(Enumerable.Empty<string>(), null).Should().BeEmpty(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Timer : MonoBehaviour { void OnTriggerEnter2D(Collider2D col) { if (col.gameObject.CompareTag("Player")) { GameManager.PlusTime(60); Destroy(gameObject); } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace OcenaKlientow.Model.Models { public class Klient { [Required] public bool CzyFizyczna { get; set; } public string DrugieImie { get; set; } public string DrugieNazwisko { get; set; } public string Imie { get; set; } [Key] [Required] public int KlientId { get; set; } [Range(0.0, Double.MaxValue)] public double KwotaKredytu { get; set; } public string Nazwa { get; set; } public string Nazwisko { get; set; } //[Unique] public string NIP { get; set; } //[Unique] public string PESEL { get; set; } } }
using System.Collections.Generic; using System.Web; using System.Web.Mvc; using Meshop.Framework.Model; namespace Meshop.Framework.Services { public interface ICart { ICart StartCart(HttpContextBase context); IEnumerable<CartItem> GetCart(); void AddToCart(int productID); int RemoveFromCart(int id); void EmptyCart(); List<CartItem> GetCartItems(); int GetCount(); decimal GetTotal(); int CreateOrder(Order order); string GetCartId(HttpContextBase context); void MigrateCart(string userName); bool ValidateOrder(string name, int id); } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using TestShop.Application.ServiceInterfaces; namespace TestShop.Web.Controllers { [Authorize] public class ShopController : BaseController { private readonly IShopService shopService; public ShopController(IShopService shopService) { this.shopService = shopService; } public IActionResult Index() { return View(shopService.GetAllProductsAsync()); } } }
using System; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Tndm_ArtShop.Services; using Tndm_ArtShop.Data; using Tndm_ArtShop.Models; namespace Tndm_ArtShop.Controllers { public class KupovinaController : Controller { private readonly ProdavnicaContext db; private readonly UserManager<ApplicationUser> um; private KorpaServis kServis; public KupovinaController(ProdavnicaContext _db, UserManager<ApplicationUser> _um, KorpaServis _kServis) { db = _db; um = _um; kServis = _kServis; } [Authorize] public async Task<IActionResult> Index() { Korpa korpa = kServis.CitajKorpu(); if (korpa.Stavke.Count() == 0) { return RedirectToAction("Index", "Home"); } ApplicationUser user = await um.GetUserAsync(User); string id = user.Id; Porudzbina p1 = new Porudzbina { KupacId = id, DatumKupovine = DateTime.Now }; try { db.Porudzbina.Add(p1); db.SaveChanges(); int pId = p1.PorudzbinaId; foreach (StavkaKorpe st in korpa.Stavke) { Stavka st1 = new Stavka { PorudzbinaId = pId, ProizvodId = st.Proizvod.ProizvodId, Kolicina = st.Kolicina }; db.Stavka.Add(st1); db.SaveChanges(); } kServis.ObrisiKorpu(); return View(); } catch (Exception) { return RedirectToAction("Index", "Home"); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _1 { class Program { static void Main(string[] args) { string grad = Console.ReadLine().ToLower(); string product = Console.ReadLine().ToLower(); double quantity = double.Parse(Console.ReadLine()); } } }
using System; using System.Collections.Generic; using System.Text; namespace PatronBuilder { class Producto { private IMotor motor; private ICubiertas llantas; private IChasis carroceria; public void colocaMotor(IMotor pMotor) { motor = pMotor; Console.WriteLine("se ha colocado un motor de : {0}", motor.especificacionesMotor()); } public void colocaCarroceria(IChasis pCarroceria) { carroceria = pCarroceria; Console.WriteLine("se ha colocado una carroceria de : {0}",carroceria.caracteristicas()); } public void colocaLlantas(ICubiertas pLlantas) { llantas = pLlantas; Console.WriteLine( "se ha colocado llantas:{0}", llantas.EquiparLlantas() ); } public void mostrarAuto() { Console.WriteLine($"tu auto tiene {motor.especificacionesMotor()}, {carroceria.caracteristicas()}, y {llantas.EquiparLlantas()}"); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Exercicio22 { class ContarPalavras { static void Main(string[] args) { { string Frase = "Hoje, joga o FCP com a Naval."; int Contapal = 0; for (int X = 1; X < Frase.Length; X++) { if (Frase.Substring(X, 1) == " " || Frase.Substring(X, 1) == ".") Contapal++; } Console.Clear(); Console.WriteLine("A frase: {0,30} tem {1,2} palavras.", Frase, Contapal); } } } }
using System; using System.Collections.Generic; using Fingo.Auth.DbAccess.Models.Policies.Enums; using Fingo.Auth.Domain.Policies.Enums; using Fingo.Auth.Domain.Policies.ExtensionMethods; using Xunit; namespace Fingo.Auth.Domain.Policies.Tests.ExtensionMethods { public class CheckTypeTest { [Fact] public void WithTypesShouldReturnAccountCreationTypes() { // arrange var list = new List<Policy> { Policy.PasswordExpirationDate , Policy.MinimumPasswordLength , Policy.RequiredPasswordCharacters , Policy.AccountExpirationDate }; // act & assert Assert.Equal(new List<Policy> {Policy.MinimumPasswordLength , Policy.RequiredPasswordCharacters} , list.WithTypes(PolicyType.AccountCreation)); } [Fact] public void WithTypesShouldReturnLogInTypes() { // arrange var list = new List<Policy> { Policy.PasswordExpirationDate , Policy.MinimumPasswordLength , Policy.RequiredPasswordCharacters , Policy.AccountExpirationDate }; // act & assert Assert.Equal( new List<Policy> { Policy.PasswordExpirationDate , Policy.AccountExpirationDate } , list.WithTypes(PolicyType.LogIn)); } [Fact] public void WithTypesShouldReturnNull() { // arrange List<Policy> list = null; // act & assert Assert.Equal(null , list.WithTypes(PolicyType.AccountCreation)); } [Fact] public void WithTypesShouldReturnWhatWasGiven() { // arrange var list = new List<Policy> { Policy.RequiredPasswordCharacters , Policy.AccountExpirationDate }; // act & assert Assert.Equal(list , list.WithTypes()); } [Fact] public void WithTypesTupleShouldReturnAccountCreationTypes() { // arrange var list = new List<Tuple<Policy , double>> { new Tuple<Policy , double>(Policy.PasswordExpirationDate , Math.E) , new Tuple<Policy , double>(Policy.MinimumPasswordLength , Math.PI) , new Tuple<Policy , double>(Policy.RequiredPasswordCharacters , Math.Exp(Math.PI)) , new Tuple<Policy , double>(Policy.AccountExpirationDate , 42) }; // act & assert Assert.Equal( new List<Tuple<Policy , double>> { new Tuple<Policy , double>(Policy.MinimumPasswordLength , Math.PI) , new Tuple<Policy , double>(Policy.RequiredPasswordCharacters , Math.Exp(Math.PI)) } , list.WithTypes(PolicyType.AccountCreation)); } [Fact] public void WithTypesTupleShouldReturnLogInTypes() { // arrange var list = new List<Tuple<Policy , int>> { new Tuple<Policy , int>(Policy.PasswordExpirationDate , 2) , new Tuple<Policy , int>(Policy.MinimumPasswordLength , 42) , new Tuple<Policy , int>(Policy.RequiredPasswordCharacters , -20000000) , new Tuple<Policy , int>(Policy.AccountExpirationDate , -41) }; // act & assert Assert.Equal( new List<Tuple<Policy , int>> { new Tuple<Policy , int>(Policy.PasswordExpirationDate , 2) , new Tuple<Policy , int>(Policy.AccountExpirationDate , -41) } , list.WithTypes(PolicyType.LogIn)); } [Fact] public void WithTypesTupleShouldReturnNull() { // arrange List<Tuple<Policy , object>> list = null; // act & assert Assert.Equal(null , list.WithTypes(PolicyType.AccountCreation)); } [Fact] public void WithTypesTupleShouldReturnWhatWasGiven() { // arrange var list = new List<Tuple<Policy , string>> { new Tuple<Policy , string>(Policy.RequiredPasswordCharacters , "a") , new Tuple<Policy , string>(Policy.AccountExpirationDate , "b") }; // act & assert Assert.Equal(list , list.WithTypes()); } } }
using UnityAtoms.MonoHooks; namespace UnityAtoms.MonoHooks { /// <summary> /// Condition of type `ColliderGameObject`. Inherits from `AtomCondition&lt;ColliderGameObject&gt;`. /// </summary> [EditorIcon("atom-icon-teal")] public abstract class ColliderGameObjectCondition : AtomCondition<ColliderGameObject> { } }
using UnityEngine; public class MovementTracking : MonoBehaviour { public Transform headProxy; private Transform head; private Transform body; private void Start() { head = transform.GetChild(0); body = transform.GetChild(1); } private void Update() { //Set rotation and position for head head.rotation = headProxy.transform.rotation; head.position = headProxy.transform.position; //Set rotation, position and scale for body (Looking towards head all the time) body.LookAt(transform.GetChild(0)); float distance = Vector3.Distance(body.position, head.position); Vector3 newScaleY = new Vector3(body.localScale.x, body.localScale.y, distance - head.localScale.z); body.localScale = newScaleY; } }
using System; using System.Collections.Generic; using BattleEngine.Actors; using BattleEngine.Utils; using Common.Composite; namespace BattleEngine.Engine { public class BattleActors { private Vector<BattleObject> _temp = new Vector<BattleObject>(); private Vector<BattleActorsGroup> _tempActors = new Vector<BattleActorsGroup>(); private Vector<Component> _tempComponents = new Vector<Component>(); private BattleEngine _battleEngine; private Dictionary<ActorsGroup, BattleActorsGroup> _groupMap; private BattleObjectFactory _factory; private Vector<BattleActorsGroup> _list; private Vector<BattleObject> _map; private BattleDamages _damages; public BattleActors(BattleEngine battleEngine) { _battleEngine = battleEngine; _groupMap = new Dictionary<ActorsGroup, BattleActorsGroup>(); _map = new Vector<BattleObject>(); _factory = new BattleObjectFactory(_map, _battleEngine); _list = new Vector<BattleActorsGroup>(); _damages = new BattleDamages(_battleEngine.context); foreach (var e in Enum.GetValues(typeof(ActorsGroup))) { group((ActorsGroup)e); } } public BattleDamages damagesFactory { get { return _damages; } } public BattleObjectFactory factory { get { return _factory; } } public Vector<BattleActorsGroup> getGroups(Vector<BattleActorsGroup> result = null) { if (result == null) result = new Vector<BattleActorsGroup>(); foreach (var item in _battleEngine.GetComponents(typeof(BattleActorsGroup), false, _tempComponents)) { result.push((BattleActorsGroup)item); } return result; } public Vector<BattleObject> getActors(Vector<BattleObject> result = null) { foreach (var item in _list) { item.getActors(null, result); } return result; } public BattleObject getActorByObjectId(int objectId) { return _map[objectId]; } public BattleActorsGroup group(ActorsGroup e) { BattleActorsGroup result; if (!_groupMap.TryGetValue(e, out result)) { _groupMap[e] = result = new BattleActorsGroup(e, _battleEngine); _list.push(result); _battleEngine.AddComponent(result); } return result; } public BattleActorsGroup buildings { get { return group(ActorsGroup.BUILDING); } } public BattleActorsGroup units { get { return group(ActorsGroup.UNIT); } } public BattleActorsGroup bullets { get { return group(ActorsGroup.BULLET); } } public BattleActorsGroup damages { get { return group(ActorsGroup.DAMAGE); } } } }
using Reportes; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace VentasD1002 { public partial class frmMovimientoRpt : Form { public frmMovimientoRpt() { InitializeComponent(); } rptMovimientoKardex movKardex = new rptMovimientoKardex(); private void mostrarReporte() { try { DataTable dt = new DatVentas.DatKardex().BuscarProducto_Kardex(frmInventarioKardex.IDPRODUCTO, "MOVIMIENTO_KARDEX"); movKardex = new rptMovimientoKardex(); movKardex.DataSource = dt; reportViewerMovimiento.Report = movKardex; reportViewerMovimiento.RefreshReport(); } catch (Exception ex) { MessageBox.Show("Error al mostrar el reporte "+ ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void frmMovimientoRpt_Load(object sender, EventArgs e) { mostrarReporte(); } } }
using System.Collections; using System.Collections.Generic; using System.IO; using UnityEditor; using UnityEngine; public class SceneImportProcessor : AssetPostprocessor { public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) { const string SCENE_PATH = "Assets/Scenes/"; foreach (string str in importedAssets) { string ext = Path.GetExtension(str).ToLower(); var importer = AssetImporter.GetAtPath(str); if (importer == null) continue; if (str.StartsWithNonAlloc(SCENE_PATH) && ext.EqualsOrdinal(".unity")) { importer.assetBundleName = string.Format("scene/scene_{0}.bundle", Path.GetFileNameWithoutExtension(str).ToLower()); } } } }
using Compent.Extensions.Trees; using Uintra.Features.Notification.Configuration.BackofficeSettings.Models; namespace Uintra.Features.Notification.Configuration.BackofficeSettings.Providers { public interface INotificationSettingsTreeProvider { ITree<TreeNodeModel> GetSettingsTree(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace dz_1 { class Program { static void Main(string[] args) { //ParameterizedThreadStart threadStart = new ParameterizedThreadStart(func); //Thread thread = new Thread(threadStart); //List<object> objectsList = new List<object>(); //objectsList.Add("hi"); //objectsList.Add(" "); //objectsList.Add("I'm"); //objectsList.Add(' '); //objectsList.Add('r'); //objectsList.Add(0); //objectsList.Add("b"); //objectsList.Add(1.000); //thread.Start(objectsList); Bank bnk = new Bank(); bnk.Money = 3000; bnk.Name = "PrivatBank"; bnk.Percent = 21; bnk.Money = 10000; } static void func(object obj) { List<object> list = ((IList<object>)obj).ToList(); foreach (var v in list) { Console.Write(v.ToString()); } Console.Write("\n\n"); } } }
using System; using System.Diagnostics; using System.Net.Http; using System.Text; using System.Text.Json; using System.Threading.Tasks; using DashBoard.Data.Data; using DashBoard.Data.Enums; using DashBoard.Data.Entities; using System.Net.Http.Headers; using DashBoard.Business.DTOs.Domains; using System.Linq; using System.Dynamic; namespace DashBoard.Business.Services { public interface IRequestService { Task<object> GetService(int id, DomainForTestDto domain, string userId, string requestType = "default", DomainModel domainBackground = null); } public class RequestsService: IRequestService { private readonly DataContext _context; private readonly IMailService _mailService; private Guid teamKey; public RequestsService(DataContext context, IMailService mailService) { _context = context; _mailService = mailService; } public async Task<object> GetService(int id, DomainForTestDto domain, string userId, string requestType = "default", DomainModel domainBackground = null) { DomainModel domainModel; if (domain == null && requestType == "default") { var user = await _context.Users.FindAsync(Convert.ToInt32(userId)); teamKey = user.Team_Key; domainModel = _context.Domains.FirstOrDefault(x => x.Id == id && x.Deleted == false && x.Team_Key == teamKey); } else if (domainBackground != null && requestType == "background") { domainModel = domainBackground; } else { domainModel = GetDomainModel(domain); } if (domainModel != null) { HttpClient client = new HttpClient(); client.BaseAddress = new Uri(domainModel.Url); client.DefaultRequestHeaders.Accept.Clear(); if (domainModel.Service_Type == ServiceType.ServiceRest) { if (domainModel.Method == RequestMethod.Get) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, ""); return await DoRequest(client, request, domainModel, "application/json"); } else if (domainModel.Method == RequestMethod.Post) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ""); return await DoRequest(client, request, domainModel, "application/json"); } } else if (domainModel.Service_Type == ServiceType.ServiceSoap) { HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ""); return await DoRequest(client, request, domainModel, "text/xml"); } } return null; } async Task<object> DoRequest(HttpClient client, HttpRequestMessage request, DomainModel domainModel, string mediaType) { try { if (domainModel.Basic_Auth) { client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( System.Text.ASCIIEncoding.ASCII.GetBytes( $"{domainModel.Auth_User}:{domainModel.Auth_Password}"))); if (domainModel.Parameters != null && request.Method != HttpMethod.Get) { var Json = domainModel.Parameters; request.Content = new StringContent(Json, Encoding.UTF8, mediaType); } } else { if (domainModel.Parameters != null && request.Method != HttpMethod.Get) { var Json = domainModel.Parameters; request.Content = new StringContent(Json, Encoding.UTF8, mediaType); } } var sw = new Stopwatch(); sw.Start(); var response = await client.SendAsync(request); sw.Stop(); if (domainModel.Id != -555 && domainModel.Service_Name != "ModelForTesting") { await SaveLog(domainModel, response); } var data = response.ToString(); var pageContents = await response.Content.ReadAsStringAsync(); return GetResponseObject(domainModel, sw, response, pageContents); } catch { if (domainModel.Id != -555 && domainModel.Service_Name != "ModelForTesting") { await SaveLogFailed(domainModel); } return GetFailObject(domainModel); } } private static object GetFailObject(DomainModel domainModel) { return new { DomainUrl = domainModel.Url, Status = "Failed" // add reason }; } private static object GetResponseObject(DomainModel domainModel, Stopwatch sw, HttpResponseMessage response, string dataText) { return new { DomainUrl = domainModel.Url, Status = response.StatusCode, RequestTime = sw.ElapsedMilliseconds, Response = dataText }; } private async Task<bool> SaveLog(DomainModel domainModel, HttpResponseMessage response) { if (!response.IsSuccessStatusCode) { // new LogModel entity added to Database var logEntry = new LogModel { Domain_Id = domainModel.Id, Log_Date = DateTime.Now, Error_Text = response.StatusCode.ToString(), Team_Key = domainModel.Team_Key, Service_Name = domainModel.Service_Name }; _context.Logs.Add(logEntry); _context.SaveChanges(); var result = await _mailService.SendEmailNew(domainModel, domainModel.Team_Key, response.StatusCode.ToString()); domainModel.Last_Fail = DateTime.Now.AddHours(2); if (result) { domainModel.Last_Notified = DateTime.Now; } _context.Domains.Update(domainModel); _context.SaveChanges(); return result; } return false; } private async Task<bool> SaveLogFailed(DomainModel domainModel) { var logEntry = new LogModel { Domain_Id = domainModel.Id, Log_Date = DateTime.Now, Error_Text = "503", Team_Key = domainModel.Team_Key, Service_Name = domainModel.Service_Name }; _context.Logs.Add(logEntry); _context.SaveChanges(); var result = await _mailService.SendEmailNew(domainModel, domainModel.Team_Key, "503"); domainModel.Last_Fail = DateTime.Now.AddHours(2); if (result) { domainModel.Last_Notified = DateTime.Now; } _context.Domains.Update(domainModel); _context.SaveChanges(); return result; } private static DomainModel GetDomainModel(DomainForTestDto domain) { DomainModel modelForTest = new DomainModel { Id = -555, Service_Name = "ModelForTesting", Service_Type = domain.Service_Type, Url = domain.Url, Method = domain.Method, Notification_Email = "test@fortest", Basic_Auth = domain.Basic_Auth, Auth_User = domain.Auth_User, Auth_Password = domain.Auth_Password, Parameters = domain.Parameters, Active = true, Interval_Ms = 4000 }; return modelForTest; } } }
using System; namespace LegacyApp.Core.Services { public class UserNotLoggedInException : Exception { } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Terminal.Gui { /// <summary> /// Helper class to handle the scan code and virtual key from a <see cref="ConsoleKey"/>. /// </summary> public static class ConsoleKeyMapping { private class ScanCodeMapping : IEquatable<ScanCodeMapping> { public uint ScanCode; public uint VirtualKey; public ConsoleModifiers Modifiers; public uint UnicodeChar; public ScanCodeMapping (uint scanCode, uint virtualKey, ConsoleModifiers modifiers, uint unicodeChar) { ScanCode = scanCode; VirtualKey = virtualKey; Modifiers = modifiers; UnicodeChar = unicodeChar; } public bool Equals (ScanCodeMapping other) { return (this.ScanCode.Equals (other.ScanCode) && this.VirtualKey.Equals (other.VirtualKey) && this.Modifiers.Equals (other.Modifiers) && this.UnicodeChar.Equals (other.UnicodeChar)); } } private static ConsoleModifiers GetModifiers (uint unicodeChar, ConsoleModifiers modifiers, bool isConsoleKey) { if (modifiers.HasFlag (ConsoleModifiers.Shift) && !modifiers.HasFlag (ConsoleModifiers.Alt) && !modifiers.HasFlag (ConsoleModifiers.Control)) { return ConsoleModifiers.Shift; } else if (modifiers == (ConsoleModifiers.Alt | ConsoleModifiers.Control)) { return modifiers; } else if ((!isConsoleKey || (isConsoleKey && (modifiers.HasFlag (ConsoleModifiers.Shift) || modifiers.HasFlag (ConsoleModifiers.Alt) || modifiers.HasFlag (ConsoleModifiers.Control)))) && unicodeChar >= 65 && unicodeChar <= 90) { return ConsoleModifiers.Shift; } return 0; } private static ScanCodeMapping GetScanCode (string propName, uint keyValue, ConsoleModifiers modifiers) { switch (propName) { case "UnicodeChar": var sCode = scanCodes.FirstOrDefault ((e) => e.UnicodeChar == keyValue && e.Modifiers == modifiers); if (sCode == null && modifiers == (ConsoleModifiers.Alt | ConsoleModifiers.Control)) { return scanCodes.FirstOrDefault ((e) => e.UnicodeChar == keyValue && e.Modifiers == 0); } return sCode; case "VirtualKey": sCode = scanCodes.FirstOrDefault ((e) => e.VirtualKey == keyValue && e.Modifiers == modifiers); if (sCode == null && modifiers == (ConsoleModifiers.Alt | ConsoleModifiers.Control)) { return scanCodes.FirstOrDefault ((e) => e.VirtualKey == keyValue && e.Modifiers == 0); } return sCode; } return null; } /// <summary> /// Get the <see cref="ConsoleKey"/> from a <see cref="Key"/>. /// </summary> /// <param name="keyValue">The key value.</param> /// <param name="modifiers">The modifiers keys.</param> /// <param name="scanCode">The resulting scan code.</param> /// <param name="outputChar">The resulting output character.</param> /// <returns>The <see cref="ConsoleKey"/> or the <paramref name="outputChar"/>.</returns> public static uint GetConsoleKeyFromKey (uint keyValue, ConsoleModifiers modifiers, out uint scanCode, out uint outputChar) { scanCode = 0; outputChar = keyValue; if (keyValue == 0) { return 0; } uint consoleKey = MapKeyToConsoleKey (keyValue, out bool mappable); if (mappable) { var mod = GetModifiers (keyValue, modifiers, false); var scode = GetScanCode ("UnicodeChar", keyValue, mod); if (scode != null) { consoleKey = scode.VirtualKey; scanCode = scode.ScanCode; outputChar = scode.UnicodeChar; } else { consoleKey = consoleKey < 0xff ? (uint)(consoleKey & 0xff | 0xff << 8) : consoleKey; } } else { var mod = GetModifiers (keyValue, modifiers, false); var scode = GetScanCode ("VirtualKey", consoleKey, mod); if (scode != null) { consoleKey = scode.VirtualKey; scanCode = scode.ScanCode; outputChar = scode.UnicodeChar; } } return consoleKey; } /// <summary> /// Get the output character from the <see cref="ConsoleKey"/>. /// </summary> /// <param name="unicodeChar">The unicode character.</param> /// <param name="modifiers">The modifiers keys.</param> /// <param name="consoleKey">The resulting console key.</param> /// <param name="scanCode">The resulting scan code.</param> /// <returns>The output character or the <paramref name="consoleKey"/>.</returns> public static uint GetKeyCharFromConsoleKey (uint unicodeChar, ConsoleModifiers modifiers, out uint consoleKey, out uint scanCode) { uint decodedChar = unicodeChar >> 8 == 0xff ? unicodeChar & 0xff : unicodeChar; uint keyChar = decodedChar; consoleKey = 0; var mod = GetModifiers (decodedChar, modifiers, true); scanCode = 0; var scode = unicodeChar != 0 && unicodeChar >> 8 != 0xff ? GetScanCode ("VirtualKey", decodedChar, mod) : null; if (scode != null) { consoleKey = scode.VirtualKey; keyChar = scode.UnicodeChar; scanCode = scode.ScanCode; } if (scode == null) { scode = unicodeChar != 0 ? GetScanCode ("UnicodeChar", decodedChar, mod) : null; if (scode != null) { consoleKey = scode.VirtualKey; keyChar = scode.UnicodeChar; scanCode = scode.ScanCode; } } if (decodedChar != 0 && scanCode == 0 && char.IsLetter ((char)decodedChar)) { string stFormD = ((char)decodedChar).ToString ().Normalize (System.Text.NormalizationForm.FormD); for (int i = 0; i < stFormD.Length; i++) { UnicodeCategory uc = CharUnicodeInfo.GetUnicodeCategory (stFormD [i]); if (uc != UnicodeCategory.NonSpacingMark && uc != UnicodeCategory.OtherLetter) { consoleKey = char.ToUpper (stFormD [i]); scode = GetScanCode ("VirtualKey", char.ToUpper (stFormD [i]), 0); if (scode != null) { scanCode = scode.ScanCode; } } } } return keyChar; } /// <summary> /// Maps a <see cref="Key"/> to a <see cref="ConsoleKey"/>. /// </summary> /// <param name="keyValue">The key value.</param> /// <param name="isMappable">If <see langword="true"/> is mapped to a valid character, otherwise <see langword="false"/>.</param> /// <returns>The <see cref="ConsoleKey"/> or the <paramref name="keyValue"/>.</returns> public static uint MapKeyToConsoleKey (uint keyValue, out bool isMappable) { isMappable = false; switch ((Key)keyValue) { case Key.Delete: return (uint)ConsoleKey.Delete; case Key.CursorUp: return (uint)ConsoleKey.UpArrow; case Key.CursorDown: return (uint)ConsoleKey.DownArrow; case Key.CursorLeft: return (uint)ConsoleKey.LeftArrow; case Key.CursorRight: return (uint)ConsoleKey.RightArrow; case Key.PageUp: return (uint)ConsoleKey.PageUp; case Key.PageDown: return (uint)ConsoleKey.PageDown; case Key.Home: return (uint)ConsoleKey.Home; case Key.End: return (uint)ConsoleKey.End; case Key.InsertChar: return (uint)ConsoleKey.Insert; case Key.DeleteChar: return (uint)ConsoleKey.Delete; case Key.F1: return (uint)ConsoleKey.F1; case Key.F2: return (uint)ConsoleKey.F2; case Key.F3: return (uint)ConsoleKey.F3; case Key.F4: return (uint)ConsoleKey.F4; case Key.F5: return (uint)ConsoleKey.F5; case Key.F6: return (uint)ConsoleKey.F6; case Key.F7: return (uint)ConsoleKey.F7; case Key.F8: return (uint)ConsoleKey.F8; case Key.F9: return (uint)ConsoleKey.F9; case Key.F10: return (uint)ConsoleKey.F10; case Key.F11: return (uint)ConsoleKey.F11; case Key.F12: return (uint)ConsoleKey.F12; case Key.F13: return (uint)ConsoleKey.F13; case Key.F14: return (uint)ConsoleKey.F14; case Key.F15: return (uint)ConsoleKey.F15; case Key.F16: return (uint)ConsoleKey.F16; case Key.F17: return (uint)ConsoleKey.F17; case Key.F18: return (uint)ConsoleKey.F18; case Key.F19: return (uint)ConsoleKey.F19; case Key.F20: return (uint)ConsoleKey.F20; case Key.F21: return (uint)ConsoleKey.F21; case Key.F22: return (uint)ConsoleKey.F22; case Key.F23: return (uint)ConsoleKey.F23; case Key.F24: return (uint)ConsoleKey.F24; case Key.BackTab: return (uint)ConsoleKey.Tab; case Key.Unknown: isMappable = true; return 0; } isMappable = true; return keyValue; } /// <summary> /// Maps a <see cref="ConsoleKey"/> to a <see cref="Key"/>. /// </summary> /// <param name="consoleKey">The console key.</param> /// <param name="isMappable">If <see langword="true"/> is mapped to a valid character, otherwise <see langword="false"/>.</param> /// <returns>The <see cref="Key"/> or the <paramref name="consoleKey"/>.</returns> public static Key MapConsoleKeyToKey (ConsoleKey consoleKey, out bool isMappable) { isMappable = false; switch (consoleKey) { case ConsoleKey.Delete: return Key.Delete; case ConsoleKey.UpArrow: return Key.CursorUp; case ConsoleKey.DownArrow: return Key.CursorDown; case ConsoleKey.LeftArrow: return Key.CursorLeft; case ConsoleKey.RightArrow: return Key.CursorRight; case ConsoleKey.PageUp: return Key.PageUp; case ConsoleKey.PageDown: return Key.PageDown; case ConsoleKey.Home: return Key.Home; case ConsoleKey.End: return Key.End; case ConsoleKey.Insert: return Key.InsertChar; case ConsoleKey.F1: return Key.F1; case ConsoleKey.F2: return Key.F2; case ConsoleKey.F3: return Key.F3; case ConsoleKey.F4: return Key.F4; case ConsoleKey.F5: return Key.F5; case ConsoleKey.F6: return Key.F6; case ConsoleKey.F7: return Key.F7; case ConsoleKey.F8: return Key.F8; case ConsoleKey.F9: return Key.F9; case ConsoleKey.F10: return Key.F10; case ConsoleKey.F11: return Key.F11; case ConsoleKey.F12: return Key.F12; case ConsoleKey.F13: return Key.F13; case ConsoleKey.F14: return Key.F14; case ConsoleKey.F15: return Key.F15; case ConsoleKey.F16: return Key.F16; case ConsoleKey.F17: return Key.F17; case ConsoleKey.F18: return Key.F18; case ConsoleKey.F19: return Key.F19; case ConsoleKey.F20: return Key.F20; case ConsoleKey.F21: return Key.F21; case ConsoleKey.F22: return Key.F22; case ConsoleKey.F23: return Key.F23; case ConsoleKey.F24: return Key.F24; case ConsoleKey.Tab: return Key.BackTab; } isMappable = true; return (Key)consoleKey; } /// <summary> /// Maps a <see cref="ConsoleKeyInfo"/> to a <see cref="Key"/>. /// </summary> /// <param name="keyInfo">The console key info.</param> /// <param name="key">The key.</param> /// <returns>The <see cref="Key"/> with <see cref="ConsoleModifiers"/> or the <paramref name="key"/></returns> public static Key MapKeyModifiers (ConsoleKeyInfo keyInfo, Key key) { Key keyMod = new Key (); if ((keyInfo.Modifiers & ConsoleModifiers.Shift) != 0) keyMod = Key.ShiftMask; if ((keyInfo.Modifiers & ConsoleModifiers.Control) != 0) keyMod |= Key.CtrlMask; if ((keyInfo.Modifiers & ConsoleModifiers.Alt) != 0) keyMod |= Key.AltMask; return keyMod != Key.Null ? keyMod | key : key; } private static HashSet<ScanCodeMapping> scanCodes = new HashSet<ScanCodeMapping> { new ScanCodeMapping (1,27,0,27), // Escape new ScanCodeMapping (1,27,ConsoleModifiers.Shift,27), new ScanCodeMapping (2,49,0,49), // D1 new ScanCodeMapping (2,49,ConsoleModifiers.Shift,33), new ScanCodeMapping (3,50,0,50), // D2 new ScanCodeMapping (3,50,ConsoleModifiers.Shift,34), new ScanCodeMapping (3,50,ConsoleModifiers.Alt | ConsoleModifiers.Control,64), new ScanCodeMapping (4,51,0,51), // D3 new ScanCodeMapping (4,51,ConsoleModifiers.Shift,35), new ScanCodeMapping (4,51,ConsoleModifiers.Alt | ConsoleModifiers.Control,163), new ScanCodeMapping (5,52,0,52), // D4 new ScanCodeMapping (5,52,ConsoleModifiers.Shift,36), new ScanCodeMapping (5,52,ConsoleModifiers.Alt | ConsoleModifiers.Control,167), new ScanCodeMapping (6,53,0,53), // D5 new ScanCodeMapping (6,53,ConsoleModifiers.Shift,37), new ScanCodeMapping (6,53,ConsoleModifiers.Alt | ConsoleModifiers.Control,8364), new ScanCodeMapping (7,54,0,54), // D6 new ScanCodeMapping (7,54,ConsoleModifiers.Shift,38), new ScanCodeMapping (8,55,0,55), // D7 new ScanCodeMapping (8,55,ConsoleModifiers.Shift,47), new ScanCodeMapping (8,55,ConsoleModifiers.Alt | ConsoleModifiers.Control,123), new ScanCodeMapping (9,56,0,56), // D8 new ScanCodeMapping (9,56,ConsoleModifiers.Shift,40), new ScanCodeMapping (9,56,ConsoleModifiers.Alt | ConsoleModifiers.Control,91), new ScanCodeMapping (10,57,0,57), // D9 new ScanCodeMapping (10,57,ConsoleModifiers.Shift,41), new ScanCodeMapping (10,57,ConsoleModifiers.Alt | ConsoleModifiers.Control,93), new ScanCodeMapping (11,48,0,48), // D0 new ScanCodeMapping (11,48,ConsoleModifiers.Shift,61), new ScanCodeMapping (11,48,ConsoleModifiers.Alt | ConsoleModifiers.Control,125), new ScanCodeMapping (12,219,0,39), // Oem4 new ScanCodeMapping (12,219,ConsoleModifiers.Shift,63), new ScanCodeMapping (13,221,0,171), // Oem6 new ScanCodeMapping (13,221,ConsoleModifiers.Shift,187), new ScanCodeMapping (14,8,0,8), // Backspace new ScanCodeMapping (14,8,ConsoleModifiers.Shift,8), new ScanCodeMapping (15,9,0,9), // Tab new ScanCodeMapping (15,9,ConsoleModifiers.Shift,15), new ScanCodeMapping (16,81,0,113), // Q new ScanCodeMapping (16,81,ConsoleModifiers.Shift,81), new ScanCodeMapping (17,87,0,119), // W new ScanCodeMapping (17,87,ConsoleModifiers.Shift,87), new ScanCodeMapping (18,69,0,101), // E new ScanCodeMapping (18,69,ConsoleModifiers.Shift,69), new ScanCodeMapping (19,82,0,114), // R new ScanCodeMapping (19,82,ConsoleModifiers.Shift,82), new ScanCodeMapping (20,84,0,116), // T new ScanCodeMapping (20,84,ConsoleModifiers.Shift,84), new ScanCodeMapping (21,89,0,121), // Y new ScanCodeMapping (21,89,ConsoleModifiers.Shift,89), new ScanCodeMapping (22,85,0,117), // U new ScanCodeMapping (22,85,ConsoleModifiers.Shift,85), new ScanCodeMapping (23,73,0,105), // I new ScanCodeMapping (23,73,ConsoleModifiers.Shift,73), new ScanCodeMapping (24,79,0,111), // O new ScanCodeMapping (24,79,ConsoleModifiers.Shift,79), new ScanCodeMapping (25,80,0,112), // P new ScanCodeMapping (25,80,ConsoleModifiers.Shift,80), new ScanCodeMapping (26,187,0,43), // OemPlus new ScanCodeMapping (26,187,ConsoleModifiers.Shift,42), new ScanCodeMapping (26,187,ConsoleModifiers.Alt | ConsoleModifiers.Control,168), new ScanCodeMapping (27,186,0,180), // Oem1 new ScanCodeMapping (27,186,ConsoleModifiers.Shift,96), new ScanCodeMapping (28,13,0,13), // Enter new ScanCodeMapping (28,13,ConsoleModifiers.Shift,13), new ScanCodeMapping (29,17,0,0), // Control new ScanCodeMapping (29,17,ConsoleModifiers.Shift,0), new ScanCodeMapping (30,65,0,97), // A new ScanCodeMapping (30,65,ConsoleModifiers.Shift,65), new ScanCodeMapping (31,83,0,115), // S new ScanCodeMapping (31,83,ConsoleModifiers.Shift,83), new ScanCodeMapping (32,68,0,100), // D new ScanCodeMapping (32,68,ConsoleModifiers.Shift,68), new ScanCodeMapping (33,70,0,102), // F new ScanCodeMapping (33,70,ConsoleModifiers.Shift,70), new ScanCodeMapping (34,71,0,103), // G new ScanCodeMapping (34,71,ConsoleModifiers.Shift,71), new ScanCodeMapping (35,72,0,104), // H new ScanCodeMapping (35,72,ConsoleModifiers.Shift,72), new ScanCodeMapping (36,74,0,106), // J new ScanCodeMapping (36,74,ConsoleModifiers.Shift,74), new ScanCodeMapping (37,75,0,107), // K new ScanCodeMapping (37,75,ConsoleModifiers.Shift,75), new ScanCodeMapping (38,76,0,108), // L new ScanCodeMapping (38,76,ConsoleModifiers.Shift,76), new ScanCodeMapping (39,192,0,231), // Oem3 new ScanCodeMapping (39,192,ConsoleModifiers.Shift,199), new ScanCodeMapping (40,222,0,186), // Oem7 new ScanCodeMapping (40,222,ConsoleModifiers.Shift,170), new ScanCodeMapping (41,220,0,92), // Oem5 new ScanCodeMapping (41,220,ConsoleModifiers.Shift,124), new ScanCodeMapping (42,16,0,0), // LShift new ScanCodeMapping (42,16,ConsoleModifiers.Shift,0), new ScanCodeMapping (43,191,0,126), // Oem2 new ScanCodeMapping (43,191,ConsoleModifiers.Shift,94), new ScanCodeMapping (44,90,0,122), // Z new ScanCodeMapping (44,90,ConsoleModifiers.Shift,90), new ScanCodeMapping (45,88,0,120), // X new ScanCodeMapping (45,88,ConsoleModifiers.Shift,88), new ScanCodeMapping (46,67,0,99), // C new ScanCodeMapping (46,67,ConsoleModifiers.Shift,67), new ScanCodeMapping (47,86,0,118), // V new ScanCodeMapping (47,86,ConsoleModifiers.Shift,86), new ScanCodeMapping (48,66,0,98), // B new ScanCodeMapping (48,66,ConsoleModifiers.Shift,66), new ScanCodeMapping (49,78,0,110), // N new ScanCodeMapping (49,78,ConsoleModifiers.Shift,78), new ScanCodeMapping (50,77,0,109), // M new ScanCodeMapping (50,77,ConsoleModifiers.Shift,77), new ScanCodeMapping (51,188,0,44), // OemComma new ScanCodeMapping (51,188,ConsoleModifiers.Shift,59), new ScanCodeMapping (52,190,0,46), // OemPeriod new ScanCodeMapping (52,190,ConsoleModifiers.Shift,58), new ScanCodeMapping (53,189,0,45), // OemMinus new ScanCodeMapping (53,189,ConsoleModifiers.Shift,95), new ScanCodeMapping (54,16,0,0), // RShift new ScanCodeMapping (54,16,ConsoleModifiers.Shift,0), new ScanCodeMapping (55,44,0,0), // PrintScreen new ScanCodeMapping (55,44,ConsoleModifiers.Shift,0), new ScanCodeMapping (56,18,0,0), // Alt new ScanCodeMapping (56,18,ConsoleModifiers.Shift,0), new ScanCodeMapping (57,32,0,32), // Spacebar new ScanCodeMapping (57,32,ConsoleModifiers.Shift,32), new ScanCodeMapping (58,20,0,0), // Caps new ScanCodeMapping (58,20,ConsoleModifiers.Shift,0), new ScanCodeMapping (59,112,0,0), // F1 new ScanCodeMapping (59,112,ConsoleModifiers.Shift,0), new ScanCodeMapping (60,113,0,0), // F2 new ScanCodeMapping (60,113,ConsoleModifiers.Shift,0), new ScanCodeMapping (61,114,0,0), // F3 new ScanCodeMapping (61,114,ConsoleModifiers.Shift,0), new ScanCodeMapping (62,115,0,0), // F4 new ScanCodeMapping (62,115,ConsoleModifiers.Shift,0), new ScanCodeMapping (63,116,0,0), // F5 new ScanCodeMapping (63,116,ConsoleModifiers.Shift,0), new ScanCodeMapping (64,117,0,0), // F6 new ScanCodeMapping (64,117,ConsoleModifiers.Shift,0), new ScanCodeMapping (65,118,0,0), // F7 new ScanCodeMapping (65,118,ConsoleModifiers.Shift,0), new ScanCodeMapping (66,119,0,0), // F8 new ScanCodeMapping (66,119,ConsoleModifiers.Shift,0), new ScanCodeMapping (67,120,0,0), // F9 new ScanCodeMapping (67,120,ConsoleModifiers.Shift,0), new ScanCodeMapping (68,121,0,0), // F10 new ScanCodeMapping (68,121,ConsoleModifiers.Shift,0), new ScanCodeMapping (69,144,0,0), // Num new ScanCodeMapping (69,144,ConsoleModifiers.Shift,0), new ScanCodeMapping (70,145,0,0), // Scroll new ScanCodeMapping (70,145,ConsoleModifiers.Shift,0), new ScanCodeMapping (71,36,0,0), // Home new ScanCodeMapping (71,36,ConsoleModifiers.Shift,0), new ScanCodeMapping (72,38,0,0), // UpArrow new ScanCodeMapping (72,38,ConsoleModifiers.Shift,0), new ScanCodeMapping (73,33,0,0), // PageUp new ScanCodeMapping (73,33,ConsoleModifiers.Shift,0), new ScanCodeMapping (74,109,0,45), // Subtract new ScanCodeMapping (74,109,ConsoleModifiers.Shift,45), new ScanCodeMapping (75,37,0,0), // LeftArrow new ScanCodeMapping (75,37,ConsoleModifiers.Shift,0), new ScanCodeMapping (76,12,0,0), // Center new ScanCodeMapping (76,12,ConsoleModifiers.Shift,0), new ScanCodeMapping (77,39,0,0), // RightArrow new ScanCodeMapping (77,39,ConsoleModifiers.Shift,0), new ScanCodeMapping (78,107,0,43), // Add new ScanCodeMapping (78,107,ConsoleModifiers.Shift,43), new ScanCodeMapping (79,35,0,0), // End new ScanCodeMapping (79,35,ConsoleModifiers.Shift,0), new ScanCodeMapping (80,40,0,0), // DownArrow new ScanCodeMapping (80,40,ConsoleModifiers.Shift,0), new ScanCodeMapping (81,34,0,0), // PageDown new ScanCodeMapping (81,34,ConsoleModifiers.Shift,0), new ScanCodeMapping (82,45,0,0), // Insert new ScanCodeMapping (82,45,ConsoleModifiers.Shift,0), new ScanCodeMapping (83,46,0,0), // Delete new ScanCodeMapping (83,46,ConsoleModifiers.Shift,0), new ScanCodeMapping (86,226,0,60), // OEM 102 new ScanCodeMapping (86,226,ConsoleModifiers.Shift,62), new ScanCodeMapping (87,122,0,0), // F11 new ScanCodeMapping (87,122,ConsoleModifiers.Shift,0), new ScanCodeMapping (88,123,0,0), // F12 new ScanCodeMapping (88,123,ConsoleModifiers.Shift,0) }; } }
namespace CarDealerApp.Controllers { using System.Collections.Generic; using System.Web.Mvc; using CarDealer.BindingModels; using CarDealer.Services; using CarDealer.ViewModels; using CarDealer.ViewModels.Customers; [RoutePrefix("customers")] public class CustomersController : Controller { private CustomersService service; public CustomersController() { this.service = new CustomersService(); } // GET: All Customers [Route("all/{criteria:regex(ascending|descending)?}")] public ActionResult All(string criteria) { IEnumerable<CustomerViewModel> allCustomersVm = this.service.GetAllCustomers(criteria); return View(allCustomersVm); } // GET: Customer and details about all sales [Route("~/customer/{id}")] public ActionResult Details(int id) { if (!this.service.CheckIfCustomerExists(id)) { return RedirectToAction("All"); } CustomerDetailsViewModel cdvm = this.service.GetCustomerDetails(id); return View(cdvm); } // GET: Add customer page [Route("add"), HttpGet] public ActionResult Add() { return View(); } // POST: [Route("add"), HttpPost] public ActionResult Add([Bind(Include = "Name,Birthdate")] AddCustomerBindingModel bindingModel) { if (ModelState.IsValid) { this.service.AddCustomer(bindingModel); } return RedirectToAction("All", new {criteria = "descending"}); } // GET: Edit customer page [Route("edit/{id}"), HttpGet] public ActionResult Edit(int id) { CustomerViewModel cvm = this.service.GetCustomerViewModelById(id); return View(cvm); } // POST: [Route("edit/{id}"), HttpPost] public ActionResult Edit([Bind(Include = "Id,Name,Birthdate")] EditCustomerBindingModel bindingModel) { if (ModelState.IsValid) { this.service.EditCustomer(bindingModel); } return RedirectToAction("Details", new { id = bindingModel.Id }); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.ServiceBus.Messaging; namespace ControlData { public class EventHubProcessor { /// <summary> /// Attach an event processor host to an event hub. /// </summary> /// <param name="processorName">Used in blob storage for grouping stored partition offsets into a container.</param> /// <param name="serviceBusConnectionString">Full connection string to the service bus containing the hub.</param> /// <param name="offsetStorageConnectionString">Full connection string to the storage stamp for storing offsets.</param> /// <param name="eventHubName">Name of the event hub.</param> /// <param name="consumerGroupName">Name of the consumer group (use $Default if you don't know).</param> /// <param name="processorFactory">EventProcessorFactory instance.</param> /// <returns></returns> public static async Task<EventProcessorHost> AttachProcessorForHub( string processorName, string serviceBusConnectionString, string offsetStorageConnectionString, string eventHubName, string consumerGroupName, IEventProcessorFactory processorFactory) { var eventProcessorHost = new EventProcessorHost(processorName, eventHubName, consumerGroupName, serviceBusConnectionString, offsetStorageConnectionString); await eventProcessorHost.RegisterEventProcessorFactoryAsync(processorFactory); return eventProcessorHost; } } }
using KinectSandbox.Common.Colors; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Media; namespace KinectSandbox.ColorPicker.AllColorPicker { public interface ILayeredColor { SupportedColorLayer SelectedLayer { get; set; } string LayerName { get; } int MinValue { get; set; } int MaxValue { get; set; } Color SelectedColor { get; set; } } }
using System; namespace OptionalTypes.JsonConverters.Tests.TestDtos { public class GuidDto { public Optional<Guid> Value { get; set; } } }
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using ServiceQuotes.Domain.Entities; namespace ServiceQuotes.Infrastructure.Context.EntityConfigurations { public class PaymentEntityConfiguration : IEntityTypeConfiguration<Payment> { public void Configure(EntityTypeBuilder<Payment> builder) { builder.HasKey(payment => payment.Id); builder.Property(payment => payment.Id).ValueGeneratedOnAdd().IsRequired(); builder.Property(payment => payment.Provider).HasMaxLength(50).IsRequired(); builder.Property(payment => payment.TransactionId).HasMaxLength(150).IsRequired(false); builder.Property(payment => payment.Amount).HasPrecision(7, 2).IsRequired(); builder.Property(payment => payment.Created).IsRequired(); builder.Property(payment => payment.Updated).IsRequired(false); builder .HasOne(payment => payment.Quote) .WithMany(quote => quote.Payments) .HasForeignKey(payment => payment.QuoteId); builder .HasOne(payment => payment.Customer) .WithMany(customer => customer.Payments) .HasForeignKey(payment => payment.CustomerId); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using TrettioEtt; static class EMethods { const double MINIMUMVALUE = 0.8, MAXIMUMVALUE = 1.25; static Random random; public static object ChangeRandomly(this object target, double randomnessExponent) { object targetCopy = target; if (random == null) random = new Random(); double preliminaryDouble = random.NextDouble(); if (targetCopy is bool) { targetCopy = (bool)(preliminaryDouble > 0.65 ? !(bool)targetCopy : targetCopy); return targetCopy; } double randomDouble = Math.Pow(preliminaryDouble * (MAXIMUMVALUE - MINIMUMVALUE) + MINIMUMVALUE, randomnessExponent); if (targetCopy is int) { if (preliminaryDouble < 0.35) { targetCopy = (int)(randomDouble * ((int)targetCopy)); return targetCopy; } if (preliminaryDouble > 0.65) { targetCopy = (int)(randomDouble * ((int)targetCopy)) + 1; return targetCopy; } return targetCopy; } if (targetCopy is double) { targetCopy = (double)targetCopy * randomDouble; return targetCopy; } return targetCopy; } public static int BestHandIndex(List<Card>[] hands) { int highestValue = hands[0].HandValue(); int highestIndex = 0; for (int i = 1; i < 3; ++i) { int thisValue = hands[i].HandValue(); if (thisValue > highestValue) { highestValue = thisValue; highestIndex = i; } } return highestIndex; } public static List<Card> BestCombination(List<Card> inputHand, out Card discardCard) { List<Card> allCards = new List<Card>(inputHand); List<Card> bestHand = new List<Card>(allCards); bestHand.RemoveAt(0); discardCard = allCards[0]; int bestValue = bestHand.HandValue(); int bestTotalValue = bestHand.TotalHandValue(); for (int i = 1; i < allCards.Count; ++i) { List<Card> thisHand = new List<Card>(allCards); Card potentialDiscardCard = thisHand[i]; thisHand.RemoveAt(i); int currentValue = thisHand.HandValue(); int currentTotalValue = thisHand.TotalHandValue(); if (currentValue < bestValue || (currentValue == bestValue && currentTotalValue <= bestTotalValue)) { continue; } bestValue = currentValue; bestTotalValue = currentTotalValue; bestHand = thisHand; discardCard = potentialDiscardCard; } return bestHand; } public static int HandValue(this IEnumerable<Card> cards) { int[] suitValues = new int[4]; foreach (Card card in cards) { suitValues[(int)card.Suit] += card.Value; } int highest = suitValues[0]; for (int i = 1; i < 4; ++i) { if (suitValues[i] > highest) { highest = suitValues[i]; } } return highest; } public static int TotalHandValue(this IEnumerable<Card> cards) { int totalValue = 0; foreach (Card card in cards) { totalValue += card.Value; } return totalValue; } public static List<Card>[] PossibleHands(List<Card> hand, Card additionalCard) { List<Card>[] returnValue = new List<Card>[3]; for (int i = 0; i < 3; ++i) { returnValue[i].AddRange(hand); returnValue[i].Add(additionalCard); } return returnValue; } public static Card DiscardCard(List<Card> hand) { List<Card> tempHand = new List<Card>(hand); Card additionalCard = tempHand[tempHand.Count - 1]; tempHand.RemoveAt(tempHand.Count - 1); return DiscardCardAdditional(tempHand, additionalCard); } public static Card DiscardCardAdditional(List<Card> hand, Card additionalCard) { List<Card> allCards = new List<Card>(hand) { additionalCard }; List<Card> optimalHand = BestCombination(allCards, out Card discardCard); return discardCard; } public static GeneticAI Combine(this GeneticAI aI, GeneticAI counterpart, int generation, int index, double mutationChance) { GeneticAI newAi = new GeneticAI(aI, false, generation, index); Dictionary<string, object> settings = new Dictionary<string, object>(newAi.Settings); if (random == null) random = new Random(); double randomDouble = random.NextDouble(); foreach (KeyValuePair<string, object> setting in aI.Settings) { if (randomDouble < mutationChance) { settings[setting.Key] = settings[setting.Key].ChangeRandomly(1); continue; } if ((randomDouble - mutationChance) / mutationChance < 0.5) { settings[setting.Key] = counterpart.Settings[setting.Key]; } } return newAi; } }
using System; using System.Collections.Generic; using System.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; namespace RimDev.AspNetCore.FeatureFlags { public class JsonBooleanConverter : JsonConverter { public override void WriteJson( JsonWriter writer, object value, JsonSerializer serializer ) { var t = JToken.FromObject(value); if (t.Type != JTokenType.Object) { t.WriteTo(writer); } else { var o = (JObject)t; IList<string> propertyNames = o.Properties().Select(p => p.Name).ToList(); o.AddFirst(new JProperty("Keys", new JArray(propertyNames))); o.WriteTo(writer); } } public override object ReadJson( JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer ) => ReadJson(reader.Value); public override bool CanConvert(Type objectType) { return objectType == typeof(string) || objectType == typeof(bool); } public object ReadJson(object value) { switch (value?.ToString()?.ToLower().Trim()) { case "true": case "yes": case "y": case "1": return true; case "false": case "no": case "n": case "0": return false; default: return null; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Linq; using System.Text; using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Identity.UI.Services; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using Microsoft.AspNetCore.WebUtilities; using Microsoft.Extensions.Logging; using MyForum.Domain; using MyForum.Domain.Enums; using MyForum.Infrastructure; namespace MyForum.Web.Areas.Identity.Pages.Account { [AllowAnonymous] public class RegisterModel : PageModel { private readonly SignInManager<ApplicationUser> _signInManager; private readonly UserManager<ApplicationUser> _userManager; private readonly ILogger<RegisterModel> _logger; public RegisterModel( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, ILogger<RegisterModel> logger) { _userManager = userManager; _signInManager = signInManager; _logger = logger; } [BindProperty] public InputModel Input { get; set; } public string ReturnUrl { get; set; } public class InputModel { [Required] [StringLength(20, ErrorMessage = GlobalConstants.LengthError, MinimumLength = 5)] [Display(Name = "Username")] public string Username { get; set; } [Required] [StringLength(20, ErrorMessage = GlobalConstants.LengthError, MinimumLength = 3)] [Display(Name = "First Name")] public string FirstName { get; set; } [Required] [StringLength(20, ErrorMessage = GlobalConstants.LengthError, MinimumLength = 3)] [Display(Name = "Last Name")] public string LastName { get; set; } [Required] [EmailAddress] [Display(Name = "Email")] public string Email { get; set; } [Required] public Gender Gender { get; set; } [Required] [StringLength(100, ErrorMessage = GlobalConstants.LengthError, MinimumLength = 6)] [DataType(DataType.Password)] [Display(Name = "Password")] public string Password { get; set; } [DataType(DataType.Password)] [Display(Name = "Confirm password")] [Compare("Password", ErrorMessage = GlobalConstants.ConfirmPasswordEr)] public string ConfirmPassword { get; set; } [Required] [RegularExpression(@"^\d{2}\.\d{2}\.\d{4}$", ErrorMessage = GlobalConstants.DateTimeFormatError)] [Display(Name = "Day of birth")] public string DayOfBirth { get; set; } } public void OnGet(string returnUrl = null) { ReturnUrl = returnUrl; } public async Task<IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content(GlobalConstants.LoginPath); if (this.ModelState.IsValid) { var dateOfBirth = DateTime.ParseExact(Input.DayOfBirth, "dd.mm.yyyy", CultureInfo.InvariantCulture); var user = new ApplicationUser { UserName = Input.Username, FirstName = Input.FirstName, LastName = Input.LastName, IsDeactivate = false, DateOfBirth = dateOfBirth, Gender = Input.Gender, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { this._logger.LogInformation("User created a new account with password."); if (this._userManager.Users.Count() == 1) { await this._userManager.AddToRoleAsync(user, GlobalConstants.AdminRole); } else { await this._userManager.AddToRoleAsync(user, GlobalConstants.UserRole); } //await _signInManager.SignInAsync(user, isPersistent: false); return LocalRedirect(returnUrl); } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return Page(); } } }
namespace ClimatesOfFerngillRebuild { public interface IClimatesOfFerngillAPI { string GetCurrentWeatherName(); } public class ClimatesOfFerngillAPI : IClimatesOfFerngillAPI { private WeatherConditions CurrentConditions; public void LoadData(WeatherConditions Cond) => CurrentConditions = Cond; public ClimatesOfFerngillAPI(WeatherConditions cond) { LoadData(cond); } public string GetCurrentWeatherName() { return CurrentConditions.Weathers[(int)CurrentConditions.GetCurrentConditions()].ConditionName; } public void SetWeather(string weather) { //TODO: Handle processing. } public double GetTodaysHigh() { return CurrentConditions.TodayHigh; } public double GetTodaysLow() { return CurrentConditions.TodayLow; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnityEngine; using TweakScale.Annotations; namespace TweakScale { [KSPAddon(KSPAddon.Startup.MainMenu, true)] internal class PrefabDryCostWriter : SingletonBehavior<PrefabDryCostWriter> { private static readonly int WAIT_ROUNDS = 120; // @60fps, would render 2 secs. internal static bool isConcluded = false; [UsedImplicitly] private void Start() { StartCoroutine("WriteDryCost"); } private IEnumerator WriteDryCost() { PrefabDryCostWriter.isConcluded = false; Debug.Log("TweakScale::WriteDryCost: Started"); for (int i = WAIT_ROUNDS; i >= 0 && null == PartLoader.LoadedPartsList; --i) { yield return null; if (0 == i) Debug.LogError("TweakScale::Timeout waiting for PartLoader.LoadedPartsList!!"); } // I Don't know if this is needed, but since I don't know that this is not needed, // I choose to be safe than sorry! { int last_count = int.MinValue; for (int i = WAIT_ROUNDS; i >= 0; --i) { if (last_count == PartLoader.LoadedPartsList.Count) break; last_count = PartLoader.LoadedPartsList.Count; yield return null; if (0 == i) Debug.LogError("TweakScale::Timeout waiting for PartLoader.LoadedPartsList.Count!!"); } } foreach (AvailablePart p in PartLoader.LoadedPartsList) { for (int i = WAIT_ROUNDS; i >= 0 && null == p.partPrefab && null == p.partPrefab.Modules && p.partPrefab.Modules.Count < 1; --i) { yield return null; if (0 == i) Debug.LogErrorFormat("TweakScale::Timeout waiting for {0}.prefab.Modules!!", p.name); } Part prefab = p.partPrefab; // Historically, we had problems here. // However, that co-routine stunt appears to have solved it. // But we will keep this as a ghinea-pig in the case the problem happens again. try { if (!prefab.Modules.Contains("TweakScale")) continue; } catch (Exception e) { Debug.LogErrorFormat("[TweakScale] Exception on {0}.prefab.Modules.Contains: {1}", p.name, e); Debug.LogWarningFormat("{0}", prefab.Modules); continue; // TODO: Cook a way to try again! } { string r = this.checkForSanity(prefab); if (null != r) { // There are some known situations where TweakScale is capsizing. If such situations are detected, we just // refuse to scale it. Sorry. Debug.LogWarningFormat("[TweakScale] Removing TweakScale support for {0}.", p.name); prefab.Modules.Remove(prefab.Modules["TweakScale"]); Debug.LogErrorFormat("[TweakScale] Part {0} didn't passed the sanity check due {1}.", p.name, r); continue; } } try { TweakScale m = prefab.Modules["TweakScale"] as TweakScale; m.DryCost = (float)(p.cost - prefab.Resources.Cast<PartResource>().Aggregate(0.0, (a, b) => a + b.maxAmount * b.info.unitCost)); m.ignoreResourcesForCost |= prefab.Modules.Contains("FSfuelSwitch"); if (m.DryCost < 0) { Debug.LogErrorFormat("TweakScale::PrefabDryCostWriter: negative dryCost: part={0}, DryCost={1}", p.name, m.DryCost); m.DryCost = 0; } #if DEBUG Debug.LogFormat("Part {0} has drycost {1} with ignoreResourcesForCost {2}", p.name, m.DryCost, m.ignoreResourcesForCost); #endif } catch (Exception e) { Debug.LogErrorFormat("[TweakScale] part={0} ({1}) Exception on writeDryCost: {2}", p.name, p.title, e); } } Debug.Log("TweakScale::WriteDryCost: Concluded"); PrefabDryCostWriter.isConcluded = true; } private string checkForSanity(Part p) { if (p.Modules.Contains("ModulePartVariants")) { PartModule m = p.Modules["ModulePartVariants"]; foreach(FieldInfo fi in m.ModuleAttributes.publicFields) { if("variantList" != fi.Name) continue; IList variantList = (IList)fi.GetValue(m); foreach (object partVariant in variantList) foreach (PropertyInfo property in partVariant.GetType().GetProperties()) { if ("Cost" == property.Name && 0.0 != (float)property.GetValue(partVariant, null)) return "having a ModulePartVariants with Cost - see issue #13 https://github.com/net-lisias-ksp/TweakScale/issues/13"; if ("Mass" == property.Name && 0.0 != (float)property.GetValue(partVariant, null)) return "having a ModulePartVariants with Mass - see issue #13 https://github.com/net-lisias-ksp/TweakScale/issues/13"; } } } if (p.Modules.Contains("FSbuoyancy")) return "using FSbuoyancy module - see issue #9 https://github.com/net-lisias-ksp/TweakScale/issues/9"; if (p.Modules.Contains("ModuleB9PartSwitch")) { if (p.Modules.Contains("FSfuelSwitch")) return "having ModuleB9PartSwitch together FSfuelSwitch - see issue #12 - https://github.com/net-lisias-ksp/TweakScale/issues/12"; if (p.Modules.Contains("ModuleFuelTanks")) return "having ModuleB9PartSwitch together ModuleFuelTanks - see issue #12 - https://github.com/net-lisias-ksp/TweakScale/issues/12";; } return null; } } }
namespace Olive.Desktop.WPF.Behavior { using System; using System.Windows; using System.Windows.Input; using System.Windows.Controls; public static class CommandsBehavior { private static void ExecuteClickCommand(DependencyObject d, DependencyPropertyChangedEventArgs e) { //var control = d as UIElement; var control = d as ListViewItem; if (control == null) { return; } if ((e.NewValue != null) && (e.OldValue == null)) { control.Selected += (snd, args) => { var command = (snd as ListViewItem).GetValue(CommandsBehavior.ClickProperty) as ICommand; command.Execute((snd as ListViewItem)); }; } //OldVersio //var control = d as UIElement; //if (control == null) //{ // return; //} //if ((e.NewValue != null) && (e.OldValue == null)) //{ // control.MouseLeftButtonDown += (snd, args) => // { // var command = (snd as UIElement).GetValue(CommandsBehavior.ClickProperty) as ICommand; // command.Execute(args); // }; //} } private static void ExecuteKeyUpCommand(DependencyObject d, DependencyPropertyChangedEventArgs e) { var control = d as TextBox; if (control == null) { return; } if ((e.NewValue != null) && (e.OldValue == null)) { control.KeyUp += (snd, args) => { var command = (snd as TextBox).GetValue(CommandsBehavior.KeyUpProperty) as ICommand; command.Execute((snd as TextBox).Text); //command.Execute(args); }; } } public static ICommand GetClick(DependencyObject obj) { return (ICommand)obj.GetValue(ClickProperty); } public static void SetClick(DependencyObject obj, ICommand value) { obj.SetValue(ClickProperty, value); } // Using a DependencyProperty as the backing store for Click. This enables animation, styling, binding, etc... public static readonly DependencyProperty ClickProperty = DependencyProperty.RegisterAttached("Click", typeof(ICommand), typeof(CommandsBehavior), new PropertyMetadata(ExecuteClickCommand)); public static ICommand GetKeyUp(TextBox textBox) { return (ICommand)textBox.GetValue(KeyUpProperty); } public static void SetKeyUp(TextBox textBox, ICommand value) { textBox.SetValue(KeyUpProperty, value); } // Using a DependencyProperty as the backing store for KeyUpProperty. This enables animation, styling, binding, etc... public static readonly DependencyProperty KeyUpProperty = DependencyProperty.RegisterAttached("KeyUp", typeof(ICommand), typeof(CommandsBehavior), new UIPropertyMetadata(ExecuteKeyUpCommand)); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace GSVM.Constructs.DataTypes { public interface IDataType { SmartPointer Pointer { get; } uint Address { get; set; } uint Length { get; } byte[] ToBinary(); void FromBinary(byte[] value); } }
// Copyright (c) Microsoft and contributors. All rights reserved. // // This source code is licensed under the MIT license found in the // LICENSE file in the root directory of this source tree. namespace Microsoft.Azure.Management.ANF.Samples { using System; using System.Threading.Tasks; using Microsoft.Azure.Management.ANF.Samples.Common; using Microsoft.Azure.Management.NetApp; using Microsoft.Azure.Management.NetApp.Models; public static class Snapshots { /// <summary> /// Executes Snapshot related operations /// </summary> /// <returns></returns> public static async Task RunSnapshotOperationsSampleAsync(ProjectConfiguration config, AzureNetAppFilesManagementClient anfClient) { // // Creating snapshot from first volume of the first capacity pool // Utils.WriteConsoleMessage("Performing snapshot operations"); Utils.WriteConsoleMessage("\tCreating snapshot..."); string snapshotName = $"Snapshot-{Guid.NewGuid()}"; Snapshot snapshotBody = new Snapshot() { Location = config.Accounts[0].Location }; Snapshot snapshot = null; try { snapshot = await anfClient.Snapshots.CreateAsync( snapshotBody, config.ResourceGroup, config.Accounts[0].Name, config.Accounts[0].CapacityPools[0].Name, config.Accounts[0].CapacityPools[0].Volumes[0].Name, snapshotName); Utils.WriteConsoleMessage($"Snapshot successfully created. Snapshot resource id: {snapshot.Id}"); } catch (Exception ex) { Utils.WriteErrorMessage($"An error occured while creating a snapshot of volume {config.Accounts[0].CapacityPools[0].Volumes[0].Name}.\nError message: {ex.Message}"); throw; } // // Creating a volume from snapshot // Utils.WriteConsoleMessage("\tCreating new volume from snapshot..."); string newVolumeName = $"Vol-{ResourceUriUtils.GetAnfSnapshot(snapshot.Id)}"; Volume snapshotVolume = null; try { snapshotVolume = await anfClient.Volumes.GetAsync( ResourceUriUtils.GetResourceGroup(snapshot.Id), ResourceUriUtils.GetAnfAccount(snapshot.Id), ResourceUriUtils.GetAnfCapacityPool(snapshot.Id), ResourceUriUtils.GetAnfVolume(snapshot.Id)); } catch (Exception ex) { Utils.WriteErrorMessage($"An error occured trying to obtain information about volume ({ResourceUriUtils.GetAnfVolume(snapshot.Id)}) from snapshot {snapshot.Id}.\nError message: {ex.Message}"); throw; } Volume newVolumeFromSnapshot = null; try { // Notice that SnapshotId is not the actual resource Id of the snapshot, this value is the unique identifier (guid) of // the snapshot, represented by the SnapshotId instead. Volume volumeFromSnapshotBody = new Volume() { SnapshotId = snapshot.SnapshotId, ExportPolicy = snapshotVolume.ExportPolicy, Location = snapshotVolume.Location, ProtocolTypes = snapshotVolume.ProtocolTypes, ServiceLevel = snapshotVolume.ServiceLevel, UsageThreshold = snapshotVolume.UsageThreshold, SubnetId = snapshotVolume.SubnetId, CreationToken = newVolumeName }; newVolumeFromSnapshot = await anfClient.Volumes.CreateOrUpdateAsync( volumeFromSnapshotBody, config.ResourceGroup, config.Accounts[0].Name, config.Accounts[0].CapacityPools[0].Name, newVolumeName); Utils.WriteConsoleMessage($"Volume successfully created from snapshot. Volume resource id: {newVolumeFromSnapshot.Id}"); } catch (Exception ex) { Utils.WriteErrorMessage($"An error occured while creating a volume ({newVolumeName}) from snapshot {snapshot.Id}.\nError message: {ex.Message}"); throw; } } } }
namespace Nca.Valdr.Tests.DTOs { using Resources.Localization; using System.ComponentModel.DataAnnotations; using System.Runtime.Serialization; /// <summary> /// Address data transfer object. /// </summary> [DataContract(Name = "address")] [ValdrType(Name = "address")] public class AddressDto { /// <summary> /// Street name. /// </summary> [DataMember(Name = "street")] [ValdrMember(Name = "street")] [Display(ResourceType = typeof(Texts), Name = "Address_Street")] public string Street { get; set; } /// <summary> /// City name /// </summary> [DataMember(Name = "city")] [ValdrMember(Name = "city")] [Required(ErrorMessageResourceType = typeof(Texts), ErrorMessageResourceName = "Generic_RequiredField")] [Display(ResourceType = typeof(Texts), Name = "Address_City")] public string City { get; set; } /// <summary> /// Zip code /// </summary> [DataMember(Name = "zipCode")] [ValdrMember(Name = "zipCode")] [Required(ErrorMessageResourceType = typeof(Texts), ErrorMessageResourceName = "Generic_RequiredField")] [StringLength(6, ErrorMessageResourceType = typeof(Texts), ErrorMessageResourceName = "Generic_MaximumLength", MinimumLength = 4)] [Display(ResourceType = typeof(Texts), Name = "Address_ZipCode")] public string ZipCode { get; set; } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; namespace CyberUI { [System.Serializable] public enum Axis { X, Y, Z } public class RandomCircleMatrix : MonoBehaviour { [System.Serializable] public class RandomSetting { public List<Mesh> mesh; public List<Texture2D> texture; public List<Texture2D> mask; public List<Color> color; // May choose between // Transparent/CutOff/CutOff // Transparent/CutOff/CutOff_TwoSide // public Shader shader; } public RandomSetting layerSetting; [System.Serializable] public class RenderSetting { public string layerTag = string.Empty; public int layerId = 0; public int sortingLayerId = 0; public int sortingOrder = 0; } public RenderSetting renderSetting; public int NumberOfLayer=20; public float minScale=.5f; public float maxScale=5f; public Axis whirlAxis = Axis.Z; public float whirlSpeedMin=-100f; public float whirlSpeedMax=100f; [Range(0f,1f)] public float angleMin=0f; [Range(0f,1f)] public float angleMax=1f; public Vector3 randomSpawnMin = Vector3.zero; public Vector3 randomSpawnMax = Vector3.zero; void Start() { if( layerSetting.mesh.Count==0 || layerSetting.texture.Count==0 || layerSetting.mask.Count==0 ) { Debug.LogError("RandomCircleMatrix : layerSetting invaild."); this.enabled=false; } RandomCreateCircle(); } public void DeleteAllCircle() { // we only want to destroy the CircleLayer. foreach(Transform _child in this.transform) { if( _child.GetComponent<CircleLayer>()!=null ) Destroy(_child.gameObject); } System.GC.Collect(); } [ContextMenu("Random Create Circle")] public void RandomCreateCircle() { if( transform.childCount>0 ) { DeleteAllCircle(); } for(int i=0; i<NumberOfLayer; i++) { CreateCircle(); } } private void CreateCircle() { int i=0; // mesh i = Random.Range(0,layerSetting.mesh.Count); Mesh _mesh = layerSetting.mesh[i]; // texture i = Random.Range(0,layerSetting.texture.Count); Texture2D _texture = layerSetting.texture[i]; // mask i = Random.Range(0,layerSetting.mask.Count); Texture2D _mask = layerSetting.mask[i]; // scale float _scale = UnityEngine.Random.Range(minScale,maxScale); // position Vector3 _pos = new Vector3(Random.Range(randomSpawnMin.x,randomSpawnMax.x), Random.Range(randomSpawnMin.y,randomSpawnMax.y), Random.Range(randomSpawnMin.z,randomSpawnMax.z)); // color override Color _color = Color.white; if( layerSetting.color.Count>0 ) { i = Random.Range(0,layerSetting.color.Count); _color = layerSetting.color[i]; } // angle float _angle = UnityEngine.Random.Range(angleMin,angleMax); // Whirl direction float _amount = UnityEngine.Random.Range (whirlSpeedMin, whirlSpeedMax); Vector3 _whirl = Vector3.zero; if (whirlAxis.Equals (Axis.X)) _whirl = new Vector3 (_amount, 0f, 0f); else if (whirlAxis.Equals (Axis.Y)) _whirl = new Vector3 (0f, _amount, 0f); else if (whirlAxis.Equals (Axis.Z)) _whirl = new Vector3 (0f, 0f, _amount); // Create layer GameObject _layer = AddLayer(_mesh,_texture,_mask,_color,_angle,_pos,_scale,_whirl); } private GameObject AddLayer(Mesh _mesh, Texture2D _texture, Texture2D _mask, Color _color, float _angle, Vector3 _pos, float _scale, Vector3 _whirl) { GameObject _obj = new GameObject(string.Format("CircleLayer{0:000}",this.transform.childCount) ); CircleLayer _layer = _obj.AddComponent<CircleLayer>(); _layer.CreateCircleLayerMaterial(_mesh,_texture,_mask,_color,_angle,_whirl); _layer.UpdateSetting(); _layer.transform.parent=this.transform; _layer.transform.localPosition=_pos; _layer.transform.localRotation=Quaternion.identity; _layer.transform.localScale = Vector3.one * _scale; _layer.gameObject.layer = renderSetting.layerId; Renderer _render = _layer.GetComponent<Renderer>(); _render.sortingLayerID = renderSetting.sortingLayerId; _render.sortingOrder = renderSetting.sortingOrder; _render.tag = renderSetting.layerTag; return _obj; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebTest.Code { /// <summary> /// 交易流水管理 /// </summary> public class TransactionManage : CRL.Account.TransactionBusiness<TransactionManage> { public static TransactionManage Instance { get { return new TransactionManage(); } } protected override CRL.DBExtend dbHelper { get { return GetDbHelper(this.GetType()); } } } }
using Tomelt.Environment.Extensions; namespace Tomelt.ContentPicker.Settings { [TomeltFeature("Tomelt.ContentPicker.LocalizationExtensions")] public class ContentPickerFieldLocalizationSettings { public ContentPickerFieldLocalizationSettings() { TryToLocalizeItems = true; } public bool TryToLocalizeItems { get; set; } public bool RemoveItemsWithoutLocalization { get; set; } public bool RemoveItemsWithNoLocalizationPart { get; set; } public bool AssertItemsHaveSameCulture { get; set; } public bool BlockForItemsWithNoLocalizationPart { get; set; } } }
using Microsoft.SharePoint; using BELCORP.GestorDocumental.BE.DDP; using BELCORP.GestorDocumental.Common; using BELCORP.GestorDocumental.DA.Comun; using BELCORP.GestorDocumental.DA.Sharepoint; using BELCORP.GestorDocumental.DA.DDP; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Microsoft.SharePoint.Administration; using Microsoft.Office.Server.UserProfiles; using System.Data; namespace BELCORP.GestorDocumental.BL.DDP.Reportes { public class ReportesBL { #region Singleton private static volatile ReportesBL _instance = null; private static object lockAccessObject = new Object(); public static ReportesBL Instance { get { if (_instance == null) { lock (lockAccessObject) { _instance = new ReportesBL(); } } return _instance; } } /// <summary> /// Contructor por defecto /// </summary> private ReportesBL() { } #endregion //public List<ReportesBE> BuscarReporteDocumentario( // int pagina, // int totalPaginasFila, // out double totalPagina, // string CodigoTipo, // string EstadoPasoFlujo, // string CodigoMacroproceso, // DateTime? FechaPublicacionDesde, // DateTime? FechaAprobacionHasta, // DateTime? FechaUltimaAprobacionDesde, // DateTime? FechaUltimaAprobacionHasta) //{ // return ReportesDA.Instance.BuscarReporteDocumentario( // pagina, // totalPaginasFila, // out totalPagina, // CodigoTipo, // EstadoPasoFlujo, // CodigoMacroproceso, // FechaPublicacionDesde, // FechaAprobacionHasta, // FechaUltimaAprobacionDesde, // FechaUltimaAprobacionHasta // ); //} public static DataTable FillDropDownWithFieldChoices_Reporte(string listName, string fieldName, string textoSeleccione) { return SharePointHelper.FillDropDownWithFieldChoices_Reporte(listName, fieldName, textoSeleccione); } #region Lista Maestra public List<ReportesBE> BuscarReporteDocumentario( int NumeroPagina, int FilasXPagina, ReportesBE oReporte, ref int TotalFilas) { return ReportesDA.Instance.BuscarReporteDocumentario(NumeroPagina, FilasXPagina, oReporte, ref TotalFilas); } public List<ReportesBE> BuscarReporteDocumentario_Todo(ReportesBE oReporte) { return ReportesDA.Instance.BuscarReporteDocumentario_Todo(oReporte); } public DataTable BuscarReporteDocumentarioTable_Todo(ReportesBE oReporte) { return ReportesDA.Instance.BuscarReporteDocumentarioTable_Todo(oReporte); } public List<ReportesBE> BuscarReporteDocumentario_Filtrado(ReportesBE oReporte) { return ReportesDA.Instance.BuscarReporteDocumentario_Filtrado(oReporte); } #endregion #region Documentos Eliminados public List<Reporte_DocEliminadosBE> BuscarReporteDocumentosEliminados( int NumeroPagina, int FilasXPagina, Reporte_DocEliminadosBE oReporte, ref int TotalFilas ) { return ReportesDA.Instance.BuscarReporteDocumentosEliminados(NumeroPagina, FilasXPagina, oReporte, ref TotalFilas); } public List<Reporte_DocEliminadosBE> BuscarReporteDocumentosEliminados_Export(Reporte_DocEliminadosBE oReporte) { return ReportesDA.Instance.BuscarReporteDocumentosEliminados_Export(oReporte); } #endregion #region Documentos Por Centro de Costo public List<Reporte_DocumentosXCCBE> BuscarReporteDocumentosXCC_Paginado( int NumeroPagina, int FilasXPagina, Reporte_DocumentosXCCBE oReporte, ref int TotalFilas) { return ReportesDA.Instance.BuscarReporte_DocumentosXCC_Paginado(NumeroPagina, FilasXPagina, oReporte, ref TotalFilas); } public List<Reporte_DocumentosXCCBE> BuscarReporteDocumentosXCC_Todo(Reporte_DocumentosXCCBE oReporte) { return ReportesDA.Instance.BuscarReporte_DocumentosXCC_Todo(oReporte); } public List<Reporte_DocumentosXCCBE> BuscarReporteDocumentosXCC_Filtrado(Reporte_DocumentosXCCBE oReporte) { return ReportesDA.Instance.BuscarReporte_DocumentosXCC_Filtrado(oReporte); } #endregion } }
using System; namespace Fingo.Auth.AuthServer.Client.Exceptions { public class AccountExpiredException : Exception { public new const string Message = "Your account has expired."; } }
namespace DFC.ServiceTaxonomy.GraphVisualiser.Models.Owl { public partial class Gravity { public long ClassDistance { get; set; } public long DatatypeDistance { get; set; } } }
using System; namespace ServerlessTemperatura { public static class ConversorTemperatura { public static double FahrenheitParaCelsius(double temperatura) { return (temperatura - 32) / 1.8; // Simulação proposital de falha //return Math.Round((temperatura - 32) / 1.8, 2); } } }
namespace Assistenza.BufDalsi.Web.Models.CogeneratoreViewModels { public class UpdateCogeneratoreViewModel { public int ipt_Id { get; set; } public int clt_id { get; set; } public int cgn_Id { get; set; } public int cgn_Potenza { get; set; } public string cgn_Marca { get; set; } public string cgn_Modello { get; set; } public string cgn_Serie { get; set; } public int cgn_Impianto { get; set; } public UpdateCogeneratoreViewModel() { } public UpdateCogeneratoreViewModel(int Id, int Potenza, string Marca, string Modello, string Serie, int Impianto) { cgn_Id = Id; cgn_Potenza = Potenza; cgn_Marca = Marca; cgn_Modello = Modello; cgn_Serie = Serie; cgn_Impianto = Impianto; } } }
using System; using System.Collections.Generic; using System.Globalization; using Newtonsoft.Json.Linq; namespace DFC.ServiceTaxonomy.GraphSync.Helpers { public static class DocumentHelper { public static (string? ContentType, Guid Id) GetContentTypeAndId(string uri) { if (string.IsNullOrEmpty(uri)) { return (string.Empty, Guid.Empty); } string pathOnly = uri.StartsWith("http") ? new Uri(uri, UriKind.Absolute).AbsolutePath : uri; pathOnly = pathOnly.ToLower().Replace("/api/execute", string.Empty); string[] uriParts = pathOnly.Trim('/').Split('/'); if (uriParts.Length == 1) { return (null, Guid.Parse(uriParts[0])); } string contentType = uriParts[0].ToLower(); var id = Guid.Parse(uriParts[1]); return (contentType, id); } public static string GetAsString(object item) { if (item is Guid guidItem) { return guidItem.ToString(); } if (item is JValue jValueItem) { return jValueItem.ToString(CultureInfo.InvariantCulture); } return (string)item; } public static List<Dictionary<string, object>> GetIncomingLinks(Dictionary<string, object> item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } var linksSection = SafeCastToDictionary(item["_links"]); var curiesSection = SafeCastToList(linksSection["curies"]); int incomingPosition = curiesSection.FindIndex(curie => (string)curie["name"] == "incoming"); var incomingObject = curiesSection.Count > incomingPosition ? curiesSection[incomingPosition] : null; if (incomingObject == null) { throw new MissingFieldException("Incoming property missing"); } return SafeCastToList(incomingObject["items"]); } public static string FirstCharToUpper(string input) => input switch { null => throw new ArgumentNullException(nameof(input)), "" => throw new ArgumentException($"{nameof(input)} cannot be empty", nameof(input)), _ => string.Concat(input[0].ToString().ToUpper(), input.AsSpan(1)) }; public static Dictionary<string, object> SafeCastToDictionary(object? value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value is JObject valObj) { return valObj.ToObject<Dictionary<string, object>>()!; } if (!(value is Dictionary<string, object> dictionary)) { throw new ArgumentException($"Didn't expect type {value.GetType().Name}"); } return dictionary; } public static bool CanCastToList(object? value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } return value is JArray || value is List<Dictionary<string, object>>; } public static List<Dictionary<string, object>> SafeCastToList(object? value) { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (value is JArray valAry) { return valAry.ToObject<List<Dictionary<string, object>>>()!; } return (List<Dictionary<string, object>>)value; } } }
using System.Collections.ObjectModel; using System.Globalization; using System.Windows; using CODE.Framework.Wpf.Mvvm; namespace CODE.Framework.Wpf.TestBench { /// <summary> /// Interaction logic for SyncCollectionTest.xaml /// </summary> public partial class SyncCollectionTest : Window { private readonly SyncTestViewModel _vm = new SyncTestViewModel(); public SyncCollectionTest() { InitializeComponent(); DataContext = _vm; } private void AddItem(object sender, RoutedEventArgs e) { _vm.Customers.Add(new SyncCustomerViewModel()); } private void RemoveItem(object sender, RoutedEventArgs e) { if (_vm.Customers.Count > 0) _vm.Customers.RemoveAt(_vm.Customers.Count - 1); } private void ResetCollection(object sender, RoutedEventArgs e) { _vm.Customers.Clear(); } private void Sync1(object sender, RoutedEventArgs e) { _vm.Customers.Sync(_vm.Target1); } private void Unsync1(object sender, RoutedEventArgs e) { _vm.Customers.RemoveSync(_vm.Target1); } private void Sync2(object sender, RoutedEventArgs e) { _vm.Customers.Sync(_vm.Target2); } private void Unsync2(object sender, RoutedEventArgs e) { _vm.Customers.RemoveSync(_vm.Target2); } } public class SyncTestViewModel { public SyncTestViewModel() { Customers = new ObservableCollection<SyncCustomerViewModel>(); Target1 = new ObservableCollection<SyncCustomerViewModel>(); Target2 = new ObservableCollection<SyncCustomerViewModel>(); } public ObservableCollection<SyncCustomerViewModel> Customers { get; set; } public ObservableCollection<SyncCustomerViewModel> Target1 { get; set; } public ObservableCollection<SyncCustomerViewModel> Target2 { get; set; } } public class SyncCustomerViewModel { public SyncCustomerViewModel() { Display = System.Environment.TickCount.ToString(CultureInfo.InvariantCulture); } public string Display { get; set; } } }
namespace Uintra.Features.Reminder.Services { public interface IReminderRunner { void Run(); } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.ComponentModel; namespace ClipModels { public class OnlineMediaDataTraf { [Key, ForeignKey("TrafficClip")] public int ID { get; set; } [DisplayName("Source Clip Title")] public string SourceClipTitle { get; set; } [DisplayName("Source TC IN")] public string TCIN { get; set; } [DisplayName("Source TC OUT")] public string TCOUT { get; set; } [DisplayName("Source Duration")] public string Duration { get; set; } public string SourceDescription { get; set; } public string SourceURL { get; set; } public string SourceID { get; set; } public int OnlineMediaType { get; set; } public DateTime DownLoadDate { get; set; } [NotMapped] public int TCINSeconds { get { return stringToSecondsRounded(TCIN); } set { } } [NotMapped] public int TCOUTSeconds { get { return stringToSecondsRounded(TCOUT); } set { } } [NotMapped] public string CallbackUrl { get; set; } public virtual TrafficClip TrafficClip { get; set; } public int TrafficClipId { get; set; } public OnlineMediaDataTraf() { SourceClipTitle = ""; TCIN = "00:00:00:00"; TCOUT = "00:00:00:00"; Duration = "00:00:00:00"; SourceURL = ""; SourceDescription = ""; SourceURL = ""; SourceID = ""; OnlineMediaType = 0; CallbackUrl = ""; DownLoadDate = Clip.DEFAULT_DATE; } /// <summary> /// /// </summary> public OnlineMediaDataTraf(string url, string sourceClipTitle, int onlineMediaType) { SourceClipTitle = sourceClipTitle; TCIN = "00:00:00:00"; TCOUT = "00:00:00:00"; Duration = "00:00:00:00"; SourceURL = url; SourceDescription = ""; SourceURL = ""; SourceID = ""; OnlineMediaType = onlineMediaType; DownLoadDate = Clip.DEFAULT_DATE; CallbackUrl = ""; } /// <summary> /// Copy constructor /// </summary> /// <param name="other"></param> public OnlineMediaDataTraf(OnlineMediaDataTraf other) { if (other != null) { SourceClipTitle = other.SourceClipTitle; TCIN = other.TCIN; TCOUT = other.TCOUT; Duration = other.Duration; SourceURL = other.SourceURL; SourceDescription = other.SourceDescription; SourceURL = other.SourceURL; SourceID = other.SourceID; OnlineMediaType = other.OnlineMediaType; DownLoadDate = other.DownLoadDate; CallbackUrl = other.CallbackUrl; } } /// <summary> /// Copy constructor for Supplier Clip data /// </summary> /// <param name="other"></param> public OnlineMediaDataTraf(OnlineMediaDataSup other) { if (other != null) { SourceClipTitle = other.SourceClipTitle; TCIN = other.TCIN; TCOUT = other.TCOUT; Duration = other.Duration; SourceURL = other.SourceURL; SourceDescription = other.SourceDescription; SourceURL = other.SourceURL; SourceID = other.SourceID; OnlineMediaType = other.OnlineMediaType; DownLoadDate = other.DownLoadDate; CallbackUrl = other.CallbackUrl; } } /// <summary> /// Copy method (from OnlineMediaDataSup object) /// </summary> /// <param name="other"></param> public void CopyFromOther(OnlineMediaDataSup other) { if (other != null) { SourceClipTitle = other.SourceClipTitle; TCIN = other.TCIN; TCOUT = other.TCOUT; Duration = other.Duration; SourceURL = other.SourceURL; SourceDescription = other.SourceDescription; SourceURL = other.SourceURL; SourceID = other.SourceID; OnlineMediaType = other.OnlineMediaType; DownLoadDate = other.DownLoadDate; CallbackUrl = other.CallbackUrl; } } /// <summary> /// Copy method (from OnlineMediaDataTraf object) /// </summary> /// <param name="other"></param> public void CopyFromOther(OnlineMediaDataTraf other) { if (other != null) { SourceClipTitle = other.SourceClipTitle; TCIN = other.TCIN; TCOUT = other.TCOUT; Duration = other.Duration; SourceURL = other.SourceURL; SourceDescription = other.SourceDescription; SourceURL = other.SourceURL; SourceID = other.SourceID; OnlineMediaType = other.OnlineMediaType; DownLoadDate = other.DownLoadDate; CallbackUrl = other.CallbackUrl; } } /// <summary> /// /// </summary> /// <param name="other"></param> public void CopyMetadataFromOther(OnlineMediaDataSup other) { if (other != null) { SourceClipTitle = other.SourceClipTitle; Duration = other.Duration; SourceURL = other.SourceURL; SourceDescription = other.SourceDescription; SourceURL = other.SourceURL; SourceID = other.SourceID; OnlineMediaType = other.OnlineMediaType; DownLoadDate = other.DownLoadDate; CallbackUrl = other.CallbackUrl; } } /// <summary> /// /// </summary> /// <param name="other"></param> public void CopyMetadataFromOther(OnlineMediaDataTraf other) { if (other != null) { SourceClipTitle = other.SourceClipTitle; Duration = other.Duration; SourceURL = other.SourceURL; SourceDescription = other.SourceDescription; SourceURL = other.SourceURL; SourceID = other.SourceID; OnlineMediaType = other.OnlineMediaType; DownLoadDate = other.DownLoadDate; CallbackUrl = other.CallbackUrl; } } /// <summary> /// Check if duration field format is valid /// </summary> /// <param name="p"></param> /// <returns></returns> private bool durationIsValid(string duration) { string[] tempStr = duration.Split(':'); int n; //Check if format HH:MM:SS:FF if (tempStr.Length != 3) return false; //Check if each segment is number and its in range for (int i = 0; i < tempStr.Length; i++) { if (!(int.TryParse(tempStr[i], out n))) return false; else { switch (i) { case 1: if (!(n >= 0 && n <= 59)) return false; break; case 2: if (!(n >= 0 && n <= 59)) return false; break; } } } //If passed all above - return TRUE return true; } //converts HH:MM:SSstring format to (int) number of actual seconds. private int stringToSecondsRounded(string duration) { if (duration != null && durationIsValid(duration)) { int hours; int minutes; int seconds; int.TryParse(duration.Substring(0, 2), out hours); int.TryParse(duration.Substring(3, 2), out minutes); int.TryParse(duration.Substring(6, 2), out seconds); return 3600 * hours + 60 * minutes + seconds; } else return 0; } } }
using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel.DataAnnotations; namespace NHibernate.DataAnnotations.Core { internal class SessionValidator : ISessionValidator { private readonly ValidationInterceptor _validationInterceptor; internal SessionValidator(ValidationInterceptor validationInterceptor) { _validationInterceptor = validationInterceptor; } public void Eval(ITransaction transaction, bool throwException = true) { if (IsValid()) { transaction.Commit(); return; } transaction.Rollback(); if (throwException) ThrowValidationException(); } public bool IsValid() { return _validationInterceptor.GetValidationResults().Count == 0; } public string GetValidationErrorString() { return _validationInterceptor.ValidationErrorString; } public void ThrowValidationException() { throw new ValidationException(GetValidationErrorString()); } public IDictionary<object, ReadOnlyCollection<ValidationResult>> GetValidationResults() { return _validationInterceptor.GetValidationResults(); } public ReadOnlyCollection<ValidationResult> GetValidationResults(object o) { return _validationInterceptor.GetValidationResults(o); } } }
using System; namespace CourseHunter_76_Generation_IS_A_inInheritance { class Program { static void Main(string[] args) { IShape rect = new Rect { Height = 6, Width = 12 }; IShape square = new Square { SizeC = 6 }; Console.WriteLine(rect.CalcSquare()); Console.WriteLine(square.CalcSquare()); //Rect rect = new Rect { Height = 6, Width = 12 }; //option inisiolazer //int rectArea = AreaCalculator.CalcSquare(rect); //Console.WriteLine($"Rect area = {rectArea}"); //Rect squre = new Square { Height = 6, Width = 12 }; //Representative по сути это не квадрат а экземпляр прямоугольника тип квадрат. //int squareArea = AreaCalculator.CalcSquare(squre); //Console.WriteLine($"Rect area = {squareArea}"); Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Euler_Logic.Problems { public class Problem233 : ProblemBase { public override string ProblemName { get { return "233: Lattice points on a circle"; } } public override string GetAnswer() { //Solve3(); return Solve2(12).ToString(); return Solve1(5).ToString(); return ""; } private void Solve3() { ulong n = 2; do { if (Solve2(n) == 420) { bool stop = true; } n += 2; } while (true); } private ulong Solve2(ulong n) { //ulong Ax = 0; //ulong Ay = 0; //ulong Bx = 0; //ulong By = n; //ulong Cx = n; //ulong Cy = 0; //var d = 2 * (Ax * (By - Cy) + Bx * (Cy - Ay) + Cx * (Ay - By)); //var Rx = ((Ax * Ax + Ay * Ay) * (By - Cy) + (Bx * Bx + By * By) * (Cy - Ay) + (Cx * Cx + Cy * Cy) * (Ay - By)) / d; //var Ry = ((Ax * Ax + Ay * Ay) * (Cx - Bx) + (Bx * Bx + By * By) * (Ax - Cx) + (Cx * Cx + Cy * Cy) * (Bx - Ax)) / d; //var rSquared = (Ax - Rx) * (Ax - Rx) + (Ay - Ry) * (Ay - Ry); var rSquared = n * (n / 2); return Solve1(rSquared); } private List<string> _nums = new List<string>(); private ulong Solve1(ulong n) { ulong count = 0; ulong max = (ulong)Math.Sqrt(n); for (ulong x = 1; x <= max; x++) { var ySquared = n - x * x; var root = (ulong)Math.Sqrt(ySquared); if (root * root == ySquared) { _nums.Add(x + "\t" + root); count++; } } return count * 4; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Raven.Client; using Integer.Domain.Agenda; namespace Integer.Web.Infra.Raven { public static class EventoDocumentSessionExtensions { public static IEnumerable<Evento> ObterEventosAgendados(this IDocumentSession session, DateTime inicio, DateTime fim) { var eventos = new List<Evento>(); using (session.Advanced.DocumentStore.AggressivelyCacheFor(TimeSpan.FromMinutes(2))) { eventos = session.Query<Evento>().Where(e => e.Estado == EstadoEventoEnum.Agendado && ((inicio <= e.DataInicio && e.DataInicio <= fim) || (inicio <= e.DataFim && e.DataFim <= fim))).ToList(); } return eventos; } public static IEnumerable<Evento> ObterEventos(this IDocumentSession session, DateTime inicio, DateTime fim) { var eventos = new List<Evento>(); eventos = session.Query<Evento>().Where(e => e.Estado != EstadoEventoEnum.Cancelado && ((inicio <= e.DataInicio && e.DataInicio <= fim) || (inicio <= e.DataFim && e.DataFim <= fim))).ToList(); return eventos; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; namespace GoogleJamRealContest2 { class Program { static void Main(string[] args) { StreamReader sr = new StreamReader("B-small-attempt1.in"); StreamWriter sw = new StreamWriter(File.Create("output.in")); sw.AutoFlush = true; string str = sr.ReadToEnd(); string[] split = str.Split('\n'); int cases = 1; for(int i = 1; i <= Convert.ToInt16(split[0]) * 2; i = i+2) { List<int[]> listTest = new List<int[]>(); List<int[]> tmpList = new List<int[]>(); string[] split2 = split[i + 1].Split(' '); int[] nbrs = new int[split2.Length]; for(int k = 0; k < split2.Length; k++) { nbrs[k] = Convert.ToInt16(split2[k]); } listTest.Add(nbrs); bool ok = false; int minute = 0; while (!ok) { tmpList = new List<int[]>(listTest); for (int l = 0; l < listTest.Count; l++ ) { int[] tmp = new int[listTest[l].Length]; Array.Copy(listTest[l], 0, tmp, 0, listTest[l].Length); if(isOK(tmp)) { ok = true; break; } eat(ref tmpList, tmp); for(int b = 0; b < tmp.Length; b++) { special(ref tmpList, tmp, b); } tmpList.RemoveAt(l); } minute++; listTest = new List<int[]>(tmpList); } sw.WriteLine("Case #" + cases + ": " + (minute - 1)); cases++; } sw.Close(); } public static bool isOK(int[] tmp) { foreach(int i in tmp) { if (i != 0) return false; } return true; } public static void eat(ref List<int[]> listTest, int[] cur) { int[] tmp = new int[cur.Length]; Array.Copy(cur, 0, tmp, 0, cur.Length); for(int i = 0; i < cur.Length; i++) { if (tmp[i] > 0) tmp[i]--; } listTest.Add(tmp); } public static void special(ref List<int[]> listTest, int[] cur, int pos) { for (int k = 1; k <= cur[pos]; k++) { for (int i = 0; i < cur.Length; i++) { int[] tmp = new int[cur.Length]; Array.Copy(cur, 0, tmp, 0, cur.Length); if (i != pos) { tmp[pos] -= k; tmp[i] += k; listTest.Add(tmp); tmp[pos] += k; tmp[i] -= k; } } int[] tmp2 = new int[cur.Length]; Array.Copy(cur, 0, tmp2, 0, cur.Length); Array.Resize(ref tmp2, tmp2.Length + 1); tmp2[pos] -= k; tmp2[tmp2.Length - 1] += k; listTest.Add(tmp2); } } } }
namespace ForumSystem.Services.Data { using System.Threading.Tasks; using ForumSystem.Web.ViewModels.Comments; public interface ICommentsService { public Task<PostCommentViewModel> AddAsync(int postId, string userId, string content, int? parentId); public Task<EditCommentViewModel> EditCommetAsync(int commentId, string content); public Task<bool> IsInPostIdAsync(int commentId, int postId); public bool IsSignInUserTheOwenerOfComment(int commentId, string userId); string GetCommentContent(int commentId); Task<string> DeleteCommentAsync(int commentId); } }
using System; using CodeCityCrew.Settings.Abstractions; using Microsoft.AspNetCore.Builder; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; namespace CodeCityCrew.Settings { public static class ServiceCollectionExtension { /// <summary> /// Adds the settings. /// </summary> /// <param name="services">The service collection.</param> /// <param name="connectionStringName">Name of the connection string.</param> public static void AddSettings(this IServiceCollection services, string connectionStringName = "DefaultConnection") { var configuration = services.BuildServiceProvider().GetRequiredService<IConfiguration>(); services.AddDbContext<SettingDbContext>( options => { options.UseSqlServer(configuration.GetConnectionString(connectionStringName)); }, ServiceLifetime.Singleton); services.AddSingleton<ISettingService, SettingService>(); } /// <summary> /// Adds the settings. /// </summary> /// <param name="services">The services.</param> /// <param name="optionsAction">The database context options builder.</param> public static void AddSettings(this IServiceCollection services, Action<DbContextOptionsBuilder> optionsAction) { services.AddDbContext<SettingDbContext>(optionsAction, ServiceLifetime.Singleton); services.AddSingleton<ISettingService, SettingService>(); } /// <summary> /// Settings the specified services. Use this method only in your Startup Configure service. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="services">The services.</param> /// <returns></returns> public static T Setting<T>(this IServiceCollection services) where T : new() { return services.BuildServiceProvider().GetRequiredService<ISettingService>().As<T>(); } /// <summary> /// Settings the specified application. Use this method only in your Startup Configure. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="app">The application.</param> /// <returns></returns> public static T Setting<T>(this IApplicationBuilder app) where T : new() { return app.ApplicationServices.GetRequiredService<ISettingService>().As<T>(); } } }
namespace SubC.Attachments.ClingyEditor { using UnityEngine; using UnityEditor; public class FlexibleTransitionerEditor : TransitionerEditor { static void DoTweenOptions(SerializedProperty optionsProp) { SerializedProperty tweenMethodProp = optionsProp.FindPropertyRelative("tweenMethod"); EditorGUILayout.PropertyField(tweenMethodProp); if (((TweenMethod) tweenMethodProp.intValue) == TweenMethod.Speed) { EditorGUI.indentLevel ++; EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("speed")); EditorGUI.indentLevel --; } else if (((TweenMethod) tweenMethodProp.intValue) == TweenMethod.Time) { EditorGUI.indentLevel ++; EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("duration")); EditorGUI.indentLevel --; } if (((TweenMethod) tweenMethodProp.intValue) != TweenMethod.None) { EditorGUI.indentLevel ++; EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("easing")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("delay")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("completeOnCancel")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("dynamicTarget")); EditorGUI.indentLevel --; } } static void DoOnAttachOptions(SerializedProperty optionsProp) { EditorGUILayout.LabelField("On Attach Options", EditorStyles.boldLabel); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rigidbodyBehavior")); SerializedProperty prop = optionsProp.FindPropertyRelative("positionOptions.behavior"); EditorGUILayout.PropertyField(prop, new GUIContent("Position behavior")); if (((PositionBehavior) prop.intValue) == PositionBehavior.Snap) { EditorGUI.indentLevel ++; EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("positionOptions.anchor1Param")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("positionOptions.anchor2Param")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("positionOptions.moveMethod")); prop = optionsProp.FindPropertyRelative("positionOptions.tweenOptions"); DoTweenOptions(prop); EditorGUI.indentLevel --; } prop = optionsProp.FindPropertyRelative("rotationOptions.behavior"); EditorGUILayout.PropertyField(prop, new GUIContent("Rotation behavior")); if (((RotationBehavior) prop.intValue) != RotationBehavior.DoNothing) { EditorGUI.indentLevel ++; if (((RotationBehavior) prop.intValue) == RotationBehavior.Snap) { EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rotationOptions.rotationParam")); } else if (((RotationBehavior) prop.intValue) == RotationBehavior.LookAt) { EditorGUILayout.PropertyField( optionsProp.FindPropertyRelative("rotationOptions.lookAtPositionParam")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rotationOptions.upParam")); } else if (((RotationBehavior) prop.intValue) == RotationBehavior.LookAt2D) { EditorGUILayout.PropertyField( optionsProp.FindPropertyRelative("rotationOptions.lookAtPositionParam")); } else if (((RotationBehavior) prop.intValue) == RotationBehavior.LookDirection) { EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rotationOptions.forwardParam")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rotationOptions.upParam")); } EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rotationOptions.offsetParam")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rotationOptions.rotateMethod")); prop = optionsProp.FindPropertyRelative("rotationOptions.tweenOptions"); DoTweenOptions(prop); EditorGUI.indentLevel --; } EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("adoptSortingOrderOptions")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("adoptFlipXOptions")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("adoptFlipYOptions")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("adoptLayerOptions")); } static void DoOnDetachOptions(SerializedProperty optionsProp) { EditorGUILayout.LabelField("On Detach Options", EditorStyles.boldLabel); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rigidbodyBehavior")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("restorePosition")); if (optionsProp.FindPropertyRelative("restorePosition").boolValue) { EditorGUI.indentLevel ++; EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("moveMethod")); DoTweenOptions(optionsProp.FindPropertyRelative("tweenPositionOptions")); EditorGUI.indentLevel --; } EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("restoreRotation")); if (optionsProp.FindPropertyRelative("restoreRotation").boolValue) { EditorGUI.indentLevel ++; EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("rotateMethod")); DoTweenOptions(optionsProp.FindPropertyRelative("tweenRotationOptions")); EditorGUI.indentLevel --; } EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("restoreScale")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("restoreLayer")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("restoreSortingOrder")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("restoreFlipX")); EditorGUILayout.PropertyField(optionsProp.FindPropertyRelative("restoreFlipY")); } new public static void DoInspectorGUI(SerializedObject obj, AttachStrategy attachStrategy) { DoOnAttachOptions(obj.FindProperty("onAttachOptions")); EditorGUILayout.Space(); DoOnDetachOptions(obj.FindProperty("onDetachOptions")); } } }
using FluentValidation; using SocialWorld.Business.DTOs.AppUserDtos; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SocialWorld.Business.ValidationRules.FluentValidation { class AppUserLoginDtoValidator : AbstractValidator<AppUserLoginDto> { public AppUserLoginDtoValidator() { RuleFor(I => I.Email).NotEmpty().WithMessage("Email alanı boş geçilemez"); RuleFor(I => I.Email).EmailAddress().WithMessage("Email düzgün yazınız"); RuleFor(I => I.Password).NotEmpty().WithMessage("Şifre alanı boş geçilemez "); } } }
using System; using System.Threading.Tasks; using AutoMapper; using DataAccess.Roles; using Entities; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Identity; using ViewModel.Roles; namespace DataAccess.DbImplementation.Roles { public class UpdateRoleCommand : IUpdateRoleCommand { private readonly RoleManager<Role> _roleManager; private readonly IHttpContextAccessor _httpContextAccessor; private readonly IMapper _mapper; private readonly IHostingEnvironment _appEnvironment; public UpdateRoleCommand(RoleManager<Role> roleManager, IMapper mapper, IHttpContextAccessor httpContextAccessor, IHostingEnvironment appEnvironment) { _roleManager = roleManager; _mapper = mapper; _httpContextAccessor = httpContextAccessor; _appEnvironment = appEnvironment; } public async Task<RoleResponse> ExecuteAsync(Guid roleId,UpdateRoleRequest request) { var foundRole = await _roleManager.FindByIdAsync(roleId.ToString()); if (foundRole == null) return null; foundRole.Name = request.Name; foundRole.RoleDescription = request.RoleDescription; await _roleManager.UpdateAsync(foundRole); return _mapper.Map<Role, RoleResponse>(foundRole); } } }
using Euler_Logic.Helpers; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2019 { public class Problem18 : AdventOfCodeBase { private Dictionary<int, Dictionary<int, Node>> _grid; private List<Node> _connectedGrid; private Node[] _startNodes; private int _maxX; private int _maxY; private Dictionary<char, ulong> _charToBit; private ulong _allKeys; private Dictionary<Node, Dictionary<ulong, int>> _hash; private BinaryHeap_Min _heap; private List<Node> _keyPaths; private ulong _keysFound; private enum enumNodeType { Empty, Wall, Door, Key, Start } public override string ProblemName { get { return "Advent of Code 2019: 18"; } } public override string GetAnswer() { _heap = new BinaryHeap_Min(); _best = int.MaxValue; SetCharToBit(); GetGrid(Input()); return Answer2().ToString(); } private string Answer1() { FindBestRoute(_startNodes[0], 0); return _best.ToString(); } private string Answer2() { AddCenterDivision(); FindBestRoute(0); return _best.ToString(); } private void AddCenterDivision() { var start = _startNodes[0]; _grid[start.X][start.Y].NodeType = enumNodeType.Wall; _grid[start.X - 1][start.Y].NodeType = enumNodeType.Wall; _grid[start.X + 1][start.Y].NodeType = enumNodeType.Wall; _grid[start.X][start.Y - 1].NodeType = enumNodeType.Wall; _grid[start.X][start.Y + 1].NodeType = enumNodeType.Wall; _startNodes[0] = _grid[start.X - 1][start.Y - 1]; _startNodes[1] = _grid[start.X - 1][start.Y + 1]; _startNodes[2] = _grid[start.X + 1][start.Y - 1]; _startNodes[3] = _grid[start.X + 1][start.Y + 1]; _startNodes[0].NodeType = enumNodeType.Start; _startNodes[1].NodeType = enumNodeType.Start; _startNodes[2].NodeType = enumNodeType.Start; _startNodes[3].NodeType = enumNodeType.Start; } private int _best; private void FindBestRoute(Node currentNode, int currentDistance) { FindPaths(currentNode); var nextPaths = _keyPaths.Select(x => new SubNode() { N = x, D = x.Num, KeysFound = x.KeysFound }).ToList(); FindBestRouteRecursive(nextPaths, currentDistance, false); } private void FindBestRoute(int currentDistance) { var nextPaths = new List<SubNode>(); for (int index = 0; index < _startNodes.Length; index++) { var start = _startNodes[index]; FindPaths(start); nextPaths.AddRange(_keyPaths.Select(x => new SubNode() { N = x, D = x.Num, KeysFound = x.KeysFound, StartNodeIndex = index })); } FindBestRouteRecursive(nextPaths, currentDistance, true); } private void FindBestRouteRecursive(List<SubNode> nextPaths, int currentDistance, bool multiplePaths) { foreach (var path in nextPaths) { var keyDiff = _keysFound ^ path.KeysFound; keyDiff &= path.KeysFound; _keysFound += keyDiff; var nextDistance = currentDistance + path.D; if (_keysFound == _allKeys && nextDistance < _best) { _best = nextDistance; } if (_hash[path.N].ContainsKey(_keysFound)) { var bestSoFar = _hash[path.N][_keysFound]; if (bestSoFar > nextDistance) { _hash[path.N][_keysFound] = nextDistance; if (multiplePaths) { var startNode = _startNodes[path.StartNodeIndex]; _startNodes[path.StartNodeIndex] = path.N; FindBestRoute(nextDistance); _startNodes[path.StartNodeIndex] = startNode; } else { FindBestRoute(path.N, nextDistance); } } } else { _hash[path.N].Add(_keysFound, nextDistance); if (multiplePaths) { var startNode = _startNodes[path.StartNodeIndex]; _startNodes[path.StartNodeIndex] = path.N; FindBestRoute(nextDistance); _startNodes[path.StartNodeIndex] = startNode; } else { FindBestRoute(path.N, nextDistance); } } _keysFound -= keyDiff; } } private void FindPaths(Node start) { _connectedGrid.ForEach(x => { x.Num = int.MaxValue; x.Prior = null; x.KeysFound = 0; }); _heap.Reset(); start.Num = 0; _heap.Adjust(start.Index); int total = _connectedGrid.Count; _keyPaths = new List<Node>(); do { var current = (Node)_heap.Top; if (current.Num == int.MaxValue) { break; } var nextDistance = current.Num + 1; // Left if (current.X > 0) { var next = _grid[current.X - 1][current.Y]; HandleNode(current, next, nextDistance); } // Right if (current.X < _maxX) { var next = _grid[current.X + 1][current.Y]; HandleNode(current, next, nextDistance); } // Up if (current.Y > 0) { var next = _grid[current.X][current.Y - 1]; HandleNode(current, next, nextDistance); } // Down if (current.Y < _maxY) { var next = _grid[current.X][current.Y + 1]; HandleNode(current, next, nextDistance); } _heap.Remove(current.Index); total--; if (total == 0) { break; } } while (true); } private void HandleNode(Node current, Node next, int nextDistance) { bool canMoveTo = false; if (next.NodeType == enumNodeType.Empty || next.NodeType == enumNodeType.Start || next.NodeType == enumNodeType.Key) { canMoveTo = true; } else if (next.NodeType == enumNodeType.Door && (_keysFound & next.DoorOrKeyBit) == next.DoorOrKeyBit) { canMoveTo = true; } if (canMoveTo) { if (next.Num > nextDistance) { next.Num = nextDistance; _heap.Adjust(next.Index); next.Prior = current; if (next.NodeType == enumNodeType.Key && (_keysFound & next.DoorOrKeyBit) == 0) { next.KeysFound = next.DoorOrKeyBit + current.KeysFound; _keyPaths.Add(next); } } } } private void GetGrid(List<string> input) { _grid = new Dictionary<int, Dictionary<int, Node>>(); _hash = new Dictionary<Node, Dictionary<ulong, int>>(); _connectedGrid = new List<Node>(); _maxX = input[0].Length - 1; _maxY = input.Count - 1; _startNodes = new Node[4]; var allKeys = new HashSet<char>(); for (int y = 0; y < input.Count; y++) { for (int x = 0; x < input[y].Length; x++) { var node = new Node() { X = x, Y = y }; var digit = input[y][x]; if (digit == '#') { node.NodeType = enumNodeType.Wall; } else { _connectedGrid.Add(node); if (digit == '.') { node.NodeType = enumNodeType.Empty; } else if (digit == '@') { node.NodeType = enumNodeType.Start; _startNodes[0] = node; _hash.Add(node, new Dictionary<ulong, int>()); } else { int ascii = (int)digit; if (ascii <= 90) { node.NodeType = enumNodeType.Door; node.DoorOrKeyChar = digit; node.DoorOrKeyBit = _charToBit[node.DoorOrKeyChar]; } else { node.NodeType = enumNodeType.Key; node.DoorOrKeyChar = (char)(ascii - 32); node.DoorOrKeyBit = _charToBit[node.DoorOrKeyChar]; allKeys.Add(digit); _allKeys += node.DoorOrKeyBit; _hash.Add(node, new Dictionary<ulong, int>()); } } } if (!_grid.ContainsKey(x)) { _grid.Add(x, new Dictionary<int, Node>()); } _grid[x].Add(y, node); } } _heap = new BinaryHeap_Min(); _connectedGrid.ForEach(x => _heap.Add(x)); } private void SetCharToBit() { _charToBit = new Dictionary<char, ulong>(); ulong power = 1; for (int ascii = 65; ascii <= 90; ascii++) { _charToBit.Add((char)ascii, power); power *= 2; } } private List<string> Input_Test1() { return new List<string>() { "#########", "#b.A.@.a#", "#########" }; } private List<string> Input_Test2() { return new List<string>() { "########################", "#f.D.E.e.C.b.A.@.a.B.c.#", "######################.#", "#d.....................#", "########################" }; } private List<string> Input_Test3() { return new List<string>() { "########################", "#...............b.C.D.f#", "#.######################", "#.....@.a.B.c.d.A.e.F.g#", "########################" }; } private List<string> Input_Test4() { return new List<string>() { "#################", "#i.G..c...e..H.p#", "########.########", "#j.A..b...f..D.o#", "########@########", "#k.E..a...g..B.n#", "########.########", "#l.F..d...h..C.m#", "#################" }; } private List<string> Input_Test5() { return new List<string>() { "########################", "#@..............ac.GI.b#", "###d#e#f################", "###A#B#C################", "###g#h#i################", "########################" }; } private List<string> Input_Test6() { return new List<string>() { "#######", "#a.#Cd#", "##...##", "##.@.##", "##...##", "#cB#Ab#", "#######" }; } private List<string> Input_Test7() { return new List<string>() { "###############", "#d.ABC.#.....a#", "######...######", "######.@.######", "######...######", "#b.....#.....c#", "###############" }; } private List<string> Input_Test8() { return new List<string>() { "#############", "#DcBa.#.GhKl#", "#.###...#I###", "#e#d#.@.#j#k#", "###C#...###J#", "#fEbA.#.FgHi#", "#############" }; } private List<string> Input_Test9() { return new List<string>() { "#############", "#g#f.D#..h#l#", "#F###e#E###.#", "#dCba...BcIJ#", "#####.@.#####", "#nK.L...G...#", "#M###N#H###.#", "#o#m..#i#jk.#", "#############" }; } private class Node : BinaryHeap_Min.Node { public enumNodeType NodeType { get; set; } public int X { get; set; } public int Y { get; set; } public char DoorOrKeyChar { get; set; } public ulong DoorOrKeyBit { get; set; } public Node Prior { get; set; } public ulong KeysFound { get; set; } } private class SubNode { public Node N { get; set; } public int D { get; set; } public ulong KeysFound { get; set; } public int StartNodeIndex { get; set; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine.UI; using UnityEngine; public class SaveLoad : MonoBehaviour { // Use this for initialization void Start () { if (PlayerPrefs.GetString("PartsSelected").Contains(this.gameObject.name + ";")) { if(this.gameObject.GetComponent<Button>() != null) { this.gameObject.GetComponent<Image>().color = Color.yellow; } else { this.gameObject.tag = "Selected"; } } } }
using TamilFruits.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; using Windows.Storage; namespace TamilFruits { public sealed partial class FruitPage : Page { private NavigationHelper navigationHelper; private ObservableDictionary defaultViewModel = new ObservableDictionary(); public ObservableDictionary DefaultViewModel { get { return this.defaultViewModel; } } public NavigationHelper NavigationHelper { get { return this.navigationHelper; } } public FruitPage() { this.InitializeComponent(); this.navigationHelper = new NavigationHelper(this); this.navigationHelper.LoadState += navigationHelper_LoadState; this.navigationHelper.SaveState += navigationHelper_SaveState; } private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e) { FruitBrowser.Source = new Uri((string)e.NavigationParameter); // Get the local folder. StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; if (local != null) { // Create a new folder name MyFolder. var dataFolder = await local.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists); try { // Get the file stream var fileStream = await dataFolder.OpenStreamForReadAsync("memo.txt"); // Read the data. using (StreamReader streamReader = new StreamReader(fileStream)) { string s = streamReader.ReadToEnd(); this.tbMango.Text = s; } } catch (Exception exception) { exception.ToString(); } } } private void navigationHelper_SaveState(object sender, SaveStateEventArgs e) { } #region NavigationHelper の登録 protected override void OnNavigatedTo(NavigationEventArgs e) { navigationHelper.OnNavigatedTo(e); } protected override void OnNavigatedFrom(NavigationEventArgs e) { navigationHelper.OnNavigatedFrom(e); } #endregion private async void Button_Click(object sender, RoutedEventArgs e) { byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(this.tbMango.Text.ToCharArray()); StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; var dataFolder = await local.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists); var file = await dataFolder.CreateFileAsync("memo.txt", CreationCollisionOption.ReplaceExisting); using (var s = await file.OpenStreamForWriteAsync()) { s.Write(fileBytes, 0, fileBytes.Length); } } } }
using System.Collections; using UnityEngine; using UnityEngine.Networking; public class AudioManager : MonoBehaviour { private Player _player; private string[] paths; private AudioClip clip; private AudioClip musicTrack; private AudioSource source; private GameObject musicObject; private AudioSource music; private string path; void Start() { path = Application.persistentDataPath + @"/Audio"; _player = GameObject.Find("Player").GetComponent<Player>(); _player.OnStateChange += PlayAudio; source = gameObject.AddComponent<AudioSource>(); paths = new string[10]{ path + @"/idle.wav", path + @"/move.wav", path + @"/jump.wav", path + @"/fall.wav", path + @"/shoot.wav", path + @"/duck.wav", path + @"/hurt.wav", path + @"/defeat.wav", path + @"/second.wav", path + @"/music.wav" }; //Init(); } private void PlayAudio(PlayerState state) { switch (state) { case PlayerState.idle: PlaySound(0); break; case PlayerState.moving: PlaySound(1); break; case PlayerState.jumping: PlaySound(2); break; case PlayerState.falling: PlaySound(3); break; case PlayerState.Shoot: PlaySound(4); break; case PlayerState.Duck: PlaySound(5); break; case PlayerState.Hurt: PlaySound(6); break; case PlayerState.Defeat: PlaySound(7); break; case PlayerState.SecondaryAttack: PlaySound(8); break; } } private void PlaySound(int index) { //StartCoroutine(GetAudioClip(paths[index])); source.clip = ES3.LoadAudio(paths[index], AudioType.WAV); source.Play(); } IEnumerator GetAudioClip(string location) { using (UnityWebRequest www = UnityWebRequestMultimedia.GetAudioClip(location, AudioType.WAV)) { yield return www.SendWebRequest(); if (www.isNetworkError) { Debug.Log(www.error); } else { print("location = " + location); clip = DownloadHandlerAudioClip.GetContent(www); } } } private void Init() { musicObject = GameObject.Find("Music"); music = musicObject.AddComponent<AudioSource>(); music.loop = true; //StartCoroutine(GetAudioClip(paths[9])); music.clip = ES3.LoadAudio(paths[9], AudioType.WAV); ; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BatchSystemMNGNT_Asimco.Entities { public class TTableMDM058 { public long PartitioningKey { get; set; } public int TreeID { get; set; } public int LeafID { get; set; } public int NameID { get; set; } public string NodeName { get; set; } public int Father { get; set; } public double UDFOrdinal { get; set; } public int NodeDepth { get; set; } public int LeafStatus { get; set; } public int CSTRoot { get; set; } public int IconID { get; set; } public int EntityID { get; set; } public string Code { get; set; } public string AlternateCode { get; set; } public DateTime CreatedTime { get; set; } } }
using ODL.ApplicationServices.DTOModel.Load; namespace ODL.ApplicationServices.DTOModel { public class OrganisationInputDTO : InputDTO { public string OrgId { get; set; } public string Namn { get; set; } } }