text
stringlengths
13
6.01M
using Microsoft.EntityFrameworkCore.Migrations; namespace WebsiteManagerPanel.Migrations { public partial class AddDescForAllTable1 : Migration { protected override void Up(MigrationBuilder migrationBuilder) { } protected override void Down(MigrationBuilder migrationBuilder) { } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace new_orleans { public partial class Form27 : Form { public Form27() { InitializeComponent(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { } private void radioButton7_CheckedChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { Form mod = new Form28(); mod.Owner = this; mod.Show(); this.Hide(); } private void radioButton2_CheckedChanged(object sender, EventArgs e) { } private void radioButton10_CheckedChanged(object sender, EventArgs e) { } private void radioButton13_CheckedChanged(object sender, EventArgs e) { } private void radioButton20_CheckedChanged(object sender, EventArgs e) { } private void label5_Click(object sender, EventArgs e) { } private void button3_Click(object sender, EventArgs e) { } private void button1_Click_1(object sender, EventArgs e) { int suma = 1; if (this.radioButton2.Checked == true) suma++; if (this.radioButton7.Checked == true) suma++; if (this.radioButton10.Checked == true) suma++; if (this.radioButton13.Checked == true) suma++; if (this.radioButton4.Checked == true) suma++; if (this.radioButton21.Checked == true) suma++; if (this.radioButton25.Checked == true) suma++; if (this.radioButton31.Checked == true) suma++; if (this.radioButton36.Checked == true) suma++; if (suma <= 5) MessageBox.Show(suma.ToString() + " Mai incearca"); else if (suma >= 6 && suma <= 8) MessageBox.Show(suma.ToString() + " Esti Bun"); else if (suma >= 9) MessageBox.Show(suma.ToString() + " Felicitari"); } private void button3_Click_1(object sender, EventArgs e) { this.Owner.Show(); this.Close(); Form1.ActiveForm.Close(); } } }
using CsvHelper; using PopulationFitness.Models; using System; using System.Collections.Generic; using System.IO; namespace PopulationFitness.Output { public class EpochsReader { public static List<Epoch> ReadEpochs(Config config, String path) { List<Epoch> epochs = new List<Epoch>(); var reader = new CsvReader(File.OpenText(path)); reader.Read(); reader.ReadHeader(); while (reader.Read()) { Epoch epoch = ReadFromRow(config, reader); epochs.Add(epoch); } return epochs; } private static Epoch ReadFromRow(Config config, CsvReader row) { Epoch epoch = new Epoch(config, row.GetField<int>(0)) { EndYear = row.GetField<int>(1), EnvironmentCapacity = row.GetField<int>(2) }; epoch.BreedingProbability(row.GetDoubleFieldWithoutRounding(3)); epoch.Disease(row.GetField<bool>(4)); epoch.Fitness(row.GetDoubleFieldWithoutRounding(5)); epoch.ExpectedMaxPopulation = row.GetField<int>(6); epoch.MaxAge(row.GetField<int>(7)); epoch.MaxBreedingAge(row.GetField<int>(8)); return epoch; } } }
using WebAPI_Connection_ReExam.Custom; using Newtonsoft.Json; using System; using System.Net; using System.Net.Http; using System.Text; using System.Web.Http; using System.Collections.Generic; using System.Data.SqlClient; //開発実験用に使っているAPI(従業員一覧を返却するコントローラ) namespace WebAPI_Connection_ReExam.Controllers { public class ExamController : ApiController { private DatabaseConnectionHelper helper; private string jsonString = "実験用文字列"; [ActionName("get")] public HttpResponseMessage GetString() { var res = Request.CreateResponse(HttpStatusCode.OK); //コード200:通信成功 helper = new DatabaseConnectionHelper( "SELECT 従業員コード,従業員名,入社日,従業員種別名 FROM 従業員,従業員種別 " + "WHERE 従業員.従業員種別コード = 従業員種別.従業員種別コード;"); //データをリストに格納するためのやーつ int workerId; string name; DateTime entryDate; string workerType; List<Worker> worker = new List<Worker>(); //データベースへ接続、結果を格納 //最初に空のリストを生成、セット可能とする SqlDataReader reader = helper.DatabaseConnect(); LWorker wk = new LWorker() { title = "従業員", worker = null }; //データのセット while (reader.Read()) { workerId = int.Parse(reader.GetValue(0).ToString()); name = (string)reader.GetValue(1); entryDate = DateTime.Parse(reader.GetValue(2).ToString()); workerType = reader.GetValue(3).ToString(); worker.Add(new Worker(workerId, name, entryDate, workerType)); } wk.worker = worker; reader.Close(); helper.closeDb(); jsonString = JsonConvert.SerializeObject(wk); //Debug.WriteLine(jsonString); //StringBuilderクラスのインスタンス//Content-Typeを指定する res.Content = new StringContent(jsonString, Encoding.UTF8, "application/json"); //Content-Typeを指定 return res; } } }
using System; using System.Collections; using System.Configuration; using System.Data; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; namespace DtCms.Web.Admin { public partial class login : DtCms.Web.UI.BasePage { DtCms.BLL.Admin bll = new DtCms.BLL.Admin(); protected void Page_Load(object sender, EventArgs e) { } protected void loginsubmit_Click(object sender, ImageClickEventArgs e) { string UserName = txtUserName.Text.Trim(); string UserPwd = txtUserPwd.Text.Trim(); if (UserName.Equals("") || UserPwd.Equals("")) { lbMsg.Text = "请输入您要登录用户名或密码"; } else { if (Session["AdminLoginSun"] == null) { Session["AdminLoginSun"] = 1; } else { Session["AdminLoginSun"] = Convert.ToInt32(Session["AdminLoginSun"]) + 1; } //判断登录 if (Session["AdminLoginSun"] != null && Convert.ToInt32(Session["AdminLoginSun"]) > 3) { lbMsg.Text = "登录错误超过3次,请关闭浏览器重新登录。"; } else if (bll.chkAdminLogin(UserName, UserPwd)) { DtCms.Model.Admin model = new DtCms.Model.Admin(); model = bll.GetModel(UserName); Session["AdminNo"] = model.Id; Session["AdminName"] = model.UserName; Session["AdminType"] = model.UserType; Session["AdminLevel"] = model.UserLevel; //设置超时时间 Session.Timeout = 45; Session["AdminLoginSun"] = null; //Syscms.Model.websetModel webset = new Syscms.Bll.webSetBll().loadConfig(Server.MapPath(ConfigurationManager.AppSettings["Configpath"].ToString())); //Syscms.Common.FsLog.SaveLogs(webset.weblogPath, model.UserName, "登录"); Response.Redirect("admin_index.aspx"); } else { lbMsg.Text = "您输入的用户名或密码不正确"; } } } } }
using System; [Serializable] public class SCTrack { public SCTrack() {} public string id; public int duration; public bool streamable; public bool downloadable; public string sharing; public string genre; public string title; public string description; public string original_format; public string license; public SCUser user; public string uri; public string permalink_url; public string artwork_url; public string stream_url; public string waveform_url; public string download_url; public string FormattedTime(int seconds) { TimeSpan ts = System.TimeSpan.FromMilliseconds(seconds); string timeString = string.Format("{0:D2}:{1:D2}:{2:D2}", ts.Hours, ts.Minutes, ts.Seconds); return timeString; } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; namespace UnityStandardAssets.CrossPlatformInput { public class SaveName : MonoBehaviour, IPointerEnterHandler { public Text player_name; string playername; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void OnPointerEnter(PointerEventData eventData) { playername = player_name.text; PlayerPrefs.SetString("playername", playername); } } }
// Copyright (c) 2018 FiiiLab Technology Ltd // Distributed under the MIT software license, see the accompanying // file LICENSE or or http://www.opensource.org/licenses/mit-license.php. using System; using System.Collections.Generic; using System.Text; namespace FiiiChain.Framework { public class ErrorCode { public const int UNKNOWN_ERROR = 0000000; public class Engine { public const int COMMON_ERROR = 1000000; public class UTXO { public const int COMMON_ERROR = 1010000; public const int UTXO_IS_SPENT= 1010001; } public class Transaction { public const int COMMON_ERROR = 1020000; public class Verify { public const int COMMON_ERROR = 1020100; public const int TRANSACTION_HASH_ERROR = 1020101; public const int TRANSACTION_HAS_BEEN_EXISTED = 1020102; public const int INPUT_AND_OUTPUT_CANNOT_BE_EMPTY = 1020103; public const int INPUT_EXCEEDED_THE_LIMIT = 1020104; public const int OUTPUT_EXCEEDED_THE_LIMIT = 1020105; public const int HASH_CANNOT_BE_EMPTY = 1020106; public const int LOCK_TIME_EXCEEDED_THE_LIMIT = 1020107; public const int TRANSACTION_SIZE_BELOW_THE_LIMIT = 1020108; public const int NUMBER_OF_SIGNATURES_EXCEEDED_THE_LIMIT = 1020109; public const int SCRIPT_FORMAT_ERROR = 1020110; public const int UTXO_HAS_BEEN_SPENT = 1020111; public const int COINBASE_UTXO_LESS_THAN_100_CONFIRMS = 1020112; public const int OUTPUT_LARGE_THAN_INPUT = 1020113; public const int TRANSACTION_FEE_IS_TOO_FEW = 1020114; public const int UTXO_UNLOCK_FAIL = 1020115; public const int UTXO_NOT_EXISTED = 1020116; public const int COINBASE_FORMAT_ERROR = 1020117; public const int COINBASE_OUTPUT_AMOUNT_ERROR = 1020118; public const int PRIVATE_KEY_IS_ERROR = 1020119; public const int TRANSACTION_IS_LOCKED = 1020120; public const int COINBASE_NEED_100_CONFIRMS = 1020121; public const int CHANGE_ADDRESS_IS_INVALID = 1020122; public const int UTXO_DUPLICATED_IN_ONE_BLOCK = 1020123; public const int SIGN_ADDRESS_NOT_EXISTS = 1020124; public const int NOT_FOUND_COINBASE = 1020115; } } public class Block { public const int COMMON_ERROR = 1030000; public class Verify { public const int COMMON_ERROR = 1030100; public const int BLOCK_HAS_BEEN_EXISTED = 1030101; public const int BLOCK_HASH_ERROR = 1030102; public const int BLOCK_SIZE_LARGE_THAN_LIMIT = 1030103; public const int TRANSACTION_VERIFY_FAIL = 1030104; public const int POC_VERIFY_FAIL = 1030105; public const int BITS_IS_WRONG = 1030106; public const int PREV_BLOCK_NOT_EXISTED = 1030107; public const int BLOCK_TIME_IS_ERROR = 1030108; public const int BLOCK_SIGNATURE_IS_ERROR = 1030109; public const int GENERATION_SIGNATURE_IS_ERROR = 1030110; public const int MINING_POOL_NOT_EXISTED = 1030111; } } public class BlockChain { public const int COMMON_ERROR = 1040000; public const int ACCOUNT_ISNOT_MININGPOOL = 1040001; } public class Account { public const int COMMON_ERROR = 1050000; } public class P2P { public const int COMMON_ERROR = 1060000; public class Connection { public const int COMMON_ERROR = 1060100; public const int HOST_NAME_CAN_NOT_RESOLVED_TO_IP_ADDRESS = 1060101; public const int THE_NUMBER_OF_CONNECTIONS_IS_FULL = 1060102; public const int THE_PEER_IS_EXISTED = 1060103; //public const int NOT_RECEIVED_PONG_MESSAGE = 1060104; public const int NOT_RECEIVED_HEARTBEAT_MESSAGE_FOR_A_LONG_TIME = 1060105; public const int P2P_VERSION_NOT_BE_SUPPORT_BY_REMOTE_PEER = 1060106; public const int TIME_NOT_MATCH_WITH_RMOTE_PEER = 1060107; public const int PEER_IN_BLACK_LIST = 1060108; } } public class Wallet { public const int COMMON_ERROR = 1070000; public const int DECRYPT_DATA_ERROR = 1070001; public const int DATA_SAVE_TO_FILE_ERROR = 1070002; public const int CHECK_PASSWORD_ERROR = 1070003; public class IO { public const int COMMON_ERROR = 1070100; public const int FILE_NOT_FOUND = 1070101; public const int EXTENSION_NAME_NOT_SUPPORT = 1070102; public const int FILE_DATA_INVALID = 1070103; } public class DB { public const int COMMON_ERROR = 1080200; public const int EXECUTE_SQL_ERROR = 1080201; public const int LOAD_DATA_ERROR = 1080202; } } } public class Service { public const int COMMON_ERROR = 2000000; public class UTXO { public const int COMMON_ERROR = 2010000; } public class Transaction { public const int COMMON_ERROR = 2020000; public const int TO_ADDRESS_INVALID = 2020001; public const int BALANCE_NOT_ENOUGH = 2020002; public const int SEND_AMOUNT_LESS_THAN_FEE = 2020003; public const int FEE_DEDUCT_ADDRESS_INVALID = 2020004; public const int WALLET_DECRYPT_FAIL = 2020005; } public class Account { public const int COMMON_ERROR = 2030000; public const int ACCOUNT_NOT_FOUND = 2030001; public const int DEFAULT_ACCOUNT_NOT_SET = 2030002; } public class AddressBook { public const int COMMON_ERROR = 2040000; public const int CAN_NOT_ADDED_SELF_ACCOUNT_INTO_ADDRESS_BOOK = 2040001; } public class Network { public const int COMMON_ERROR = 2050000; public const int P2P_SERVICE_NOT_START = 2050001; public const int NODE_EXISTED = 2050002; public const int NODE_NOT_EXISTED = 2050003; public const int NODE_IN_THE_BLACK_LIST = 2050004; public const int NODE_ADDRESS_FORMAT_INVALID = 2050005; public const int SET_BAN_COMMAND_PARAMETER_NOT_SUPPORTED = 2050006; } public class BlockChain { public const int COMMON_ERROR = 2060000; public const int SAME_HEIGHT_BLOCK_HAS_BEEN_GENERATED = 2060001; public const int BLOCK_DESERIALIZE_FAILED = 2060002; public const int BLOCK_SAVE_FAILED = 2060003; } public class Wallet { public const int COMMON_ERROR = 2070000; public const int CAN_NOT_ENCRYPT_AN_ENCRYPTED_WALLET = 2010001; public const int CAN_NOT_LOCK_AN_UNENCRYPTED_WALLET = 2010002; public const int CAN_NOT_UNLOCK_AN_UNENCRYPTED_WALLET = 2010003; public const int CAN_NOT_CHANGE_PASSWORD_IN_AN_UNENCRYPTED_WALLET = 2010004; public const int WALLET_HAS_BEEN_LOCKED = 2010005; } } } }
using Cs_Notas.Dominio.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Aplicacao.Interfaces { public interface IAppServicoNomes:IAppServicoBase<Nomes> { List<Nomes> ObterNomesPorIdAto(int IdAto); List<Nomes> ObterNomesPorNome(string nome); List<Nomes> ObterNomesPorIdProcuracao(int IdProcuracao); List<Nomes> ObterNomesPorIdTestamento(int IdTestamento); } }
using BDTest.NetCore.Razor.ReportMiddleware.Models; namespace BDTest.NetCore.Razor.ReportMiddleware.Interfaces; public interface IBDTestCustomHeaderLinksProvider { IEnumerable<CustomLinkData> GetCustomLinks(); }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WalkByInput : MoveBehaviour { /// <summary> /// Hit에 아무것도 들어온 적 없는 상태를 나타내는 flag 역할. /// </summary> private RaycastHit2D globalHit = new RaycastHit2D(); private bool isGlobalHitNull = true; /// <summary> /// 플레이어가 몬스터에서 얼마나 떨어져서 나타나는가? (몬스터의 콜라이더 사이즈 = 1) /// </summary> public float spawnMargin = 0.1f; /// <summary> /// 객체의 y값을 중앙라인으로 정렬한다. /// </summary> /// <param name="obj"></param> /// <returns></returns> public override IEnumerator _Move(GameObject obj, float? speed = null) { GameObject[] lines = GetLines(); List<float> linesY = GetLinePosY(); while (true) { if (Input.GetKeyDown(KeyCode.RightArrow)) { RaycastAndMoveNext(obj, new Vector2(1, 0), 20, 1 << 8); } else if (Input.GetKeyDown(KeyCode.LeftArrow)) { //왼쪽 레이캐스트 결과에 아무것도 없으면 라인의 원점으로 이동한다. if (!RaycastAndMoveNext(obj, new Vector2(-1, 0), 20, 1 << 8)) { foreach(var line in lines) { if(obj.transform.position.y == line.transform.position.y) { obj.transform.SetParent(line.transform); obj.transform.localPosition = Vector2.zero; } } } } else if (Input.GetKeyDown(KeyCode.UpArrow)) { Vector3 origin = obj.transform.position; for (int i = 0; i < linesY.Count; i++) { //origin.y가 마지막 라인의 y값 +- 0.5 범위에 들어가면 0번째 라인으로 간다. if (linesY[linesY.Count-1]-0.5< origin.y && origin.y < linesY[linesY.Count - 1] + 0.5) { origin.y = linesY[0]; break; } else if (linesY[i]-0.5 < origin.y && origin.y < linesY[i] + 0.5) { origin.y = linesY[i + 1]; break; } } obj.transform.position = origin; RaycastBothSideAndMove(obj, 100, 1 << 8); } else if (Input.GetKeyDown(KeyCode.DownArrow)) { Vector3 origin = obj.transform.position; for (int i = 0; i < linesY.Count; i++) { if (linesY[0] - 0.5 < origin.y && origin.y < linesY[0] + 0.5) { origin.y = linesY[linesY.Count - 1]; break; } else if (linesY[i] - 0.5 < origin.y && origin.y < linesY[i] + 0.5) { origin.y = linesY[i - 1]; break; } } obj.transform.position = origin; RaycastBothSideAndMove(obj, 100, 1 << 8); } yield return null; } } /// <summary> /// 레이캐스트 힛 포인트로 이동한다. /// </summary> /// <param name="obj"></param> /// <param name="hit"></param> private void MoveToHit(GameObject obj, RaycastHit2D hit) { obj.transform.SetParent(hit.transform.Find("WayPoint").transform); obj.transform.localPosition = new Vector3(0, 0, 0); } /// <summary> /// 양쪽으로 레이캐스트 한 후 더 가까운 객체 앞으로 이동한다. /// </summary> /// <param name="obj"></param> private bool RaycastBothSideAndMove(GameObject obj, float Maxdistance, int layerMask) { Vector2 origin = obj.transform.position; Vector2 right = new Vector2(1, 0); Vector2 left = new Vector2(-1, 0); //콜라이더 일시해제(원활한 레이캐스트를 위해) BoxCollider2D col = obj.transform.GetComponent<BoxCollider2D>(); Vector2 rayOrigin = obj.transform.position; rayOrigin.y += col.size.y/2; col.enabled = false; RaycastHit2D hitR = Physics2D.Raycast(rayOrigin, right, Maxdistance, layerMask); RaycastHit2D hitL = Physics2D.Raycast(rayOrigin, left, Maxdistance, layerMask); Debug.DrawRay(rayOrigin, right * 20, Color.red, 3f); Debug.DrawRay(rayOrigin, left * 20, Color.red, 3f); //둘중 하나가 null일 경우 if (hitR || hitL && !(hitR && hitL)) { RaycastHit2D hit = hitR ? hitR : hitL; MoveToHit(obj, hit); return true; } //둘다 null이 아닐 경우 else if (hitR && hitL) { if (hitR.transform.position.x - origin.x > hitL.transform.position.x - origin.x) { MoveToHit(obj, hitL); } else { MoveToHit(obj, hitR); } return true; } return false; } /// <summary> /// 레이캐스트 후, 레이캐스트 된 객체 앞으로 이동한다. 그 객체의 다음 객체가 있으면 그 객체로도 이동할 수 있다. /// </summary> /// <param name="obj"></param> /// <param name="dirction"></param> /// <param name="Maxdistance"></param> /// <param name="layerMask"></param> private bool RaycastAndMoveNext(GameObject obj, Vector2 dirction, float Maxdistance, int layerMask) { BoxCollider2D col = obj.transform.GetComponent<BoxCollider2D>(); Vector2 rayOrigin = obj.transform.position; rayOrigin.y += col.size.y/2; col.enabled = false; RaycastHit2D[] hits = Physics2D.RaycastAll(rayOrigin, dirction, Maxdistance, layerMask); Debug.DrawRay(rayOrigin, dirction * 20, Color.red, 3f); //null체크가 불가하므로 길이로 체크. if (hits.Length <= 0) return false; globalHit = hits[0]; if (hits.Length >= 2 && !isGlobalHitNull) MoveToHit(obj, hits[1]); else MoveToHit(obj, hits[0]); isGlobalHitNull = false; col.enabled = true; return true; } }
using Backend.Communication.RabbitMqConfuguration; using RabbitMQ.Client; namespace Backend.Communication.RabbitMqConnection { public interface IRabbitMqConnection { RabbitMqConfiguration Configuration { get; } IConnection Connection { get; } } }
namespace Tree { using System; using System.Collections.Generic; public class Tree<T> : IAbstractTree<T> { private readonly List<Tree<T>> _children; public Tree(T value) { throw new NotImplementedException(); } public Tree(T value, params Tree<T>[] children) : this(value) { throw new NotImplementedException(); } public T Value { get; private set; } public Tree<T> Parent { get; private set; } public IReadOnlyCollection<Tree<T>> Children => this._children.AsReadOnly(); public ICollection<T> OrderBfs() { throw new NotImplementedException(); } public ICollection<T> OrderDfs() { throw new NotImplementedException(); } public void AddChild(T parentKey, Tree<T> child) { throw new NotImplementedException(); } public void RemoveNode(T nodeKey) { throw new NotImplementedException(); } public void Swap(T firstKey, T secondKey) { throw new NotImplementedException(); } } }
using System; using System.Collections.Generic; using System.Text; namespace ScoutingModels.Data { /// <summary> /// What went on during the match /// -GeoEngel /// </summary> public class MatchEvent { /// <summary> /// The performance where the event took place /// </summary> public Performance Performance { get; set; } /// <summary> /// What action the robot took /// </summary> public MatchEventType EventType { get; set; } /// <summary> /// The period where the event took place /// </summary> public MatchPeriod Period { get; set; } /// <summary> /// The Match Event's unique identifer /// </summary> public string Id { get; set; } } /// <summary> /// The Periods of the match /// </summary> public enum MatchPeriod { Autonomous, TeleOp, Final } /// <summary> /// The Possible actions a robot could do as a match event /// </summary> public enum MatchEventType { ReachDefense, CrossDefense1, CrossDefense2, CrossDefense3, CrossDefense4, CrossDefense5, MakeHighGoal, MakeLowGoal, MissHighGoal, MissLowGoal, FailedChallengeTower, ChallengeTower, FailedScaleTower, ScaleTower, Foul, TeachnicalFoul } }
using System; using CashSys.Controller; using CashSys.Model; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using CashierSystem.View; namespace CashierSystem { public partial class LoginForm : Form { public LoginForm() { InitializeComponent(); } private void LoginForm_Load(object sender, EventArgs e) { } private void label1_Click(object sender, EventArgs e) { } private void label1_Click_1(object sender, EventArgs e) { } private void Login_SelectedIndexChanged(object sender, EventArgs e) { } private void label1_Click_2(object sender, EventArgs e) { } private void SubmitButtonLog_Click(object sender, EventArgs e) { CashierRepository cashier = new CashierRepository(); /****************************************************************************************** ** Get field values ** ******************************************************************************************/ //Get String of field. var FieldName = UserNameCashierLogField.Text.ToString(); //Get String of password. var FieldPass = PasswordCashierLogField.Text.ToString(); /****************************************************************************************** ** Get model values ** ******************************************************************************************/ //Get whole data of user (user name and pass). var UserNamePass = cashier.GetCashier().FirstOrDefault(x => x.cashier_user_name == FieldName && x.cashier_password == FieldPass); /****************************************************************************************** ** Log in proccessing ** ******************************************************************************************/ // Checking empty fields if (FieldName.Length == 0 || FieldPass.Length == 0) { MessageBox.Show("Не сте въвели някое от полетата !"); } else { // Check user name and pass. if (UserNamePass != null) { //If there are user name and password. Program will proceed to Admin panel. this.Hide(); AdministrationPanel adminPanel = new AdministrationPanel(); adminPanel.ShowDialog(); } else { //Else message will show MessageBox.Show("Въвели сте грешен user name или парола !"); } } } private void ConfirmButtonReg_Click(object sender, EventArgs e) { var context = new CashierSystemEntities(); /****************************************************************************************** ** Getting values in registration form ** ******************************************************************************************/ // Get value in registration form – text field first name. var FirstNameReg = NameCashierRegField.Text.ToString(); // Get value in registration form – text field last name. var LastNameReg = LnameCashierRegField.Text.ToString(); // Get value in registration form – text field user name. var UserNameReg = UserNameCashierRegField.Text.ToString(); // Get value in registration form – text field password. var PassReg = PasswordCashierRegField.Text.ToString(); // Get value in registration form – text field confirm password. var PassConfig = ConfirmPassCashierRegFiedl.Text.ToString(); /****************************************************************************************** ** Getting data model ** ******************************************************************************************/ // Object newCashier of type CashierRepository. CashierRepository newCashier = new CashierRepository(); // Get only user name from table Cashier. var onlyUserName = context.Cashier.FirstOrDefault(un => un.cashier_user_name == UserNameReg); /****************************************************************************************** ** Registration proccessing ** ******************************************************************************************/ // Check if any field is empty. if (FirstNameReg.Length == 0 || LastNameReg.Length == 0 || UserNameReg.Length == 0 || PassReg.Length == 0 || PassConfig.Length == 0) { // If there is empty field, it shows message. MessageBox.Show("Не сте въвели някое от полетата!"); } else { // Check password and confirm password match. if (PassReg.Equals(PassConfig)) { // Check is user exist if (onlyUserName != null) { // Return message that user exists MessageBox.Show("Съществува такъв потребител ! Сменете потребителското име"); }else { // Add to table new cashier newCashier.AddCashier(FirstNameReg, LastNameReg, UserNameReg, PassReg); // Clear all fields NameCashierRegField.Text = ""; LnameCashierRegField.Text = ""; UserNameCashierRegField.Text = ""; PasswordCashierRegField.Text = ""; ConfirmPassCashierRegFiedl.Text = ""; // Confirmed record MessageBox.Show("Успешен запис !"); } } else { // If there is no matching of confirm pass and pass, shows message. MessageBox.Show("Паролите не съвпадат !"); } } } private void LnameCashierRegField_TextChanged(object sender, EventArgs e) { } private void PasswordCashierLogField_TextChanged(object sender, EventArgs e) { } private void ClearButtonReg_Click(object sender, EventArgs e) { /****************************************************************************************** ** Clear Button Functionality ** ******************************************************************************************/ // Clear all fields NameCashierRegField.Text = ""; LnameCashierRegField.Text = ""; UserNameCashierRegField.Text = ""; PasswordCashierRegField.Text = ""; ConfirmPassCashierRegFiedl.Text = ""; } } }
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Threading.Tasks; using PopulationWars.Map; using PopulationWars.Components; using System.Threading; using static PopulationWars.Utilities.Constants; namespace PopulationWars.Mechanics { public class Gameplay { private List<Player> m_players; private World m_worldMap; private int m_turns; private int m_minTurns; private int m_maxTurns; private double m_populationGrowthRate; private Action<Tuple<int, int>, Color, int> UpdateTile; private Action<Tuple<int, int>> LoadEnvironment; private Action<bool> RequestHumanPlayerMove; private Action ShowGameResult; public int CurrentTurn { get; private set; } public int Speed { get; set; } public bool SkipHumanPlayerTurn { get; set; } public bool SkipPlayerTurn { get; set; } public bool SkipGameTurn { get; set; } public bool HoldOn { get; set; } public bool StopGame { get; set; } public Decision PlayerDecision { get; set; } public List<TrainSet> TrainSets { get; set; } public Gameplay(Tuple<int, int> gameDuration, double populationGrowthRate, List<Player> players, World worldMap) { m_players = players; m_worldMap = worldMap; m_turns = new Random().Next(gameDuration.Item1, gameDuration.Item2); m_minTurns = gameDuration.Item1; m_maxTurns = gameDuration.Item2; m_populationGrowthRate = populationGrowthRate; CurrentTurn = 0; Speed = 1; TrainSets = new List<TrainSet>(); } public void CreateInitialColonies() => m_players.ForEach(player => { var tile = m_worldMap.GetRandomEmptyTile(); player.CreateColony(tile, 100); UpdateTile(tile.Position, player.Color, 100); }); public void Play() => Task.Factory.StartNew(() => { m_players.ForEach(p => { if (!p.IsAgent) TrainSets.Add(new TrainSet { Name = p.Name, Date = DateTime.Now }); }); while (++CurrentTurn < m_turns) { SkipGameTurn = false; MakeGameTurn(); if (StopGame) break; } ShowGameResult(); }); public void SetActions(Action<Tuple<int, int>, Color, int> tileUpdateAction, Action<Tuple<int, int>> environmentLoadAction, Action gameResultShowAction, Action<bool> humanPlayerMoveRequestAction) { UpdateTile = tileUpdateAction; LoadEnvironment = environmentLoadAction; ShowGameResult = gameResultShowAction; RequestHumanPlayerMove = humanPlayerMoveRequestAction; } private void MakeColonyTurn(Player player, Colony colony, Decision decision) { if (!decision.IsLeaving) { var population = (int)(colony.Population * m_populationGrowthRate); colony.Population = population > MaximumPopulationInColony ? MaximumPopulationInColony : population; UpdateTile(colony.Tile.Position, player.Color, colony.Population); return; } var tileToMove = m_worldMap.GetNeighbourTile(colony.Tile, decision.Direction); if (tileToMove.IsWall) { return; } var populationToMove = (int)Math.Ceiling(colony.Population * decision.PopulationToMove); colony.Population -= populationToMove; if (colony.Population < 1) { player.DestroyColony(colony.Tile); } UpdateTile(colony.Tile.Position, player.Color, colony.Population); if (tileToMove.IsEmpty) { player.CreateColony(tileToMove, populationToMove); UpdateTile(tileToMove.Position, player.Color, populationToMove); } else { if (colony.Nation == tileToMove.OwnedBy.Nation) { player.MoveToColony(tileToMove, populationToMove); UpdateTile(tileToMove.Position, player.Color, tileToMove.OwnedBy.Population); } else { var difference = populationToMove - tileToMove.OwnedBy.Population; var enemy = m_players.Where(p => p.Nation == tileToMove.OwnedBy.Nation). First(); if (difference > 0) { enemy.DestroyColony(tileToMove); player.CreateColony(tileToMove, difference); UpdateTile(tileToMove.Position, player.Color, difference); } else if (difference < 0) { tileToMove.OwnedBy.Population -= populationToMove; UpdateTile(tileToMove.Position, enemy.Color, tileToMove.OwnedBy.Population); } else { enemy.DestroyColony(tileToMove); UpdateTile(tileToMove.Position, player.Color, 0); } } } } private void MakeGameTurn() => m_players.ForEach(player => { SkipPlayerTurn = false; SkipHumanPlayerTurn = false; MakePlayerTurn(player); }); private void MakePlayerTurn(Player player) { var colonies = new List<Colony>(); colonies.AddRange(player.Colonies); colonies.ForEach(colony => { if (Speed < 32 && !SkipPlayerTurn && !SkipGameTurn || !player.IsAgent) LoadEnvironment(colony.Tile.Position); var situation = new Situation(colony.Population, player.Colonies.Count, m_worldMap.GetEnvironment(colony.Tile), m_minTurns, m_maxTurns, CurrentTurn); Decision decision; if (player.IsAgent) { decision = colony.Nation.Government.MakeDecision(situation); } else { if (SkipHumanPlayerTurn) decision = new Decision(); else { RequestHumanPlayerMove(true); HoldOn = true; while (HoldOn) Thread.Sleep(1000); decision = PlayerDecision; var trainSet = TrainSets.Where(t => t.Name == player.Name).First(); trainSet.Situation.Add(situation); trainSet.Decision.Add(decision); RequestHumanPlayerMove(false); } } MakeColonyTurn(player, colony, decision); while (HoldOn) Thread.Sleep(1000); if (!SkipPlayerTurn && !SkipGameTurn && Speed < 15) Thread.Sleep(2048 / Speed); }); } } }
using NUnit.Framework; namespace Training { [TestFixture] public class Test19 : TestBase { [Test] public void CanAddAndDeleteProductsToCart() { var numberOfElements = 3; app.AddElementsToCart(numberOfElements); var productsInCart = app.GetNumberOfProductsInCart(); Assert.True(productsInCart.Equals(numberOfElements.ToString())); app.DeleteAllFromCart(); } } }
using System.Configuration; using System.Data.Entity; using CodeFirst.Entities; namespace CodeFirst.Contextes { public class SampleContext : DbContext { internal SampleContext() : base(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString) //public SampleContext() : base() { //Database.SetInitializer<SampleContext>(new DBInitializer()); //var cs = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString; //Database.Connection.ConnectionString = cs; } internal SampleContext(string conStr): base (conStr) { } //static SampleContext() //{ // //Database.SetInitializer(new DBInitializer()); //} public DbSet<Customer> Customers { get; set; } public DbSet<Order> Orders { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BlogEngine.Domain.Entities { public class Post { public int PostId { get; set; } public string Title { get; set; } public string Content { get; set; } public DateTime DateCreated { get; set; } public bool CommentsAllowed { get; set; } public PostStatus Status { get; set; } public int BlogId { get; set; } public virtual Blog Blog { get; set; } public virtual ICollection<Comment> Comments { get; set; } public int BlogUserId { get; set; } public virtual BlogUser BlogUser { get; set; } public virtual ICollection<Tag> Tags { get; set; } public virtual Topic Topic { get; set; } } public enum PostStatus { Staged, Posted, Archived, Deleted } }
using System; using System.IO; using System.Linq; using System.Reflection; using Uintra.Core.Controls.FileUpload; using Uintra.Core.UmbracoEvents.Services.Contracts; using Uintra.Features.Media; using Uintra.Features.Media.Models; using Uintra.Features.Media.Video.Converters.Contracts; using Uintra.Features.Media.Video.Helpers.Contracts; using Uintra.Infrastructure.Constants; using Umbraco.Core.Events; using Umbraco.Core.Models; using Umbraco.Core.Services; namespace Uintra.Core.UmbracoEvents.Services.Implementations { public class VideoConvertEventService : IUmbracoMediaSavedEventService { private readonly IVideoConverter _videoConverter; private readonly IVideoHelper _videoHelper; private readonly IContentTypeService _contentTypeService; private readonly IMediaService _mediaService; private readonly IMediaTypeService _mediaTypeService; public VideoConvertEventService( IVideoConverter videoConverter, IVideoHelper videoHelper, IContentTypeService contentTypeService, IMediaService mediaService, IMediaTypeService mediaTypeService) { _videoConverter = videoConverter; _videoHelper = videoHelper; _contentTypeService = contentTypeService; _mediaService = mediaService; _mediaTypeService = mediaTypeService; } public void ProcessMediaSaved(IMediaService sender, SaveEventArgs<IMedia> args) { var newMedia = args .SavedEntities .Where(m => m.WasPropertyDirty("Id")).ToList(); foreach (var media in newMedia) { var convertInProgress = _videoConverter.IsConverting(media); if (convertInProgress || media.ContentType.Alias == UmbracoAliases.Media.ImageTypeAlias) { continue; } var umbracoFile = media.GetValue<string>(UmbracoAliases.Media.UmbracoFilePropertyAlias); if (_videoConverter.IsVideo(umbracoFile)) { var videoContentType = _mediaTypeService.Get(UmbracoAliases.Media.VideoTypeAlias); // BECOME //media.ChangeContentType(videoContentType, false);// TODO Resolve changeContentType umbraco v8 // Due to ChangeContentType is internal var method = typeof(Media) .GetMethod( name: "ChangeContentType", bindingAttr: BindingFlags.NonPublic | BindingFlags.Instance, binder: null, types: new Type[] { typeof(IMediaType), typeof(bool) }, modifiers: null ); method?.Invoke(media, new object[] { videoContentType, false }); _mediaService.Save(media); var video = _mediaService.GetById(media.Id); if (_videoConverter.IsMp4(umbracoFile)) { var thumbnailUrl = _videoHelper.CreateThumbnail(video); video.SetValue(UmbracoAliases.Video.ThumbnailUrlPropertyAlias, thumbnailUrl); _mediaService.Save(video); continue; } video.SetValue(UmbracoAliases.Video.ThumbnailUrlPropertyAlias, _videoHelper.CreateConvertingThumbnail()); _mediaService.Save(video); var fileBytes = System.IO.File.ReadAllBytes(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory + umbracoFile)); System.Threading.Tasks.Task.Run(() => { _videoConverter.Convert(new MediaConvertModel() { File = new TempFile { FileName = umbracoFile, FileBytes = fileBytes }, MediaId = media.Id }); }); } } } } }
using System.Collections.Generic; using UnityEngine; class LineDistance { public Gate nextGate; public float distance; } class Block { public Vector2 vector2; public List<Gate> gates; Dictionary<Gate, List<LineDistance>> lineDistance = new Dictionary<Gate, List<LineDistance>>(); public Block(Vector2 vector2) { this.vector2 = vector2; gates = new List<Gate>(); InitDistance(); } void InitDistance() { } } class Gate { public Block b1; public Block b2; } public class MapBlocks { private MapInfo info; const float BLOCK_SIZE = 10f; Block[,] _blocks; int Width = 0; int Height = 0; public MapBlocks(MapInfo info) { this.info = info; Width = Mathf.CeilToInt(info.Width / BLOCK_SIZE); Height = Mathf.CeilToInt(info.Width / BLOCK_SIZE); _blocks = new Block[Width, Height]; for (int i = 0; i < Width; i++) { for (int j = 0; j < Height; j++) { _blocks[i,j] = new Block(new Vector2(i, j)); } } } void InitGates() { for (int j = 0; j < Height; j++) { for (int i = 1; i < Width; i++) { } } for (int j = 1; j < Height; j++) { } } }
// Code generated by Microsoft (R) AutoRest Code Generator 0.9.7.0 // Changes may cause incorrect behavior and will be lost if the code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using ApartmentApps.Client; using ApartmentApps.Client.Models; using Microsoft.Rest; namespace ApartmentApps.Client { public static partial class InspectionsExtensions { /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> /// <param name='finishInspectionViewModel'> /// Required. /// </param> public static object FinishInspection(this IInspections operations, FinishInspectionViewModel finishInspectionViewModel) { return Task.Factory.StartNew((object s) => { return ((IInspections)s).FinishInspectionAsync(finishInspectionViewModel); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> /// <param name='finishInspectionViewModel'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<object> FinishInspectionAsync(this IInspections operations, FinishInspectionViewModel finishInspectionViewModel, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Microsoft.Rest.HttpOperationResponse<object> result = await operations.FinishInspectionWithOperationResponseAsync(finishInspectionViewModel, cancellationToken).ConfigureAwait(false); return result.Body; } /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> public static IList<InspectionViewModel> Get(this IInspections operations) { return Task.Factory.StartNew((object s) => { return ((IInspections)s).GetAsync(); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<IList<InspectionViewModel>> GetAsync(this IInspections operations, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<ApartmentApps.Client.Models.InspectionViewModel>> result = await operations.GetWithOperationResponseAsync(cancellationToken).ConfigureAwait(false); return result.Body; } /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> /// <param name='id'> /// Required. /// </param> public static object PauseInspection(this IInspections operations, int id) { return Task.Factory.StartNew((object s) => { return ((IInspections)s).PauseInspectionAsync(id); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> /// <param name='id'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<object> PauseInspectionAsync(this IInspections operations, int id, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Microsoft.Rest.HttpOperationResponse<object> result = await operations.PauseInspectionWithOperationResponseAsync(id, cancellationToken).ConfigureAwait(false); return result.Body; } /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> /// <param name='id'> /// Required. /// </param> public static object StartInspection(this IInspections operations, int id) { return Task.Factory.StartNew((object s) => { return ((IInspections)s).StartInspectionAsync(id); } , operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); } /// <param name='operations'> /// Reference to the ApartmentApps.Client.IInspections. /// </param> /// <param name='id'> /// Required. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> public static async Task<object> StartInspectionAsync(this IInspections operations, int id, CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Microsoft.Rest.HttpOperationResponse<object> result = await operations.StartInspectionWithOperationResponseAsync(id, cancellationToken).ConfigureAwait(false); return result.Body; } } }
using System; using System.Linq; using System.Collections; using System.Collections.Generic; namespace Aquamonix.Mobile.Lib.Services { public struct ServerVersion : IComparable { private readonly string _versionString; private readonly List<int> _versionNumbers; private bool _isValid; private static ServerVersion _null = new ServerVersion("0"); public bool IsValid { get { return _isValid; } } public bool IsNull { get { return this.Equals("0"); } } public static ServerVersion Null { get { return _null; } } private ServerVersion(string versionString) { if (versionString == null) throw new NullReferenceException("Version string cannot be null"); if (String.IsNullOrEmpty(versionString)) versionString = "0"; _versionString = versionString.Trim(); _versionNumbers = new List<int>(); _isValid = false; this.ParseInternal(); } public override int GetHashCode() { return _versionString.GetHashCode(); } public override string ToString() { return _versionString; } public bool Equals(string obj) { return (this._versionString == obj); } public override bool Equals(object obj) { if (obj != null) { return this.Equals(obj.ToString()); } return false; } public int CompareTo(object obj) { if (obj is ServerVersion) return this.CompareTo((ServerVersion)obj); else return this.CompareTo(obj == null ? "" : obj.ToString()); } public int CompareTo(string obj) { return CompareTo(new ServerVersion(obj)); } public int CompareTo(ServerVersion obj) { int output = 0; int min = Math.Min(this._versionNumbers.Count, obj._versionNumbers.Count); int max = Math.Max(this._versionNumbers.Count, obj._versionNumbers.Count); for (int n = 0; n < min; n++) { if (this._versionNumbers[n] > obj._versionNumbers[n]) { output = 1; break; } else if (this._versionNumbers[n] < obj._versionNumbers[n]) { output = -1; break; } } if (output == 0) { if (this._versionNumbers.Count != obj._versionNumbers.Count) { if (this._versionNumbers.Count > obj._versionNumbers.Count) { for (int n=min; n<max; n++) { if (this._versionNumbers[n] > 0) { output = 1; break; } } } else { for (int n = min; n < max; n++) { if (obj._versionNumbers[n] > 0) { output = -1; break; } } } } } return output; } public static ServerVersion Parse(string version) { return new ServerVersion(version); } public static bool operator ==(ServerVersion a, ServerVersion b) { return (a.CompareTo(b) == 0); } public static bool operator ==(ServerVersion a, string b) { return (a.CompareTo(b) == 0); } public static bool operator ==(string a, ServerVersion b) { return (b.CompareTo(a) == 0); } public static bool operator !=(ServerVersion a, ServerVersion b) { return (a.CompareTo(b) != 0); } public static bool operator !=(ServerVersion a, string b) { return (a.CompareTo(b) != 0); } public static bool operator !=(string a, ServerVersion b) { return (b.CompareTo(a) != 0); } public static bool operator >(ServerVersion a, ServerVersion b) { return (a.CompareTo(b) > 0); } public static bool operator >(ServerVersion a, string b) { return (a.CompareTo(b) > 0); } public static bool operator >(string a, ServerVersion b) { return (b.CompareTo(a) < 0); } public static bool operator >=(ServerVersion a, ServerVersion b) { return (a.CompareTo(b) >= 0); } public static bool operator >=(ServerVersion a, string b) { return (a.CompareTo(b) >= 0); } public static bool operator >=(string a, ServerVersion b) { return (b.CompareTo(a) <= 0); } public static bool operator <(ServerVersion a, ServerVersion b) { return (a.CompareTo(b) < 0); } public static bool operator <(ServerVersion a, string b) { return (a.CompareTo(b) < 0); } public static bool operator <(string a, ServerVersion b) { return (b.CompareTo(a) > 0); } public static bool operator <=(ServerVersion a, ServerVersion b) { return (a.CompareTo(b) <= 0); } public static bool operator <=(ServerVersion a, string b) { return (a.CompareTo(b) <= 0); } public static bool operator <=(string a, ServerVersion b) { return (b.CompareTo(a) >= 0); } private void ParseInternal() { _isValid = false; if (_versionString != null) { string[] parts = _versionString.Split('.'); if (parts.Length > 0) { _isValid = true; for (int n = 0; n < parts.Length; n++) { //each one must be a digit if (parts[n].All(Char.IsDigit)) { _versionNumbers.Add(Int32.Parse(parts[n])); } else { _isValid = false; break; } } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; using GraphicalEditor.DTO; using GraphicalEditor.Service; namespace GraphicalEditor { /// <summary> /// Interaction logic for AppointmentInRoomMoreDetailsDialog.xaml /// </summary> public partial class AppointmentInRoomMoreDetailsDialog : Window { public int ExaminationId { get; set; } public ExaminationDTO ExaminationForDisplay { get; set; } public PatientBasicDTO ExaminationPatient { get; set; } AppointmentService _appointmentService; PatientService _patientService; public AppointmentInRoomMoreDetailsDialog(int examinationId) { InitializeComponent(); DataContext = this; ExaminationId = examinationId; _appointmentService = new AppointmentService(); _patientService = new PatientService(); ExaminationForDisplay = _appointmentService.GetExaminationById(ExaminationId); ExaminationPatient = _patientService.GetPatientByPatientCardId(ExaminationForDisplay.PatientCardId); } public AppointmentInRoomMoreDetailsDialog(ExaminationDTO examinationDTO) { InitializeComponent(); DataContext = this; _patientService = new PatientService(); ExaminationForDisplay = examinationDTO; ExaminationPatient = _patientService.GetPatientByPatientCardId(ExaminationForDisplay.PatientCardId); CancelExaminationButton.Visibility = Visibility.Collapsed; } private void ShowAppointmentSuccessfullyCancelledDialog() { InfoDialog infoDialog = new InfoDialog("Uspešno ste otkazali pregled!"); infoDialog.ShowDialog(); } private void CancelExaminationButton_Click(object sender, RoutedEventArgs e) { _appointmentService.DeleteAppointment(ExaminationId); this.Close(); ShowAppointmentSuccessfullyCancelledDialog(); } private void CloseButton_Click(object sender, RoutedEventArgs e) { this.Close(); } } }
namespace TripDestination.Web.MVC.Areas.Admin.Controllers { using System.Web.Mvc; using Kendo.Mvc.Extensions; using Kendo.Mvc.UI; using TripDestination.Services.Data.Contracts; using TripDestination.Web.MVC.Areas.Admin.ViewModels; using TripDestination.Common.Infrastructure.Mapping; using MVC.Controllers; public class PageParagraphAdminController : BaseController { private readonly IPageParagraphServices pageParagraphServices; public PageParagraphAdminController(IPageParagraphServices pageParagraphServices) { this.pageParagraphServices = pageParagraphServices; } public ActionResult Index() { return this.View(); } public ActionResult PageParagraphs_Read([DataSourceRequest]DataSourceRequest request) { var result = this.pageParagraphServices .GetAll() .To<PageParagraphViewModel>() .ToDataSourceResult(request); return this.Json(result); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult PageParagraphs_Create([DataSourceRequest]DataSourceRequest request, PageParagraphViewModel pageParagraph) { if (this.ModelState.IsValid) { var dbPageParagraph = this.pageParagraphServices.Create( pageParagraph.PageId, pageParagraph.MainHeading, pageParagraph.MainSubHeading, pageParagraph.Type, pageParagraph.Heading, pageParagraph.Text, pageParagraph.AdditionalHeading, pageParagraph.AdditionalText); pageParagraph.Id = dbPageParagraph.Id; } return this.Json(new[] { pageParagraph }.ToDataSourceResult(request, this.ModelState)); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult PageParagraphs_Update([DataSourceRequest]DataSourceRequest request, PageParagraphViewModel pageParagraph) { if (this.ModelState.IsValid) { var dbPageParagraph = this.pageParagraphServices.Edit( pageParagraph.Id, pageParagraph.PageId, pageParagraph.MainHeading, pageParagraph.MainSubHeading, pageParagraph.Type, pageParagraph.Heading, pageParagraph.Text, pageParagraph.AdditionalHeading, pageParagraph.AdditionalText); } return this.Json(new[] { pageParagraph }.ToDataSourceResult(request, this.ModelState)); } [AcceptVerbs(HttpVerbs.Post)] public ActionResult PageParagraphs_Destroy([DataSourceRequest]DataSourceRequest request, PageParagraphViewModel pageParagraph) { if (this.ModelState.IsValid) { this.pageParagraphServices.Delete(pageParagraph.Id); } return this.Json(new[] { pageParagraph }.ToDataSourceResult(request, this.ModelState)); } protected override void Dispose(bool disposing) { base.Dispose(disposing); } } }
using System; using Newtonsoft.Json; namespace Shared { public static class Logging { public static void LogMessage(LogLevel logLevel, string message, params object[] propertryValues) => LogMessage(logLevel, $"Message: {message}, Values: {JsonConvert.SerializeObject(propertryValues)}"); public static void LogMessage(LogLevel logLevel, string message) => Console.WriteLine($"{logLevel.GetLogLevelLinePrefix()}: {message}"); private static string GetLogLevelLinePrefix(this LogLevel logLevel) { switch (logLevel) { case LogLevel.Debug: return "🐛 DEBUG"; case LogLevel.Info: return "ℹ INFO"; case LogLevel.Warn: return "⚠ WARN"; case LogLevel.Error: return "😵 ERROR"; case LogLevel.Exception: return "🔫 EXCEPTION"; default: throw new ArgumentOutOfRangeException(nameof(logLevel), logLevel, null); } } } public enum LogLevel { Debug, Info, Warn, Error, Exception } }
using System.Collections.Generic; namespace MealTime.Interface { public interface IInputParser { IParameters Parse(string input); string[] ValidateInitialInput(string input); string ValidateTimeOfDay(string timeOfDay); IList<int> ValidateDishes(string[] inputDishes); } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace AMS { public partial class Contact : Page { protected void Page_Load(object sender, EventArgs e) { } protected void btnBack_Click(object sender, EventArgs e) { //Enzo int whereto = SessionManager.UserRole; switch (whereto) { case 1: Response.Redirect("~/AdminPages/Administrator.aspx"); break; case 2: Response.Redirect("~/TutorPages/Tutor.aspx"); break; case 3: Response.Redirect("~/StudentPages/StudentPage.aspx"); break; } } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace CirAnime.Migrations { public partial class Uploader : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<string>( name: "OriginalFileName", table: "UploadEntry", nullable: true); migrationBuilder.AddColumn<string>( name: "Owner", table: "UploadEntry", nullable: true); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "OriginalFileName", table: "UploadEntry"); migrationBuilder.DropColumn( name: "Owner", table: "UploadEntry"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Input action script. A scriptable object which holds code to execute when an action is needed. /// We made the 'Go' action which allows us to change rooms. Other actions fallows. /// </summary> public abstract class InputActionScript : ScriptableObject { public string keyWord; public abstract void RespondToInput(GameControllerScript gameController, string[] separatedInputWords); }
namespace RabbitMQ.Client.Service.Options { public class QueueOptions { public string Name { get; set; } public bool Durable { get; set; } public bool AutoDelete { get; set; } public bool Exclusive { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Uintra.Attributes; using Uintra.Features.UserList.Models; namespace Uintra.Features.UserList.Helpers { public static class UsersPresentationHelper { public static IEnumerable<ProfileColumnModel> AddManagementColumn(IEnumerable<ProfileColumnModel> columns) => columns.Append(new ProfileColumnModel { Id = 100, Name = "Management", PropertyName = "management", SupportSorting = false, Type = ColumnType.GroupManagement }); public static IEnumerable<ProfileColumnModel> ExtendIfGroupMembersPage( Guid? groupId, IEnumerable<ProfileColumnModel> columns) { if (!groupId.HasValue) return columns; return columns.Append(new ProfileColumnModel { Id = 99, Name = "Group", PropertyName = "role", SupportSorting = false, Type = ColumnType.GroupRole }).Append(new ProfileColumnModel { Id = 100, Name = "Management", PropertyName = "management", SupportSorting = false, Type = ColumnType.GroupManagement }); } public static IEnumerable<ProfileColumnModel> GetProfileColumns() { var columns = typeof(MemberModel).GetCustomAttributes<UIColumnAttribute>().Select(i => new ProfileColumnModel() { Id = i.Id, Name = i.DisplayName, Type = i.Type, PropertyName = i.PropertyName, SupportSorting = i.SupportSorting }).OrderBy(i => i.Id); return columns; } public static bool RestrictAdminSelfDelete( MembersRowsViewModel rows, MemberModel member) => rows.IsCurrentMemberGroupAdmin && rows.CurrentMember.Id != member.Member.Id; public static bool RestrictDeleteCreator( MembersRowsViewModel rows, MemberModel member) => rows.IsCurrentMemberGroupAdmin && member.IsCreator; public static bool RestrictInvite(MembersRowsViewModel rows) => rows.IsInvite; public static bool CanRenderToggleControl( MembersRowsViewModel rows, MemberModel member) => RestrictAdminSelfDelete(rows, member) && !RestrictInvite(rows) && !RestrictDeleteCreator(rows, member); public static bool CanRenderDeleteControl( MembersRowsViewModel rows, MemberModel member) => CanRenderToggleControl(rows, member); public static bool CanRenderInviteControl( MembersRowsViewModel rows, MemberModel member) => RestrictAdminSelfDelete(rows, member) && RestrictInvite(rows); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Canal : MonoBehaviour { public GameObject gatePrefab; public GameObject waterPrefab; public GameObject boatPrefab; public int NumeroDeCompuertas = 3; public float wOffset = 10; public float hOffset = 3; private List<Gate> gates; private List<Water> waters; private Vector3 start; private Vector3 end; // Start is called before the first frame update void Start() { //Creating start water GameObject go = Instantiate(waterPrefab, Vector3.zero, Quaternion.identity); } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using SmartHome.Service.Response; using SmartHome.Model; namespace SmartHome.Droid.Common { class HouseAdapter : BaseAdapter<House> { Activity currentContext; List<House> lstHouse; public HouseAdapter(Activity currentContext, List<House> lstHouse) { this.currentContext = currentContext; this.lstHouse = lstHouse; } public override long GetItemId(int position) { return position; } public override View GetView(int position, View convertView, ViewGroup parent) { var item = lstHouse[position]; if (convertView == null) convertView = currentContext.LayoutInflater.Inflate(Resource.Layout.HouseGridViewItem, null); //else //{ convertView.FindViewById<TextView>(Resource.Id.txtName).Text = item.name; convertView.FindViewById<TextView>(Resource.Id.txtHouseId).Text = item.houseId; //convertView.FindViewById<ImageView>(Resource.Id.img).SetImageResource(Resource.Drawable.monkey); //} return convertView; } //Fill in cound here, currently 0 public override int Count { get { return lstHouse == null ? -1 : lstHouse.Count; } } public override House this[int position] { get { return lstHouse == null ? null : lstHouse[position]; } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace CMS.Models { public class Project { public int Id { get; set; } [Display(Name = "Project Name"), DataType(DataType.Text, ErrorMessage = "Project name is invalid!")] public string ProjectName { get; set; } [Display(Name = "Project Description"), DataType(DataType.Text, ErrorMessage = "Project description is invalid!")] public string ProjectDesc { get; set; } [Display(Name = "Project Image"), DataType(DataType.ImageUrl, ErrorMessage = "Project image is invalid!")] public string ProjectImage { get; set; } [Display(Name = "Post Date"), DataType(DataType.DateTime, ErrorMessage = "Project date is invalid!")] public DateTime PostedOn { get; set; } } }
using UnityEngine; public enum Direction { North, NorthEast, East, SouthEast, South, SouthWest, West, NorthWest } public static class Directions { public const int Count = 8; public static Direction Opposite (this Direction original) { return (Direction)(((int)original + (Count / 2)) % Count); } public static Direction Clockwise (this Direction original, bool majorOnly = true) { if (majorOnly) { // Return next major direction return (Direction)((((int)original + 2) / 2 * 2) % Count); } else { // Return next whatever direction return (Direction)(((int)original + 1) % Count); } } public static bool IsHorizontal (this Direction direction) { return direction == Direction.East || direction == Direction.West; } public static bool IsVertical (this Direction direction) { return direction == Direction.North || direction == Direction.South; } private static readonly Vector2Int[] vector2IntArray = { Vector2Int.up, Vector2Int.up + Vector2Int.right, Vector2Int.right, Vector2Int.right + Vector2Int.down, Vector2Int.down, Vector2Int.down + Vector2Int.left, Vector2Int.left, Vector2Int.left + Vector2Int.up }; public static Vector2Int ToVector2Int (this Direction direction) { return vector2IntArray [(int)direction]; } // Does this make even sense public static int Sign (this Direction direction) { return (int)direction < Count / 2 ? 1 : -1; } }
using UnityEngine; public class ARCamera : MonoBehaviour { public IARCamera Camera { get { if (arCamera == null) SetARCamera(); return arCamera; } } // For debugging, use this texture in editor instead of the camera feed public Texture defaultTexture; private IARCamera arCamera; private void SetARCamera() { #if UNITY_ANDROID && !UNITY_EDITOR arCamera = gameObject.AddComponent<ARCoreCamera>(); #elif UNITY_IOS && !UNITY_EDITOR ARKitCamera arkitCamera = gameObject.AddComponent<ARKitCamera>(); var arVideo = UnityEngine.Camera.main.GetComponent<UnityEngine.XR.iOS.UnityARVideo>(); Debug.Assert(arVideo); arkitCamera.clearMaterial = arVideo.m_ClearMaterial; arCamera = arkitCamera; #else AREditorCamera editorCamera = gameObject.AddComponent<AREditorCamera> (); editorCamera.defaultTexture = defaultTexture; arCamera = editorCamera; #endif Debug.Assert(arCamera!=null); } }
using System; using System.Collections.Generic; using ServiceDesk.Ticketing.Domain.CategoryAggregate; using ServiceDesk.Ticketing.Domain.TaskAggregate; using ServiceDesk.Ticketing.Domain.TicketComment; using ServiceDesk.Ticketing.Domain.UserAggregate; namespace ServiceDesk.Ticketing.Domain.TicketAggregate { public class TicketState { public Guid Id { get; set; } public int TicketNumber { get; set; } public string Description { get; set; } public string Title { get; set; } public TicketStatus Status { get; set; } public TicketPriority Priority { get; set; } public TicketType Type { get; set; } public DateTime? DueDate { get; set; } public string ResolutionComments { get; set; } public Requestor Requestor { get; set; } public DateTime RequestedDate { get; set; } public virtual UserState AssignedTo { get; set; } public virtual CategoryState Category { get; set; } public virtual List<TaskState> Tasks { get; set; } public virtual List<TicketCommentState> Comments { get; set; } public Ticket ToTicket() { return new Ticket(this); } public static Ticket ToTicket(TicketState state) { return new Ticket(state); } } }
using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Extensions.DurableTask; using Microsoft.Extensions.Logging; using System; using System.IO; using System.Threading.Tasks; namespace AzureAI.CallCenterTalksAnalysis.FunctionApps.Functions { public class MediaFileTrigger { [FunctionName("func-media-file-trigger")] public async Task RunAsync([BlobTrigger("files-for-analysis/{name}", Connection = "BlobStorageConnectionString")] Stream fileForAnalysis, string name, Uri uri, [DurableClient] IDurableOrchestrationClient starter, ILogger log) { log.LogInformation($"C# Blob trigger function Processed blob\n Name:{name} \n Size: {fileForAnalysis.Length} Bytes"); string instanceId = await starter.StartNewAsync("func-file-analysis-orchestrator", null, uri.ToString()); log.LogInformation($"Started orchestration with ID = '{instanceId}'."); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GuessTheNumberGame : MonoBehaviour { public InputField input; public Text infoText; private int GuessNumber; private int userGuess; // Start is called before the first frame update void Start() { GuessNumber = Random.Range(0, 100); } public void CheckGuess() { userGuess = int.Parse(input.text); if (userGuess == GuessNumber) { infoText.text = "You guessed the number, it is " + userGuess; } else if (userGuess > GuessNumber) { infoText.text = "You guess is "+ userGuess + " and it is grater than the guessed number"; } else if (userGuess < GuessNumber) { infoText.text = "You guess is " + userGuess + " and it is lower than the guessed number"; } input.text = ""; } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using SimpleIO; using System.Threading; namespace Ajustador_Calibrador_ADR3000.Devices { /// <summary> /// Class to perform configurations on the 5 outputs transformer command circuit /// </summary> public class Transformer5Out { /// <summary> /// Time to wait for the relay to turn off /// </summary> private const int _RELAY_OFF_TIME_MS_ = 55; /// <summary> /// Time to wait for the relay to turn on /// </summary> private const int _RELAY_ON_TIME_MS_ = 500; /// <summary> /// No voltage, open circuit /// </summary> public const uint _TRANSFORMER_OFF_ = 0x0F; /// <summary> /// RL5 - 100 V /// </summary> public const uint _TRANSFORMER_100V_ = 0x0C; /// <summary> /// RL4 - 120 V /// </summary> public const uint _TRANSFORMER_120V_ = 0x04; /// <summary> /// RL3 - 180 V /// </summary> public const uint _TRANSFORMER_180V_ = 0x01; /// <summary> /// RL2 - 220 V /// </summary> public const uint _TRANSFORMER_220V_ = 0x08; /// <summary> /// RL1 - 240 V /// </summary> public const uint _TRANSFORMER_240V_ = 0x05; /// <summary> /// Get the output value for the MCP2200 pins according to a real voltage level /// </summary> /// <param name="voltage">The voltage level</param> /// <returns>MCP2200 gpio value</returns> public static uint GetVoltageDiscreteLevel(float voltage) { if (voltage <= 100) return _TRANSFORMER_100V_; else if ((voltage > 100) && (voltage <= 120)) return _TRANSFORMER_120V_; else if ((voltage > 120) && (voltage <= 180)) return _TRANSFORMER_180V_; else if ((voltage > 180) && (voltage <= 220)) return _TRANSFORMER_220V_; else return _TRANSFORMER_240V_; } /// <summary> /// Get the real voltage value according to a MCP2200 gpio value /// </summary> /// <param name="discreteLevel">MCP2200 gpio value</param> /// <returns>Real voltage value</returns> public static float GetVoltageRealValue(uint discreteLevel) { switch (discreteLevel) { case _TRANSFORMER_100V_: return 100.0f; case _TRANSFORMER_120V_: return 120.0f; case _TRANSFORMER_180V_: return 180.0f; case _TRANSFORMER_220V_: return 220.0f; case _TRANSFORMER_240V_: return 240.0f; default: return 0.0f; } } /// <summary> /// Set the MCP2200 gpio to wanted value /// </summary> /// <param name="output">Wanted value</param> public static void EnableOutput(uint output) { SimpleIOClass.WritePort(_TRANSFORMER_OFF_); Thread.Sleep(_RELAY_OFF_TIME_MS_); SimpleIOClass.WritePort(output); Thread.Sleep(_RELAY_ON_TIME_MS_); } } }
using System; namespace SocketProxy.Decoders { public class Packet { public PacketType Type; public int Id; public int RequestId; public object CommandKey; public byte[] Bytes; public object Data; public T GetData<T>() where T : class => Data as T; public object Content; public Type ContentType; public T ContentAs<T>() where T : class => Content as T; } public class Packet<T> where T : class { public Packet(Packet packet) { CommandKey = packet.CommandKey; Content = packet.ContentAs<T>(); } public object CommandKey { get; } public T Content { get; } } }
using FluentNHibernate.Automapping; using FluentNHibernate.Automapping.Alterations; using Profiling2.Domain.Prf.Sources; namespace Profiling2.Infrastructure.NHibernateMaps.Overrides { public class SourceMappingOverride : IAutoMappingOverride<Source> { public void Override(AutoMapping<Source> mapping) { // 2013-03-16 currently breaks audit of PersonSource.SourceID field with 'no persister for SourceProxy' exception. //mapping.Map(x => x.FileData).LazyLoad(); mapping.HasMany<SourceRelationship>(x => x.SourceRelationshipsAsParent) .KeyColumn("ParentSourceID") .Cascade.AllDeleteOrphan() .Inverse(); mapping.HasMany<SourceRelationship>(x => x.SourceRelationshipsAsChild) .KeyColumn("ChildSourceID") .Cascade.AllDeleteOrphan() .Inverse(); mapping.HasManyToMany<SourceAuthor>(x => x.SourceAuthors) .Table("PRF_SourceAuthorSource") .ParentKeyColumn("SourceID") .ChildKeyColumn("SourceAuthorID") .AsBag(); mapping.HasManyToMany<SourceOwningEntity>(x => x.SourceOwningEntities) .Table("PRF_SourceOwner") .ParentKeyColumn("SourceID") .ChildKeyColumn("SourceOwningEntityID") .AsBag(); } } }
namespace MQTTnet.Server { public sealed class GetSubscribedMessagesFilter { public bool IsNewSubscription { get; set; } public MqttTopicFilter TopicFilter { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace negyedik_feladat { class Program { static void Main(string[] args) { int bekertSzam; int negyzetreEmeltSzam; int egymassalSzorozva; Console.WriteLine("Kérek egy számot!"); bekertSzam = Convert.ToInt32(Console.ReadLine()); negyzetreEmeltSzam = Convert.ToInt32(Math.Pow(bekertSzam, 2)); egymassalSzorozva = bekertSzam * bekertSzam; Console.WriteLine("\nMath.Pow() függvénnyel"); Console.WriteLine(negyzetreEmeltSzam); Console.WriteLine("\nSimán összeszorozva egymással"); Console.WriteLine(egymassalSzorozva); Console.ReadKey(); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Text; 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.Navigation; using System.Windows.Shapes; using System.Linq; using System.Windows.Threading; using SCITSchedule.Properties; using System.Windows.Forms; using System.Drawing; namespace SCITSchedule { /// <summary> /// MainWindow.xaml에 대한 상호 작용 논리 /// </summary> public partial class MainWindow : Window { WebClient wc = null; List<string> filters = new List<string>(); NotifyIcon ni = new NotifyIcon(); DispatcherTimer timer = null; const int MAX_TIME = 15; const string TITLE_DESC = " - 트레이아이콘 복원 문제 해결, 스플리터 해결 180515"; string titledef = "Hi " + System.Reflection.Assembly.GetExecutingAssembly().GetName().Version.ToString()+TITLE_DESC+": "; int refTimer = MAX_TIME; public MainWindow() { InitializeComponent(); Title = titledef + "Ready"; tboxFilter.Text = Settings.Default.filter; chkFilter.IsChecked = Settings.Default.invisible; filters = tboxFilter.Text.Split(',').ToList(); DataForming.OnChanged += DataForming_OnChanged; String lastfile = null; try { lastfile = System.IO.File.ReadAllText(@"lastlist.txt"); } catch { Debug.WriteLine("NO LAST FILE: First run?"); } if (lastfile != null) DataForming.SelectAll(lastfile, true); ni.BalloonTipClicked += Ni_DoubleClick; ni.DoubleClick += Ni_DoubleClick; ni.MouseClick += Ni_MouseClick; System.Windows.Forms.ContextMenu ct = new System.Windows.Forms.ContextMenu(); ct.MenuItems.Add("보기", (o, e) => { if (WindowState == WindowState.Minimized) { WindowState = WindowState.Normal; } Show(); Activate(); }); ct.MenuItems.Add("정보", (o, e) => { System.Windows.MessageBox.Show("Created by Jinbaek Lee","SCITSchedule Hi 2018"); }); ct.MenuItems.Add("-"); ct.MenuItems.Add("종료", (o, e) => { Close(); }); ni.ContextMenu = ct; string[] args = Environment.GetCommandLineArgs(); if (args.Contains("-h")) { Hide(); } ni.Icon = System.Drawing.Icon.ExtractAssociatedIcon( System.Reflection.Assembly.GetEntryAssembly().ManifestModule.Name); ni.Visible = true; } private void Ni_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e) { if(e.Button != MouseButtons.Right) { if (IsVisible) { Hide(); } else { if (WindowState == WindowState.Minimized) { WindowState = WindowState.Normal; } Show(); Activate(); } } } private void Ni_DoubleClick(object sender, EventArgs e) { if (IsVisible) { Activate(); } else { if (WindowState == WindowState.Minimized) { WindowState = WindowState.Normal; } Show(); Activate(); } } protected override void OnStateChanged(EventArgs e) { if(WindowState == WindowState.Minimized) { this.Hide(); } base.OnStateChanged(e); } private void DataForming_OnChanged(object sender, EventArgs e) { if(sender != null) { List<Appointment> lst = (List<Appointment>)sender; StringBuilder sbLog = new StringBuilder(); ni.BalloonTipTitle = "스케쥴 변경됨"; sbLog.AppendLine(DateTime.Now.ToShortTimeString()+": 하기 내용으로 추가/변경됨"); if(lst.Count == 0) { ni.BalloonTipText = "새로 추가된 항목은 없으나 변경되었습니다."; sbLog.AppendLine("일부 삭제되었거나 신규 추가 내용 없이 변경됨"); } StringBuilder sb = new StringBuilder(); foreach(Appointment a in lst) { sb.AppendLine(string.Format("*{1}:{0}:{2}",a.date_start,a.schedule_title,a.schedule_content)); sbLog.AppendLine(string.Format("*{1}:{0}:{2}", a.date_start, a.schedule_title, a.schedule_content)); } if(sb.Length > 0) { ni.BalloonTipText = sb.ToString(); lvLog.Items.Add(sbLog.ToString()); lvLog.SelectedIndex = lvLog.Items.Count - 1; ni.ShowBalloonTip(100000); } } } private void Timer_Tick(object sender, EventArgs e) { Title = titledef + refTimer+"s remaining"; if (refTimer <= 0) { refTimer = MAX_TIME; timer.Stop(); DownloadData(); } else { refTimer--; } } private void Wc_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e) { //Debug.WriteLine(e.Error?.ToString() ?? "NOERROR"); if (e.Error is WebException && ((WebException)e.Error).Status == WebExceptionStatus.RequestCanceled) { Title = titledef + "RETRY"; Debug.WriteLine(e.Error?.ToString() ?? "NON ERROR ABORT"); DownloadData(); return; } timer.Start(); if (e.Error != null) { /*lvLog.Items.Add(DateTime.Now.ToShortTimeString()+" "+(e.Cancelled?"사용자 취소":"통신 오류")+": "+e.Error.ToString()); lvLog.SelectedIndex = lvLog.Items.Count - 1;*/ Debug.WriteLine(e.Error.ToString()); Title = titledef + "Comm Error!!"; return; } Title = titledef + "Finished"; Encoding en = new UTF8Encoding(); string res = en.GetString(e.Result); DataForming.SelectAll(res); FillCalendar(); if (wc != null) { wc.Dispose(); wc = null; } } private void DownloadData() { Title = titledef+"Downloading..."; wc = new WebClient(); wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore); wc.UploadDataCompleted += Wc_UploadDataCompleted; wc.UploadDataAsync(new Uri("http://sesoc.global/society_mypage/selectAllSchedule"), new byte[] { }); } public void FillCalendar() { lvSchedule.Items.Clear(); if(DataForming.List != null) { int rownum = 1; foreach(Appointment a in DataForming.List){ a.Highlight = false; bool isfound = false; if(filters != null && filters.Any(s => a.schedule_title.ToLower().Contains(s.ToLower()))) { a.Highlight = filters.Count > 0 && (filters.FirstOrDefault(each=>each.Length == 0) != ""); isfound = true; } if (!chkFilter.IsChecked.GetValueOrDefault() ||(chkFilter.IsChecked.GetValueOrDefault() && isfound)) { //필터 옵션이 꺼져있거나, 필터 옵션이 켜있으며 검색이 성공한 경우에 추가 a.RowNum = rownum++; lvSchedule.Items.Add(a); } } } } private void tboxFilter_TextChanged(object sender, TextChangedEventArgs e) { if (DataForming.List != null) { filters = tboxFilter.Text.Split(',').ToList(); FillCalendar(); Settings.Default.filter = tboxFilter.Text; Settings.Default.Save(); } } private void chkFilter_Checked(object sender, RoutedEventArgs e) { Settings.Default.invisible = chkFilter.IsChecked == true; Settings.Default.Save(); if (DataForming.List != null) { FillCalendar(); } } private void Window_Activated(object sender, EventArgs e) { if (DataForming.List == null) { DownloadData(); timer = new DispatcherTimer(); timer.Interval = new TimeSpan(0, 0, 1); timer.Tick += Timer_Tick; timer.Start(); } } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (System.Windows.MessageBox.Show("종료하면 다음 실행시까지 알림을 받을 수 없어요."+Environment.NewLine+"그래도 끄시겠어요?", "SCITSchedule 2018", MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.No)==MessageBoxResult.No) { e.Cancel = true; } } } }
// Copyright © 2020 Void-Intelligence All Rights Reserved. using Nomad.Core; using Vortex.Regularization.Utility; namespace Vortex.Regularization.Kernels { /// <summary> /// Ridge Regularization /// </summary> public sealed class L2 : BaseRegularization { public L2(double lambda = 1) : base(lambda) { } public override double CalculateNorm(Matrix input) { return input.EuclideanNorm() * Lambda; } public override ERegularizationType Type() { return ERegularizationType.L2; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Data.SqlClient; namespace PROG1_PROYECTO_FINAL { public partial class C_Child_Pedidos : Form { //DB private Connection conexion = new Connection(); private string query; SqlDataAdapter adpt; DataTable dt; //INSTANSEAS Cliente cliente = new Cliente_Regular(); Facturas facturas = new Facturas(); public C_Child_Pedidos() { InitializeComponent(); } private void C_Child_Pedidos_Load(object sender, EventArgs e) { ComboBoxCliente_Load(); ComboBoxProducto_Load(); CleanForm(); } private void ComboBoxCliente_Load() { try { //CLIENTES query = "SELECT * FROM Clientes"; adpt = new SqlDataAdapter(query, conexion.AbrirConexion()); dt = new DataTable(); adpt.Fill(dt); comboBxCliente.DataSource = dt; comboBxCliente.DisplayMember = "nombre"; comboBxCliente.ValueMember = "cl_id"; } catch (Exception) { } } private void ComboBoxProducto_Load() { try { //PRODUCTOS query = "SELECT Prod.nombre, I.prod_id FROM Inventario AS I " + $"INNER JOIN Productos AS Prod ON I.prod_id = Prod.prod_id;"; adpt = new SqlDataAdapter(query, conexion.AbrirConexion()); dt = new DataTable(); adpt.Fill(dt); comboBxProducto.DataSource = dt; comboBxProducto.DisplayMember = "nombre"; comboBxProducto.ValueMember = "prod_id"; } catch (Exception) { } } private void comboBxProducto_SelectedIndexChanged(object sender, EventArgs e) { try { //CANTIDAD DEL PRODUCTO query = "SELECT I.cantidad FROM Productos AS Prod " + $"INNER JOIN Inventario AS I ON I.prod_id = Prod.prod_id WHERE Prod.nombre = '{comboBxProducto.Text}';"; SqlCommand cmd = new SqlCommand(query, conexion.AbrirConexion()); SqlDataReader data = cmd.ExecuteReader(); while (data.Read()) { cantidadProducto.Text = data.GetValue(0).ToString(); } conexion.CerrarConexion(); } catch (Exception) { } } private void comboBxCliente_SelectedIndexChanged(object sender, EventArgs e) { try { //CATEGORIAS query = "SELECT Cat.nombre FROM Clientes AS Cliente " + $"INNER JOIN CategoriasClientes AS Cat ON Cliente.categoria_id = Cat.categoria_id WHERE cl_id = {comboBxCliente.SelectedValue};"; SqlCommand cmd = new SqlCommand(query, conexion.AbrirConexion()); SqlDataReader data = cmd.ExecuteReader(); while (data.Read()) { categoriaCliente.Text = data.GetValue(0).ToString(); } conexion.CerrarConexion(); } catch (Exception) { } } private void getTotal() { query = $"SELECT SUM({cantidad.Value}*p.precio) FROM Productos AS p WHERE prod_id = {comboBxProducto.SelectedValue}"; SqlCommand cmd = new SqlCommand(query, conexion.AbrirConexion()); SqlDataReader data = cmd.ExecuteReader(); while (data.Read()) { precioXcantidad.Text = data.GetValue(0).ToString(); } conexion.CerrarConexion(); } private void iconBtnInsert_Click(object sender, EventArgs e) { try { getTotal(); switch (categoriaCliente.Text) { case "Premium": cliente = new Cliente_Premium(); MessageBox.Show("Haz elegido un Cliente Premium, se le aplicará un descuento de 5%."); break; case "Regular": cliente = new Cliente_Regular(); MessageBox.Show("Haz elegido un Cliente Regular."); break; default: MessageBox.Show("Elija un cliente hasta que cambie el tipo"); break; } facturas.Crear(comboBxCliente.SelectedValue.ToString(), comboBxProducto.SelectedValue.ToString(), cantidad.Value, 0, cliente.Descuento(Convert.ToDouble(precioXcantidad.Text)), "", 0); //GENERANDO FACTURA Factura_Generada factura = new Factura_Generada(); factura.ShowDialog(); CleanForm(); } catch (Exception err) { MessageBox.Show(err.Message); } } private void CleanForm() { comboBxCliente.SelectedIndex = -1; comboBxProducto.SelectedIndex = -1; } private void iconBtnEntradas_Click(object sender, EventArgs e) { Facturas_Modal modal = new Facturas_Modal(); modal.Owner = this; // we want the new form to float on top of this one modal.Show(); } } }
using System.Web.Mvc; using DevExpress.Web.Mvc; using System.Collections; using System.Linq; using DevExpress.Web.Demos.Models; using DevExpress.Data; namespace DevExpress.Web.Demos { public partial class GridViewController: DemoController { public ActionResult AdvancedCustomBinding() { return DemoView("AdvancedCustomBinding"); } public ActionResult AdvancedCustomBindingPartial() { var viewModel = GridViewExtension.GetViewModel("gridView"); if(viewModel == null) viewModel = CreateGridViewModelWithSummary(); return AdvancedCustomBindingCore(viewModel); } // Paging public ActionResult AdvancedCustomBindingPagingAction(GridViewPagerState pager) { var viewModel = GridViewExtension.GetViewModel("gridView"); viewModel.Pager.Assign(pager); return AdvancedCustomBindingCore(viewModel); } // Filtering public ActionResult AdvancedCustomBindingFilteringAction(GridViewColumnState column) { var viewModel = GridViewExtension.GetViewModel("gridView"); viewModel.Columns[column.FieldName].Assign(column); return AdvancedCustomBindingCore(viewModel); } // Sorting public ActionResult AdvancedCustomBindingSortingAction(GridViewColumnState column, bool reset) { var viewModel = GridViewExtension.GetViewModel("gridView"); viewModel.SortBy(column, reset); return AdvancedCustomBindingCore(viewModel); } // Grouping public ActionResult AdvancedCustomBindingGroupingAction(GridViewColumnState column) { var viewModel = GridViewExtension.GetViewModel("gridView"); viewModel.Columns[column.FieldName].Assign(column); return AdvancedCustomBindingCore(viewModel); } PartialViewResult AdvancedCustomBindingCore(GridViewModel viewModel) { viewModel.ProcessCustomBinding( GridViewCustomBindingHandlers.GetDataRowCountAdvanced, GridViewCustomBindingHandlers.GetDataAdvanced, GridViewCustomBindingHandlers.GetSummaryValuesAdvanced, GridViewCustomBindingHandlers.GetGroupingInfoAdvanced, GridViewCustomBindingHandlers.GetUniqueHeaderFilterValuesAdvanced ); return PartialView("AdvancedCustomBindingPartial", viewModel); } static GridViewModel CreateGridViewModelWithSummary() { var viewModel = new GridViewModel(); viewModel.KeyFieldName = "ID"; viewModel.Columns.Add("From"); viewModel.Columns.Add("Subject"); viewModel.Columns.Add("Sent"); viewModel.Columns.Add("Size"); viewModel.Columns.Add("HasAttachment"); viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Size", SummaryType = SummaryItemType.Sum }); viewModel.TotalSummary.Add(new GridViewSummaryItemState() { FieldName = "Subject", SummaryType = SummaryItemType.Count }); viewModel.GroupSummary.Add(new GridViewSummaryItemState() { FieldName = string.Empty, SummaryType = SummaryItemType.Count }); return viewModel; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using Xlns.BusBook.Core.Model; namespace Xlns.BusBook.UI.Web.Models { public class AllegatoViewModel { public virtual Viaggio Viaggio { get; set; } public virtual TipoAllegato Tipo { get; set; } public String Errore { get; set; } public enum TipoAllegato { DEPLIANT, IMMAGINE} } }
using DataLibrary.Models; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataLibrary.Models { public class IssueModel //Logic Model { public int Id { get; set; } public string ProjectName { get; set; } public string CreatedBy { get; set; } public string IssueType { get; set; } public string Summary { get; set; } public string Description { get; set; } public string Priority { get; set; } //public ArrayList Labels { get; set; } public string Environment { get; set; } public IssueModel() { } public IssueModel(string projectName, string createdBy, string issueType, string summary, string description, string priority, string environmentDetails) { ProjectName = projectName; CreatedBy = createdBy; IssueType = issueType; Summary = summary; Description = description; Priority = priority; Environment = environmentDetails; } } }
 using System; using System.Collections.Generic; using System.Text; namespace EmberMemory.Listener { public class PorcessListenerConfiguration { public int SearchDelay { get; set; } = 1000; } }
namespace TripDestination.Data.Models { using Common.Models; using System.ComponentModel.DataAnnotations; using TripDestination.Common.Infrastructure.Constants; public abstract class BaseComment : BaseModel<int> { [Required] public string AuthorId { get; set; } public virtual User Author { get; set; } [Required] [MinLength(ModelConstants.CommentTextMinLength, ErrorMessage = "Comment text can no be less than 5 symbols long.")] [MaxLength(ModelConstants.CommentTextMaxLength, ErrorMessage = "Comment text can no be more than 1000 symbosl long,")] public string Text { get; set; } } }
using Com.Colin.Forms.Common; using Com.Colin.Forms.Properties; using System.Drawing; using System.Windows.Forms; namespace Com.Colin.Forms.Template { public partial class TestCenter : UserControl { public TestCenter() { InitializeComponent(); } private void panel6_Paint(object sender, PaintEventArgs e) { CommonFuc.drawHRV(panel6, e.Graphics); } private void panel7_Paint(object sender, PaintEventArgs e) { // 画图 int baseHeight = panel6.Height; int baseWidth = panel6.Width; int top = (int)(baseHeight * 0.1); int left = (int)(baseWidth * 0.1); Font font = new Font("微软雅黑", 12); Pen pen = Pens.Black; // 即时心率 e.Graphics.DrawString("即时心率", font, Brushes.Black, left - 25, top); SizeF sizeF = e.Graphics.MeasureString("即时心率", font); font = new Font("微软雅黑", 24, FontStyle.Bold); SizeF sizeF2 = e.Graphics.MeasureString("80", font); e.Graphics.DrawString("80", font, Brushes.Black, left - 25 - (sizeF2.Width - sizeF.Width) / 2, (float)(baseHeight * 0.20)); // 即时心能量 font = new Font("微软雅黑", 12); sizeF2 = e.Graphics.MeasureString("即时心能量", font); e.Graphics.DrawString("即时心能量", font, Brushes.Black, left - 25 - (sizeF2.Width - sizeF.Width) / 2, (float)(baseHeight * 0.5)); e.Graphics.DrawImage(Resources._0130切片_09, new Rectangle((int)(left - 80 + sizeF.Width / 2), (int)(baseHeight * 0.65), 110, 60)); // 心能量比例 e.Graphics.DrawString("心能量比例", font, Brushes.Black, (float)(baseWidth * 0.4), top); sizeF = e.Graphics.MeasureString("心能量比例", font); //e.Graphics.DrawEllipse(pen, (float)(baseWidth * 0.4) - (top * 7 - sizeF.Width) / 2, (float)(baseHeight * 0.20), top * 7, top * 7); //e.Graphics.DrawEllipse(pen, (float)(baseWidth * 0.4 - top + sizeF.Width / 2), (float)(baseHeight * 0.20 + top * 2.5), top * 2, top * 2); e.Graphics.DrawEllipse(pen, (float)(baseWidth * 0.4 - top * 1.5 + sizeF.Width / 2), (float)(baseHeight * 0.20 + top * 2), (top * 3), (top * 3)); //e.Graphics.DrawPie(pen, (float)(baseWidth * 0.4) - (top * 7 - sizeF.Width) / 2, (float)(baseHeight * 0.20), top * 7, top * 7, -260, 180); //e.Graphics.DrawPie(pen, (float)(baseWidth * 0.4) - (top * 7 - sizeF.Width) / 2, (float)(baseHeight * 0.20), top * 7, top * 7, -80, 80); //e.Graphics.DrawPie(pen, (float)(baseWidth * 0.4) - (top * 7 - sizeF.Width) / 2, (float)(baseHeight * 0.20), top * 7, top * 7, 0, 100); TextureBrush brush = new TextureBrush(Resources._0130切片_61); e.Graphics.FillPie(brush, (float)(baseWidth * 0.4) - (top * 7 - sizeF.Width) / 2, (float)(baseHeight * 0.20), top * 7, top * 7, -260, 180); brush = new TextureBrush(Resources._0130切片_61_2); e.Graphics.FillPie(brush, (float)(baseWidth * 0.4 - top + sizeF.Width / 2-10), (float)(baseHeight * 0.20 + top * 2.5 -10), top * 2+20, top * 2+20, -260, 180); brush = new TextureBrush(Resources._0130切片_67); e.Graphics.FillPie(brush, (float)(baseWidth * 0.4) - (top * 7 - sizeF.Width) / 2, (float)(baseHeight * 0.20), top * 7, top * 7, -80, 80); brush = new TextureBrush(Resources._0130切片_67_2); e.Graphics.FillPie(brush, (float)(baseWidth * 0.4 - top + sizeF.Width / 2 - 10), (float)(baseHeight * 0.20 + top * 2.5 - 10), top * 2 + 20, top * 2 + 20, -80, 80); brush = new TextureBrush(Resources._0130切片_72); e.Graphics.FillPie(brush, (float)(baseWidth * 0.4) - (top * 7 - sizeF.Width) / 2, (float)(baseHeight * 0.20), top * 7, top * 7, 0, 100); brush = new TextureBrush(Resources._0130切片_72_2); e.Graphics.FillPie(brush, (float)(baseWidth * 0.4 - top + sizeF.Width / 2 - 10), (float)(baseHeight * 0.20 + top * 2.5 - 10), top * 2 + 20, top * 2 + 20, 0, 100); e.Graphics.FillEllipse(Brushes.White, (float)(baseWidth * 0.4 - top + sizeF.Width / 2), (float)(baseHeight * 0.20 + top * 2.5), top * 2, top * 2); // 心能量指数 e.Graphics.DrawString("心能量指数", font, Brushes.Black, (float)(baseWidth * 0.8), top); font = new Font("微软雅黑", 10); pen = new Pen(Color.LightGray, 1); e.Graphics.DrawRectangle(pen, (float)(baseWidth * 0.725 + sizeF.Width / 2), (float)(baseHeight * 0.20), (float)(baseWidth * 0.15), (float)(baseHeight * 0.7)); StringFormat sf = StringFormat.GenericDefault; sf.Alignment = StringAlignment.Far; // 画Y轴 for (int j = 0; j < 6; j++) { e.Graphics.DrawLine(pen, (float)(baseWidth * 0.725 + sizeF.Width / 2 - 5), (float)(baseHeight * 0.9 - j * 0.19 * baseHeight * 0.7), (float)(baseWidth * 0.875 + sizeF.Width / 2), (float)(baseHeight * 0.9 - j * 0.19 * baseHeight * 0.7)); e.Graphics.DrawString(20 * j + "", font, Brushes.Black, (float)(baseWidth * 0.725 + sizeF.Width / 2 - 10), (float)(baseHeight * 0.9 - j * 0.19 * baseHeight * 0.7) - 5, sf); } // 高能量、中能量、低能量 e.Graphics.DrawImage(Resources._0130切片_61, new Rectangle((int)((baseWidth * 0.4) + (top * 7 + sizeF.Width) / 2 + 15), (int)(baseHeight * 0.65), 10, 10)); e.Graphics.DrawImage(Resources._0130切片_67, new Rectangle((int)((baseWidth * 0.4) + (top * 7 + sizeF.Width) / 2 + 15), (int)(baseHeight * 0.75), 10, 10)); e.Graphics.DrawImage(Resources._0130切片_72, new Rectangle((int)((baseWidth * 0.4) + (top * 7 + sizeF.Width) / 2 + 15), (int)(baseHeight * 0.85), 10, 10)); e.Graphics.DrawString("高能量", font, Brushes.Black, (float)(baseWidth * 0.4) + (top * 7 + sizeF.Width) / 2 + 30, (float)(baseHeight * 0.65)); e.Graphics.DrawString("中能量", font, Brushes.Black, (float)(baseWidth * 0.4) + (top * 7 + sizeF.Width) / 2 + 30, (float)(baseHeight * 0.75)); e.Graphics.DrawString("低能量", font, Brushes.Black, (float)(baseWidth * 0.4) + (top * 7 + sizeF.Width) / 2 + 30, (float)(baseHeight * 0.85)); } } }
using MChooser.UI; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace MChooser.Execution { public class ExecutionController { SelectionForm SelectionForm; AddMechForm AddMechForm; MechCountForm MechCountForm; public ExecutionController() { this.SelectionForm = new SelectionForm(SwitchToAddMechWindow, SwitchToMechCountWindow); this.AddMechForm = new AddMechForm(SwitchToSelectionWindow, SwitchToMechCountWindow); this.MechCountForm = new MechCountForm(SwitchToSelectionWindow, SwitchToAddMechWindow); Application.Run(SelectionForm); } public void SwitchToAddMechWindow() { this.SelectionForm.Hide(); this.MechCountForm.Hide(); this.AddMechForm.Show(); } public void SwitchToSelectionWindow() { this.SelectionForm.Show(); this.AddMechForm.Hide(); this.MechCountForm.Hide(); } public void SwitchToMechCountWindow() { this.SelectionForm.Hide(); this.AddMechForm.Hide(); this.MechCountForm.Show(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.AzureAD.UI; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authentication.OpenIdConnect; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Formatters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Newtonsoft.Json.Serialization; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc.Authorization; using Microsoft.EntityFrameworkCore; using Vereyon.Web; using AutoMapper; using DemoApp.Entities; using DemoApp.Services; using DemoApp.ServiceMappers; namespace DemoApp { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.Unspecified; // Handling SameSite cookie according to https://docs.microsoft.com/en-us/aspnet/core/security/samesite?view=aspnetcore-3.1 //options.HandleSameSiteCookieCompatibility(); }); services.AddAuthentication(sharedOptions => { sharedOptions.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddAzureAd(options => Configuration.Bind("AzureAd", options)) .AddCookie(); services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options => { options.Authority = options.Authority + "/v2.0/"; // options.TokenValidationParameters.ValidIssuers collection options.TokenValidationParameters.ValidateIssuer = false; }); services.AddHttpCacheHeaders((expirationModelOptions) => { expirationModelOptions.MaxAge = 60; expirationModelOptions.CacheLocation = Marvin.Cache.Headers.CacheLocation.Private; }, (validationModelOption) => { validationModelOption.MustRevalidate = true; }); services.AddResponseCaching(); //use th addController to configure what you want to configure //services.AddControllers(); services.AddControllers(setupAction => { setupAction.ReturnHttpNotAcceptable = true; setupAction.CacheProfiles.Add("240SecondsCacheProfile", new CacheProfile() { Duration = 240 }); }) .AddNewtonsoftJson(setupAction => { setupAction.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver(); }) .AddXmlDataContractSerializerFormatters() .ConfigureApiBehaviorOptions(setupAction => { setupAction.InvalidModelStateResponseFactory = context => { var problemDetailsFactory = context.HttpContext.RequestServices .GetRequiredService<ProblemDetailsFactory>(); var problemDetails = problemDetailsFactory.CreateValidationProblemDetails( context.HttpContext, context.ModelState ); //add additional infor not added by default problemDetails.Detail = "See the error fields for details."; problemDetails.Instance = context.HttpContext.Request.Path; //fill out which status code to use var actionExecutionContext = context as Microsoft.AspNetCore.Mvc.Filters.ActionExecutingContext; //if there are modelstate error & all argument were correct //found/parsed we 're dealing with validation errors if ((context.ModelState.ErrorCount > 0) && (actionExecutionContext?.ActionArguments.Count == context.ActionDescriptor.Parameters.Count)) { problemDetails.Type = "http://documenttrack.waec.org.ng/modelvalidationproblem"; problemDetails.Status = StatusCodes.Status422UnprocessableEntity; problemDetails.Title = "One or more validation error occured"; return new UnprocessableEntityObjectResult(problemDetails) { ContentTypes = { "application/problem+json" } }; } //if one of the arguement was not correctly found/couldn't be found //we are dealing with null/unparsable input problemDetails.Status = StatusCodes.Status400BadRequest; problemDetails.Title = "One or more error on input occured."; return new BadRequestObjectResult(problemDetails) { ContentTypes = { "application/problem+json" } }; }; }); services.Configure<MvcOptions>(config => { var newtonsoftJsonOutputFormatter = config.OutputFormatters .OfType<NewtonsoftJsonOutputFormatter>()?.FirstOrDefault(); if (newtonsoftJsonOutputFormatter != null) { newtonsoftJsonOutputFormatter. SupportedMediaTypes.Add("application/vnd.waec.hateoas+json"); } }); services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //define the connection var connection = Configuration.GetConnectionString("SchoolRecognitionConString"); // Add services required for flash message to work. services.AddFlashMessage(); services.AddDbContext<SchoolRecognitionContext>(options => { options.UseSqlServer(connection); //Enable lazy loading proxies //.UseLazyLoadingProxies(); }); //Register the interfaces services.AddScoped<ICentreRepository, CentreRepository>(); // register PropertyMappingService services.AddTransient<IPropertyMappingService, PropertyMappingService>(); // register PropertyCheckerService services.AddTransient<IPropertyCheckerService, PropertyCheckerService>(); services.AddControllersWithViews(options => { var policy = new AuthorizationPolicyBuilder() .RequireAuthenticatedUser() .Build(); options.Filters.Add(new AuthorizeFilter(policy)); }); services.AddRazorPages(); services.AddSession(options => { options.IdleTimeout = TimeSpan.FromSeconds(10); options.Cookie.HttpOnly = true; options.Cookie.IsEssential = true; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseSession(); app.UseRouting(); app.UseCookiePolicy(); app.UseAuthentication(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); endpoints.MapRazorPages(); }); } } }
using UBaseline.Shared.SvgPanel; using Uintra.Core.Search.Converters.SearchDocumentPanelConverter; using Uintra.Core.Search.Entities; namespace Uintra.Features.Search.Converters.Panel { public class SvgPanelSearchConverter : SearchDocumentPanelConverter<SvgPanelViewModel> { protected override SearchablePanel OnConvert(SvgPanelViewModel panel) { return new SearchablePanel { Title = panel.Title, Content = panel.Description }; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class WellTile : ActiveTile { private void Awake() { //LevelManager.FireTurn += WellTurn; } void WellTurn() { Vector3 wellScale = new Vector3(1.5f, 1.5f, 1.5f); Vector3 addScale = new Vector3(0.1f, 0.1f, 0.1f); if (transform.localScale != wellScale) { transform.localScale += addScale; } else transform.localScale = new Vector3 (1,1,1); } override public void OwnAction (){ print ("its Magic!"); } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace Inventory.Data { public class City : BaseEntity { [Required] [MaxLength(50)] public string Name { get; set; } public virtual ICollection<Address> Addresses { get; set; } public virtual ICollection<Street> Streets { get; set; } public virtual ICollection<Order> Orders { get; set; } } }
// File: Program.cs // Author: Matt Nitzken // <summary> // Class file for Program. // </summary> namespace DisplayTextFile { using System; /// <summary> /// Program that will read a text file and print each line to the console. /// </summary> public static class Program { /// <summary> /// This is the main function that will read and display the file. /// </summary> public static void Main() { string filePath, lineInFile; Console.WriteLine(Properties.Resources.QueryPathPrompt); filePath = Console.ReadLine(); if (System.IO.File.Exists(filePath)) { using (System.IO.StreamReader fileToBeRead = new System.IO.StreamReader(filePath)) { while ((lineInFile = fileToBeRead.ReadLine()) != null) { Console.WriteLine(lineInFile); } } } else { Console.WriteLine(Properties.Resources.ErrorPathDoesNotExist); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace AweShur.Core { public partial class BusinessBase { public virtual void SetNew(bool preserve = false, bool withoutCollections = false) { if (!preserve) { dataItem = Decorator.New(this); } IsNew = true; if (!withoutCollections) { foreach (BusinessCollectionBase col in relatedCollections.Values) { col.SetNew(preserve, withoutCollections); } } PostSetNew(); } public virtual bool ReadFromDB(string key) { if (key.StartsWith("-")) { throw new Exception("Invalid key (" + key + ") for object " + ObjectName + ". Minus char is for new object"); } string[] keys = DataItem.SplitKey(key); if (keys.Length != Decorator.PrimaryKeys.Count) { throw new Exception("Invalid key (" + key + ") for object " + ObjectName); } foreach (int index in Decorator.PrimaryKeys) { Decorator.ListProperties[index].SetValue(this, keys[index]); } return ReadFromDB(); } public virtual bool ReadFromDB(int key) { if (!Decorator.primaryKeyIsOneInt) { throw new Exception("Primary key is not int."); } this[Decorator.PrimaryKeys[0]] = key; return ReadFromDB(); } public virtual bool ReadFromDB(long key) { if (!Decorator.primaryKeyIsOneLong) { throw new Exception("Primary key is not long."); } this[Decorator.PrimaryKeys[0]] = key; return ReadFromDB(); } public virtual bool ReadFromDB(Guid key) { if (!Decorator.primaryKeyIsOneGuid) { throw new Exception("Primary key is not guid."); } this[Decorator.PrimaryKeys[0]] = key; return ReadFromDB(); } public virtual bool ReadFromDB() { bool readed = true; if (!IsNew) { try { CurrentDB.ReadBusinessObject(this); IsNew = false; IsModified = false; IsDeleting = false; AfterReadFromDB(); } catch(Exception exp) { readed = false; } } return readed; } public virtual void AfterReadFromDB() { foreach (BusinessCollectionBase c in relatedCollections.Values) { c.Reset(); } } public virtual void StoreToDB() { LastErrorMessage = ""; LastErrorProperty = ""; if (IsDeleting || IsNew || IsModified) { bool isValidated = IsDeleting ? true : Validate(); if (isValidated) { if (BeforeStoreToDB()) { bool wasNew = IsNew; bool wasModified = IsModified; bool wasDeleting = IsDeleting; if (IsDeleting) { foreach (BusinessCollectionBase col in relatedCollections.Values) { col.SetForDeletion(); col.StoreToDB(); } } CurrentDB.StoreBusinessObject(this); foreach (BusinessCollectionBase col in relatedCollections.Values) { if (col.MustSave) { col.StoreToDB(); } } IsNew = false; IsModified = false; IsDeleting = false; BusinessBaseProvider.ListProvider.Invalidate(ObjectName); AfterStoreToDB(wasNew, wasModified, wasDeleting); } } else { throw new Exception(LastErrorMessage); } } } protected virtual bool BeforeStoreToDB() { return true; } protected virtual void AfterStoreToDB(bool wasNew, bool wasModified, bool wasDeleting) { } public virtual void SetPropertiesFrom(BusinessBase source) { } public virtual void PostSetNew() { } public virtual void CopyTo(BusinessBase Target, List<string> excludeFieldNames) { foreach (PropertyDefinition prop in Decorator.ListProperties) { if (!prop.IsReadOnly && !prop.IsPrimaryKey && (excludeFieldNames == null || (excludeFieldNames != null && !excludeFieldNames.Contains(prop.FieldName)))) { Target[prop.FieldName] = this[prop.FieldName]; } } } } }
using System; namespace NETTRASH.BOT.Telegram.Core.Data { public class Contact { #region Public properties public string phone_number { get; set; } public string first_name { get; set; } public string last_name { get; set; } public UInt64 user_id { get; set; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace GoogleHome.Models { public class LuluVM { public PostLibrary PostLibrary { get; set; } public string NewPost { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Rigidbody2D))] public class Player : MonoBehaviour { //getters as shortcuts variables public Rigidbody2D rb { get { return GetComponent<Rigidbody2D>(); } } public Collider2D coll { get { return GetComponent<PolygonCollider2D>(); } } public TrailRenderer trailRend { get { return GetComponent<TrailRenderer>(); } } public GameObject splash; //this list keeps track of all current player colliders touching this players attack trigger/colliders. private List<Player> collision = new List<Player>(); //A bool to keep track of if the player is alive atm. private bool alive = true; public bool Alive { get { return alive; } } //A bool to keep track of if the player is stunned atm. private bool stunned = false; public bool Stunned { get { return stunned; } } //A bool to keep track of if the player is jumping (aka freefalling in the air) private bool jumping; public bool Jumping { get { return jumping; } } //this players score private int score; public int Score { get { return score; } } //reference to the sprite renderer. public SpriteRenderer playerSprite; public SpriteRenderer playerHeadSprite; //Color getter and setter that actually get/set the color of the player sprite. public Color Color{ set { playerSprite.color = value; } get { return playerSprite.color; } } //variables and references concerning the kick action. float currentKickCooldown = 0; float KickCD = 1.5f; float kickAnimDuration = 0.5f; public GameObject kickWind; public ParticleSystem stun; public UnityEngine.UI.Text kickCoolDownText; //old player options public float kickForce; public float jumpForce; public float stunDuration; public int maxAirJumps; private int airJumps; public float maxRunSpeed; //variable that holds the current would be killer, if the player dies with this variable set, the killer get the score. private Player killer; private void OnTriggerEnter2D(Collider2D target) { //if a player enters this players collider/trigger, add the player to collision list. if (!target.isTrigger && target.tag == "Player" && !collision.Contains(target.GetComponent<Player>())) { collision.Add(target.GetComponent<Player>()); } else if(target.tag == "Ocean") //if this player enters a trigger with the tag ocean, then he dies. { //instantiate a splash. GameObject sp = GameObject.Instantiate(splash); sp.transform.position = this.transform.position; Die(); } } private void OnTriggerExit2D(Collider2D target) { //if a player leaves this players collider/trigger, remove him from the collision list. if (!target.isTrigger && target.tag == "Player" && collision.Contains(target.GetComponent<Player>())) { collision.Remove(target.GetComponent<Player>()); } } private void OnCollisionEnter2D(Collision2D target) { //if this player collides with the ship, then he landed. if (!target.collider.isTrigger && target.collider.tag == "Ship") { if (jumping) { AudioManager.Instance.PlayAudioClip("Land"); } if(validateJumpCoroutine != null) { StopCoroutine(validateJumpCoroutine); validateJumpCoroutine = null; } jumping = false; airJumps = maxAirJumps; } } private void OnCollisionExit2D(Collision2D target) { //if this player is not colliding with the ship, he is jumping. if (!target.collider.isTrigger && target.collider.tag == "Ship") { validateJumpCoroutine = StartCoroutine(ValidateJump()); ValidateJump(); } } Coroutine validateJumpCoroutine; //coroutine function that sets stunned variable, and removes it after "duration" IEnumerator ValidateJump() { yield return new WaitForSeconds(0.15f); jumping = true; } //coroutine function that displays the kick sprite for kickAnimDuration time. IEnumerator KickAnimation() { kickWind.SetActive(true); yield return new WaitForSeconds(kickAnimDuration); kickWind.SetActive(false); } //coroutine function that displays the kick cooldown above the player for the duration of the cooldown. IEnumerator KickCoolDown() { kickCoolDownText.gameObject.SetActive(true); float currTime = KickCD; while (currTime > 0) { kickCoolDownText.text = currTime.ToString("#.##"); yield return new WaitForSeconds(0.1f); currTime -= .1f; } kickCoolDownText.gameObject.SetActive(false); } //coroutine function that sets stunned variable, and removes it after "duration" IEnumerator ApplyStun(float duration) { stunned = true; stun.Play(); float currTime = duration; yield return new WaitForSeconds(duration); stun.Stop(); stunned = false; } //a function that starts the stun process (via coroutines) public void Stun() { StartCoroutine(ApplyStun(stunDuration)); } //reference to the tagKillerCoroutine coroutine, used to interrupt it. Coroutine tagKillerCoroutine; //coroutine function that sets the killer tag, if it the player is still alive after 5sec, remove killer tag. IEnumerator ApplyKiller(Player murderedBy) { killer = murderedBy; yield return new WaitForSeconds(5f); killer = null; tagKillerCoroutine = null; } //function that starts the apply killer coroutine public void TagKiller(Player murderedBy) { if(tagKillerCoroutine != null) { StopCoroutine(tagKillerCoroutine); } tagKillerCoroutine = StartCoroutine(ApplyKiller(murderedBy)); } //function that delivers the kick to the player target and sets off visuals/cooldowns. public void Kick() { //StartCoroutine("KickCoolDown"); for (int i = 0; i < collision.Count; i++) { bool targetLeft = (collision[i].transform.position.x < transform.position.x); collision[i].rb.AddForce((Vector2)(collision[i].transform.position - transform.position).normalized * kickForce); kickWind.transform.LookAt(collision[i].transform); Vector3 pos = kickWind.transform.localScale; kickWind.transform.eulerAngles = new Vector3(0, 0, (targetLeft ? kickWind.transform.eulerAngles.x + 180 : -kickWind.transform.eulerAngles.x + -180)); kickWind.transform.localScale = new Vector3(targetLeft ? Mathf.Abs(pos.x) : -Mathf.Abs(pos.x), -Mathf.Abs(pos.y), pos.z); StartCoroutine("KickAnimation"); AudioManager.Instance.PlayAudioClip("Attack"); collision[i].Stun(); collision[i].TagKiller(this); } } //function that jumps the player if he has jumps left. public void Jump() { if ((!jumping) || (jumping && airJumps > 0)) { airJumps--; rb.velocity = new Vector2(rb.velocity.x/2, (jumping ? 8 : 10)); //rb.AddForce(new Vector2(0, jumpForce)); AudioManager.Instance.PlayAudioClip("Jump"); } } //function that calls the jump/kick functions at the right time. //if player is in range of another player, kick, else jump. public void Action() { if(!stunned && alive) { if (collision.Count == 0) { Jump(); } else { Kick(); } } } //a function that moves the player to the left public void Left() { if (!stunned && alive) { //Debug.Log("left"); float x = Mathf.Clamp(rb.velocity.x - (jumping ? .25f : .5f), -10, 10); rb.velocity = new Vector2(x, rb.velocity.y); playerHeadSprite.flipX = true; //rb.AddForce(new Vector2(-maxRunSpeed, 0)); } } //a function that moves the player to the right public void Right() { if (!stunned && alive) { //Debug.Log("right"); float x = Mathf.Clamp(rb.velocity.x + (jumping ? .25f : .5f), -10, 10); rb.velocity = new Vector2(x, rb.velocity.y); playerHeadSprite.flipX = false; //rb.AddForce(new Vector2(maxRunSpeed, 0)); } } //a function that adds 1 to this player's score. public void Kill() { score++; } // a function that sets the player as dead, gives score to the player's killer, updates the score ui and respawns the player after death. public void Die() { alive = false; trailRend.Clear(); if (killer != null) { killer.Kill(); killer = null; } else { score = (int)Mathf.Clamp(score-1, 0, float.MaxValue); } rb.velocity = new Vector2(0, 0); stun.Stop(); transform.position = Game.Instance.tempRespawnList[Random.Range(0, Game.Instance.tempRespawnList.Count - 1)]; alive = true; UIManager.Instance.UpdateScore(); } }
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Web.Mvc; using log4net; using Mvc.JQuery.Datatables; using Profiling2.Domain; using Profiling2.Domain.Contracts.Tasks; using Profiling2.Domain.Contracts.Tasks.Sources; using Profiling2.Domain.DTO; using Profiling2.Domain.Prf; using Profiling2.Domain.Prf.Sources; using Profiling2.Domain.Scr; using Profiling2.Infrastructure.Security; using Profiling2.Infrastructure.Util; using Profiling2.Web.Mvc.Areas.Sources.Controllers.ViewModels; using Profiling2.Web.Mvc.Controllers; using SharpArch.Web.Mvc.JsonNet; namespace Profiling2.Web.Mvc.Areas.Sources.Controllers { [PermissionAuthorize(AdminPermission.CanViewAndSearchSources)] public class ExplorerController : BaseController { protected static readonly ILog log = LogManager.GetLogger(typeof(ExplorerController)); protected readonly ISourceTasks sourceTasks; protected readonly ISourceContentTasks sourceContentTasks; protected readonly IUserTasks userTasks; protected readonly ILuceneTasks luceneTasks; protected readonly ISourcePermissionTasks sourcePermissionTasks; public ExplorerController(ISourceTasks sourceTasks, ISourceContentTasks sourceContentTasks, IUserTasks userTasks, ILuceneTasks luceneTasks, ISourcePermissionTasks sourcePermissionTasks) { this.sourceTasks = sourceTasks; this.sourceContentTasks = sourceContentTasks; this.userTasks = userTasks; this.luceneTasks = luceneTasks; this.sourcePermissionTasks = sourcePermissionTasks; } public ActionResult Index() { return View(); } public JsonNetResult Paths(string code) { IList<SourceFolderDTO> list = null; string prefix = this.sourcePermissionTasks.GetSourceOwningEntityPrefixPath(code); if (!string.IsNullOrEmpty(prefix)) { list = this.sourceTasks.GetFolderDTOs(prefix) .Where(x => string.Equals(x.OwnerCode, code)) .ToList(); } return JsonNet(list); } public ActionResult Browse(string code) { AdminUser user = this.userTasks.GetAdminUser(User.Identity.Name); ScreeningEntity screeningEntity = user.GetScreeningEntity(); if (!string.IsNullOrEmpty(code)) { ViewBag.Code = code; return View(); } return new HttpNotFoundResult(); } public JsonNetResult DataTables(DataTablesParam p) { if (p != null) { // calculate total results to request from lucene search int numResults = (p.iDisplayStart >= 0 && p.iDisplayLength > 0) ? (p.iDisplayStart + 1) * p.iDisplayLength : 10; // figure out sort column - tied to frontend table columns. assuming one column for now. string sortField = "FileDateTimeStamp"; if (p.iSortCol != null) { switch (p.iSortCol.First()) { case 0: sortField = "Name"; break; case 1: sortField = "FileDateTimeStamp"; break; case 2: sortField = "FileSize"; break; } } // figure out sort direction bool descending = true; if (p.sSortDir != null && string.Equals(p.sSortDir.First(), "asc")) descending = false; // get user affiliations AdminUser user = this.userTasks.GetAdminUser(User.Identity.Name); // run search bool showAllSubdirectories = Convert.ToBoolean(Request.QueryString["showAllSubDirectories"]); IList<LuceneSearchResult> results; if (showAllSubdirectories) { results = this.luceneTasks.SourcePathPrefixSearch(p.sSearch, numResults, ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchAllSources), ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchRestrictedSources), User.Identity.Name, user.Affiliations.Select(x => x.Name).ToList(), sortField, descending ); } else { results = this.luceneTasks.SourcePathExactSearch(p.sSearch, numResults, ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchAllSources), ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchRestrictedSources), User.Identity.Name, user.Affiliations.Select(x => x.Name).ToList(), sortField, descending ); } int iTotalRecords = 0; if (results != null && results.Count > 0) iTotalRecords = results.First().TotalHits; object[] aaData = results .Select(x => new SourcePathDataTableLuceneView(x)) .Skip(p.iDisplayStart) .Take(p.iDisplayLength) .ToArray<SourcePathDataTableLuceneView>(); return JsonNet(new DataTablesData { iTotalRecords = iTotalRecords, iTotalDisplayRecords = iTotalRecords, sEcho = p.sEcho, aaData = aaData.ToArray() }); } return JsonNet(null); } /// <summary> /// Just preview - doesn't record the fact like SourcesController.Preview() does. Also accessible by conditionality participants. /// </summary> /// <param name="id"></param> public void Preview(int id) { Source source = this.sourceTasks.GetSource(id); if (source == null || source.FileData == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; Response.StatusDescription = "That source doesn't exist."; return; } if (!((PrfPrincipal)User).CanAccess(source)) { Response.StatusCode = (int)HttpStatusCode.Forbidden; Response.StatusDescription = "You don't have permission to view this source."; return; } string contentType = MIMEAssistant.GetMIMEType(source.SourceName); if (!string.IsNullOrEmpty(contentType) && source.HasOcrText()) { Response.ContentType = "text/plain"; Response.OutputStream.Write(source.FileData, 0, source.FileData.Length); } else if (!string.IsNullOrEmpty(contentType) && (contentType.StartsWith("image") || contentType.StartsWith("text/plain"))) { Response.ContentType = contentType; Response.OutputStream.Write(source.FileData, 0, source.FileData.Length); } else if (!string.IsNullOrEmpty(contentType) && contentType.StartsWith("text/html")) { Response.ContentType = contentType; Response.OutputStream.Write(source.FileData, 0, source.FileData.Length); } else { try { using (MemoryStream ms = new MemoryStream()) { byte[] previewBytes = this.sourceContentTasks.GetHtmlPreview(source, ms); if (previewBytes != null) { Response.ContentType = "text/html"; Response.OutputStream.Write(previewBytes, 0, previewBytes.Length); } else { Response.StatusCode = (int)HttpStatusCode.NotImplemented; byte[] error = Encoding.UTF8.GetBytes("Preview for this file not supported."); Response.OutputStream.Write(error, 0, error.Length); } } } catch (Exception e) { log.Error("Problem generating HTML preview.", e); byte[] error = Encoding.UTF8.GetBytes("Problem generating HTML preview: " + e.Message); Response.ContentType = "text/html"; Response.OutputStream.Write(error, 0, error.Length); } } } /// <summary> /// Just download - doesn't record the fact like SourcesController.Download() does. /// </summary> /// <param name="id"></param> public ActionResult Download(int id) { SourceDTO dto = this.sourceTasks.GetSourceDTO(id); if (dto != null && dto.FileSize > 0) { if (((PrfPrincipal)User).CanAccess(dto, this.sourceTasks.GetSourceAuthors(id).ToArray(), this.sourceTasks.GetSourceOwners(id).ToArray()) && !dto.IsReadOnly) { string contentType = dto.GetDTOFileExtension(); Stream stream = this.sourceTasks.GetSourceData(id, dto.HasOcrText); return new FileStreamResult(stream, contentType) { FileDownloadName = dto.GetFileDownloadName() }; } else { return new HttpUnauthorizedResult(); } } else { return new HttpNotFoundResult(); } } // source preview references public ActionResult Images(string filename) { string contentType = MIMEAssistant.GetMIMEType(filename); string folderName = ConfigurationManager.AppSettings["PreviewTempFolder"]; if (!Directory.Exists(folderName)) Directory.CreateDirectory(folderName); return File(folderName + "\\" + filename, contentType); } public JsonNetResult MoreLikeThis(int id) { // TODO check for restricted sources IList<LuceneSearchResult> results = this.luceneTasks.GetSourcesLikeThis(id, 10); if (results != null && results.Any()) return JsonNet((from result in results select new SourceResultDataTableLuceneView(result))); Response.StatusCode = (int)HttpStatusCode.NoContent; return JsonNet("No sources like this."); } public JsonNetResult SearchGetFacets() { // parse search term string term = Request.Params["term"]; if (!string.IsNullOrEmpty(term)) { // parse date filter inputs DateTime s, e; DateTime? start = null, end = null; if (DateTime.TryParse(Request.Params["start-date"], out s)) start = s; if (DateTime.TryParse(Request.Params["end-date"], out e)) end = e; // get path prefix string prefix = this.sourcePermissionTasks.GetSourceOwningEntityPrefixPath(Request.Params["code"]); // need user's affiliations AdminUser user = this.userTasks.GetAdminUser(User.Identity.Name); IList<string> affiliations = user.Affiliations.Select(x => x.Name).ToList(); // run search IDictionary<IDictionary<string, string>, long> facets = this.luceneTasks.SourceSearchFacets(term, prefix, start, end, 50, ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchAllSources), ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchRestrictedSources), User.Identity.Name, affiliations); return JsonNet(facets.Select(x => new { Facets = x.Key.Select(y => new { Name = y.Key, Value = y.Value }), Count = x.Value })); } return JsonNet(null); } public JsonNetResult DataTablesSearch(DataTablesParam p) { if (p != null) { // calculate total results to request from lucene search int numResults = (p.iDisplayStart >= 0 && p.iDisplayLength > 0) ? (p.iDisplayStart + 1) * p.iDisplayLength : 10; // figure out sort column - tied to frontend table columns. assuming one column for now. string sortField = null; if (p.iSortCol != null) { switch (p.iSortCol.First()) { case 0: sortField = null; break; case 1: sortField = "SourceName"; break; case 2: sortField = "FileDateTimeStamp"; break; } } // figure out sort direction bool descending = true; if (p.sSortDir != null && string.Equals(p.sSortDir.First(), "asc")) descending = false; // parse date filter inputs DateTime s, e; DateTime? start = null, end = null; if (DateTime.TryParse(Request.Params["start-date"], out s)) start = s; if (DateTime.TryParse(Request.Params["end-date"], out e)) end = e; // get path prefix string prefix = this.sourcePermissionTasks.GetSourceOwningEntityPrefixPath(Request.Params["code"]); // need user's affiliations AdminUser user = this.userTasks.GetAdminUser(User.Identity.Name); IList<string> affiliations = user.Affiliations.Select(x => x.Name).ToList(); // run search IList<LuceneSearchResult> results = null; if (start.HasValue || end.HasValue) { results = this.luceneTasks.SourceSearch(p.sSearch, prefix, start, end, numResults, ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchAllSources), ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchRestrictedSources), User.Identity.Name, affiliations, sortField, descending); } else { results = this.luceneTasks.SourceSearch(p.sSearch, prefix, numResults, ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchAllSources), ((PrfPrincipal)User).HasPermission(AdminPermission.CanViewAndSearchRestrictedSources), User.Identity.Name, affiliations, sortField, descending); } int iTotalRecords = 0; if (results != null && results.Count > 0) iTotalRecords = results.First().TotalHits; // NOTE HasOcrText not included here (but those and other attrs available via extra call to Sources/Details/sourceId from frontend...) object[] aaData = results .Select(x => new SourceResultDataTableLuceneView(x)) .Skip(p.iDisplayStart) .Take(p.iDisplayLength) .ToArray<SourceResultDataTableLuceneView>(); return JsonNet(new DataTablesData { iTotalRecords = iTotalRecords, iTotalDisplayRecords = iTotalRecords, sEcho = p.sEcho, aaData = aaData.ToArray() }); } return JsonNet(null); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Npgsql; namespace yemeksepeti { public partial class Form5 : Form { anasayfa an; int mid,f; public Form5(anasayfa a,int id,int fiyat) { an = a; f = fiyat; InitializeComponent(); string connString = String.Format( "Server=localhost;User Id=postgres;Database=yemegimigetir;Port=5432;Password=benbuyum123;SSLMode=Prefer"); NpgsqlConnection con = new NpgsqlConnection(connString); con.Open(); using (var command = new NpgsqlCommand("SELECT kurye_adi,kurye_soyadi From kurye where kurye_magazaid=@id", con)) { command.Parameters.AddWithValue("id", id); NpgsqlDataReader dr = command.ExecuteReader(); while (dr.Read()) { string x = dr["kurye_adi"].ToString(); string y = dr["kurye_soyadi"].ToString(); x +=" "+ y; comboBox1.Items.Add(x); } con.Close(); } } private void button1_Click(object sender, EventArgs e) { MessageBox.Show("Siparişiniz alınmıştır"); an.fiyatkes(f); this.Hide(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace WAP_Aula06 { public partial class _Default : Page { protected void Page_Load(object sender, EventArgs e) { } protected void Botao_Lista_Click(object sender, EventArgs e) { List<int> lista = new List<int>(); Random aleatorio = new Random(); //for (int i = 0; i < 100; i++) //{ // lista.Add(aleatorio.Next(1, 50)); //} //lista.Sort(); //Lbl_Resultado.Text = String.Empty; //Lbl_Resultado.Text = String.Format("A lista ordenada é {0} e {1} possui o número {2}", // String.Join(", ", lista), lista.Contains(Convert.ToInt32(CaixaTexto_Inteiro.Text))?String.Empty:"não", CaixaTexto_Inteiro.Text); while (lista.Count != 50) { int x = aleatorio.Next(1, 50); if (!lista.Contains(x)) lista.Add(x); } Lbl_Resultado.Text = String.Empty; Lbl_Resultado.Text = String.Format("A lista ordenada é {0} e {1} possui o número {2}", String.Join(", ", lista), lista.Contains(Convert.ToInt32(CaixaTexto_Inteiro.Text)) ? String.Empty : "não", CaixaTexto_Inteiro.Text); } } }
namespace JigsawLibrary { public class Directions { public int X { get; init; } public int Y { get; init; } public Location Location { get; init; } } }
namespace RPG.Stats { public enum CharacterClass { Player, Archer, Skeleton, Ghost, Goblin, Knight, Golem, Wizard, } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using TestGr4d3.BOL; using TestGr4d3.DAL.Contexto; using TestGr4d3.DAL.IRepositorio; namespace TestGr4d3.BLL { public class AsignaturaRepo : BaseContext, IAsignaturaRepo { public AsignaturaRepo(DataContext context) : base(context) { } public async Task<IEnumerable<Asignatura>> ObtenerTodos() => await _context.Asignaturas.ToListAsync(); public async Task<Asignatura> Obtener(int id) => await _context.Asignaturas.FindAsync(id); public async Task Agregar(Asignatura Asignatura) { Asignatura.AgregadaEn = DateTime.Now; await _context.Asignaturas.AddAsync(Asignatura); await _context.SaveChangesAsync(); } public async Task Actualizar(Asignatura Asignatura) { _context.Asignaturas.Update(Asignatura); await _context.SaveChangesAsync(); } public async Task Eliminar(int id) { _context.Asignaturas.Remove(await Obtener(id)); await _context.SaveChangesAsync(); } } }
namespace GrabFileGui { class DiskUsageLog //this effectively works as a C struct { public int Sec { get; set; } public string TSK { get; set; } public string Seize { get; set; } public string Queue { get; set; } public string App { get; set; } public string IAR { get; set; } public string TimeStamp { get; set; } } }
// // IBEncodedValue.cs // // Authors: // Alan McGovern alan.mcgovern@gmail.com // // Copyright (C) 2006 Alan McGovern // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using System.Text; using ResumeEditor.BEncoding; using ResumeEditor.Common; namespace ResumeEditor.BEncoding { /// <summary> /// Base interface for all BEncoded values. /// </summary> public abstract class BEncodedValue { internal abstract void DecodeInternal(RawReader reader); /// <summary> /// Encodes the BEncodedValue into a byte array /// </summary> /// <returns>Byte array containing the BEncoded Data</returns> public byte[] Encode() { byte[] buffer = new byte[LengthInBytes()]; if (Encode(buffer, 0) != buffer.Length) throw new BEncodingException("Error encoding the data"); return buffer; } /// <summary> /// Encodes the BEncodedValue into the supplied buffer /// </summary> /// <param name="buffer">The buffer to encode the information to</param> /// <param name="offset">The offset in the buffer to start writing the data</param> /// <returns></returns> public abstract int Encode(byte[] buffer, int offset); public static T Clone <T> (T value) where T : BEncodedValue { Check.Value (value); return (T) BEncodedValue.Decode (value.Encode ()); } /// <summary> /// Interface for all BEncoded values /// </summary> /// <param name="data">The byte array containing the BEncoded data</param> /// <returns></returns> public static BEncodedValue Decode(byte[] data) { if (data == null) throw new ArgumentNullException("data"); using (RawReader stream = new RawReader(new MemoryStream(data))) return (Decode(stream)); } internal static BEncodedValue Decode(byte[] buffer, bool strictDecoding) { return Decode(buffer, 0, buffer.Length, strictDecoding); } /// <summary> /// Decode BEncoded data in the given byte array /// </summary> /// <param name="buffer">The byte array containing the BEncoded data</param> /// <param name="offset">The offset at which the data starts at</param> /// <param name="length">The number of bytes to be decoded</param> /// <returns>BEncodedValue containing the data that was in the byte[]</returns> public static BEncodedValue Decode(byte[] buffer, int offset, int length) { return Decode(buffer, offset, length, true); } public static BEncodedValue Decode(byte[] buffer, int offset, int length, bool strictDecoding) { if (buffer == null) throw new ArgumentNullException("buffer"); if (offset < 0 || length < 0) throw new IndexOutOfRangeException("Neither offset or length can be less than zero"); if (offset > buffer.Length - length) throw new ArgumentOutOfRangeException("length"); using (RawReader reader = new RawReader(new MemoryStream(buffer, offset, length), strictDecoding)) return (BEncodedValue.Decode(reader)); } /// <summary> /// Decode BEncoded data in the given stream /// </summary> /// <param name="stream">The stream containing the BEncoded data</param> /// <returns>BEncodedValue containing the data that was in the stream</returns> public static BEncodedValue Decode(Stream stream) { if (stream == null) throw new ArgumentNullException("stream"); return Decode(new RawReader(stream)); } /// <summary> /// Decode BEncoded data in the given RawReader /// </summary> /// <param name="reader">The RawReader containing the BEncoded data</param> /// <returns>BEncodedValue containing the data that was in the stream</returns> public static BEncodedValue Decode(RawReader reader) { if (reader == null) throw new ArgumentNullException("reader"); BEncodedValue data; switch (reader.PeekByte()) { case ('i'): // Integer data = new BEncodedNumber(); break; case ('d'): // Dictionary data = new BEncodedDictionary(); break; case ('l'): // List data = new BEncodedList(); break; case ('1'): // String case ('2'): case ('3'): case ('4'): case ('5'): case ('6'): case ('7'): case ('8'): case ('9'): case ('0'): data = new BEncodedString(); break; default: throw new BEncodingException("Could not find what value to decode"); } data.DecodeInternal(reader); return data; } /// <summary> /// Interface for all BEncoded values /// </summary> /// <param name="data">The byte array containing the BEncoded data</param> /// <returns></returns> public static T Decode<T>(byte[] data) where T : BEncodedValue { return (T)BEncodedValue.Decode(data); } /// <summary> /// Decode BEncoded data in the given byte array /// </summary> /// <param name="buffer">The byte array containing the BEncoded data</param> /// <param name="offset">The offset at which the data starts at</param> /// <param name="length">The number of bytes to be decoded</param> /// <returns>BEncodedValue containing the data that was in the byte[]</returns> public static T Decode<T>(byte[] buffer, int offset, int length) where T : BEncodedValue { return BEncodedValue.Decode<T>(buffer, offset, length, true); } public static T Decode<T>(byte[] buffer, int offset, int length, bool strictDecoding) where T : BEncodedValue { return (T)BEncodedValue.Decode(buffer, offset, length, strictDecoding); } /// <summary> /// Decode BEncoded data in the given stream /// </summary> /// <param name="stream">The stream containing the BEncoded data</param> /// <returns>BEncodedValue containing the data that was in the stream</returns> public static T Decode<T>(Stream stream) where T : BEncodedValue { return (T)BEncodedValue.Decode(stream); } public static T Decode<T>(RawReader reader) where T : BEncodedValue { return (T)BEncodedValue.Decode(reader); } /// <summary> /// Returns the size of the byte[] needed to encode this BEncodedValue /// </summary> /// <returns></returns> public abstract int LengthInBytes(); } }
namespace Nan.Configuration.Notification { /// <summary> /// 操作方式 /// </summary> public enum Operation { /// <summary> /// 創建欄位 /// </summary> Create = 1, /// <summary> /// 更新欄位資料 /// </summary> Update, /// <summary> /// 取回欄位資料 /// </summary> Retrieve, /// <summary> /// 刪除欄位 /// </summary> Delete } }
using System; namespace Seguim.Netcore.Store.Infra { public class Class1 { } }
using System.Collections.Generic; using UnityEngine; using UnityEngine.VFX; using UnityEngine.VFX.Utility; public class TemperatureAndIntegrity : MonoBehaviour, IObserver<bool> { [Header("Temperature")] [Tooltip("How much fire obstacles affects the car's temperature level.")] public float fireTempEffect = 10.0f; [Tooltip("How much frost obstacles affects the car's temperature level.")] public float frostTempEffect = 10.0f; [Tooltip("How much laser obstacles affect the car's temperature level.")] public float laserTempEffect = 10.0f; [Tooltip("How much using the boost affects the car's temperature level.")] public float boostTempEffect = 15.0f; [Space] [Tooltip("How many seconds between each tick of DOT damage and cooling effects.")] public float tickRate = 1.0f; [Tooltip("How quickly the car cools down by itself over time. Higher number = quicker cooling.")] public float coolingRate = 1.0f; [Tooltip("How hot does the car need to get before the heat affects its boost capability?")] public float boostTempThreshold = 30.0f; [Tooltip("At what temperature has the heat's detrimental influence on boost reached its maximum?")] public float boostTempMax = 70.0f; [Tooltip("How hot does the car need to get before the heat starts damaging it?")] public float integrityTempThreshold = 70.0f; [Tooltip("How much integrity damage the car receives every tick while being too hot.")] public float integrityTempDOT = 3.0f; [Header("Car Integrity")] [Tooltip("The car's maximum integrity value. Should be different for different cars.")] public float maxIntegrity = 100.0f; [Tooltip("How many seconds between each possible damage function call.")] public float damageRate = 0.5f; [Space] [Tooltip("How much fire obstacles affects the car's integrity level.")] public float fireIntegEffect = 10.0f; [Tooltip("How much frost obstacles affects the car's integrity level.")] public float frostIntegEffect = 10.0f; [Tooltip("How much laser obstacles affect the car's integrity level.")] public float laserIntegEffect = 10.0f; [Tooltip("How much saw obstacles affect the car's integrity level.")] public float sawIntegEffect = 10.0f; [Space] [Tooltip("How much rock obstacles affect the car's integrity level.")] public float rockIntegEffect = 10.0f; [Tooltip("How high velocity is required for taking any rock collision damage, and at how high velocity max damage is taken.")] [Min(0)] public Vector2 rockVelocityMinMax = Vector2.zero; [Tooltip("How much % of rock collision damage is taken at velocities between min and max velocity thresholds.")] public AnimationCurve rockVelocityDamageCurve = AnimationCurve.Linear(0, 0, 1, 1); [Header("Colors")] public Color ExplodeColor = Color.red; public Color InstakillColor = Color.red; [Header("Smoke")] public VisualEffect Smoke; private ExposedProperty smokeValue = "SmokeValue"; // public Vector2 SmokeMinMaxIntegrity = new Vector2(0.1f, 0.9f); [Range(0, 1)] public float SmokeMinIntegrity = .1f; [Range(0, 1)] public float SmokeMaxIntegrity = .9f; public AnimationCurve SmokeCurve = AnimationCurve.Linear(0, 0, 1, 1); // [Header("UI Scripts")] // [Tooltip("This car's associated temperature UI bar")] // public TemperatureUIScript temperatureUI; // [Tooltip("This car's associated integrity UI bar")] // public IntegrityUIScript integrityUI; private SteeringScript carControls; // TODO: speed penalty when reaching low temperature //Arbitrary bottom of the temperature UI bar. Only used for display purposes private float zeroTemp = 95.0f; //Around the standard celsius temperature for running car engines. Only used for display purposes private float standardTemp = 100.0f; //Around where engine celsius temperature would be dangerously high. Only used for display purposes private float highTemp = 180.0f; //Temperature values used for calculations private float currTemp = 0.0f; private float goalTemp = 0.0f; private bool tooHotBoost = false; private bool tooHotInteg = false; //The car's current integrity value, used in calculations private float currIntegrity; //The timer for DOT and cooling ticks private float tickTimer = 0.0f; //The timer for damage function calls private float damageTimer = 0.0f; TemperatureUIScript temperatureUI; IntegrityUIScript integrityUI; [HideInInspector] public List<IObserver<ContactPoint, float>> RockCollisionObservers = new List<IObserver<ContactPoint, float>>(); private void Start() { carControls = GetComponent<SteeringScript>(); carControls.BoostStartObservers.Add(this); currIntegrity = maxIntegrity; temperatureUI = TemperatureUIScript.MainInstance; if (temperatureUI == null) Debug.Log("TemperatureAndIntegrity: " + gameObject.name + " is missing a reference to its TemperatureUIScript"); integrityUI = IntegrityUIScript.MainInstance; if (integrityUI == null) Debug.Log("TemperatureAndIntegrity: " + gameObject.name + " is missing a reference to its IntegrityUIScript"); UpdateSmoke(); } public void BoostHeat() { goalTemp += boostTempEffect * Time.deltaTime; ValueCheck(); } public void FireHit() { if (damageTimer <= 0.0f) { goalTemp += fireTempEffect; currIntegrity -= fireIntegEffect; Hit(); } } public void FireHit(float dt) { // if (damageTimer <= 0.0f) { goalTemp += fireTempEffect * dt; currIntegrity -= fireIntegEffect * dt; Hit(); // } } public void FrostHit(bool safe = false) { if (damageTimer <= 0.0f) { goalTemp -= frostTempEffect; // NOTE: decreases heat if (!safe) currIntegrity -= frostIntegEffect; Hit(); } } public void FrostHit(float dt, bool safe = false) { // if (damageTimer <= 0.0f) { goalTemp -= frostTempEffect * dt; // NOTE: decreases heat if (!safe) currIntegrity -= frostIntegEffect * dt; Hit(); // } } public void LaserHit() { if (damageTimer <= 0.0f) { goalTemp += laserTempEffect; currIntegrity -= laserIntegEffect; Hit(); } } public void LaserHit(float dt) { // if (damageTimer <= 0.0f) { goalTemp += laserTempEffect * dt; currIntegrity -= laserIntegEffect * dt; Hit(); // } } public void SawHit() { if (damageTimer <= 0.0f) { currIntegrity -= sawIntegEffect; Hit(); } } public void RockHit(float sqrImpactVelocity, ContactPoint contact) { float sqrVelocity = sqrImpactVelocity;//carControls.Velocity.sqrMagnitude; float sqrMin = rockVelocityMinMax.x * rockVelocityMinMax.x; if (damageTimer <= 0.0f && !carControls.IsInvulnerable && sqrVelocity > sqrMin) { float sqrMax = rockVelocityMinMax.y * rockVelocityMinMax.y; float percentage = 1f; if (sqrVelocity < sqrMax && rockVelocityMinMax.x != rockVelocityMinMax.y) percentage = Mathf.Clamp01((sqrVelocity - sqrMin) / (sqrMax - sqrMin)); currIntegrity -= rockIntegEffect * rockVelocityDamageCurve.Evaluate(percentage); Hit(); } foreach (var item in RockCollisionObservers) item.Notify(contact, sqrImpactVelocity); } public void Instakill() { // if (!carControls.IsInvulnerable) { // currIntegrity = 0; UINotificationSystem.Notify("Your car got crushed!", InstakillColor, 2); carControls.ResetTransform(); carControls.CallResetEvents(); ResetTempAndInteg(); // } } private void Update() { if (damageTimer > 0.0f) damageTimer -= Time.deltaTime; tickTimer += Time.deltaTime; if (tickTimer >= tickRate) { if (currTemp > 0.0f) goalTemp = Mathf.MoveTowards(goalTemp, 0f, coolingRate); if (currTemp < 0.0f) goalTemp = 0.0f; if (tooHotInteg) { currIntegrity -= integrityTempDOT; var integrityUI = IntegrityUIScript.MainInstance; if (integrityUI != null) integrityUI.SetIntegPercentage(currIntegrity / maxIntegrity); ValueCheck(); } //A bit of randomization for a slightly more "realistic" temperature reading float randFlux = Random.Range(-0.2f, 0.2f); currTemp += randFlux; tickTimer = 0.0f; } //Do whatever effects we may want temperature to have on boost every frame //Like maybe updating max boost amount if (tooHotBoost) { carControls.SetBoostLimit((currTemp - boostTempThreshold) / (boostTempMax - boostTempThreshold)); } //Lerping temperature fluctuations to make it look more natural currTemp = Mathf.Lerp(currTemp, goalTemp, 5.0f * Time.deltaTime); SetTempUI(); } private void Hit() { SetIntegUI(); damageTimer = damageRate; UpdateSmoke(); ValueCheck(); } private void UpdateSmoke() { if (Smoke) { float smokePercent = 1f - (currIntegrity / maxIntegrity); smokePercent = (smokePercent - SmokeMinIntegrity) / (SmokeMaxIntegrity - SmokeMinIntegrity); float smokeIntensity = SmokeCurve.Evaluate(Mathf.Clamp01(smokePercent)); Smoke.enabled = smokeIntensity > 0; Smoke.SetFloat(smokeValue, smokeIntensity); // Debug.Log("smoke updated to " + smokeIntensity + ", " + smokePercent); } } private void SetTempUI() { if (temperatureUI != null) { float displayTempPercent = ((standardTemp + currTemp) - zeroTemp) / (highTemp - zeroTemp); temperatureUI.SetTempPercentage(displayTempPercent, (standardTemp + currTemp)); } } private void SetIntegUI() { if (integrityUI != null) integrityUI.SetIntegPercentage(currIntegrity / maxIntegrity); } private void ValueCheck() { if (currIntegrity <= 0.0f) { Debug.Log("Integrity reached 0!"); // UINotificationSystem.Notify("Your car exploded!", ExplodeColor, 5); UINotificationSystem.Notify("Your car broke down! Restarting with penalty.", ExplodeColor, 5); // TODO: time and/or score penalty carControls.ResetTransform(); carControls.CallResetEvents(); ResetTempAndInteg(); } if (currTemp >= boostTempThreshold) { tooHotBoost = true; } else { tooHotBoost = false; carControls.SetBoostLimit(0.0f); } if (currTemp >= integrityTempThreshold) { tooHotInteg = true; TemperatureWarningTextScript.Show(); } else { tooHotInteg = false; TemperatureWarningTextScript.Hide(); } } private void ResetTempAndInteg() { currIntegrity = maxIntegrity; currTemp = 0.0f; goalTemp = 0.0f; SetTempUI(); SetIntegUI(); UpdateSmoke(); Smoke?.Reinit(); } // on car boost start public void Notify(bool carIsInvulnerable) { BoostHeat(); } }
using UnityEngine; using VRTK; public class Pistol : Weapon { private GameObject currentPrimaryGrabbingObject; private GameObject currentSecondaryGrabbingObject; private VRTK_InteractableObject interactableObject; private VRTK_ControllerEvents controllerEvents; private Rigidbody rb; private void Awake() { interactableObject = GetComponent<VRTK_InteractableObject>(); } protected override void Start() { base.Start(); rb = GetComponent<Rigidbody>(); } private void OnEnable() { interactableObject.InteractableObjectGrabbed += OnGrab; interactableObject.InteractableObjectUngrabbed += OnUngrab; interactableObject.InteractableObjectUnused += OnUnuse; interactableObject.InteractableObjectUsed += OnUse; } private void OnGrab(object sender, InteractableObjectEventArgs e) { Debug.Log("Grab"); if (currentPrimaryGrabbingObject == null) { currentPrimaryGrabbingObject = e.interactingObject; } } private void OnUngrab(object sender, InteractableObjectEventArgs e) { Debug.Log("Ungrab"); if (e.interactingObject == currentPrimaryGrabbingObject) { currentPrimaryGrabbingObject = null; currentSecondaryGrabbingObject = null; if (rb.isKinematic) rb.isKinematic = false; } } private void OnUse(object sender, InteractableObjectEventArgs e) { if (e.interactingObject == currentPrimaryGrabbingObject) { Shoot(); } } private void OnUnuse(object sender, InteractableObjectEventArgs e) { if (e.interactingObject == currentPrimaryGrabbingObject) { } } private void OnDisable() { interactableObject.InteractableObjectGrabbed -= OnGrab; interactableObject.InteractableObjectUngrabbed -= OnUngrab; interactableObject.InteractableObjectUnused -= OnUnuse; interactableObject.InteractableObjectUsed -= OnUse; } public override void Shoot() { if (!canFire) { if (reloading) weaponAudioManager.Play("DryFire"); return; } Haptics.Instance.StartHaptics(gameObject, hapticStrenght, hapticDuration, .01f); if (hitScan) FireWithHitScan(); else if (!hitScan) FireProjectile(); OnShotFired(); ReloadAndCooldown(); } }
// (c) Copyright Microsoft Corporation. // This source is subject to the Microsoft Public License (Ms-PL). // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details. // All other rights reserved. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("General", "SWC1001:XmlDocumentationCommentShouldBeSpelledCorrectly", MessageId = "globalizable", Justification = "Spelled correctly.")] [assembly: SuppressMessage("General", "SWC1001:XmlDocumentationCommentShouldBeSpelledCorrectly", MessageId = "validators", Justification = "Spelled correctly.")]
using System.Threading.Tasks; using SFA.DAS.CommitmentsV2.Shared.Interfaces; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Requests.Apprentices; using SFA.DAS.ProviderCommitments.Infrastructure.OuterApi.Types; using SFA.DAS.ProviderCommitments.Web.Models.Apprentice.Edit; namespace SFA.DAS.ProviderCommitments.Web.Mappers.Apprentice { public class SelectDeliveryModelViewModelFromEditApprenticeshipRequestViewModelMapper : IMapper<EditApprenticeshipRequestViewModel, EditApprenticeshipDeliveryModelViewModel> { private readonly IOuterApiClient _apiClient; public SelectDeliveryModelViewModelFromEditApprenticeshipRequestViewModelMapper(IOuterApiClient apiClient) { _apiClient = apiClient; } public async Task<EditApprenticeshipDeliveryModelViewModel> Map(EditApprenticeshipRequestViewModel source) { var apiRequest = new GetEditApprenticeshipDeliveryModelRequest(source.ProviderId, source.ApprenticeshipId); var apiResponse = await _apiClient.Get<GetEditApprenticeshipDeliveryModelResponse>(apiRequest); return new EditApprenticeshipDeliveryModelViewModel { DeliveryModel = (DeliveryModel)source.DeliveryModel, DeliveryModels = apiResponse.DeliveryModels }; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Projectile : MonoBehaviour { private Rigidbody rb; public ParticleSystem explosion; private void Start() { rb = GetComponent<Rigidbody>(); } public void Launch(Vector3 direction, float velocity) { rb = GetComponent<Rigidbody>(); rb.velocity = Vector3.zero; rb.angularVelocity = Vector3.zero; rb.AddForce(direction * velocity, ForceMode.VelocityChange); } private void OnCollisionEnter(Collision collision) { gameObject.SetActive(false); explosion.transform.position = transform.position; explosion.gameObject.SetActive(true); explosion.Play(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public class Stats : MonoBehaviour { public static int money = 0, Q01price = 5; public static byte currentState = 0, onTrigger = 0, currentQuest = 0, subQuest02 = 1, currentScene = 0; //default 0, shop 1, receiving-quest 2, death 3, endOfQuest 4 public static float[] stats = new float[shop.n]; public static byte[] Quest_id = new byte[] {3, 4, 5}; public static int[] prices = new int[] {1}; private static string stats_path = @"stats.txt", scene_path = @"game_scene.txt"; public static void ReadPlayerPos(GameObject player) { if (!File.Exists(scene_path)) File.Create(scene_path); else using(StreamReader sr = File.OpenText(scene_path)) { float x = float.Parse(sr.ReadLine()); float y = float.Parse(sr.ReadLine()); float z = float.Parse(sr.ReadLine()); player.transform.position = new Vector3(x, y, z); sr.Close(); } } public static void SavePlayerPos(GameObject player) { using(StreamWriter sw = File.CreateText(scene_path)) { sw.WriteLine(player.transform.position.x.ToString()); sw.WriteLine(player.transform.position.y.ToString()); sw.WriteLine(player.transform.position.z.ToString()); sw.Close(); } } public static void ReadAllStats() { if (!File.Exists(stats_path)) File.Create(stats_path); else { using(StreamReader sr = File.OpenText(stats_path)) { money = int.Parse(sr.ReadLine()); currentQuest = byte.Parse(sr.ReadLine()); stats[0] = float.Parse(sr.ReadLine()); prices[0] = int.Parse(sr.ReadLine()); sr.Close(); } } } public static void SaveAllStats() { using(StreamWriter sw = File.CreateText(stats_path)) { sw.WriteLine(money.ToString()); sw.WriteLine(currentQuest.ToString()); sw.WriteLine(stats[0].ToString()); sw.WriteLine(prices[0].ToString()); sw.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Basic_Math { class Program { static void Main(string[] args) { string[] command = Console.ReadLine().Split(); while (command[0] != "End") { float n1 = float.Parse(command[0]); float n2 = float.Parse(command[1]); switch (command[2]) { case "Sum": Console.WriteLine(MathUtil.Sum(n1, n2)); break; case "Subtract": Console.WriteLine(MathUtil.Subtract(n1, n2)); break; case "Multiply": Console.WriteLine(MathUtil.Multiply(n1, n2)); break; case "Divide": Console.WriteLine(MathUtil.Divide(n1, n2)); break; case "Percentage": Console.WriteLine(MathUtil.Percentage(n1, n2)); break; } command = Console.ReadLine().Split(); } } } }
using System; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; namespace VoxelSpace { public class TileTexture : IDisposable { public TextureAtlas Atlas { get; private set; } public Texture2D Texture { get; private set; } public QuadUVs UV; public TileTexture(Texture2D texture) { Texture = texture; } public void AddToAtlas(TextureAtlas atlas, QuadUVs uv) { Atlas = atlas; UV = uv; } public void Dispose() { if (Texture != null) { Texture.Dispose(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sound : MonoSingleton<Sound> { public string M_ResourceDir = ""; AudioSource m_bg; AudioSource m_effect; protected override void Awake() { base.Awake(); m_bg = gameObject.AddComponent<AudioSource>(); m_bg.playOnAwake = false; m_bg.loop = true; m_effect = gameObject.AddComponent<AudioSource>(); m_effect.playOnAwake = false; m_effect.loop = false; } /// <summary> /// 播放背景音乐 /// </summary> /// <param name="clipName">想要播放的背景音乐的名字</param> public void PlayBG(string clipName) { if (m_bg.clip != null) if (m_bg.clip.name == clipName) return; string path = M_ResourceDir + "/" + clipName; AudioClip clip = Resources.Load<AudioClip>(path); if (clip != null) { m_bg.clip = clip; m_bg.Play(); } } /// <summary> /// 播放音效 /// </summary> /// <param name="clipName">音效名字</param> public void PlayEffect(string clipName) { string path = M_ResourceDir + "/" + clipName; AudioClip clip = Resources.Load<AudioClip>(path); m_effect.PlayOneShot(clip); } }
using Allyn.Domain.Models.Basic; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Allyn.Domain.Models.Basic { /// <summary> /// 表示"用户"领域聚合根类型. /// </summary> public class User : AggregateRoot { /// <summary> /// 获取或设置父级. /// </summary> public User Parent { get; set; } /// <summary> /// 获取或设置用户名. /// </summary> public string Account { get; set; } /// <summary> /// 获取或设置密码. /// </summary> public string Password { get; set; } /// <summary> /// 获取或设置注册时间. /// </summary> public DateTime CreateDate { get; set; } /// <summary> /// 获取或设置更新时间. /// </summary> public DateTime? UpdateDate { get; set; } /// <summary> /// 获取或设置锁定标识. /// </summary> public bool Disabled { get; set; } /// <summary> /// 获取或设置创建人. /// </summary> public Guid Creater { get; set; } /// <summary> /// 获取或设置修改者. /// </summary> public Guid? Modifier { get; set; } /// <summary> /// 获取或设置子用户. /// </summary> public List<User> Children { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using Events; public class Note_Controller : MonoBehaviour { private readonly QteHitEvent ev_qtehit = new QteHitEvent(); private readonly QtePlayEvent ev_qteplay = new QtePlayEvent(); public bool canbepressed; public KeyCode keytopress; void Start() { canbepressed = false; } void Update() { if (Input.GetKeyDown(keytopress)) { if(canbepressed) { gameObject.SetActive(false); ev_qtehit.success = true; if(this.tag == "ArrowBlue") { ev_qtehit.color = 0; } if (this.tag == "ArrowRed") { ev_qtehit.color = 1; } if (this.tag == "ArrowYellow") { ev_qtehit.color = 2; } if (this.tag == "ArrowGreen") { ev_qtehit.color = 3; } EventController.TriggerEvent(ev_qtehit); } } } private void OnTriggerEnter(Collider other) { if (other.tag.StartsWith("Activator")) { canbepressed = true; } //if (other.tag == "ActivatorBlue") //{ // canbepressed = true; // ev_qtehit.color = 0; //} //else if (other.tag == "ActivatorRed") //{ // canbepressed = true; // ev_qtehit.color = 1; //} //else if (other.tag == "ActivatorYellow") //{ // canbepressed = true; // ev_qtehit.color = 2; //} //else if (other.tag == "ActivatorGreen") //{ // canbepressed = true; // ev_qtehit.color = 3; //} } private void OnTriggerExit(Collider other) { if (other.tag.StartsWith("Activator")) { canbepressed = false; } //if (other.tag == "ActivatorBlue") //{ // canbepressed = false; //} //else if(other.tag == "ActivatorRed") //{ // canbepressed = false; //} //else if (other.tag == "ActivatorYellow") //{ // canbepressed = false; //} //else if (other.tag == "ActivatorGreen") //{ // canbepressed = false; //} } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public partial class ChessEntity { public virtual void BeSelect() { transform.localScale = Vector3.one * 4; ChessPathManager.HideAllPath(); ShowChessPath(); MaterialsColor(Color.green); } public virtual void UnSelect() { transform.localScale = Vector3.one * 2; ChessPathManager.HideAllPath(); RevertMaterialsColor(); } public virtual void ShowChessPath() { } public virtual void MoveTo(int index_x, int index_z) { this.transform.localPosition = new Vector3(ChessInterval * index_x, 0, ChessInterval * index_z); } public virtual void MoveTo(Vector3 pos) { this.transform.localPosition = pos; } public virtual ChessType GetChessType() { return ChessType.ChessTypeNone; } } public enum ChessType { ChessTypeNone, ChessTypeJu, ChessTypeMa, ChessTypeXiang, ChessTypeShi, ChessTypeJiang, ChessTypePao, ChessTypeZu }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Runtime.CompilerServices; using System.Windows; using System.Windows.Controls; using System.Windows.Input; using Jace; using OxyPlot; using OxyPlot.Axes; using OxyPlot.Series; using JetBrains.Annotations; using WaveShaper.Commands; using WaveShaper.Controls; using WaveShaper.Core; using WaveShaper.Core.Bezier; using WaveShaper.Core.PiecewiseFunctions; using WaveShaper.Core.Shaping; using WaveShaper.Core.Utilities; namespace WaveShaper { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window, INotifyPropertyChanged { private PlotModel shapingFunctionPlot; private ObservableCollection<PiecewiseFunctionRow> rows; private ObservableCollection<PiecewiseFunctionRow> piecewiseFunctionRows = new ObservableCollection<PiecewiseFunctionRow> { new PiecewiseFunctionRow(ProcessingType.PiecewiseFunction) { FromOperator = Operator.LessOrEqualThan, ToOperator = Operator.LessOrEqualThan, Expression = "x" } }; private ObservableCollection<PiecewiseFunctionRow> piecewisePolynomialRows = new ObservableCollection<PiecewiseFunctionRow> { new PiecewiseFunctionRow(ProcessingType.PiecewisePolynomial) { FromOperator = Operator.LessOrEqualThan, ToOperator = Operator.LessOrEqualThan, Expression = "0, 1" } }; private readonly Dictionary<ProcessingType, bool> mirroredPerMode = new Dictionary<ProcessingType, bool>(); public MainWindow() { InitialisePlot(); InitializeComponent(); PlotShapingFunction(Player.ShapingFunction); } private void InitialisePlot() { shapingFunctionPlot = new PlotModel { IsLegendVisible = false, Title = "Shaping function", TitleFontSize = 12, TitleFont = "Segoe UI", TitleFontWeight = 1 }; shapingFunctionPlot.Axes.Add(new LinearAxis { Position = AxisPosition.Left, Minimum = -1.1, Maximum = 1.1, ExtraGridlines = new[] { 0d }, ExtraGridlineColor = OxyColors.LightGray, Title = "f(x)" }); shapingFunctionPlot.Axes.Add(new LinearAxis { Position = AxisPosition.Bottom, Minimum = -1.1, Maximum = 1.1, ExtraGridlines = new[] { 0d }, ExtraGridlineColor = OxyColors.LightGray, Title = "x" }); } public ObservableCollection<PiecewiseFunctionRow> Rows { get => rows; set { if (Equals(value, rows)) return; rows = value; OnPropertyChanged(); } } public PlotModel ShapingFunctionPlot { get => shapingFunctionPlot; set { if (Equals(value, shapingFunctionPlot)) return; shapingFunctionPlot = value; OnPropertyChanged(); } } private void DdlProcessingType_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { if (TabControl == null) return; var previousType = (ProcessingType) e.RemovedItems.Cast<EnumUtil.EnumListItem>().Single().Value; var newType = (ProcessingType) e.AddedItems.Cast<EnumUtil.EnumListItem>().Single().Value; if (!mirroredPerMode.TryGetValue(newType, out bool mirroredNew)) mirroredNew = true; mirroredPerMode[previousType] = CbMirrored.IsChecked.HasValue && CbMirrored.IsChecked.Value; switch (newType) { case ProcessingType.NoProcessing: TabControl.SelectedItem = TabNone; CbMirrored.IsEnabled = false; CbMirrored.IsChecked = false; break; case ProcessingType.PiecewisePolynomial: InitFunctionRows(previousType, newType); TabControl.SelectedItem = TabTable; CbMirrored.IsEnabled = true; CbMirrored.IsChecked = mirroredNew; break; case ProcessingType.PiecewiseFunction: InitFunctionRows(previousType, newType); TabControl.SelectedItem = TabTable; CbMirrored.IsEnabled = true; CbMirrored.IsChecked = mirroredNew; break; case ProcessingType.Bezier: TabControl.SelectedItem = TabBezier; CbMirrored.IsEnabled = false; CbMirrored.IsChecked = true; break; default: throw new ArgumentOutOfRangeException(); } SetupPresets(newType); } private void SetupPresets(ProcessingType type) { BtnPresets.IsEnabled = type != ProcessingType.NoProcessing; var menu = BtnPresets.ContextMenu ?? (BtnPresets.ContextMenu = new ContextMenu()); menu.Items.Clear(); menu.Items.Add(CustomCommands.Presets.Identity.ToMenuItem(commandParameter: type)); menu.Items.Add(CustomCommands.Presets.SoftClip1.ToMenuItem(commandParameter: type)); if (type == ProcessingType.PiecewiseFunction || type == ProcessingType.Bezier) menu.Items.Add(CustomCommands.Presets.SoftClip2.ToMenuItem(commandParameter: type)); menu.Items.Add(CustomCommands.Presets.HardClip.ToMenuItem(commandParameter: type)); if (type == ProcessingType.Bezier) { menu.Items.Add(new MenuItem { Header = "Crossover distortion", Command = new ActionCommand(p => PresetCrossoverDistortion_OnExecuted(), p => true) }); } } private void BtnApply_OnClick(object sender, RoutedEventArgs e) { Player.ShapingFunction = BuildFunction(); PlotShapingFunction(Player.ShapingFunction); } private void InitFunctionRows(ProcessingType old, ProcessingType newType) { switch (old) { case ProcessingType.PiecewisePolynomial: piecewisePolynomialRows = Rows; break; case ProcessingType.PiecewiseFunction: piecewiseFunctionRows = Rows; break; } switch (newType) { case ProcessingType.PiecewisePolynomial: Rows = piecewisePolynomialRows; break; case ProcessingType.PiecewiseFunction: Rows = piecewiseFunctionRows; break; } } private void PlotShapingFunction(Func<double, double> shapingFunction) { try { ShapingFunctionPlot.Series.Clear(); ShapingFunctionPlot.Series.Add(new FunctionSeries(shapingFunction, -1, 1, 100, "f(x)")); ShapingFunctionPlot.InvalidatePlot(true); } catch (PiecewiseFunctionInputOutOfRange) { MessageBox.Show(this, "Function does not cover all possible values.", "Error"); } } private Func<double, double> BuildFunction() { var mode = (ProcessingType)DdlProcessingType.SelectedValue; bool mirrored = CbMirrored.IsChecked == true; Func<double, double> func = null; switch (mode) { case ProcessingType.NoProcessing: func = ShapingProvider.DefaultShapingFunction; break; case ProcessingType.PiecewiseFunction: func = BuildPiecewiseFunction(Rows, mirrored).Calculate; break; case ProcessingType.PiecewisePolynomial: foreach (var row in Rows) row.Mode = ProcessingType.PiecewisePolynomial; func = BuildPiecewisePolynomial(Rows, mirrored).Calculate; break; case ProcessingType.Bezier: func = BuildBezierFunction(Bezier.GetCurves()).Calculate; break; } return func; } private static PiecewiseFunction<double> BuildPiecewiseFunction(IEnumerable<PiecewiseFunctionRow> rows, bool mirrored = false) { var function = new PiecewiseFunction<double>(); var mirroredList = new List<Piece<double>>(); var engine = new CalculationEngine(); foreach (var row in rows) { var pieceFunction = (Func<double, double>) engine .Formula(row.Expression.Replace("pi", Math.PI.ToString(CultureInfo.InvariantCulture))) .Parameter("x", DataType.FloatingPoint) .Result(DataType.FloatingPoint) .Build(); if (mirrored) { function.AddPiece(new Piece<double>(row.GetCondition(inverted: false), x => pieceFunction(x))); mirroredList.Add(new Piece<double>(row.GetCondition(inverted: true), x => -pieceFunction(Math.Abs(x)))); } else { function.AddPiece(new Piece<double>(row.GetCondition(), pieceFunction)); } } if (mirroredList.Any()) { mirroredList.Reverse(); function.AddPieces(mirroredList); } function.AddPiece(Piece<double>.DefaultPiece); return function; } private static PiecewiseFunction<double> BuildPiecewisePolynomial(IEnumerable<PiecewiseFunctionRow> rows, bool mirrored = false) { var function = new PiecewiseFunction<double>(); var mirroredList = new List<Piece<double>>(); foreach (var row in rows) { var pieceFunction = row.GetPolynomialFunction(); if (mirrored) { function.AddPiece(new Piece<double>(row.GetCondition(inverted: false), x => pieceFunction(x))); mirroredList.Add(new Piece<double>(row.GetCondition(inverted: true), x => -pieceFunction(Math.Abs(x)))); } else { function.AddPiece(new Piece<double>(row.GetCondition(), pieceFunction)); } } if (mirroredList.Any()) { mirroredList.Reverse(); function.AddPieces(mirroredList); } function.AddPiece(Piece<double>.DefaultPiece); return function; } private static PiecewiseFunction<double> BuildBezierFunction(IEnumerable<BezierCurve> curves) { var function = new PiecewiseFunction<double>(); foreach (var curve in curves.OrderBy(c => c.P0.X)) { var func = curve.GetFunctionOfX(); function.AddPiece(new Piece<double> { Condition = x => curve.P0.X <= x && x <= curve.P3.X, Function = func }); function.AddPiece(new Piece<double> { Condition = x => -curve.P3.X <= x && x <= -curve.P0.X, Function = func }); } function.AddPiece(Piece<double>.DefaultPiece); return function; } #region PropertyChanged public event PropertyChangedEventHandler PropertyChanged; [NotifyPropertyChangedInvocator] protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion private void BtnPreviewEffect_OnClick(object sender, RoutedEventArgs e) { var func = BuildFunction(); var window = new EffectPreview(func); window.Show(); } private void PresetIdentity_OnExecuted(object sender, ExecutedRoutedEventArgs e) { var type = (ProcessingType) e.Parameter; if (type == ProcessingType.PiecewiseFunction) { Rows.Clear(); Rows.Add(new PiecewiseFunctionRow { Expression = "x" }); } else if (type == ProcessingType.PiecewisePolynomial) { Rows.Clear(); Rows.Add(new PiecewiseFunctionRow(mode: ProcessingType.PiecewisePolynomial) { Expression = "0,1" }); } else if (type == ProcessingType.Bezier) { Bezier.ClearAndSetCurves(BezierCurve.GetIdentity()); } } private void PresetSoftClip1_OnExecuted(object sender, ExecutedRoutedEventArgs e) { var type = (ProcessingType)e.Parameter; if (type == ProcessingType.PiecewiseFunction) { Rows.Clear(); Rows.Add(new PiecewiseFunctionRow { ToOperator = Operator.LessOrEqualThan, To = -1, Expression = "-2/3" }); Rows.Add(new PiecewiseFunctionRow { From = -1, FromOperator = Operator.LessThan, ToOperator = Operator.LessThan, To = 1, Expression = "x - (x^3)/3" }); Rows.Add(new PiecewiseFunctionRow { FromOperator = Operator.LessOrEqualThan, From = 1, Expression = "2/3" }); } else if (type == ProcessingType.PiecewisePolynomial) { Rows.Clear(); Rows.Add(new PiecewiseFunctionRow(mode: ProcessingType.PiecewisePolynomial) { ToOperator = Operator.LessOrEqualThan, To = -1, Expression = "-0.666" }); Rows.Add(new PiecewiseFunctionRow(mode: ProcessingType.PiecewisePolynomial) { From = -1, FromOperator = Operator.LessThan, ToOperator = Operator.LessThan, To = 1, Expression = "0, 1, 0, -0.333" }); Rows.Add(new PiecewiseFunctionRow(mode: ProcessingType.PiecewisePolynomial) { FromOperator = Operator.LessOrEqualThan, From = 1, Expression = "0.666" }); } else if (type == ProcessingType.Bezier) { Bezier.ClearAndSetCurves(new List<BezierCurve> { new BezierCurve { P0 = new Point(0, 0), P1 = new Point(0.5, 0.5), P2 = new Point(0.75, 2/3d), P3 = new Point(1.00001, 2/3d) } }); } } private void PresetSoftClip2_OnExecuted(object sender, ExecutedRoutedEventArgs e) { var type = (ProcessingType)e.Parameter; if (type == ProcessingType.PiecewiseFunction) { Rows.Clear(); Rows.Add(new PiecewiseFunctionRow {ToOperator = Operator.LessOrEqualThan, To = -0.5, Expression = "-1"}); Rows.Add(new PiecewiseFunctionRow { From = -0.5, FromOperator = Operator.LessThan, ToOperator = Operator.LessThan, To = 0.5, Expression = "sin(pi * x / (2 * 0.5))" }); Rows.Add(new PiecewiseFunctionRow {FromOperator = Operator.LessOrEqualThan, From = 0.5, Expression = "1"}); } else if (type == ProcessingType.Bezier) { var c1 = new BezierCurve { P0 = new Point(0, 0), P1 = new Point(0.23, 0.57), P2 = new Point(0.38, 1d), P3 = new Point(0.5, 1d) }; var c2 = new BezierCurve { P0 = new Point(0.5, 1d), P1 = new Point(0.6, 1d), P2 = new Point(0.9, 1d), P3 = new Point(1.00001, 1d), Next = c1.Id }; Bezier.ClearAndSetCurves(new List<BezierCurve> {c1, c2}); } } private void PresetCrossoverDistortion_OnExecuted() { var c1 = new BezierCurve { P0 = new Point(0, 0), P1 = new Point(0.00771647431488687, 0.339152299202495), P2 = new Point(0.0183373761381656, 0.520136097439118), P3 = new Point(0.104281683229052, 0.527784641633753) }; var c2 = new BezierCurve { P0 = new Point(0.104281683229052, 0.527784641633753), P1 = new Point(0.186037864902091, 0.52909220615369), P2 = new Point(0.228472552509041, 0.465639968190406), P3 = new Point(0.257637099742363, 0.134952766531714), Prev = c1.Id }; var c3 = new BezierCurve { P0 = new Point(0.257637099742363, 0.134952766531714), P1 = new Point(0.427643506643505, 0.375676320528773), P2 = new Point(0.538222622546174, 0.556048264767812), P3 = new Point(0.641025641025641, 0.706262062907364), Prev = c2.Id }; var c4 = new BezierCurve { P0 = new Point(0.641025641025641, 0.706262062907364), P1 = new Point(0.728887282335496, 0.854099583545941), P2 = new Point(0.855589975114535, 0.820785215161322), P3 = new Point(1.00001, 0.828251933505092), Prev = c3.Id }; c1.Next = c2.Id; c2.Next = c3.Id; c3.Next = c4.Id; Bezier.ClearAndSetCurves(new List<BezierCurve> {c1, c2, c3, c4}); } private void PresetHardClip_OnExecuted(object sender, ExecutedRoutedEventArgs e) { var type = (ProcessingType)e.Parameter; if (type == ProcessingType.PiecewiseFunction) { Rows.Clear(); Rows.Add(new PiecewiseFunctionRow { ToOperator = Operator.LessOrEqualThan, To = -0.666, Expression = "-1" }); Rows.Add(new PiecewiseFunctionRow { From = -0.666, FromOperator = Operator.LessThan, ToOperator = Operator.LessThan, To = 0.666, Expression = "1.5*x" }); Rows.Add(new PiecewiseFunctionRow { FromOperator = Operator.LessOrEqualThan, From = 0.666, Expression = "1" }); } else if (type == ProcessingType.PiecewisePolynomial) { Rows.Clear(); Rows.Add(new PiecewiseFunctionRow(mode: ProcessingType.PiecewisePolynomial) { ToOperator = Operator.LessOrEqualThan, To = -0.666, Expression = "-1" }); Rows.Add(new PiecewiseFunctionRow(mode: ProcessingType.PiecewisePolynomial) { From = -0.666, FromOperator = Operator.LessThan, ToOperator = Operator.LessThan, To = 0.666, Expression = "0, 1.5" }); Rows.Add(new PiecewiseFunctionRow(mode: ProcessingType.PiecewisePolynomial) { FromOperator = Operator.LessOrEqualThan, From = 0.666, Expression = "1" }); } else if (type == ProcessingType.Bezier) { var c1 = new BezierCurve { P0 = new Point(0, 0), P1 = new Point(0.25, 0.375), P2 = new Point(0.5, 0.75), P3 = new Point(0.666, 1d) }; var c2 = new BezierCurve { P0 = new Point(0.666, 1d), P1 = new Point(0.7, 1d), P2 = new Point(0.9, 1d), P3 = new Point(1.00001, 1d), Next = c1.Id }; Bezier.ClearAndSetCurves(new List<BezierCurve> { c1, c2 }); } } private void CbOversampling_OnSelectionChanged(object sender, SelectionChangedEventArgs e) { var item = (ComboBoxItem) CbOversampling.SelectedItem; int oversampling = int.Parse((string) item.Tag); Player.Oversampling = oversampling; } } }
using System; namespace OpenCTM { public class RawDecoder : MeshDecoder { public static readonly int RAW_TAG = CtmFileReader.getTagInt("RAW\0"); public const int FORMAT_VERSION = 5; public override Mesh decode(MeshInfo minfo, CtmInputStream input) { int vc = minfo.getVertexCount(); AttributeData[] tex = new AttributeData[minfo.getUvMapCount()]; AttributeData[] att = new AttributeData[minfo.getAttrCount()]; checkTag(input.readLittleInt(), INDX); int[] indices = readIntArray(input, minfo.getTriangleCount(), 3, false); checkTag(input.readLittleInt(), VERT); float[] vertices = readFloatArray(input, vc * Mesh.CTM_POSITION_ELEMENT_COUNT, 1); float[] normals = null; if (minfo.hasNormals()) { checkTag(input.readLittleInt(), NORM); normals = readFloatArray(input, vc, Mesh.CTM_NORMAL_ELEMENT_COUNT); } for (int i = 0; i < tex.Length; ++i) { checkTag(input.readLittleInt(), TEXC); tex[i] = readUVData(vc, input); } for (int i = 0; i < att.Length; ++i) { checkTag(input.readLittleInt(), ATTR); att[i] = readAttrData(vc, input); } return new Mesh(vertices, normals, indices, tex, att); } protected void checkTag(int readTag, int expectedTag) { if (readTag != expectedTag) { throw new BadFormatException("Instead of the expected data tag(\"" + CtmFileReader.unpack(expectedTag) + "\") the tag(\"" + CtmFileReader.unpack(readTag) + "\") was read!"); } } protected virtual int[] readIntArray(CtmInputStream input, int count, int size, bool signed) { int[] array = new int[count * size]; for (int i = 0; i < array.Length; i++) { array[i] = input.readLittleInt(); } return array; } protected virtual float[] readFloatArray(CtmInputStream input, int count, int size) { float[] array = new float[count * size]; for (int i = 0; i < array.Length; i++) { array[i] = input.readLittleFloat(); } return array; } private AttributeData readUVData(int vertCount, CtmInputStream input) { String name = input.readString(); String matname = input.readString(); float[] data = readFloatArray(input, vertCount, Mesh.CTM_UV_ELEMENT_COUNT); return new AttributeData(name, matname, AttributeData.STANDARD_UV_PRECISION, data); } private AttributeData readAttrData(int vertCount, CtmInputStream input) { String name = input.readString(); float[] data = readFloatArray(input, vertCount, Mesh.CTM_ATTR_ELEMENT_COUNT); return new AttributeData(name, null, AttributeData.STANDARD_PRECISION, data); } public override bool isFormatSupported(int tag, int version) { return tag == RAW_TAG && version == FORMAT_VERSION; } } }
using System; using System.Collections.Generic; using Alabo.Data.People.Stores.Domain.Services; using Alabo.Domains.Entities; using Alabo.Domains.Query; using Alabo.Exceptions; using Alabo.Extensions; using Alabo.Framework.Core.WebApis; using Alabo.Framework.Core.WebApis.Service; using Alabo.Helpers; using Alabo.Industry.Shop.Deliveries.Domain.Services; using Alabo.Industry.Shop.Orders.Domain.Entities; using Alabo.Industry.Shop.Orders.Domain.Enums; using Alabo.Industry.Shop.Orders.Domain.Services; using Alabo.UI; using Alabo.UI.Design.AutoLists; using Alabo.UI.Design.AutoTables; using OrderType = Alabo.Industry.Shop.Orders.Domain.Enums.OrderType; namespace Alabo.Industry.Shop.Orders.PcDtos { public class SupplierOrder : BaseApiOrderList, IAutoTable<SupplierOrder>, IAutoList { public PageResult<AutoListItem> PageList(object query, AutoBaseModel autoModel) { var dic = HttpWeb.HttpContext.ToDictionary(); dic = dic.RemoveKey("userId"); // 否则查出的订单都是同一个用户 var model = ToQuery<PlatformApiOrderList>(); var expressionQuery = new ExpressionQuery<Order>(); if (model.OrderStatus > 0) { expressionQuery.And(e => e.OrderStatus == model.OrderStatus); } //expressionQuery.And(e => e.OrderStatus != OrderStatus.WaitingBuyerPay); //var isAdmin = Resolve<IUserService>().IsAdmin(model.UserId); //if (!isAdmin) { // throw new ValidException("非管理员不能查看平台订单"); //} // expressionQuery.And(e => e.StoreId > 0); model.UserId = 0; var pageList = Resolve<IOrderApiService>().GetPageList(dic.ToJson(), expressionQuery); var list = new List<AutoListItem>(); foreach (var item in pageList) { var apiData = new AutoListItem { Title = $"金额{item.TotalAmount}元", Intro = item.UserName, Value = item.TotalAmount, Image = Resolve<IApiService>().ApiUserAvator(item.UserId), Id = item.Id, Url = $"/pages/user?path=Asset_recharge_view&id={item.Id}" }; list.Add(apiData); } return ToPageList(list, pageList); } public Type SearchType() { throw new NotImplementedException(); } public List<TableAction> Actions() { var list = new List<TableAction> { ToLinkAction("查看订单", "/User/order/Store/Edit", TableActionType.ColumnAction) //管理员后端查看订单 //ToLinkAction("查看订单", "/Admin/Purchase/Edit",TableActionType.ColumnAction),//采购订单查看 }; return list; } public PageResult<SupplierOrder> PageTable(object query, AutoBaseModel autoModel) { var dic = HttpWeb.HttpContext.ToDictionary(); dic = dic.RemoveKey("userId"); // 否则查出的订单都是同一个用户 dic = dic.RemoveKey("filter"); // var model = ToQuery<SupplierOrder>(); var model = dic.ToJson().ToObject<SupplierOrder>(); var expressionQuery = new ExpressionQuery<Order> { PageIndex = 1, EnablePaging = true }; //供应商只能查看财务已打款后的订单以及该订单后相关的状态 expressionQuery.And(e => e.OrderStatus == OrderStatus.Remited || e.OrderStatus == OrderStatus.WaitingReceiptProduct || e.OrderStatus == OrderStatus.WaitingEvaluated || e.OrderStatus == OrderStatus.Success); // // expressionQuery.And(e => e.StoreId > 0); expressionQuery.And(e => e.UserId > 0); if (Enum.IsDefined(typeof(OrderType), model.OrderType)) { expressionQuery.And(e => e.OrderType == model.OrderType); } var store = Resolve<IStoreService>().GetSingle(u => u.UserId == autoModel.BasicUser.Id); if (store == null) { throw new ValidException("您不是供应商,暂无店铺"); } expressionQuery.And(e => e.StoreId == store.Id.ToString()); //if (autoModel.Filter == FilterType.Admin || autoModel.Filter == FilterType.All) { //var isAdmin = Resolve<IUserService>().IsAdmin(autoModel.BasicUser.Id); //if (!isAdmin) { // throw new ValidException("非管理员不能查看平台订单"); //} //} else if (autoModel.Filter == FilterType.Store) { // var store = Resolve<IStoreService>().GetUserStore(autoModel.BasicUser.Id); // if (store == null) { // throw new ValidException("您不是供应商,暂无店铺"); // } // expressionQuery.And(e => e.StoreId == store.Id); // // 供应商 // //expressionQuery.And(e => e.OrderExtension.IsSupplierView == true); // expressionQuery.And(u => u.OrderStatus == OrderStatus.Remited || u.OrderStatus == OrderStatus.Success // || u.OrderStatus == OrderStatus.WaitingReceiptProduct || u.OrderStatus == OrderStatus.WaitingEvaluated); //} else if (autoModel.Filter == FilterType.User) { // var store = Resolve<IStoreService>().GetUserStore(autoModel.BasicUser.Id); // if (store == null) { // throw new ValidException("您不是供应商,暂无店铺"); // } // expressionQuery.And(e => e.UserId == autoModel.BasicUser.Id); //} else { // throw new ValidException("方式不对"); //} var list = Resolve<IOrderApiService>().GetPageList(dic.ToJson(), expressionQuery); return ToPageResult<SupplierOrder, ApiOrderListOutput>(list); } } }
using System; using Content.Client.CombatMode; using Content.Shared.Hands.Components; using Content.Shared.Weapons.Ranged.Components; using JetBrains.Annotations; using Robust.Client.GameObjects; using Robust.Client.Graphics; using Robust.Client.Input; using Robust.Client.Player; using Robust.Shared.GameObjects; using Robust.Shared.Input; using Robust.Shared.IoC; using Robust.Shared.Map; using Robust.Shared.Timing; namespace Content.Client.Weapons.Ranged { [UsedImplicitly] public sealed class RangedWeaponSystem : EntitySystem { [Dependency] private readonly IPlayerManager _playerManager = default!; [Dependency] private readonly IEyeManager _eyeManager = default!; [Dependency] private readonly IMapManager _mapManager = default!; [Dependency] private readonly IInputManager _inputManager = default!; [Dependency] private readonly IGameTiming _gameTiming = default!; [Dependency] private readonly InputSystem _inputSystem = default!; [Dependency] private readonly CombatModeSystem _combatModeSystem = default!; private bool _blocked; private int _shotCounter; public override void Initialize() { base.Initialize(); UpdatesOutsidePrediction = true; } public override void Update(float frameTime) { base.Update(frameTime); if (!_gameTiming.IsFirstTimePredicted) { return; } var state = _inputSystem.CmdStates.GetState(EngineKeyFunctions.Use); if (!_combatModeSystem.IsInCombatMode() || state != BoundKeyState.Down) { _shotCounter = 0; _blocked = false; return; } var entity = _playerManager.LocalPlayer?.ControlledEntity; if (!EntityManager.TryGetComponent(entity, out SharedHandsComponent? hands)) { return; } if (hands.ActiveHandEntity is not EntityUid held || !EntityManager.TryGetComponent(held, out ClientRangedWeaponComponent? weapon)) { _blocked = true; return; } switch (weapon.FireRateSelector) { case FireRateSelector.Safety: _blocked = true; return; case FireRateSelector.Single: if (_shotCounter >= 1) { _blocked = true; return; } break; case FireRateSelector.Automatic: break; default: throw new ArgumentOutOfRangeException(); } if (_blocked) return; var mapCoordinates = _eyeManager.ScreenToMap(_inputManager.MouseScreenPosition); EntityCoordinates coordinates; if (_mapManager.TryFindGridAt(mapCoordinates, out var grid)) { coordinates = EntityCoordinates.FromMap(grid.GridEntityId, mapCoordinates); } else { coordinates = EntityCoordinates.FromMap(_mapManager.GetMapEntityId(mapCoordinates.MapId), mapCoordinates); } SyncFirePos(coordinates); } private void SyncFirePos(EntityCoordinates coordinates) { RaiseNetworkEvent(new FirePosEvent(coordinates)); } } }
using System; using System.Collections.Generic; using System.Text; namespace Generic.Dapper.UnitOfWork { public interface IGeneralUnitOfWork { void SaveChanges(); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PersonProject { public interface ISpeaking { string SayHello(); string SayThanks(); } public class EnglishSpeaking : ISpeaking { public string SayHello() { return "Hello!"; } public string SayThanks() { return "Thank you!"; } } public class ItalianSpeaking : ISpeaking { public string SayHello() { return "Ciao!"; } public string SayThanks() { return "Grazie mille!"; } } public class GermanSpeaking : ISpeaking { public string SayHello() { return "Halo!"; } public string SayThanks() { return "Dank!"; } } public class SpanishSpeaking : ISpeaking { public string SayHello() { return "Hola!"; } public string SayThanks() { return "Gracias!"; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace PartStore { public class VansViewModel { public IEnumerable<Van> Vans { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DevBuild.ChooseYourOwnAdventure_JoshuaZimmerman { class Program { enum GameState { StartingPosition, ChoiceFortune500, ChoiceGovernmentContractor, ChoiceFriendStartup} struct PathChoice { public int choiceNumber; public string choiceText; public GameState stateToMoveTo; public PathChoice(int choiceNo, string text, GameState state) { choiceNumber = choiceNo; choiceText = text; stateToMoveTo = state; } } static void Main(string[] args) { GameState userGameState = GameState.StartingPosition; int userChoice = -1; PathChoice startOver = new PathChoice(0, "Start Over", GameState.StartingPosition); PathChoice fortune500Choice = new PathChoice(1, "(1) Get job with Fortune 500 company", GameState.ChoiceFortune500); PathChoice governmentContractorChoice = new PathChoice(2, "(2) Get job with government contractor", GameState.ChoiceGovernmentContractor); PathChoice friendStartupChoice = new PathChoice(3, "(3) Get job with your friend's startup company", GameState.ChoiceFriendStartup); Console.Write( "***********************************************************\n" + "* Dev.Build(2.0) - Choose your own Adventure *\n" + "***********************************************************\n\n"); //present adventure synopsis to user Console.WriteLine( "Congratulations! You've graduated from a reputable coding bootcamp and you're off to start your first adventure " + "as a\nprofessional developer. The offers are lining up, and it's time for you to choose where to apply. \nA Fortune 500 company with a sterling reputation has made a formal offer, as have a few government contractors. \nIf you're feeling especially adventurous, you can also see about a job with one of a few startup companies run by your fellow bootcamp alumnists."); Console.WriteLine("\n"); //present user with five choices, record user's choice Console.WriteLine(fortune500Choice.choiceText); Console.WriteLine(governmentContractorChoice.choiceText); Console.WriteLine(friendStartupChoice.choiceText); userChoice = int.Parse(Console.ReadLine()); //process user's choice, use switch statement switch (userChoice) { } } } }
using System; namespace RazorTute.Models { public class Location { public int ID { get; set; } public string Name { get; set; } public DateTime captureDate { get; set; } public string resources { get; set; } public decimal distance { get; set; } } }
using Backend.Model; using FeedbackAndSurveyService.CustomException; using FeedbackAndSurveyService.FeedbackService.Model; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; namespace FeedbackAndSurveyService.FeedbackService.Repository { public class FeedbackRepository : IFeedbackRepository { private readonly MyDbContext _context; public FeedbackRepository(MyDbContext context) { _context = context; } public void Add(Feedback entity) { try { var feedback = entity.ToBackendFeedback(); feedback.Id = 0; _context.Add(feedback); _context.SaveChanges(); } catch (DbUpdateException e) { throw new ValidationException(e.Message); } catch (Exception e) { throw new DataStorageException(e.Message); } } public void Update(Feedback entity) { try { var memento = entity.GetMemento(); var feedback = _context.Feedbacks.Find(memento.Id); feedback.IsPublished = memento.IsPublished; _context.Update(feedback); _context.SaveChanges(); } catch (DbUpdateException e) { throw new ValidationException(e.Message); } catch (Exception e) { throw new DataStorageException(e.Message); } } public Feedback Get(int id) { try { var feedback = _context.Feedbacks.Find(id); if (feedback == null) throw new NotFoundException("Feedback with id " + id + " does not exist."); return feedback.ToFeedback(); } catch (FeedbackAndSurveyServiceException) { throw; } catch (Exception e) { throw new DataStorageException(e.Message); } } public IEnumerable<Feedback> GetPublished() { try { return _context.Feedbacks.Where(f => f.IsPublished == true).Select(f => f.ToFeedback()); } catch (Exception e) { throw new DataStorageException(e.Message); } } public IEnumerable<Feedback> GetUnpublished() { try { return _context.Feedbacks.Where(f => f.IsPublished == false).Select(f => f.ToFeedback()); } catch (Exception e) { throw new DataStorageException(e.Message); } } } }
using System; using System.Data; using System.Text; using System.Data.SqlClient; using Maticsoft.DBUtility;//Please add references namespace ITCastOCSS.DAL { /// <summary> /// 数据访问类:Student /// </summary> public partial class Student { public Student() {} #region BasicMethod /// <summary> /// 得到最大ID /// </summary> public int GetMaxId() { return DbHelperSQL.GetMaxID("SID", "Student"); } /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(int SID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) from Student"); strSql.Append(" where SID=@SID"); SqlParameter[] parameters = { new SqlParameter("@SID", SqlDbType.Int,4) }; parameters[0].Value = SID; return DbHelperSQL.Exists(strSql.ToString(),parameters); } /// <summary> /// 增加一条数据 /// </summary> public int Add(ITCastOCSS.Model.Student model) { StringBuilder strSql=new StringBuilder(); strSql.Append("insert into Student("); strSql.Append("SNo,SName,SPwd,SSex,SClass,SType,SDepartment,SMajor,SMaxNum,SActualNum,SBirthday,SInTime,SGrade,SNote)"); strSql.Append(" values ("); strSql.Append("@SNo,@SName,@SPwd,@SSex,@SClass,@SType,@SDepartment,@SMajor,@SMaxNum,@SActualNum,@SBirthday,@SInTime,@SGrade,@SNote)"); strSql.Append(";select @@IDENTITY"); SqlParameter[] parameters = { new SqlParameter("@SNo", SqlDbType.Char,9), new SqlParameter("@SName", SqlDbType.NVarChar,8), new SqlParameter("@SPwd", SqlDbType.VarChar,20), new SqlParameter("@SSex", SqlDbType.NChar,1), new SqlParameter("@SClass", SqlDbType.VarChar,10), new SqlParameter("@SType", SqlDbType.VarChar,10), new SqlParameter("@SDepartment", SqlDbType.NVarChar,20), new SqlParameter("@SMajor", SqlDbType.NVarChar,20), new SqlParameter("@SMaxNum", SqlDbType.Int,4), new SqlParameter("@SActualNum", SqlDbType.Int,4), new SqlParameter("@SBirthday", SqlDbType.DateTime), new SqlParameter("@SInTime", SqlDbType.DateTime), new SqlParameter("@SGrade", SqlDbType.NVarChar,10), new SqlParameter("@SNote", SqlDbType.NVarChar,100)}; parameters[0].Value = model.SNo; parameters[1].Value = model.SName; parameters[2].Value = model.SPwd; parameters[3].Value = model.SSex; parameters[4].Value = model.SClass; parameters[5].Value = model.SType; parameters[6].Value = model.SDepartment; parameters[7].Value = model.SMajor; parameters[8].Value = model.SMaxNum; parameters[9].Value = model.SActualNum; parameters[10].Value = model.SBirthday; parameters[11].Value = model.SInTime; parameters[12].Value = model.SGrade; parameters[13].Value = model.SNote; object obj = DbHelperSQL.GetSingle(strSql.ToString(),parameters); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 更新一条数据 /// </summary> public bool Update(ITCastOCSS.Model.Student model) { StringBuilder strSql=new StringBuilder(); strSql.Append("update Student set "); strSql.Append("SNo=@SNo,"); strSql.Append("SName=@SName,"); strSql.Append("SPwd=@SPwd,"); strSql.Append("SSex=@SSex,"); strSql.Append("SClass=@SClass,"); strSql.Append("SType=@SType,"); strSql.Append("SDepartment=@SDepartment,"); strSql.Append("SMajor=@SMajor,"); strSql.Append("SMaxNum=@SMaxNum,"); strSql.Append("SActualNum=@SActualNum,"); strSql.Append("SBirthday=@SBirthday,"); strSql.Append("SInTime=@SInTime,"); strSql.Append("SGrade=@SGrade,"); strSql.Append("SNote=@SNote"); strSql.Append(" where SID=@SID"); SqlParameter[] parameters = { new SqlParameter("@SNo", SqlDbType.Char,9), new SqlParameter("@SName", SqlDbType.NVarChar,8), new SqlParameter("@SPwd", SqlDbType.VarChar,20), new SqlParameter("@SSex", SqlDbType.NChar,1), new SqlParameter("@SClass", SqlDbType.VarChar,10), new SqlParameter("@SType", SqlDbType.VarChar,10), new SqlParameter("@SDepartment", SqlDbType.NVarChar,20), new SqlParameter("@SMajor", SqlDbType.NVarChar,20), new SqlParameter("@SMaxNum", SqlDbType.Int,4), new SqlParameter("@SActualNum", SqlDbType.Int,4), new SqlParameter("@SBirthday", SqlDbType.DateTime), new SqlParameter("@SInTime", SqlDbType.DateTime), new SqlParameter("@SGrade", SqlDbType.NVarChar,10), new SqlParameter("@SNote", SqlDbType.NVarChar,100), new SqlParameter("@SID", SqlDbType.Int,4)}; parameters[0].Value = model.SNo; parameters[1].Value = model.SName; parameters[2].Value = model.SPwd; parameters[3].Value = model.SSex; parameters[4].Value = model.SClass; parameters[5].Value = model.SType; parameters[6].Value = model.SDepartment; parameters[7].Value = model.SMajor; parameters[8].Value = model.SMaxNum; parameters[9].Value = model.SActualNum; parameters[10].Value = model.SBirthday; parameters[11].Value = model.SInTime; parameters[12].Value = model.SGrade; parameters[13].Value = model.SNote; parameters[14].Value = model.SID; int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(int SID) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from Student "); strSql.Append(" where SID=@SID"); SqlParameter[] parameters = { new SqlParameter("@SID", SqlDbType.Int,4) }; parameters[0].Value = SID; int rows=DbHelperSQL.ExecuteSql(strSql.ToString(),parameters); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 批量删除数据 /// </summary> public bool DeleteList(string SIDlist ) { StringBuilder strSql=new StringBuilder(); strSql.Append("delete from Student "); strSql.Append(" where SID in ("+SIDlist + ") "); int rows=DbHelperSQL.ExecuteSql(strSql.ToString()); if (rows > 0) { return true; } else { return false; } } /// <summary> /// 得到一个对象实体 /// </summary> public ITCastOCSS.Model.Student GetModel(int SID) { StringBuilder strSql=new StringBuilder(); strSql.Append("select top 1 SID,SNo,SName,SPwd,SSex,SClass,SType,SDepartment,SMajor,SMaxNum,SActualNum,SBirthday,SInTime,SGrade,SNote from Student "); strSql.Append(" where SID=@SID"); SqlParameter[] parameters = { new SqlParameter("@SID", SqlDbType.Int,4) }; parameters[0].Value = SID; ITCastOCSS.Model.Student model=new ITCastOCSS.Model.Student(); DataSet ds=DbHelperSQL.Query(strSql.ToString(),parameters); if(ds.Tables[0].Rows.Count>0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } /// <summary> /// 得到一个对象实体 /// </summary> public ITCastOCSS.Model.Student DataRowToModel(DataRow row) { ITCastOCSS.Model.Student model=new ITCastOCSS.Model.Student(); if (row != null) { if(row["SID"]!=null && row["SID"].ToString()!="") { model.SID=int.Parse(row["SID"].ToString()); } if(row["SNo"]!=null) { model.SNo=row["SNo"].ToString(); } if(row["SName"]!=null) { model.SName=row["SName"].ToString(); } if(row["SPwd"]!=null) { model.SPwd=row["SPwd"].ToString(); } if(row["SSex"]!=null) { model.SSex=row["SSex"].ToString(); } if(row["SClass"]!=null) { model.SClass=row["SClass"].ToString(); } if(row["SType"]!=null) { model.SType=row["SType"].ToString(); } if(row["SDepartment"]!=null) { model.SDepartment=row["SDepartment"].ToString(); } if(row["SMajor"]!=null) { model.SMajor=row["SMajor"].ToString(); } if(row["SMaxNum"]!=null && row["SMaxNum"].ToString()!="") { model.SMaxNum=int.Parse(row["SMaxNum"].ToString()); } if(row["SActualNum"]!=null && row["SActualNum"].ToString()!="") { model.SActualNum=int.Parse(row["SActualNum"].ToString()); } if(row["SBirthday"]!=null && row["SBirthday"].ToString()!="") { model.SBirthday=DateTime.Parse(row["SBirthday"].ToString()); } if(row["SInTime"]!=null && row["SInTime"].ToString()!="") { model.SInTime=DateTime.Parse(row["SInTime"].ToString()); } if(row["SGrade"]!=null) { model.SGrade=row["SGrade"].ToString(); } if(row["SNote"]!=null) { model.SNote=row["SNote"].ToString(); } } return model; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select SID,SNo,SName,SPwd,SSex,SClass,SType,SDepartment,SMajor,SMaxNum,SActualNum,SBirthday,SInTime,SGrade,SNote "); strSql.Append(" FROM Student "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// 获得前几行数据 /// </summary> public DataSet GetList(int Top,string strWhere,string filedOrder) { StringBuilder strSql=new StringBuilder(); strSql.Append("select "); if(Top>0) { strSql.Append(" top "+Top.ToString()); } strSql.Append(" SID,SNo,SName,SPwd,SSex,SClass,SType,SDepartment,SMajor,SMaxNum,SActualNum,SBirthday,SInTime,SGrade,SNote "); strSql.Append(" FROM Student "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } strSql.Append(" order by " + filedOrder); return DbHelperSQL.Query(strSql.ToString()); } /// <summary> /// 获取记录总数 /// </summary> public int GetRecordCount(string strWhere) { StringBuilder strSql=new StringBuilder(); strSql.Append("select count(1) FROM Student "); if(strWhere.Trim()!="") { strSql.Append(" where "+strWhere); } object obj = DbHelperSQL.GetSingle(strSql.ToString()); if (obj == null) { return 0; } else { return Convert.ToInt32(obj); } } /// <summary> /// 分页获取数据列表 /// </summary> public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex) { StringBuilder strSql=new StringBuilder(); strSql.Append("SELECT * FROM ( "); strSql.Append(" SELECT ROW_NUMBER() OVER ("); if (!string.IsNullOrEmpty(orderby.Trim())) { strSql.Append("order by T." + orderby ); } else { strSql.Append("order by T.SID desc"); } strSql.Append(")AS Row, T.* from Student T "); if (!string.IsNullOrEmpty(strWhere.Trim())) { strSql.Append(" WHERE " + strWhere); } strSql.Append(" ) TT"); strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex); return DbHelperSQL.Query(strSql.ToString()); } /* /// <summary> /// 分页获取数据列表 /// </summary> public DataSet GetList(int PageSize,int PageIndex,string strWhere) { SqlParameter[] parameters = { new SqlParameter("@tblName", SqlDbType.VarChar, 255), new SqlParameter("@fldName", SqlDbType.VarChar, 255), new SqlParameter("@PageSize", SqlDbType.Int), new SqlParameter("@PageIndex", SqlDbType.Int), new SqlParameter("@IsReCount", SqlDbType.Bit), new SqlParameter("@OrderType", SqlDbType.Bit), new SqlParameter("@strWhere", SqlDbType.VarChar,1000), }; parameters[0].Value = "Student"; parameters[1].Value = "SID"; parameters[2].Value = PageSize; parameters[3].Value = PageIndex; parameters[4].Value = 0; parameters[5].Value = 0; parameters[6].Value = strWhere; return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds"); }*/ #endregion BasicMethod #region ExtensionMethod /// <summary> /// 得到一个对象实体 /// </summary> public ITCastOCSS.Model.Student GetModel(string no) { StringBuilder strSql = new StringBuilder(); strSql.Append("select top 1 SID,SNo,SName,SPwd,SSex,SClass,SType,SDepartment,SMajor,SMaxNum,SActualNum,SBirthday,SInTime,SGrade,SNote from Student "); strSql.Append(" where SNo=@SNo"); SqlParameter[] parameters = { new SqlParameter("@SNo", SqlDbType.Char) }; parameters[0].Value = no; ITCastOCSS.Model.Student model = new ITCastOCSS.Model.Student(); DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters); if (ds.Tables[0].Rows.Count > 0) { return DataRowToModel(ds.Tables[0].Rows[0]); } else { return null; } } public int StudentPwd(int sid,string pwd) { string sql =string.Format("update student set SPwd='{0}' where sid={1} ",pwd,sid); return DbHelperSQL.ExecuteSql(sql); } #endregion ExtensionMethod } }
using System; using GatewayEDI.Logging; using GatewayEDI.Logging.Formatters; using log4net; namespace Log4netFacade { /// <summary> An implementation of the <see cref="GatewayEDI.Logging.ILog" /> interface which logs messages via the log4net framework. </summary> public class Log4netLog : FormattableLogBase { /// <summary> The log4net log which this class wraps. </summary> private readonly log4net.ILog log; /// <summary> Constructs an instance of <see cref="Log4netLog" /> by wrapping a log4net log. </summary> /// <param name="log"> The log4net log to wrap </param> internal Log4netLog(log4net.ILog log) : base(SingleLineFormatter.Instance) { this.log = log; } /// <summary> Logs the given message. Output depends on the associated log4net configuration. </summary> /// <param name="item"> A <see cref="LogItem" /> which encapsulates information to be logged. </param> /// <exception cref="ArgumentNullException"> If <paramref name="item" /> is a null reference. </exception> public override void Write(LogItem item) { if (item == null) throw new ArgumentNullException("item"); string message = FormatItem(item); switch (item.LogLevel) { case LogLevel.Fatal: log.Fatal(message, item.Exception); break; case LogLevel.Error: log.Error(message, item.Exception); break; case LogLevel.Warn: log.Warn(message, item.Exception); break; case LogLevel.Info: log.Info(message, item.Exception); break; case LogLevel.Debug: log.Debug(message, item.Exception); break; default: log.Info(message, item.Exception); break; } } /// <summary> Overriden to delegate to the log4net IsXxxEnabled properties. </summary> protected override bool IsLogLevelEnabled(LogLevel level) { switch (level) { case LogLevel.Debug: return log.IsDebugEnabled; case LogLevel.Error: return log.IsErrorEnabled; case LogLevel.Fatal: return log.IsFatalEnabled; case LogLevel.Info: return log.IsInfoEnabled; case LogLevel.Warn: return log.IsWarnEnabled; default: return true; } } #region NDC /// <summary> Pushes a new context message on to the stack implementation of the underlying logger. </summary> /// <param name="message"> The new context message. </param> /// <returns> An IDisposable reference to the stack. </returns> public override IDisposable Push(string message) { return ThreadContext.Stacks["NDC"].Push(message); } /// <summary> Pops a context message off of the stack implementation of the underlying logger. </summary> /// <returns> The context message that was on the top of the stack. </returns> public override string Pop() { return ThreadContext.Stacks["NDC"].Pop(); } /// <summary> Clears all the contextual information held on the stack implementation of the underlying logger. </summary> public override void ClearNdc() { ThreadContext.Stacks["NDC"].Clear(); } #endregion #region MDC /// <summary> Add an entry to the contextual properties of the underlying logger. </summary> /// <param name="key"> The key to store the value under. </param> /// <param name="value"> The value to store. </param> public override void Set(string key, string value) { ThreadContext.Properties[key] = value; } /// <summary> Gets the context value identified by the <paramref name="key" /> parameter. </summary> /// <param name="key"> The key to lookup in the underlying logger. </param> /// <returns> The value of the named context property. </returns> public override string Get(string key) { object obj = ThreadContext.Properties[key]; if (obj == null) { return null; } return obj.ToString(); } /// <summary> Removes the key value mapping for the key specified. </summary> /// <param name="key"> The key to remove. </param> public override void Remove(string key) { ThreadContext.Properties.Remove(key); } /// <summary> Clear all entries in the underlying logger. </summary> public override void ClearMdc() { ThreadContext.Properties.Clear(); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SAAS.FrameWork { public enum ServerErrcodeEnum : int { Normal = 0, /// <summary> /// 服务异常 /// </summary> ServiceError = 1, /// <summary> /// 登录异常 /// </summary> LoginError = 2, /// <summary> /// tocken验证失败 /// </summary> TokenError = 3, /// <summary> /// 码不存在 /// </summary> BusError = 4, /// <summary> /// 码被使用 /// </summary> BusCodeDoError = 5, /// <summary> /// 码未被激活 /// </summary> BusCodeUndoError = 6, /// <summary> /// 该项目无路由 /// </summary> BusProjectNoRouterError = 7, /// <summary> /// 当前码无路由 /// </summary> BusCodeNoRouterError = 8 } public enum LogType { Mongodb = 1, Redis = 2, Track = 3, Queue = 4, IPCheck = 5, ES = 6, JS = 7, Other = 0, Rabbitmq = 8, Error = 9, Warring = 10, } public enum LoggerType { WebExceptionLog, ServiceExceptionLog, Error, Warnning, Info, Trace } /// <summary> /// 排序 /// </summary> public enum Sort { Asc = 0, Desc = 1 } }
using System; using System.Collections.Generic; using Microsoft.AspNetCore.Http; namespace NetEscapades.AspNetCore.SecurityHeaders.Headers.ContentSecurityPolicy; /// <summary> /// The sandbox directive enables a sandbox for the requested resource similar /// to the &lt;script&gt; sandbox attribute. It applies restrictions to a /// page's actions including preventing popups, preventing the execution /// of plugins and scripts, and enforcing a same-origin policy. /// </summary> public class SandboxDirectiveBuilder : CspDirectiveBuilderBase { private const string Separator = " "; /// <summary> /// Initializes a new instance of the <see cref="SandboxDirectiveBuilder"/> class. /// </summary> public SandboxDirectiveBuilder() : base("sandbox") { } /// <summary> /// The sandbox tokens to apply. /// </summary> private List<string> Tokens { get; } = new(); /// <summary> /// Allows for downloads after the user clicks a button or link. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowDownloads() { Tokens.Add("allow-downloads"); return this; } /// <summary> /// Allows the page to submit forms. If this keyword is not used, this operation is not allowed. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowForms() { Tokens.Add("allow-forms"); return this; } /// <summary> /// Allows the page to open modal windows. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowModals() { Tokens.Add("allow-modals"); return this; } /// <summary> /// Allows the page to disable the ability to lock the screen orientation. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowOrientationLock() { Tokens.Add("allow-orientation-lock"); return this; } /// <summary> /// Allows the page to use the Pointer Lock API. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowPointerLock() { Tokens.Add("allow-pointer-lock"); return this; } /// <summary> /// Allows popups (like from <c>window.open</c>, <c>target="_blank"</c>, <c>showModalDialog</c>). /// If this keyword is not used, that functionality will silently fail. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowPopups() { Tokens.Add("allow-popups"); return this; } /// <summary> /// Allows a sandboxed document to open new windows without forcing the sandboxing /// flags upon them. This will allow, for example, a third-party advertisement /// to be safely sandboxed without forcing the same restrictions upon the /// page the ad links to. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowPopupsToEscapeSandbox() { Tokens.Add("allow-popups-to-escape-sandbox"); return this; } /// <summary> /// Allows embedders to have control over whether an iframe can start a presentation session. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowPresentation() { Tokens.Add("allow-presentation"); return this; } /// <summary> /// Allows the content to be treated as being from its normal origin. /// If this keyword is not used, the embedded content is treated as being from a unique origin. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowSameOrigin() { Tokens.Add("allow-same-origin"); return this; } /// <summary> /// Allows the page to run scripts (but not create pop-up windows). /// If this keyword is not used, this operation is not allowed. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowScripts() { Tokens.Add("allow-scripts"); return this; } /// <summary> /// Allows the page to navigate (load) content to the top-level /// browsing context. If this keyword is not used, this operation is not allowed. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowTopNavigation() { Tokens.Add("allow-top-navigation"); return this; } /// <summary> /// Lets the resource navigate the top-level browsing context, /// but only if initiated by a user gesture /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowTopNavigationByUserActivation() { Tokens.Add("allow-top-navigation-by-user-activation"); return this; } /// <summary> /// Allows navigations toward non-fetch schemes to be /// handed off to external software. /// </summary> /// <returns>The CSP builder for method chaining</returns> public SandboxDirectiveBuilder AllowTopNavigationToCustomProtocols() { Tokens.Add("allow-top-navigation-to-custom-protocols"); return this; } /// <summary> /// Adds a custom token to the sandbox directive. Useful for adding /// experimental tokens. /// </summary> /// <returns>The CSP builder for method chaining</returns> /// <param name="token">The token to add</param> public SandboxDirectiveBuilder AddCustomToken(string token) { Tokens.Add(token); return this; } /// <inheritdoc /> internal override Func<HttpContext, string> CreateBuilder() { var sources = string.Join(Separator, Tokens); var result = string.IsNullOrEmpty(sources) ? Directive : $"{Directive} {sources}"; return _ => result; } }