text
stringlengths
13
6.01M
namespace OpenKnife.States { [System.Serializable] public enum GameState { MAIN_MENU, IN_GAME, GAME_OVER } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MortgageCalculator.DAL.Data; using MortgageCalculator.DAL.Repositories; using MortgageCalculator.Contracts.Repositories; using MortgageCalculator.Model; using MortgageCalculator.Service; namespace MortgageCalculator.WebUI.Controllers { public class HomeController : Controller { IRepositoryBase<Mortgage> mortgages; public HomeController(IRepositoryBase<Mortgage> mortgages) { this.mortgages = mortgages; } public ActionResult Index() { Mortgage model = new Mortgage(); return View(model); } [HttpPost] public ActionResult Index(Mortgage mortgage, FormCollection formCollection) { mortgage.insertedIn = DateTime.Now; mortgage.monthlypayment = Decimal.Parse(formCollection["monthlypayment"]); mortgages.Insert(mortgage); mortgages.Commit(); return RedirectToAction("CheckOutput", "Home", new { id = mortgage.mortgageId }); } public ActionResult CheckOutput(int id) { Mortgage mortgage = mortgages.GetById(id); return View(mortgage); } [HttpPost] public ActionResult SendEmail(FormCollection formCollection) { string email = formCollection["email"]; int mortgageId = 0; if (Int32.TryParse(formCollection["mortgageId"], out mortgageId)) { Mortgage mortgage = mortgages.GetById(mortgageId); mortgage.email = email; /* * Call Email Service * if Successfully sent: * set mortgage.sent = true * update mortgage Object on Database */ mortgage.sent = true; mortgages.Update(mortgage); mortgages.Commit(); } TempData["message"] = "OK"; //return RedirectToAction("SentEmail","Home"); return RedirectToAction("CheckOutput", "Home", new { id = mortgageId }); } public ActionResult SentEmail() { return View(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Data; using System.Data.SqlClient; using Accounting.Entity; using Accounting.Utility; namespace Accounting.DataAccess { public class BusinessTypeDA { public BusinessTypeDA() { } public int SaveOrUpdate(BusinessType objBusinessType) { SqlConnection con = null; SqlCommand com = null; SqlTransaction trans = null; try { con = ConnectionHelper.getConnection(); trans = con.BeginTransaction(); com = new SqlCommand(); com.Connection = con; com.Transaction = trans; if (objBusinessType.BusinessTypeID == 0) { objBusinessType.BusinessTypeID = ConnectionHelper.GetID(con, trans, "BusinessTypeID", "BusinessType"); com.CommandText = "Insert Into BusinessType(BusinessTypeID, Name) Values(@BusinessTypeID, @Name)"; } else { com.CommandText = "Update BusinessType SET Name = @Name WHERE BusinessTypeID = @BusinessTypeID"; } com.Parameters.Add("@BusinessTypeID", SqlDbType.Int).Value = objBusinessType.BusinessTypeID; com.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = objBusinessType.Name; com.ExecuteNonQuery(); trans.Commit(); ConnectionHelper.closeConnection(con); } catch (Exception Ex) { if (trans != null) { trans.Rollback(); ConnectionHelper.closeConnection(con); } throw new Exception("Can not save or update" + Ex.Message); } return objBusinessType.BusinessTypeID; } public ArrayList getBusinessType(int numBusinessTypeID) { ArrayList list = new ArrayList(); try { var data = new DataTable(); string qstr = numBusinessTypeID == 0 ? "Select * FROM BusinessType" : "Select * FROM BusinessType WHERE BusinessTypeID = " + numBusinessTypeID.ToString(); using (SqlDataAdapter adapter = new SqlDataAdapter(qstr, ConnectionHelper.DefaultConnectionString)) { adapter.Fill(data); adapter.Dispose(); } foreach (DataRow row in data.Rows) { list.Add(CreateObject(row)); } } catch (Exception Ex) { throw new Exception("Can not get BusinessType" + Ex.Message); } return list; } public void Delete(int numBusinessTypeID) { SqlConnection con = null; SqlCommand com = null; SqlTransaction trans = null; try { con = ConnectionHelper.getConnection(); trans = con.BeginTransaction(); com = new SqlCommand(); com.Connection = con; com.Transaction = trans; com.CommandText = "DELETE FROM BusinessType WHERE BusinessTypeID = @BusinessTypeID"; com.Parameters.Add("@BusinessTypeID", SqlDbType.Int).Value = numBusinessTypeID; com.ExecuteNonQuery(); trans.Commit(); ConnectionHelper.closeConnection(con); } catch (Exception Ex) { if (trans != null) { trans.Rollback(); } throw new Exception("Can not get BusinessType" + Ex.Message); } } #region CreateObjects private BusinessType CreateObject(IDataReader objReader) { BusinessType objBusinessType = new BusinessType(); NullManager reader = new NullManager(objReader); try { objBusinessType.BusinessTypeID = reader.GetInt32("BusinessTypeID"); objBusinessType.Name = reader.GetString("Name"); objBusinessType.CompanyID = reader.GetInt32("CompanyID"); objBusinessType.UserID = reader.GetInt32("UserID"); objBusinessType.ModifiedDate = reader.GetDateTime("ModifiedDate"); } catch (Exception Ex) { throw new Exception("Error while creating object" + Ex.Message); } return objBusinessType; } private BusinessType CreateObject(DataRow row) { BusinessType objBusinessType = new BusinessType(); try { objBusinessType.BusinessTypeID = GlobalFunctions.isNull(row["BusinessTypeID"], 0); objBusinessType.Name = GlobalFunctions.isNull(row["Name"], ""); } catch (Exception Ex) { throw new Exception("Error while creating object" + Ex.Message); } return objBusinessType; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using Business.Helper; using eIVOGo.Module.Base; using Model.DataEntity; using Model.InvoiceManagement; using Model.Locale; using Model.Security.MembershipManagement; using Utility; using Uxnet.Web.Module.Common; namespace eIVOGo.Module.Inquiry { public partial class InquireInvoiceCancellationItem : InquireInvoiceItem { protected override void buildQueryItem() { Expression<Func<InvoiceCancellation, bool>> queryExpr = i => true; if (_userProfile.CurrentUserRole.RoleID != ((int)Naming.RoleID.ROLE_SYS)) { queryExpr = queryExpr.And(d => d.InvoiceItem.InvoiceSeller.SellerID == _userProfile.CurrentUserRole.OrganizationCategory.CompanyID || d.InvoiceItem.InvoiceBuyer.BuyerID == _userProfile.CurrentUserRole.OrganizationCategory.CompanyID); } if (DateFrom.HasValue) { queryExpr = queryExpr.And(i => i.InvoiceItem.InvoiceDate >= DateFrom.DateTimeValue); } if (DateTo.HasValue) { queryExpr = queryExpr.And(i => i.InvoiceItem.InvoiceDate < DateTo.DateTimeValue.AddDays(1)); } if (!string.IsNullOrEmpty(this.txtCancellationNO.Text.Trim())) { queryExpr = queryExpr.And(i => (i.CancellationNo.Trim()).Equals(this.txtCancellationNO.Text.Trim())); } itemList.BuildQuery = table => { var invoices = table.Context.GetTable<InvoiceItem>() .Join(table.Context.GetTable<InvoiceCancellation>().OrderByDescending(ic => ic.CancelDate).Where(queryExpr), i => i.InvoiceID, c => c.InvoiceID, (i, c) => i); if (!String.IsNullOrEmpty(CompanyID.SelectedValue)) { int companyID = int.Parse(CompanyID.SelectedValue); if (!String.IsNullOrEmpty(BusinessID.SelectedValue)) { if (Naming.InvoiceCenterBusinessType.進項 == (Naming.InvoiceCenterBusinessType)int.Parse(BusinessID.SelectedValue)) { invoices = invoices.Join(table.Context.GetTable<InvoiceSeller>().Where(s => s.SellerID == companyID) , i => i.InvoiceID, s => s.InvoiceID, (i, s) => i); } else { invoices = invoices.Join(table.Context.GetTable<InvoiceBuyer>().Where(b => b.BuyerID == companyID) , i => i.InvoiceID, s => s.InvoiceID, (i, s) => i); } } else { invoices = invoices.Join(table.Context.GetTable<InvoiceSeller>().Where(i => i.SellerID == companyID), i => i.InvoiceID, s => s.InvoiceID, (i, s) => i) .Concat(invoices.Join(table.Context.GetTable<InvoiceBuyer>().Where(i => i.BuyerID == companyID), i => i.InvoiceID, s => s.InvoiceID, (i, s) => i)); } } else { if (!String.IsNullOrEmpty(BusinessID.SelectedValue)) { if (Naming.InvoiceCenterBusinessType.進項 == (Naming.InvoiceCenterBusinessType)int.Parse(BusinessID.SelectedValue)) { invoices = invoices.Where(i => i.InvoiceBuyer.BuyerID == _userProfile.CurrentUserRole.OrganizationCategory.CompanyID); ; } else { invoices = invoices.Where(i => i.InvoiceSeller.SellerID == _userProfile.CurrentUserRole.OrganizationCategory.CompanyID); } } } if (!String.IsNullOrEmpty(LevelID.SelectedValue)) { if (!setdayrange) return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation && d.CurrentStep == int.Parse(LevelID.SelectedValue)) .Join(table.Context.GetTable<DerivedDocument>() .Join(invoices.Where(i => i.InvoiceDate <= DateTime.Today & i.InvoiceDate >= DateTime.Today.AddMonths(-5)), d => d.SourceID, i => i.InvoiceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d); else return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation && d.CurrentStep == int.Parse(LevelID.SelectedValue)) .Join(table.Context.GetTable<DerivedDocument>() .Join(invoices, d => d.SourceID, i => i.InvoiceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d); } else { if (!setdayrange) return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation) .Join(table.Context.GetTable<DerivedDocument>() .Join(invoices.Where(i => i.InvoiceDate <= DateTime.Today & i.InvoiceDate >= DateTime.Today.AddMonths(-5)), d => d.SourceID, i => i.InvoiceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d); else return table.Where(d => d.DocType == (int)Naming.DocumentTypeDefinition.E_InvoiceCancellation) .Join(table.Context.GetTable<DerivedDocument>() .Join(invoices, d => d.SourceID, i => i.InvoiceID, (d, i) => d) , d => d.DocID, r => r.DocID, (d, r) => d); } }; if (itemList.Select().Count() > 0) { tblAction.Visible = true; } else { tblAction.Visible = false; } } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using log4net; namespace XorLog.Core { public class RawFileReaderEx : IRawFileReader { const char LINE_SEPARATOR = '\n'; const char CARRIAGE_RETURN = '\r'; private static readonly ILog Log = LogManager.GetLogger("RawFileReaderEx"); private FileStream _stream; private FileInfo _fileInfo; private string _path; private long _currentPosition; private SeekOrigin _currentSeekOrigin; Encoding _encoding = Encoding.Default; public void Open(string path) { _path = path; CheckPath(); _currentPosition = 0; } private void OpenFile() { CheckPath(); int bufferSize = 1000; try { _stream = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite|FileShare.Delete, bufferSize); _fileInfo = new FileInfo(_path); } catch (IOException e) { Log.Debug(e); } } private void CheckPath() { if (string.IsNullOrEmpty(_path)) { throw new ArgumentNullException("Path"); } if (!File.Exists(_path)) { throw new FileNotFoundException(_path); } } public void SetLength(long value) { _stream.SetLength(value); } private void CloseFile() { if (_stream!=null) { _stream.Close(); _stream.Dispose(); _stream = null; } } public void Close() { _path = null; } private void ReloadCurrentPosition() { _stream.Seek(_currentPosition, _currentSeekOrigin); } public void SetPosition(long offset, SeekOrigin origin) { _currentPosition = offset; _currentSeekOrigin = origin; } public long GetPosition() { return _currentPosition; } public void SetEncoding(Encoding itemEncoder) { Log.Debug("encoding is changed to "+ itemEncoder); _encoding = itemEncoder; } public ReadBlock ReadBlock(char[] buffer, long count, IList<string> rejectionList) { OpenFile(); ReloadCurrentPosition(); byte[] array = new byte[count]; int nbRead = _stream.Read(array, 0, (int)count); string decoded = _encoding.GetString(array, 0, nbRead); string char2StringTrimmed = decoded.TrimEnd(); string[] lines = char2StringTrimmed.Split(LINE_SEPARATOR); IList<string> linesNotFiltered = lines.Select(x => x.TrimEnd()).ToList(); IList<string> linesFiltered = FilterLines(rejectionList, linesNotFiltered); var ret = new ReadBlock { Content = linesFiltered, SizeInBytes = nbRead }; _currentPosition = _stream.Position; _currentSeekOrigin = SeekOrigin.Begin; CloseFile(); return ret; } private IList<string> FilterLines(IList<string> rejectionList, IList<string> linesNotFiltered) { IList<string> ret; if (rejectionList == null) { ret = linesNotFiltered; } else if (!rejectionList.Any()) { ret = linesNotFiltered; } else { ret = new List<string>(); foreach (string line in linesNotFiltered) { var validLine = IsValidLine(rejectionList, line); if (validLine) { ret.Add(line); } } } return ret; } private bool IsValidLine(IList<string> rejectionList, string line) { bool validLine = true; foreach (string blackWord in rejectionList) { if (line.Contains(blackWord)) { validLine = false; } } return validLine; } public IList<string> CreateLinesFromBuffer(char[] buffer, long length) { string char2String = new string(buffer, 0, (int) length); string char2StringTrimmed = char2String.TrimEnd(); string[] lines = char2StringTrimmed.Split(LINE_SEPARATOR); IList<string> ret = lines.Select(x => x.TrimEnd()).ToList(); return ret; } public int Peek() { throw new NotImplementedException("peek not done"); } public IList<string> GetEndOfFile(long offsetStart, IList<string> rejectionList) { OpenFile(); _fileInfo.Refresh(); if (offsetStart>_fileInfo.Length) { Log.Error("file reduced size"); return new List<string>(); } _currentPosition = offsetStart; _stream.Seek(offsetStart, SeekOrigin.Begin); long bytesToRead = _fileInfo.Length - offsetStart; char[] buffer = new char[bytesToRead]; ReadBlock block= ReadBlock(buffer, bytesToRead, rejectionList); CloseFile(); IList<string> ret = block.Content; return ret; } public string ReadLine() { StringBuilder sb = new StringBuilder(100); OpenFile(); ReloadCurrentPosition(); while (true) { char c = (char) _stream.ReadByte(); if (c==CARRIAGE_RETURN || c==LINE_SEPARATOR) { break; } sb.Append(c); } string ret = sb.ToString(); _currentPosition = _stream.Position; _currentSeekOrigin = SeekOrigin.Begin; CloseFile(); return ret; } } public class ReadBlock { public int SizeInBytes; public IList<string> Content; } }
namespace WpfAppAbit2.Models { public class EntranceTestType : SimpleClass { } }
namespace Codewars.SplitString { public class SplitString { internal static string[] Solution(string text) { if(text.Length%2 >0) { text += "_"; } var totalSplitString = text.Length / 2; string[] splitString = new string[totalSplitString]; // abc ==> string[] {"ab", "c_"} // abcdef ==> string[] {"ab, "cd", "ef"} for (int i = 0, j = 0; i < totalSplitString; i++, j += 2) { splitString[i] = text.Substring(j, 2); } return splitString; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace ProyectoIntegrado { public partial class FormIdioma : Form { public FormIdioma() { InitializeComponent(); } private void btnAtras_Click(object sender, EventArgs e) { FormPrincipal formPortada = new FormPrincipal(); formPortada.Show(); this.Close(); } private void btnAtras_Click_1(object sender, EventArgs e) { FormPrincipal formPortada = new FormPrincipal(); formPortada.Show(); this.Dispose(); } private void FormIdioma_Load(object sender, EventArgs e) { } private void btnAceptarIdioma_Click(object sender, EventArgs e) { if (rdbSpanish.Checked == true) { MessageBox.Show("El idioma ha sido cambiado"); } else { MessageBox.Show("Language has been changed"); } } private void btnCerrar_Click(object sender, EventArgs e) { Application.Exit(); //Boton que hace que se cierre la pagina } private void btnMinimizar_Click(object sender, EventArgs e) { this.WindowState = FormWindowState.Minimized; //Boton para minimizar la pagina } } }
using System; namespace RulesFakes { public class CCState { // cannot use string.Empty to initialize a constant public const string UnknownStateAbbrAlpha = ""; public DateTime? LastUpdated { get; set; } public string StateAbbrAlpha { get; set; } public string StateDesc { get; set; } public string StateNumb { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace InterfaceClasseAbstr.Modelo.Contratos { interface IForma { double Area(); } }
/******************************************************************** * FulcrumWeb RAD Framework - Fulcrum of your business * * Copyright (c) 2002-2009 FulcrumWeb, ALL RIGHTS RESERVED * * * * THE SOURCE CODE CONTAINED WITHIN THIS FILE AND ALL RELATED * * FILES OR ANY PORTION OF ITS CONTENTS SHALL AT NO TIME BE * * COPIED, TRANSFERRED, SOLD, DISTRIBUTED, OR OTHERWISE MADE * * AVAILABLE TO OTHER INDIVIDUALS WITHOUT EXPRESS WRITTEN CONSENT * * AND PERMISSION FROM FULCRUMWEB. CONSULT THE END USER LICENSE * * AGREEMENT FOR INFORMATION ON ADDITIONAL RESTRICTIONS. * ********************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using Framework.Entity; using Framework.Utils; namespace Framework.Remote { [DataContract] public class CxExpressionResult : IxErrorContainer { [DataMember] public Dictionary<CxClientAttributeMetadata, object> Entity { get; set; } //---------------------------------------------------------------------------- [DataMember] public Dictionary<string, CxClientRowSource> UnfilteredRowSources = new Dictionary<string, CxClientRowSource>(); //---------------------------------------------------------------------------- [DataMember] public List<CxClientRowSource> FilteredRowSources = new List<CxClientRowSource>(); //---------------------------------------------------------------------------- [DataMember] public CxExceptionDetails Error { get; internal set; } //---------------------------------------------------------------------------- /// <summary> /// Gets or sets actual entity to calculate expressions. /// </summary> public CxBaseEntity ActualEntity { get; set; } } }
using System.Drawing; namespace PairsGame.Controls { public class GridParameters { public int Width { get; set; } public int Height { get; set; } public Image Shirt { get; set; } public Image[] Images { get; set; } public GridParameters(int width, int height) { Width = width; Height = height; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using SmallHouseManagerDAL; using SmallHouseManagerModel; namespace SmallHouseManagerBLL { public class RoomBLL { RoomDAL dal = new RoomDAL(); public bool CheckRooms(string code) { int result = dal.CheckRooms(code); return result == 0 ? false : true; } public List<RoomModel> GetAllRoom() { return dal.GetAllRoom(); } public List<RoomModel> GetAllRoomUsed(string code) { return dal.GetAllRoomUsed(code); } public List<RoomModel> GetAllRoomNotUsed(string code) { return dal.GetAllRoomNotUsed(code); } public RoomModel GetRoomByID(string code) { return dal.GetRoomByID(code); } public List<RoomModel> GetRoomByCondition(string condition) { return dal.GetRoomByCondition(condition); } public bool UpdateRoom(RoomModel room) { int result = dal.UpdateRoom(room); return result == 0 ? false : true; } //public bool UpdateRoomForSale(string code,int state) //{ // int result = dal.UpdateRoomForSale(code,state); // return result == 0 ? false : true; //} public bool InsertRoom(RoomModel[] room) { int result = dal.InsertRoom(room); return result == 0 ? false : true; } public int DeleteRoom(string code) { return dal.DeleteRoom(code); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; //[RequireComponent(typeof(TriggerControl))] [RequireComponent(typeof(MeshRenderer))] [RequireComponent(typeof(Collider))] public class Grass : MonoBehaviour { MeshRenderer m_Renderer; //TriggerControl m_Trigger; Bounds m_Bounds; Vector3 m_Pos; int m_State = -1; //public static event Action<Grass, GameObject, bool> GrassEvent; public Vector3 Position { get { return m_Pos; } } public bool ContainsXZ(Vector3 pos) { pos.y = m_Bounds.center.y; return Contains(pos); } public bool Contains(Vector3 pos) { return m_Bounds.Contains(pos); } private void Awake() { //m_Trigger = GetComponent<TriggerControl>(); m_Renderer = GetComponent<MeshRenderer>(); m_Bounds = GetComponent<Collider>().bounds; //m_Trigger.EventTrigger += OnEnter; } private void Start() { m_Pos = transform.position; } public void SetFade(int state, float value) { if (m_State == state) return; m_State = state; var mat = m_Renderer.material; var color = mat.color; color.a = value; mat.color = color; } //private void OnEnter(Collider cld, bool state, bool condition) //{ // if (GrassEvent != null) GrassEvent(this, cld.GameObject(), state && condition); //} }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class Timer : MonoBehaviour { public Text timeTexts; public Text CountText; float totalTime = 100; int retime; float countdown = 3f; int count; // Start is called before the first frame update void Start() { retime = (int)totalTime; timeTexts.text = retime.ToString(); } // Update is called once per frame void Update() { if (countdown >= 0) { countdown -= Time.deltaTime; count = (int)countdown; CountText.text = count.ToString(); } if (countdown <= 0) { CountText.text = ""; totalTime -= Time.deltaTime; retime = (int)totalTime; timeTexts.text = retime.ToString(); if (retime == 0) { // new scene SceneManager.LoadScene("Scenes/Result"); } } } }
using System; namespace Sample.Web.Models { public class CurrentTimeModel { public DateTime CurrentTime { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BasePotion : BaseStatItem { public enum PotionTypes{ HEALTH, ENERGY, STRENGTH, INTELLECT, VITALITY, ENDURANCE } private PotionTypes potionType; public PotionTypes PotionType{ get{return potionType;} set{potionType = value;} } public int SpellEffectID { get; set; } }
using System; using MiHomeLibrary.Devices; using NUnit.Framework; namespace MiHomeLibrary.Test { [TestFixture] public class TokenKeeperTest { [Test] public void GetTokenForGateway_EmptyList_Ok() { TokenKeeperService tokenKeeper = new TokenKeeperService(); Assert.That(tokenKeeper.GetTokenForGateway("aaa"), Is.Null); } [Test] public void GetTokenForGateway_SingleToken_Ok() { string gid = "aaa"; string token = "123456"; TokenKeeperService tokenKeeper = new TokenKeeperService(); tokenKeeper.SetTokenForGateway(gid, token); Assert.That(tokenKeeper.GetTokenForGateway(gid), Is.EqualTo(token)); } [Test] public void GetTokenForGateway_ManyTokens_Ok() { string gid = "aaa"; string token = "123456"; string gid2 = "bbb"; string token2 = "7655432"; TokenKeeperService tokenKeeper = new TokenKeeperService(); tokenKeeper.SetTokenForGateway(gid, token); tokenKeeper.SetTokenForGateway(gid2,token2); Assert.That(tokenKeeper.GetTokenForGateway(gid), Is.EqualTo(token)); Assert.That(tokenKeeper.GetTokenForGateway(gid2), Is.EqualTo(token2)); } [Test] public void GetTokenForGateway_TokenUpdate_Ok() { string gid = "aaa"; string token = "123456"; string token2 = "7655432"; TokenKeeperService tokenKeeper = new TokenKeeperService(); tokenKeeper.SetTokenForGateway(gid, token); tokenKeeper.SetTokenForGateway(gid,token2); Assert.That(tokenKeeper.GetTokenForGateway(gid), Is.EqualTo(token2)); } [Test] public void GetTokenForGateway_WrongGatewaySid_ArgumentException() { string gid = ""; string token = "123456"; TokenKeeperService tokenKeeper = new TokenKeeperService(); Assert.Throws<ArgumentException>(() => tokenKeeper.SetTokenForGateway(gid, token)); } [Test] public void GetTokenForGateway_GatewaySidIsNull_ArgumentException() { string token = "123456"; TokenKeeperService tokenKeeper = new TokenKeeperService(); Assert.Throws<ArgumentException>(() => tokenKeeper.SetTokenForGateway(null, token)); } [Test] public void GetTokenForGateway_WrongToken_ArgumentException() { string gid = "aaa"; string token = ""; TokenKeeperService tokenKeeper = new TokenKeeperService(); Assert.Throws<ArgumentException>(() => tokenKeeper.SetTokenForGateway(gid, token)); } [Test] public void GetTokenForGateway_TokenIsNull_ArgumentException() { string gid = "aaa"; TokenKeeperService tokenKeeper = new TokenKeeperService(); Assert.Throws<ArgumentException>(() => tokenKeeper.SetTokenForGateway(gid, null)); } } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // namespace DotNetNuke.Framework.JavaScriptLibraries { /// <summary> /// determine which version of a script is to be used /// </summary> public enum SpecificVersion { /// <summary>The most recent version</summary> Latest, /// <summary>Match the major version</summary> LatestMajor, /// <summary>Match the major and minor versions</summary> LatestMinor, /// <summary>Match version exactly</summary> Exact, } }
using System; using System.Collections.Generic; using System.Data.SqlClient; using System.Linq; using System.Threading.Tasks; namespace EmployeeManagement.Models { public class EmployeeList { static SqlConnection con; static List<Employee> employeeList = null; static EmployeeList() { string connectionstring = "Data Source=(localdb)\\MSSQLLocalDB;Initial Catalog=EmployeeManagementDB;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"; employeeList = new List<Employee>(); Department department = new Department(); con = new SqlConnection(connectionstring); } public static List<Employee> GetEmployeeList() { con.Open(); SqlCommand cmd = new SqlCommand("select * from dbo.Employee inner join dbo.Department on Employee.DepartmentID=Department.DepartmentID", con); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { Employee emp = new Employee(); emp.EmployeeID = Convert.ToInt32(reader[0]); emp.Name = reader[1].ToString(); emp.Surname = reader[2].ToString(); emp.Address = reader[3].ToString(); emp.Qualification = reader[4].ToString(); emp.ContactNumber = long.Parse(Convert.ToString(reader[5])); emp.DepartmentID = Convert.ToInt32(reader[6]); emp.department = new Department(); emp.department.DepartmentID = Convert.ToInt32(reader[7]); emp.department.DepartmentName = reader[8].ToString(); employeeList.Add(emp); } con.Close(); return employeeList; } public static Employee AddToList(Employee emp) { con.Open(); string qry = "INSERT INTO dbo.Employee(Name, Surname, Address, Qualification, ContactNumber, DepartmentID) VALUES(@Name, @Surname, @Address, @Qualification, @Cnumber, @DepartmentID)"; SqlCommand cmd = new SqlCommand(qry, con); cmd.Parameters.AddWithValue("@Name", emp.Name); cmd.Parameters.AddWithValue("@Surname", emp.Surname); cmd.Parameters.AddWithValue("@Address", emp.Address); cmd.Parameters.AddWithValue("@Qualification", emp.Qualification); cmd.Parameters.AddWithValue("@Cnumber", emp.ContactNumber); cmd.Parameters.AddWithValue("@DepartmentID", emp.DepartmentID); cmd.ExecuteNonQuery(); con.Close(); return emp; } public static Employee EditInList(int id,Employee emp) { employeeList.Clear(); con.Open(); string qry = "UPDATE dbo.Employee SET Name=" + emp.Name + ",Surname=" + emp.Surname + ",Address=" + emp.Address + "" + ",Qualification=" + emp.Qualification + ",ContactNumber=" + emp.ContactNumber + ",DepartmentID=" + emp.DepartmentID + " WHERE EmployeeID=" + id; SqlCommand cmd = new SqlCommand(qry, con); cmd.ExecuteNonQuery(); con.Close(); return emp; } public static void DeleteInList(int id) { employeeList.Clear(); con.Open(); string qry = "DELETE FROM dbo.Employee WHERE EmployeeID=" + id; SqlCommand cmd = new SqlCommand(qry, con); cmd.ExecuteNonQuery(); con.Close(); } } /*public class EmployeeList { static List<Employee> employeeList = null; static EmployeeList() { employeeList = new List<Employee>() { new Employee(){EmployeeID = 1, Name = "Tahseen", Surname = "Khan", Address = "Vadodara,Gujarat", ContactNumber = 11223344, Qualification="Graduate"} }; } public static List<Employee> GetEmployeeList() { return employeeList; } public static void AddToList(Employee emp) { emp.EmployeeID = employeeList.Max(m => m.EmployeeID); emp.EmployeeID += 1; employeeList.Add(emp); } public static void EditInList(Employee emp) { Employee editEmployee = employeeList.Find(x => x.EmployeeID == emp.EmployeeID); editEmployee.EmployeeID = emp.EmployeeID; editEmployee.Name = emp.Name; editEmployee.Surname = emp.Surname; editEmployee.Address = emp.Address; editEmployee.ContactNumber = emp.ContactNumber; editEmployee.Qualification = emp.Qualification; } public static void DeleteInList(int id) { Employee deleteEmployee = employeeList.Find(x => x.EmployeeID == id); employeeList.Remove(deleteEmployee); } }*/ }
using System; namespace Test { class Program { static void Main(string[] args) { double c = double.Parse(Console.ReadLine()); Console.WriteLine(c); } } }
using UnityEngine; using System.Collections; public static class ColorCode { private static Color[] colors = new Color[] { new Color(1, 0, 0), new Color(0.5f, 0.5f, 0.5f), new Color(0, 1, 0), new Color(0, 0, 1), new Color(1, 0.5f, 0.5f), new Color(0, 0.5f, 0.5f), new Color(0.5f, 0, 0.5f), new Color(1, 0.5f, 1) }; public static Color Palette(int index) { return colors[index%colors.Length]; } static ColorCode() { for(int i = 0; i < 2000; i += 11) { if(ToIndex(ToColor(i)) != i) { Debug.LogError("Test failed with: " + i); break; } } } public static Color32 ToColor(int index) { byte r = (byte)(index % 255); byte g = (byte)((index - r) / 255); return new Color32( r, g, 0, 0); } public static int ToIndex(Color32 color) { return color.r + color.g * 255; } }
// Copyright 2017-2019 Elringus (Artyom Sovetnikov). All Rights Reserved. using UnityCommon; using UnityEngine; namespace Naninovel { [System.Serializable] public class CameraConfiguration : Configuration { [Tooltip("The reference resolution is used to evaluate proper rendering dimensions, so that sprite assets (like backgrounds and characters) are correctly positioned on scene. As a rule of thumb, set this equal to the resolution of the background textures you make for the game.")] public Vector2Int ReferenceResolution = new Vector2Int(1920, 1080); [Tooltip("Whether to automatically correct camera's orthographic size based on the current display aspect ratio to ensure the backgrounds and characters are position correctly.")] public bool AutoCorrectOrthoSize = true; [Tooltip("The orthographic size to set by default when auto correction is disabled.")] public float DefaultOrthoSize = 5.35f; [Tooltip("Initial world position of the camera.")] public Vector3 InitialPosition = new Vector3(0, 0, -10); [Tooltip("Whether the camera should render in orthographic (enabled) or perspective (disabled) mode by default. Has no effect when a custom camera prefab is assigned.")] public bool Orthographic = true; [Tooltip("A prefab with a camera component to use for rendering. Will use a default one when not specified. In case you wish to set some camera properties (background color, FOV, HDR, etc) or add post-processing scripts, create a prefab with the desired camera setup and assign the prefab to this field.")] public Camera CustomCameraPrefab = null; [Tooltip("Whether to render the UI in a separate camera. This will allow to use individual configuration for the main and UI cameras and prevent post-processing (image) effects from affecting the UI at the cost of a slight rendering overhead.")] public bool UseUICamera = true; [Tooltip("A prefab with a camera component to use for UI rendering. Will use a default one when not specified. Has no effect when `UseUICamera` is disabled")] public Camera CustomUICameraPrefab = null; [Tooltip("Eeasing function to use by default for all the camera modifications (changing zoom, position, rotation, etc).")] public EasingType DefaultEasing = EasingType.Linear; [Header("Thumbnails")] [Tooltip("The resolution in which thumbnails to preview game save slots will be captured.")] public Vector2Int ThumbnailResolution = new Vector2Int(240, 140); [Tooltip("Whether to ignore UI layer when capturing thumbnails.")] public bool HideUIInThumbnails = false; } }
using Core.Base; using Core.Enums; namespace Entities { public sealed class Product : BaseEntity { public string Number { get; set; } public string Name { get; set; } public ProductType Type { get; set; } public Color Color { get; set; } } }
using System.Collections; namespace BaselineAssembly { public class PublicClass { public int Method(bool b) => 1; public string GetCoolString(int coolArgument) => coolArgument.ToString(); public void Protecc() { } protected void GenericMethod<T>(T t) where T:IComparer { } } internal class InternalClass { } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Web.Mvc; using System.Xml; using System.Xml.Serialization; namespace OC.JQGrid { /// <summary> /// Holds all information regarding the generated view /// Knows how to convert this information into raw HTML and XML /// </summary> public class JQGridBuilder { private HtmlHelper helper; private string id; private string url; private string pagerId; private string style; private List<ColumnBuilder> columns; private int pageSize; private string defaultSortColumn; private bool defaultSortOrderAsc; private bool autoWidth; public JQGridBuilder(HtmlHelper helper, string id, string url) { this.helper = helper; this.id = id; this.url = url; this.columns = new List<ColumnBuilder>(); this.pageSize = 10; this.defaultSortColumn = null; this.defaultSortOrderAsc = true; this.autoWidth = true; } public JQGridBuilder Pager(string pagerId) { this.pagerId = pagerId; return this; } public JQGridBuilder Column(string propertyName, string columnHeader, int? width = null, bool visible = true) { ColumnBuilder column = new ColumnBuilder(propertyName, columnHeader, width, visible); this.columns.Add(column); return this; } public JQGridBuilder DefaultSortColumn(string columnName) { this.defaultSortColumn = columnName; return this; } public JQGridBuilder DefaultSortOrder(bool ascending) { this.defaultSortOrderAsc = ascending; return this; } public JQGridBuilder PageSize(int pageSize) { this.pageSize = pageSize; return this; } public JQGridBuilder Style(string style) { this.style = style; return this; } public JQGridBuilder AutoWidth(bool enable) { this.autoWidth = enable; return this; } public void Render() { Validate(); // // Convert grid information into xml descriptors // JQGridXml gridLayout = new JQGridXml() { Url = this.url, pageSize = this.pageSize, sortColumn = this.defaultSortColumn, sortOrder = (this.defaultSortOrderAsc ? "asc" : "desc"), AutoWidth = this.autoWidth, }; foreach (ColumnBuilder column in this.columns) { JQGridColumnXml layoutColumn = new JQGridColumnXml() { name = column.Name, header = column.Header, width = (column.Width == null ? "" : column.Width.ToString()), visible = column.Visible }; gridLayout.columns.Add(layoutColumn); } // // Covert Xml descriptors to raw XML // string xml = ToXML(gridLayout); // // Build the HTML reuired by the grid // helper.ViewContext.Writer.Write("<div id=\"" + this.id + "\""); helper.ViewContext.Writer.Write(" data-jqgrid=\"true\""); helper.ViewContext.Writer.Write(" class=\"" + this.style + "\""); helper.ViewContext.Writer.WriteLine(">"); helper.ViewContext.Writer.WriteLine("<script type=\"text/xml\" id=\"" + this.id + "_xml\">"); helper.ViewContext.Writer.WriteLine(xml); helper.ViewContext.Writer.WriteLine("</script>"); helper.ViewContext.Writer.WriteLine("</div>"); } private string ToXML(JQGridXml gridLayout) { XmlSerializer serializer = new XmlSerializer(typeof(JQGridXml)); XmlSerializerNamespaces ns = new XmlSerializerNamespaces(); ns.Add("", ""); XmlWriterSettings settings = new XmlWriterSettings() { Indent = true, OmitXmlDeclaration = true, }; using (StringWriter stringWriter = new StringWriter()) using (XmlWriter xmlWriter = XmlWriter.Create(stringWriter, settings)) { serializer.Serialize(xmlWriter, gridLayout, ns); xmlWriter.Flush(); return stringWriter.ToString(); } } private void Validate() { Dictionary<string, ColumnBuilder> columns = new Dictionary<string, ColumnBuilder>(); foreach (ColumnBuilder column in this.columns) { if (columns.ContainsKey(column.Name)) { throw new Exception("Grid contains multiple columns with the same property name"); } } } private class ColumnBuilder { public string Name; public string Header; public int? Width; public bool Visible; public ColumnBuilder(string propertyName, string columnHeader, int? width, bool visible) { this.Name = propertyName; this.Header = columnHeader; this.Width = width; this.Visible = visible; } } } }
using System.Net.Http; using System.Threading; using System.Threading.Tasks; namespace BuindingBlocks.Resilience.Http { public interface IHttpClient { Task<string> GetStringAsync( string uri, Authorization authorization = default(Authorization), CancellationToken cancellationToken = default(CancellationToken) ); Task<HttpResponseMessage> PutAsync<T>( string uri, T item, string requestId = null, Authorization authorization = default(Authorization), CancellationToken cancellationToken = default(CancellationToken) ); } }
using Microsoft.AspNetCore.Identity; using ServiceHost.Models; using ServiceHost.Repository; using ServiceHost.Tools; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ServiceHost.Services { public interface IAccountService { Task<Account> CreateAccountAsync(string userId, string accountName, string Iban, string currencyId, decimal depositFee = -1); Task<Account> DepositAsync(string accountId, decimal sum); Task<Account> TransferAsync(string accountId, decimal amount, string Iban); Task<IEnumerable<Transaction>> GetTransactionsByAccountAsync(string accountId, DateTime fromDate, DateTime toDate); Task<IEnumerable<Transaction>> GetTransactionsByOwnerAsync(string ownerId, DateTime fromDate, DateTime toDate); Task<IEnumerable<Account>> GetAccountsAsync(string ownerId); Task<Account> GetAccountAsync(string accountId); Task<Account> RenameAccountAsync(string accountId, string newAccountName); Task<IEnumerable<Account>> GetAllAccountsAsync(); Task DeleteAccountAsync(string accountId); } public class AccountService : IAccountService { private readonly IAccountRepository _accountRepository; private readonly IRepository<GlobalFee> _globalFeeRepository; private readonly ITransactionRepository _transactionRepository; private readonly UserManager<ApplicationUser> _userManager; private readonly IRepository<Currency> _currencyRepository; public AccountService(IAccountRepository accountRepository, IRepository<GlobalFee> globalFeeRepository, ITransactionRepository transactionRepository, UserManager<ApplicationUser> userManager, IRepository<Currency> currencyRepository) { _accountRepository = accountRepository; _globalFeeRepository = globalFeeRepository; _transactionRepository = transactionRepository; _userManager = userManager; _currencyRepository = currencyRepository; } public async Task<Account> CreateAccountAsync(string userId, string accountName, string Iban, string currencyId, decimal depositFee = -1) { var user = await _userManager.FindByIdAsync(userId); if (user == null) { throw new Exception(); } var currency = await _currencyRepository.GetByIDAsync(new Guid(currencyId)); if (currency == null) { throw new Exception("Non-available currency"); } var account = new Account { Name = accountName, Owner = user, IBAN = Iban, Currency = currency, DepositFee = depositFee, Balance = (decimal)0 }; _accountRepository.Insert(account); var dbAccount = await _accountRepository.GetAccountAsync(user, Iban); return dbAccount; } public async Task<Account> DepositAsync(string accountId, decimal sum) { var globalFees = _globalFeeRepository.Get(x => x.ValidFrom <= DateTime.UtcNow && (x.ValidTo == null || x.ValidTo >= DateTime.UtcNow)); var globalFee = globalFees.FirstOrDefault(); var owners = await _userManager.GetUsersInRoleAsync("Owner"); var owner = owners.FirstOrDefault(); if (owner == null) { throw new Exception("Cannot locate Owner!"); } if (globalFee == null) { throw new Exception("Global fee is not present"); } var ownerAccounts = await _accountRepository.GetAccountsAsync(owner); var ownerAccount = ownerAccounts.FirstOrDefault(); if (ownerAccount == null) { throw new Exception("Cannot locate owners account"); } var account = await _accountRepository.GetAccountAsync(accountId); if (account == null) { throw new Exception("Account missing"); } var feePercentage = account.DepositFee == -1 ? globalFee.FeePercentace : account.DepositFee; var fee = sum * feePercentage; var amountToDeposit = sum - fee; //Create the transactions. var userTransaction = new Transaction { Amount = sum, Currency = account.Currency, Owner = account.Owner, FromAccount = null, ToAccount = account, TransactionDate = DateTime.UtcNow }; var userFeeTransaction = new Transaction { Amount = (fee * (-1)), Currency = account.Currency, Owner = account.Owner, FromAccount = account, ToAccount = ownerAccount, TransactionDate = DateTime.UtcNow }; var ownerTransaction = new Transaction { Amount = fee, Currency = account.Currency, Owner = owner, FromAccount = account, ToAccount = ownerAccount, TransactionDate = DateTime.UtcNow }; //Update the accounts. account.Balance = account.Balance + amountToDeposit; ownerAccount.Balance = ownerAccount.Balance + fee; //Now save it all. //Save transactions... await _transactionRepository.InsertAsync(ownerTransaction); await _transactionRepository.InsertAsync(userTransaction); await _transactionRepository.InsertAsync(userFeeTransaction); await _accountRepository.UpdateAsync(account); await _accountRepository.UpdateAsync(ownerAccount); return await _accountRepository.GetAccountAsync(account.Id.ToString()); } public async Task<Account> TransferAsync(string accountId, decimal amount, string Iban) { if (!IbanValidator.ValidateChecksum(Iban)) { throw new Exception("Invalid destination Iban"); } var toAccount = await _accountRepository.GetAccountByIbanAsync(Iban); if (toAccount == null) { throw new Exception("Can not locate desintation account"); } var account = await _accountRepository.GetAccountAsync(accountId); if (account == null) { throw new Exception("Account missing."); } if (amount > account.Balance) { throw new Exception("Account balance too low to transaction"); } //Transactions var fromTranscation = new Transaction { Amount = (amount * -1), Currency = account.Currency, Owner = account.Owner, FromAccount = account, ToAccount = toAccount, TransactionDate = DateTime.UtcNow }; var ToTranscation = new Transaction { Amount = amount, Currency = account.Currency, Owner = toAccount.Owner, FromAccount = account, ToAccount = toAccount, TransactionDate = DateTime.UtcNow }; //Update balances account.Balance = account.Balance - amount; toAccount.Balance = toAccount.Balance + amount; //Save it all await _transactionRepository.InsertAsync(fromTranscation); await _transactionRepository.InsertAsync(ToTranscation); await _accountRepository.UpdateAsync(account); await _accountRepository.UpdateAsync(toAccount); return await _accountRepository.GetAccountAsync(account.Id.ToString()); } public async Task<IEnumerable<Transaction>> GetTransactionsByAccountAsync(string accountId, DateTime fromDate, DateTime toDate) { var account = await _accountRepository.GetAccountAsync(accountId); if (account == null) { throw new Exception("Account missing"); } var transactions = await _transactionRepository.GetTransactionsAsync(account, fromDate, toDate); return transactions; } public async Task<IEnumerable<Transaction>> GetTransactionsByOwnerAsync(string ownerId, DateTime fromDate, DateTime toDate) { var owner = await _userManager.FindByIdAsync(ownerId); if (owner == null) { throw new Exception("Account owner missing"); } var transactions = await _transactionRepository.GetTransactionsAsync(owner, fromDate, toDate); return transactions; } public async Task<IEnumerable<Account>> GetAccountsAsync(string ownerId) { var owner = await _userManager.FindByIdAsync(ownerId); if (owner == null) { throw new Exception("Account owner missing"); } var accounts = await _accountRepository.GetAccountsAsync(owner); return accounts; } public async Task<Account> GetAccountAsync(string accountId) { var account = await _accountRepository.GetAccountAsync(accountId); return account; } public async Task<Account> RenameAccountAsync(string accountId, string newAccountName) { var account = await _accountRepository.GetByIDAsync(accountId); if (account == null) { throw new Exception("Account missing"); } account.Name = newAccountName; await _accountRepository.UpdateAsync(account); return await _accountRepository.GetAccountAsync(account.Id.ToString()); } public async Task<IEnumerable<Account>> GetAllAccountsAsync() { var accounts = await _accountRepository.GetAccountsAsync(); return accounts; } public async Task DeleteAccountAsync(string accountId) { await _accountRepository.DeleteAsync(new Guid(accountId)); } } }
#region Copyright (C) // --------------------------------------------------------------------------------------------------------------- // <copyright file="HandleMappingThread.cs" company="Smurf-IV"> // // Copyright (C) 2011-2012 Smurf-IV // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 2 of the License, or // any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // </copyright> // <summary> // Url: http://amalgam.codeplex.com // Email: http://www.codeplex.com/site/users/view/smurfiv // </summary> // -------------------------------------------------------------------------------------------------------------------- #endregion using System.Collections.Generic; using System.Threading; using AmalgamClientTray.ClientForms; namespace AmalgamClientTray.Dokan { internal static class Handlers { public static readonly Dictionary<string, HandleMappingThread> ClientMappings = new Dictionary<string, HandleMappingThread>(); } class HandleMappingThread { private DokanManagement mapManager; public bool Start(ClientShareDetail csd) { if (mapManager != null) mapManager.Stop(); mapManager = new DokanManagement {csd = csd}; ThreadPool.QueueUserWorkItem(mapManager.Start, mapManager); int repeatWait = 10; while (!mapManager.IsRunning && (repeatWait-- > 0) ) { Thread.Sleep(250); } return mapManager.IsRunning; } public bool Stop() { bool runningState; if (mapManager != null) { mapManager.Stop(); int repeatWait = 10; while (mapManager.IsRunning && (repeatWait-- > 0) ) { Thread.Sleep(250); //Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, // new Action(delegate { })); } runningState = mapManager.IsRunning; } else { runningState = true; } return ! runningState; } } }
using System.Collections; using GameLib; using JumpAndRun.API; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Collections.Generic; namespace JumpAndRun.Actors { public abstract class NpcBase : Actor { protected Actor Player; protected Platform Platform; protected NpcBase(Game game) { Game = game; } protected void BaseInit(IGlobalCache globalCache) { Cache = new LocalCache(globalCache, new Index2(2,2)); _boxes = new List<BoundingBox>(); Platform = GameContext.Instance.Platform; } public abstract override void Init(Actor player, IGlobalCache cache, Game game, CameraBase camera); protected LocalCache Cache; public abstract override void Dispose(); protected abstract override void OnDead(); public abstract override void Update(JumpAndRunTime gameTime); protected void BaseUpdate(JumpAndRunTime gameTime) { if (!_lastMoveDirection.X.NearlyEqual(0)) { ItemPosition = _lastMoveDirection.X > 0 ? new Vector3(1, 0, 0) : new Vector3(0, 0, 0); ActiveItemRenderer.RotationReflection = _lastMoveDirection.X > 0; } ActiveItemRenderer.Item.Position = Position + new Vector3(0, 0.4f, 0) + ItemPosition; ActiveItemRenderer.Update(gameTime); } private List<BoundingBox> _boxes; private Vector3 _lastPosition; protected Matrix World; protected Vector3 ResolveCollisions(Vector3 direction) { Cache.SetCenter(ChunkPosition); var blockPosition = new Vector3((int)Position.X, (int)Position.Y, (int)Position.Z); if(blockPosition != _lastPosition) { _boxes.Clear(); for (var x = (int)Position.X - 2; x < Position.X + 2; x++) { for (var y = (int)Position.Y - 2; y < Position.Y + 2; y++) { for (var z = 0; z < Chunk.Sizez; z++) { if (Cache.GetBlock(new Index3(x, y, z)) == null || ContentManager.Instance .GetBlockDefinitionFromType(Cache.GetBlock(new Index3(x, y, z)).GetType()) .GetBoundingBoxes() == null) continue; foreach (var box in ContentManager.Instance.GetBlockDefinitionFromType(Cache.GetBlock(new Index3(x, y, z)).GetType()).GetBoundingBoxes()) { _boxes.Add(new BoundingBox(box.Min + new Vector3(x, y, z), box.Max + new Vector3(x, y, z))); } } } } _lastPosition = blockPosition; } direction = Collision.ResloveCollision(direction, Position, new BoundingBox(Vector3.Zero, new Vector3(1, 1, 0.5f)), _boxes, 10); _lastMoveDirection = direction; return Position + direction; } protected Texture2D Texture; protected VertexBuffer VertexBuffer; protected IndexBuffer IndexBuffer; protected ItemRenderer ActiveItemRenderer; protected Vector3 ItemPosition { get; set; } private Vector3 _lastMoveDirection; protected void GenerateVertexBuffer(GraphicsDevice graphicsDevice) { Texture = ContentManager.Instance.Textures["Player"]; var vertices = new VertexPositionNormalTexture[4]; vertices[0] = new VertexPositionNormalTexture(new Vector3(0, 0, -0.5f), Vector3.Forward, new Vector2(0, 1)); vertices[1] = new VertexPositionNormalTexture(new Vector3(0, 1, -0.5f), Vector3.Forward, new Vector2(0, 0)); vertices[2] = new VertexPositionNormalTexture(new Vector3(1, 1, -0.5f), Vector3.Forward, new Vector2(1, 0)); vertices[3] = new VertexPositionNormalTexture(new Vector3(1, 0, -0.5f), Vector3.Forward, new Vector2(1, 1)); var indices = new short[] { 0, 1, 3, 3, 1, 2 }; IndexBuffer = new IndexBuffer(graphicsDevice, IndexElementSize.SixteenBits, 6, BufferUsage.WriteOnly); VertexBuffer = new VertexBuffer(graphicsDevice, VertexPositionNormalTexture.VertexDeclaration, 4, BufferUsage.WriteOnly); VertexBuffer.SetData(vertices); IndexBuffer.SetData(indices); } public override void Draw(Effect effect, Matrix view, Matrix proj) { Game.GraphicsDevice.SetVertexBuffer(VertexBuffer); Game.GraphicsDevice.Indices = IndexBuffer; switch (Platform) { case Platform.WindowsForms: effect.Parameters["DiffuseTexture"].SetValue(Texture); effect.Parameters["World"].SetValue(World); effect.Parameters["WorldViewProj"].SetValue(World * view * proj); break; case Platform.Android: ((AlphaTestEffect) effect).Texture = Texture; ((AlphaTestEffect) effect).View = view; ((AlphaTestEffect) effect).Projection = proj; ((AlphaTestEffect) effect).World = World; break; } foreach (var pass in effect.CurrentTechnique.Passes) { pass.Apply(); Game.GraphicsDevice.DrawIndexedPrimitives(PrimitiveType.TriangleList, 0, 0, IndexBuffer.IndexCount / 3); } ActiveItemRenderer.Draw(effect, view, proj); } } }
using _01___ESTRUTURADOPROGRAMA._01_Heranca; using System; namespace _01___ESTRUTURADOPROGRAMA { class Program { static void Main(string[] args) { //var s = new Pilha(); //s.Empilha(1); //s.Empilha(10); //s.Empilha(100); //Console.WriteLine(s.Desempilha()); //Console.WriteLine(s.Desempilha()); //Console.WriteLine(s.Desempilha()); Instrucoes instrucoes = new Instrucoes(); instrucoes.Declaracoes(); string[] a = new string[] { "1", "2" }; string[] b = { "teste", "teste010", "teste0100"}; instrucoes.InstrucaoIf(a); Ponto ponto = new Ponto(2,3); ponto.CalcularDistancia3(); Ponto3D ponto2 = new Ponto3D(1,2,3); Ponto3D.Calcular(); } } }
/* * Copyright 2014 Technische Universitšt Darmstadt * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Windows; namespace KaVE.VS.FeedbackGenerator.Interactivity { public class ConfirmationRequestHandler { private readonly Window _window; public ConfirmationRequestHandler(DependencyObject parent) { _window = Window.GetWindow(parent); } public void Handle(object sender, InteractionRequestedEventArgs<Confirmation> args) { var confirmation = args.Notification; var answer = _window == null ? MessageBox.Show(confirmation.Message, confirmation.Caption, MessageBoxButton.YesNo) : MessageBox.Show(_window, confirmation.Message, confirmation.Caption, MessageBoxButton.YesNo); confirmation.Confirmed = answer == MessageBoxResult.Yes; args.Callback(); } } }
using System; using System.Data; using System.Collections.Generic; using Maticsoft.Common; using PDTech.OA.Model; namespace PDTech.OA.BLL { /// <summary> /// RIGHT_INFO /// </summary> public partial class RIGHT_INFO { private readonly PDTech.OA.DAL.RIGHT_INFO dal=new PDTech.OA.DAL.RIGHT_INFO(); public RIGHT_INFO() {} #region BasicMethod /// <summary> /// 是否存在该记录 /// </summary> public bool Exists(decimal RIGHT_ID) { return dal.Exists(RIGHT_ID); } /// <summary> /// 增加一条数据 /// </summary> public int Add(PDTech.OA.Model.RIGHT_INFO model, string HostName, string Ip, decimal operId) { return dal.Add(model, HostName,Ip,operId); } /// <summary> /// 更新一条数据 /// </summary> public int Update(PDTech.OA.Model.RIGHT_INFO model, string HostName, string Ip, decimal operId) { return dal.Update(model,HostName, Ip, operId); } /// <summary> /// 删除一条数据 /// </summary> public bool Delete(decimal RIGHT_ID) { return dal.Delete(RIGHT_ID); } /// <summary> /// 删除一条数据 /// </summary> public bool DeleteList(string RIGHT_IDlist ) { return dal.DeleteList(RIGHT_IDlist ); } /// <summary> /// 得到一个对象实体 /// </summary> public PDTech.OA.Model.RIGHT_INFO GetModel(decimal RIGHT_ID) { return dal.GetModel(RIGHT_ID); } /// <summary> /// 得到一个对象实体,从缓存中 /// </summary> public PDTech.OA.Model.RIGHT_INFO GetModelByCache(decimal RIGHT_ID) { string CacheKey = "RIGHT_INFOModel-" + RIGHT_ID; object objModel = Maticsoft.Common.DataCache.GetCache(CacheKey); if (objModel == null) { try { objModel = dal.GetModel(RIGHT_ID); if (objModel != null) { int ModelCache = Maticsoft.Common.ConfigHelper.GetConfigInt("ModelCache"); Maticsoft.Common.DataCache.SetCache(CacheKey, objModel, DateTime.Now.AddMinutes(ModelCache), TimeSpan.Zero); } } catch{} } return (PDTech.OA.Model.RIGHT_INFO)objModel; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetList(string strWhere) { return dal.GetList(strWhere); } /// <summary> /// 获得数据列表 /// </summary> public List<PDTech.OA.Model.RIGHT_INFO> GetModelList(string strWhere) { DataSet ds = dal.GetList(strWhere); return DataTableToList(ds.Tables[0]); } /// <summary> /// 获得数据列表 /// </summary> public List<PDTech.OA.Model.RIGHT_INFO> DataTableToList(DataTable dt) { List<PDTech.OA.Model.RIGHT_INFO> modelList = new List<PDTech.OA.Model.RIGHT_INFO>(); int rowsCount = dt.Rows.Count; if (rowsCount > 0) { PDTech.OA.Model.RIGHT_INFO model; for (int n = 0; n < rowsCount; n++) { model = dal.DataRowToModel(dt.Rows[n]); if (model != null) { modelList.Add(model); } } } return modelList; } /// <summary> /// 获得数据列表 /// </summary> public DataSet GetAllList() { return GetList(""); } /// <summary> /// 分页获取数据列表 /// </summary> public int GetRecordCount(string strWhere) { return dal.GetRecordCount(strWhere); } /// <summary> /// 分页获取数据列表 /// </summary> //public DataSet GetList(int PageSize,int PageIndex,string strWhere) //{ //return dal.GetList(PageSize,PageIndex,strWhere); //} /// <summary> /// 获取权限信息---未分页 /// </summary> /// <param name="where"></param> /// <returns></returns> public IList<Model.RIGHT_INFO> get_RiInfoList(Model.RIGHT_INFO where) { return dal.get_RiInfoList(where); } /// <summary> /// 获取权限信息--返回dataTable /// </summary> /// <param name="where"></param> /// <returns></returns> public DataTable get_RightInfoTab(Model.RIGHT_INFO where) { return dal.get_RightInfoTab(where); } /// <summary> /// 获取一条权限信息 /// </summary> /// <param name="where"></param> /// <returns></returns> public Model.RIGHT_INFO GetRightInfo(decimal uId) { return dal.GetRightInfo(uId); } /// <summary> /// 获取权限信息-使用分页 /// </summary> /// <param name="where"></param> /// <param name="currentpage"></param> /// <param name="pagesize"></param> /// <param name="totalrecord"></param> /// <returns></returns> public IList<Model.RIGHT_INFO> get_Paging_RightInfoList(Model.RIGHT_INFO where, int currentpage, int pagesize, out int totalrecord) { return dal.get_Paging_RightInfoList(where, currentpage, pagesize, out totalrecord); } #endregion BasicMethod #region ExtensionMethod #endregion ExtensionMethod } }
#region using statements using System; #endregion namespace ObjectLibrary.BusinessObjects { #region class Address [Serializable] public partial class Address { #region Private Variables #endregion #region Constructor public Address() { } #endregion #region Methods #region Clone() public Address Clone() { // Create New Object Address newAddress = (Address) this.MemberwiseClone(); // Return Cloned Object return newAddress; } #endregion #region GetStateCode() /// <summary> /// This method returns the State Code /// </summary> public string GetStateCode() { // initial value string stateCode = ""; // Determine the action by the StateId switch (StateId) { case 1: // set the return value stateCode = "AK"; // required break; case 2: // set the return value stateCode = "AL"; // required break; case 3: // set the return value stateCode = "AZ"; // required break; case 4: // set the return value stateCode = "AR"; // required break; case 5: // set the return value stateCode = "CA"; // required break; case 6: // set the return value stateCode = "CO"; // required break; case 7: // set the return value stateCode = "CT"; // required break; case 8: // set the return value stateCode = "DE"; // required break; case 9: // set the return value stateCode = "DC"; // required break; case 10: // set the return value stateCode = "FL"; // required break; case 11: // set the return value stateCode = "GA"; // required break; case 12: // set the return value stateCode = "HI"; // required break; case 13: // set the return value stateCode = "ID"; // required break; case 14: // set the return value stateCode = "IL"; // required break; case 15: // set the return value stateCode = "IN"; // required break; case 16: // set the return value stateCode = "IA"; // required break; case 17: // set the return value stateCode = "KS"; // required break; case 18: // set the return value stateCode = "KY"; // required break; case 19: // set the return value stateCode = "LA"; // required break; case 20: // set the return value stateCode = "ME"; // required break; case 21: // set the return value stateCode = "MD"; // required break; case 22: // set the return value stateCode = "MA"; // required break; case 23: // set the return value stateCode = "MI"; // required break; case 24: // set the return value stateCode = "MN"; // required break; case 25: // set the return value stateCode = "MS"; // required break; case 26: // set the return value stateCode = "MO"; // required break; case 27: // set the return value stateCode = "MT"; // required break; case 28: // set the return value stateCode = "NE"; // required break; case 29: // set the return value stateCode = "NV"; // required break; case 30: // set the return value stateCode = "NH"; // required break; case 31: // set the return value stateCode = "NJ"; // required break; case 32: // set the return value stateCode = "NM"; // required break; case 33: // set the return value stateCode = "NY"; // required break; case 34: // set the return value stateCode = "NC"; // required break; case 35: // set the return value stateCode = "ND"; // required break; case 36: // set the return value stateCode = "OH"; // required break; case 37: // set the return value stateCode = "OK"; // required break; case 38: // set the return value stateCode = "OR"; // required break; case 39: // set the return value stateCode = "PA"; // required break; case 40: // set the return value stateCode = "RI"; // required break; case 41: // set the return value stateCode = "SC"; // required break; case 42: // set the return value stateCode = "SD"; // required break; case 43: // set the return value stateCode = "TN"; // required break; case 44: // set the return value stateCode = "TX"; // required break; case 45: // set the return value stateCode = "UT"; // required break; case 46: // set the return value stateCode = "VT"; // required break; case 47: // set the return value stateCode = "VA"; // required break; case 48: // set the return value stateCode = "WA"; // required break; case 49: // set the return value stateCode = "WV"; // required break; case 50: // set the return value stateCode = "WI"; // required break; case 51: // set the return value stateCode = "WY"; // required break; } // return value return stateCode; } #endregion #region ToString() /// <summary> /// This method is used to return the full address when ToString is called /// </summary> /// <returns></returns> public override string ToString() { // initial value string address = ""; // if the Unit exists if (!String.IsNullOrEmpty(Unit)) { // set the return value including the unit address = this.StreetAddress + " " + Unit + ", " + City + ", " + GetStateCode() + " " + ZipCode; } else { // set the return value address = this.StreetAddress + ", " + City + ", " + GetStateCode() + " " + ZipCode; } // return value return address; } #endregion #endregion #region Properties #endregion } #endregion }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LibraryManagement.Librarian { public partial class LibrarianMaster : System.Web.UI.MasterPage { protected void Page_Load(object sender, EventArgs e) { } protected void btnHome_Click(object sender, EventArgs e) { } protected void btnIssueBook_Click(object sender, EventArgs e) { } protected void btnBookReturn_Click(object sender, EventArgs e) { } protected void btnSearchLibrary_Click(object sender, EventArgs e) { } protected void btnProfiles_Click(object sender, EventArgs e) { } protected void btnReports_Click(object sender, EventArgs e) { } } }
using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using Medit1.Validation; using Microsoft.AspNetCore.Http; namespace Medit1.Models.ViewModels { public class CreateCruiseViewModel { public ICollection<TypeCruise>TypeCruises { get; set; } public ICollection<Port> Ports { get; set; } public ICollection<Boat> Boats { get; set; } public ICollection<Commodite> Commodites { get; set; } public Cruise Cruise { get; set; } [Required(ErrorMessage = "Un bateau est nécessaire pour la croissière")] [BoatVerifaction("Cruise")] public int BoatId{ get; set; } [Required(ErrorMessage = "Le type de la croissiere est obligatoire")] public int TypeCruiseId{ get; set; } [Required(ErrorMessage = "Le port de départ est nécessaire")] public int DeparturePortId{ get; set; } [Required(ErrorMessage = "Un port de destination est obligatoire")] public int ArrivalPortId{ get; set; } public ICollection<int> TransitPortId{ get; set; } public ICollection<int> CommoditesIds{ get; set; } public ICollection<IFormFile> File { get; set; } } }
using UnityEngine; using System; using System.Globalization; namespace BeliefEngine.HealthKit { /*! @brief A small helper class to bridge dates between C# and Objective-C */ public class DateTimeBridge : ScriptableObject { // 2017-04-25T14:18:52-07:00 // 2017-04-25T22:12:50Z // 2017-04-26T01:14:43 public static string dateBridgeFormat = "yyyy-MM-ddTHH:mm:ss"; /*!< @brief all timestamps from Objective-C should be in this format." */ private static DateTimeOffset referenceDate { get { return new DateTimeOffset(1970, 1, 1, 0, 0, 0, 0, TimeSpan.Zero); } } /*! @brief Convert a DateTimeOffset to a string datestamp to be passed to Objective-C @param date the date to convert. */ public static string DateToString(DateTimeOffset date) { TimeSpan span = date - DateTimeBridge.referenceDate; double interval = span.TotalSeconds; string dateString = Convert.ToString(interval); Debug.Log("date string:" + dateString); return dateString; } /*! @brief Convert a string timestamp from Objective-C to a DateTimeOffset @param stamp the timestamp to convert. */ public static DateTimeOffset DateFromString(string stamp) { Double d; if (Double.TryParse(stamp, out d)) { DateTimeOffset date = DateTimeBridge.referenceDate.AddSeconds(d); // return TimeZoneInfo.ConvertTime(date, TimeZoneInfo.Local); return date.ToLocalTime(); } else { Debug.LogErrorFormat("error parsing '{0}'", stamp); return new DateTimeOffset(); } } } }
using Abp.Domain.Entities; using Abp.Domain.Entities.Auditing; using SPACore.PhoneBook.PhoneBooks.Persons; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Text; using SPACore.PhoneBook; namespace SPACore.PhoneBook.PhoneBooks.PhoneNumbers { public class PhoneNumber : Entity<long>, IHasCreationTime { /// <summary> /// 电话号码 /// </summary> [Required] [MaxLength(PhoneBookConsts.MaxPhoneNumberLength)] public string Number { get; set; } /// <summary> /// 类型 /// </summary> public PhoneNumberType Type { get; set; } public int PersonId { get; set; } public Person Person { get; set; } public DateTime CreationTime { get; set; } } }
using System; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Collections.Generic; namespace HobbyHub.Models { public class Hobby { [Key] public int HobbyId {get;set;} public int CreatedById {get; set;} [Required] public string Name {get; set;} [Required] public string Description {get; set;} public List<Enthusiast> Users {get; set;} public DateTime CreatedAt {get; set;} = DateTime.Now; public DateTime UpdatedAt {get; set;} = DateTime.Now; } }
using System.Drawing; namespace TutteeFrame2 { class Rim { public int[] Hori = new int[12]; public int[] Ver = new int[8]; public Point[,] Intersec = new Point[12, 8]; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ObjectDataTypes { public class PlayerInteractableData : ObjectData { //all of the data from Object plus... ///<value>Controlls how long a PlayerInteractable is allowed on the screen (in milliseconds) before it is removed. NOTE: This variable is a TimeSpan in the PlayerInteractable class in the PirateWars namespace. TimeSpan has problems when being serialized. Store the float and account for that when creating the TimeSpan from it in the PlayerIneractable class</value> public int timeAllowedOnScreen; } }
using AutoUpdate.MainService; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; 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; namespace AutoUpdate { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { private readonly UpdateInfo _info = null; public MainWindow(UpdateInfo info) { InitializeComponent(); //this.Left = SystemParameters.WorkArea.Width - this.Width; //this.Top = SystemParameters.WorkArea.Height - this.Height; this._info = info; this.Btn_Update_Click(); } //下载更新 private void Btn_Update_Click() { ProcessClose(_info.AppName); DownLoadFile(); } /// <summary> /// 下载文件 /// </summary> private void DownLoadFile() { var downloadUrl = string.Format("{0}/Home/Download", _info.Url); var client = new System.Net.WebClient(); client.DownloadProgressChanged += (clientSender, clientE) => { UpdateProcess(clientE.BytesReceived, clientE.TotalBytesToReceive); }; #region client.DownloadDataCompleted += (clientSender, clientE) => { string zipFilePath = DownloadDataCompleted(clientE); Action f = () => { txtProcess.Text = "开始更新程序..."; }; this.Dispatcher.Invoke(f); string tempDir = System.IO.Path.Combine(_info.LocalFilePathTemp, "TempFile"); if (!Directory.Exists(tempDir)) { Directory.CreateDirectory(tempDir); } UnZipFile(zipFilePath, tempDir); UpdateDll(tempDir); //移动文件 if (Directory.Exists(_info.LocalFilePath)) { CopyDirectory(tempDir, _info.AppFilePath); } f = () => { txtProcess.Text = "更新完成!"; try { FileStream fs = new FileStream(System.IO.Path.Combine(_info.LocalFilePath, _info.ConfigurationName), FileMode.Create); StreamWriter streamWriter = new StreamWriter(fs); streamWriter.Write(_info.ServerVersion); streamWriter.Close(); fs.Close(); DeleteFolder(_info.LocalFilePathTemp); } catch (Exception ex) { } }; this.Dispatcher.Invoke(f); try { f = () => { string readMe = _info.AppFilePath + @"\ReadMe.txt"; if (File.Exists(readMe)) System.Diagnostics.Process.Start("notepad.exe", readMe); string exePath = System.IO.Path.Combine(_info.AppFilePath, _info.AppName + ".exe"); var info = new System.Diagnostics.ProcessStartInfo(exePath); System.Diagnostics.Process.Start(info); this.Close(); }; this.Dispatcher.Invoke(f); } catch (Exception) { throw; } }; #endregion client.DownloadDataAsync(new Uri(downloadUrl)); } /// <summary> /// 删除文件夹和文件 /// </summary> /// <param name="dir"></param> private void DeleteFolder(string dir) { if (Directory.Exists(dir)) { foreach (string p in System.IO.Directory.GetFileSystemEntries(dir)) { if (!p.EndsWith("AutoUpdate", StringComparison.OrdinalIgnoreCase)) { if (File.Exists(p)) File.Delete(p); else DeleteFolder(p); } } Directory.Delete(dir); } } /// <summary> /// 清楚列表dll /// </summary> public void UpdateDll(string tempath) { string updatepath = System.IO.Path.Combine(tempath, "updatelist.txt"); if (File.Exists(updatepath)) { StreamReader streamReader = new StreamReader(updatepath); string updateStr = streamReader.ReadToEnd(); streamReader.Close(); if (string.IsNullOrEmpty(updateStr)) return; if (string.Equals(updateStr, "all", StringComparison.OrdinalIgnoreCase)) { DeleteFolder(_info.AppFilePath); } else { string[] dllList = updateStr.Split(','); for (int i = 0; i < dllList.Length; i++) { string deletepath = System.IO.Path.Combine(_info.AppFilePath, dllList[i]); if (File.Exists(deletepath)) File.Delete(deletepath); else DeleteFolder(deletepath); } } } File.Delete(updatepath); } /// <summary> /// 下载完成时执行 /// </summary> /// <param name="clientE"></param> /// <returns></returns> private string DownloadDataCompleted(System.Net.DownloadDataCompletedEventArgs clientE) { string zipFilePath = System.IO.Path.Combine(_info.LocalFilePathTemp, "update.zip"); byte[] data = clientE.Result; BinaryWriter writer = new BinaryWriter(new FileStream(zipFilePath, FileMode.OpenOrCreate)); writer.Write(data); writer.Flush(); writer.Close(); return zipFilePath; } /// <summary> /// 关闭进程 /// </summary> /// <param name="appName"></param> private void ProcessClose(string appName) { Process[] processes = Process.GetProcessesByName(appName); if (processes.Length > 0) { foreach (var p in processes) { p.Kill(); } } } /// <summary> /// 进度条 /// </summary> /// <param name="current"></param> /// <param name="total"></param> private void UpdateProcess(long current, long total) { this.Dispatcher.Invoke(new Action(() => { string status = (int)((float)current * 100 / (float)total) + "%"; this.txtProcess.Text = status; rectProcess.Width = ((float)current / (float)total) * bProcess.ActualWidth; })); } /// <summary> /// 文件解压 /// </summary> /// <param name="zipFilePath"></param> /// <param name="targetDir"></param> private void UnZipFile(string zipFilePath, string targetDir) { if (!File.Exists(zipFilePath)) throw new Exception("文件不存在!"); ICCEmbedded.SharpZipLib.Zip.FastZipEvents evt = new ICCEmbedded.SharpZipLib.Zip.FastZipEvents(); ICCEmbedded.SharpZipLib.Zip.FastZip fz = new ICCEmbedded.SharpZipLib.Zip.FastZip(evt); fz.ExtractZip(zipFilePath, targetDir, ""); } /// <summary> /// 移动文件 /// </summary> /// <param name="sourceDirName"></param> /// <param name="destDirName"></param> public void CopyDirectory(string sourceDirName, string destDirName) { try { if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); File.SetAttributes(destDirName, File.GetAttributes(sourceDirName)); } if (destDirName[destDirName.Length - 1] != System.IO.Path.DirectorySeparatorChar) destDirName = destDirName + System.IO.Path.DirectorySeparatorChar; string[] files = Directory.GetFiles(sourceDirName); foreach (string file in files) { try { File.Copy(file, destDirName + System.IO.Path.GetFileName(file), true); Console.WriteLine(file); File.SetAttributes(destDirName + System.IO.Path.GetFileName(file), FileAttributes.Normal); } catch { } } string[] dirs = Directory.GetDirectories(sourceDirName); foreach (string dir in dirs) { CopyDirectory(dir, destDirName + System.IO.Path.GetFileName(dir)); } } catch (Exception) { } } } }
using System; using System.Collections; namespace QuitSmokeWebAPI.Controllers.Entity { public class UserInfo { public string uid { get; set; } public string name { get; set; } public string smoker_indicator { get; set; } public string partner_indicator { get; set; } public string partner_email { get; set; } public string register_date { get; set; } public int point { get; set; } public int age { get; set; } public string gender { get; set; } public int price_per_pack { get; set; } } }
using bank_account_ddd_studies.domain.command; using bank_account_ddd_studies.domain.repository; namespace bank_account_ddd_studies.domain.commandHandler { public class DebitHandler : IHandler { private readonly IAccountRepository _accountRepository; public string Operation => "Debit"; public DebitHandler(IAccountRepository accountRepository) { _accountRepository = accountRepository; } public void Execute(ICommand command) { var debitCommand = (DebitCommand)command; var account = _accountRepository.Get(debitCommand.AccountId); if (account is not null) { account.Debit(debitCommand.Amount); } } } }
using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace EntitiesDB { public class Block { public int ID { get; set; } public string Name { get; set; } public string Vrizka { get; set; } public string AddOns { get; set; } public int DoorOneID { get; set; } public Door DoorOne { get; set; } public int? DoorTwoID { get; set; } public Door DoorTwo { get; set; } public int BoxID { get; set; } public DoorBox Box { get; set; } public int HingeOneID { get; set; } public Hinge HingeOne { get; set; } public int? HingeTwoID { get; set; } public Hinge HingeTwo { get; set; } public byte CountHinges { get; set; } public int LockID { get; set; } public Lock Lock { get; set; } public string InsertPotai { get; set; } public int DoorstepID { get; set; } public DoorStep Doorstep { get; set; } public string Note { get; set; } public string OrderNumber { get; set; } [ForeignKey("TechCard")] public int TechCardID { get; set; } public TechnologicalCard TechCard { get; set; } public byte Status { get; set; } } }
using Core.Base; namespace Entities { public sealed class Territory : BaseEntity { public string CountryName { get; set; } } }
using UnityEngine; using System.Collections; using GameRockManEXE; /// <summary> /// 戰鬥晶片 /// </summary> public class BattleChip { public int _iChipID; public int _iChipIDGame; public string _sChipCode; public string _sChipName; public string _sChipInfo; public int _iChipIconID; public int _iChipSpriteID; public int _iChipAttack; public WorldObject.GameType _enumChipType; public WorldObject.ChipLevel _enymChipLevel; public BattleChip(int _iID, int _iIDGame, string _sCode, string _sName, string _sInfo, int _iIconID, int _iSpriteID, int _iAttack, WorldObject.GameType _enumType, WorldObject.ChipLevel _enumLevel) { _iChipID = _iID; _iChipIDGame = _iIDGame; _sChipCode = _sCode; _sChipName = _sName; _sChipInfo = _sInfo; _iChipIconID = _iIconID; _iChipSpriteID = _iSpriteID; _iChipAttack = _iAttack; _enumChipType = _enumType; _enymChipLevel = _enumLevel; } }
using System; using System.Collections.Generic; using Android.App; using Android.Content; using Android.Widget; using Android.Views; using StudyEspanol.Data.Models; using StudyEspanol.UI.Screens; namespace StudyEspanol.Droid { public class ConjugationQuizAdapter : ArrayAdapter<List<QuizWord>>, GestureDetector.IOnGestureListener { #region Fields private int layout; private ConjugationQuizScreen activity; private List<List<QuizWord>> words; private GestureDetector gestureDetector; private AdapterViewFlipper parent; private string[] tense; #endregion #region Delegate public delegate void DisplayNewViewEvent(int current, int previous); #endregion #region Event public event DisplayNewViewEvent DisplayNewView; #endregion #region Intialization public ConjugationQuizAdapter(ConjugationQuizScreen activity, int layout, List<List<QuizWord>> words) : base(activity, layout, words) { this.layout = layout; this.activity = activity; this.words = words; gestureDetector = new GestureDetector(this); tense = activity.Resources.GetStringArray(Resource.Array.conjugations); } #endregion #region Adapter public override int Count{ get{ return words.Count; } } public override long GetItemId(int position){ return position; } public override View GetView(int position, View convertView, ViewGroup parent) { this.parent = (AdapterViewFlipper)parent; View column = convertView; Holder holder = null; if (column == null) { LayoutInflater inflater = ((Activity)activity).LayoutInflater; column = inflater.Inflate(layout, parent, false); holder = new Holder(); holder.word = column.FindViewById<TextView>(Resource.Id.textview_word); holder.tense = column.FindViewById<TextView>(Resource.Id.textview_tense); holder.yo = column.FindViewById<AutoCompleteTextView>(Resource.Id.textview_yo); holder.tu = column.FindViewById<AutoCompleteTextView>(Resource.Id.textview_tu); holder.el = column.FindViewById<AutoCompleteTextView>(Resource.Id.textview_el); holder.nos = column.FindViewById<AutoCompleteTextView>(Resource.Id.textview_nosotros); holder.vos = column.FindViewById<AutoCompleteTextView>(Resource.Id.textview_vosotros); holder.ellos = column.FindViewById<AutoCompleteTextView>(Resource.Id.textview_ellos); column.Tag = holder; } else { holder = (Holder)column.Tag; } List<QuizWord> list = words[position]; holder.word.Text = list[0].Word; holder.tense.Text = tense[(int)list[0].Tense]; SetTextView(holder.yo, list[0]); ShowKeyboard(holder.yo); SetTextView(holder.tu, list[1]); SetTextView(holder.el, list[2]); SetTextView(holder.nos, list[3]); SetTextView(holder.vos, list[4]); SetTextView(holder.ellos, list[5]); parent.Touch += (sender, e) => gestureDetector.OnTouchEvent(e.Event); return column; } #endregion #region GestureDetector.IOnGetureListener public bool OnDown(MotionEvent e){return false;} public bool OnFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY){return NextView(e1, e2);} public void OnLongPress(MotionEvent e){} public bool OnScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY){return false;} public void OnShowPress(MotionEvent e){} public bool OnSingleTapUp(MotionEvent e){return false;} #endregion #region Methods private void SetTextView(AutoCompleteTextView textview, QuizWord word) { textview.Text = word.Answer; textview.AfterTextChanged += (sender, e) => word.Answer = textview.Text; textview.Touch += (sender, e) => { gestureDetector.OnTouchEvent(e.Event); gestureDetector.SingleTapConfirmed += (s, em) => { textview.RequestFocus(); ShowKeyboard(textview); }; }; } private void ShowKeyboard(AutoCompleteTextView textview) { ((Android.Views.InputMethods.InputMethodManager)activity.GetSystemService(Context.InputMethodService)).ShowSoftInput(textview, 0); } private bool NextView(MotionEvent e1, MotionEvent e2) { if(e2.RawX < e1.RawX) { parent.SetInAnimation(activity, Resource.Animation.in_from_right); parent.SetOutAnimation(activity, Resource.Animation.out_to_left); int previousIndex = parent.DisplayedChild; if (parent.DisplayedChild < words.Count - 1) { parent.ShowNext(); } else { parent.DisplayedChild = 0; } if (DisplayNewView != null) { DisplayNewView(parent.DisplayedChild, previousIndex); } } else if(e2.RawX > e1.RawX) { parent.SetInAnimation(activity, Resource.Animation.in_from_left); parent.SetOutAnimation(activity, Resource.Animation.out_to_right); int previousIndex = parent.DisplayedChild; if (parent.DisplayedChild >= 1) { parent.ShowPrevious(); } else { parent.DisplayedChild = words.Count - 1; } if (DisplayNewView != null) { DisplayNewView(parent.DisplayedChild, previousIndex); } } return true; } #endregion #region Inner Classes private class Holder : Java.Lang.Object { public TextView word; public TextView tense; public AutoCompleteTextView yo; public AutoCompleteTextView tu; public AutoCompleteTextView el; public AutoCompleteTextView nos; public AutoCompleteTextView vos; public AutoCompleteTextView ellos; } #endregion } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class playerMovement : MonoBehaviour { Vector2 endPos; playerAnimation playerAnimation; Rigidbody2D playerRB; public float dashTime; public float dashDuration; // Start is called before the first frame update void Start() { playerAnimation = GetComponent<playerAnimation>(); playerRB = GetComponent<Rigidbody2D>(); } // Update is called once per frame void Update() { playerAnimation.movementAnim(); Vector2 playerVelocity = playerRB.velocity; if ((Input.GetAxis("Horizontal")) < 0) { //moving left //playerVelocity.x = -1 * 5; transform.Translate (Vector2.left * 5 * Time.deltaTime); } if (Input.GetAxis("Horizontal") > 0) { //moving right //playerVelocity.x = 5; transform.Translate(Vector2.right * 5 * Time.deltaTime); } if ((Input.GetAxis("Vertical")) > 0) { //moving up //playerVelocity.y = -1 * 5; transform.Translate (Vector2.up * 5 * Time.deltaTime); } if (Input.GetAxis("Vertical") < 0) { //moving down //playerVelocity.y = 5; transform.Translate(Vector2.down * 5 * Time.deltaTime); } if (Input.GetButton("Dash") && Time.time > dashTime) { dashTime = Time.time + dashDuration; Vector2 direction = new Vector2(Camera.main.ScreenToViewportPoint(Input.mousePosition).x - 0.5f, Camera.main.ScreenToViewportPoint(Input.mousePosition).y - 0.5f); direction.Normalize(); if (direction != Vector2.zero) { transform.position = Vector2.Lerp((Vector2)transform.position, (Vector2)transform.position + direction * 100 , Time.deltaTime); } } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace LateOS.Models { [MetadataType(typeof(cFactura))] public partial class tbFactura { } public class cFactura { [Display(Name ="ID Factura")] public int fact_Id { get; set; } [Display(Name = "Código")] public string fact_Codigo { get; set; } [Display(Name = "Fecha")] public System.DateTime fact_Fecha { get; set; } [Display(Name = "ID Cliente")] public int clte_Id { get; set; } [Display(Name = "ID Tipo Pago")] public int tipp_Id { get; set; } [Display(Name = "ID Forma pago")] public int forp_Id { get; set; } [Display(Name = "Usuario crea")] public int fact_UsuarioCrea { get; set; } [Display(Name = "Fecha crea")] public System.DateTime fact_FechaCrea { get; set; } [Display(Name = "Usuario modifica")] public Nullable<int> fact_UsuarioModifica { get; set; } [Display(Name = "Fecha modifica")] public Nullable<System.DateTime> fact_FechaModifica { get; set; } } }
using Godot; using System; public class Scoring : Label { public int score = 0; public TextShaker textshaker; public override void _Ready() { } public void incrementScore(int score){ textshaker = (TextShaker)GetNode("TextShaker"); textshaker.Trigger(); score+= score; } public void setScore(int score) { this.score += score; this.Text = this.score.ToString(); } }
using System.Data.Entity.ModelConfiguration; using Logs.Models; namespace Logs.Data.Mappings { public class MeasurementMap : EntityTypeConfiguration<Measurement> { public MeasurementMap() { // Primary Key this.HasKey(t => t.MeasurementsId); // Properties this.Property(t => t.UserId) .HasMaxLength(128); // Table & Column Mappings this.ToTable("Measurements"); this.Property(t => t.MeasurementsId).HasColumnName("MeasurementsId"); this.Property(t => t.Height).HasColumnName("Height"); this.Property(t => t.WeightKg).HasColumnName("WeightKg"); this.Property(t => t.BodyFatPercent).HasColumnName("BodyFatPercent"); this.Property(t => t.Chest).HasColumnName("Chest"); this.Property(t => t.Shoulders).HasColumnName("Shoulders"); this.Property(t => t.Forearm).HasColumnName("Forearm"); this.Property(t => t.Arm).HasColumnName("Arm"); this.Property(t => t.Waist).HasColumnName("Waist"); this.Property(t => t.Hips).HasColumnName("Hips"); this.Property(t => t.Thighs).HasColumnName("Thighs"); this.Property(t => t.Calves).HasColumnName("Calves"); this.Property(t => t.Neck).HasColumnName("Neck"); this.Property(t => t.Wrist).HasColumnName("Wrist"); this.Property(t => t.Ankle).HasColumnName("Ankle"); this.Property(t => t.Date).HasColumnName("Date"); this.Property(t => t.UserId).HasColumnName("UserId"); // Relationships this.HasOptional(t => t.User) .WithMany(t => t.Measurements) .HasForeignKey(d => d.UserId); } } }
using iTextSharp.text; using iTextSharp.text.pdf; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; namespace ConsoleAppITextSharpPDF { public class PdfRepositoryV1 { public static string GetConnectionString() { string connetionString = "Data Source=DESKTOP-6DSO6AT\\SQLEXPRESS; Database=JunkEFCodeFrist1; Trusted_Connection=True"; if (ConfigurationManager.ConnectionStrings["MyDbConnectionString"] == null) { return connetionString; } else { return ConfigurationManager.ConnectionStrings["MyDbConnectionString"].ConnectionString; } } public static void GetXmlDataFromDatatBase() { string SQL = "GetAllXMLDataObjects"; SqlConnection con = new SqlConnection(GetConnectionString()); SqlCommand com = new SqlCommand(SQL, con); try { con.Open(); XmlReader reader = com.ExecuteXmlReader(); while (reader.Read()) { Console.WriteLine(reader.Name); if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); Console.Write(reader.Name + ": " + reader.Value); } reader.MoveToElement(); } } reader.Close(); } catch (Exception err) { Console.WriteLine(err.ToString()); } finally { con.Close(); } } public static void TestPdfRepositoryV1() { GetXmlDataFromDatatBase(); //Sample XML //var xml = CreateXml(); #region -- ******************************* -- // https://ehikioya.com/get-xml-document-nodes-recursively/ XmlReader xmlFile; xmlFile = XmlReader.Create("..\\..\\Employees.xml", new XmlReaderSettings()); DataSet ds = new DataSet(); ds.ReadXml(xmlFile); int i = 0; for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { Console.WriteLine(" ===> " + ds.Tables[0].Rows[i].ItemArray[2].ToString()); } // - Search in XML -- DataView dv; dv = new DataView(ds.Tables[0]); //dv.Sort = "Product_Name"; //int index = dv.Find("Product2"); #endregion XElement xelement = XElement.Load("..\\..\\Employees.xml"); var employees = (from nm in xelement.Elements("Employee") select nm).ToList(); XDocument xml = XDocument.Load("..\\..\\Employees.xml"); foreach (XElement element in xml.Descendants()) { Console.WriteLine(element.Name); } XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load("..\\..\\Employees.xml"); XmlNodeList xnList = xmlDocument.SelectNodes("/Employees/Employee"); foreach (XmlNode xn in xnList) { string id = xn["EmpId"].InnerText; string lastName = xn["Name"].InnerText; string sex = xn["EmpId"].InnerText; string phone = xn["Phone"].InnerText; Console.WriteLine("Employee : {0} {1} {2} {3}", id, lastName, sex, phone); } //File to write to var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf"); //Standard PDF creation, nothing special here using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (var doc = new Document()) { using (var writer = PdfWriter.GetInstance(doc, fs)) { doc.Open(); //Count the columns var columnCount = xml.Root.Elements("Employee").First().Nodes().Count(); //Create a table with one column for every child node of <cd> var t = new PdfPTable(columnCount); //Flag that the first row should be repeated on each page break t.HeaderRows = 1; //Loop through the first item to output column headers foreach (var N in xml.Root.Elements("Employee").First().Elements()) { t.AddCell(N.Name.ToString()); } //Loop through each CD row (this is so we can call complete later on) foreach (var CD in xml.Root.Elements()) { //Loop through each child of the current CD. Limit the number of children to our initial count just in case there are extra nodes. foreach (var N in CD.Elements().Take(columnCount)) { t.AddCell(N.Value); } //Just in case any rows have too few cells fill in any blanks t.CompleteRow(); } //Add the table to the document doc.Add(t); doc.Close(); Process.Start(testFile); } } } } #region -- Do Work -- private static XDocument CreateXml() { //Create our sample XML document var xml = new XDocument(new XDeclaration("1.0", "utf-8", "yes")); //Add our root node var root = new XElement("catalog"); //All child nodes var nodeNames = new[] { "SR.No", "test", "code", "unit", "sampleid", "boreholeid", "pieceno" }; XElement cd; //Create a bunch of <cd> items for (var i = 0; i < 1000; i++) { cd = new XElement("cd"); foreach (var nn in nodeNames) { cd.Add(new XElement(nn) { Value = String.Format("{0}:{1}", nn, i.ToString()) }); } root.Add(cd); } xml.Add(root); return xml; } public static void DoWork() { //Sample XML var xml = CreateXml(); //File to write to var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf"); //Standard PDF creation, nothing special here using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) { using (var doc = new Document()) { using (var writer = PdfWriter.GetInstance(doc, fs)) { doc.Open(); //Count the columns var columnCount = xml.Root.Elements("cd").First().Nodes().Count(); //Create a table with one column for every child node of <cd> var t = new PdfPTable(columnCount); //Flag that the first row should be repeated on each page break t.HeaderRows = 1; //Loop through the first item to output column headers foreach (var N in xml.Root.Elements("cd").First().Elements()) { t.AddCell(N.Name.ToString()); } //Loop through each CD row (this is so we can call complete later on) foreach (var CD in xml.Root.Elements()) { //Loop through each child of the current CD. Limit the number of children to our initial count just in case there are extra nodes. foreach (var N in CD.Elements().Take(columnCount)) { t.AddCell(N.Value); } //Just in case any rows have too few cells fill in any blanks t.CompleteRow(); } //Add the table to the document doc.Add(t); doc.Close(); Process.Start(testFile); } } } } #endregion public static void CreatePDFFile() { /* var data = new DataSet(); data.ReadXml("report.xml"); // Create empty document. var document = new DocumentModel(); var section = new Section(document); document.Sections.Add(section); // Create a header content. var headerData = data.Tables["Header"]; var header = new HeaderFooter(document, HeaderFooterType.HeaderDefault); foreach (DataColumn column in headerData.Columns) { //header.Blocks.Add( // new Paragraph(document, // new Run(document, column.ColumnName) { CharacterFormat = { Bold = true } }, // new SpecialCharacter(document, SpecialCharacterType.Tab), // new Run(document, headerData.Rows[0][column].ToString()), // new SpecialCharacter(document, SpecialCharacterType.LineBreak))); } section.HeadersFooters.Add(header); // Create table content. var tableData = data.Tables["Test"]; var table = new Table(document, tableData.Rows.Count, tableData.Columns.Count, (row, column) => { return new TableCell(document, new Paragraph(document, tableData.Rows[row][column].ToString())); }); section.Blocks.Add(table); // Save as PDF. document.Save("report.pdf", SaveOptions.PdfDefault); */ } } }
using System; using System.Collections.Generic; using System.Text; namespace Checkout.Payment.Processor.Domain.Models.PaymentCommand { public class UpdatePaymentResponse { Guid PaymentId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Data; using System.Data.SqlClient; using SimuladorPrestamos.BO; using iTextSharp.text; using iTextSharp.text.pdf; using System.IO; namespace SimuladorPrestamos.DAO { public class SimulacionesDAO { ConexionDAO Conexion; public SimulacionesDAO() { Conexion = new ConexionDAO(); } public int Agregar(SimulacionBO simulacion) { SqlCommand command = new SqlCommand("insert into Simulaciones values(@idCliente, @Monto, @Taza, @Plazo, @FechaIni)"); command.Parameters.Add("@idCliente", SqlDbType.Int).Value = simulacion.CodigoCliente; command.Parameters.Add("@Monto", SqlDbType.Real).Value = simulacion.Monto; command.Parameters.Add("@Taza", SqlDbType.Real).Value = simulacion.TazaInteres; command.Parameters.Add("@Plazo", SqlDbType.Int).Value = simulacion.PlazoPago; command.Parameters.Add("@FechaIni", SqlDbType.Date).Value = simulacion.FechaIncio.ToString("yyyy/MM/dd"); return Conexion.EjecutarComando(command); } public int Modificar(SimulacionBO simulacion) { SqlCommand command = new SqlCommand("update Simulaciones set idCliente = @idCliente, Monto = @Monto, Taza = @Taza, Plazo = @Plazo, FechaInicio = @FechaIni where idPrestamo = @idPrestamo"); command.Parameters.Add("@idPrestamo", SqlDbType.Int).Value = simulacion.CodigoPrestamo; command.Parameters.Add("@idCliente", SqlDbType.Int).Value = simulacion.CodigoCliente; command.Parameters.Add("@Monto", SqlDbType.Real).Value = simulacion.Monto; command.Parameters.Add("@Taza", SqlDbType.Real).Value = simulacion.TazaInteres; command.Parameters.Add("@Plazo", SqlDbType.Int).Value = simulacion.PlazoPago; command.Parameters.Add("@FechaIni", SqlDbType.Date).Value = simulacion.FechaIncio.ToString("yyyy/MM/dd"); return Conexion.EjecutarComando(command); } public int Eliminar(SimulacionBO simulacion) { SqlCommand command = new SqlCommand("delete from Simulaciones where idPrestamo = @idPrestamo"); command.Parameters.Add("@idPrestamo", SqlDbType.Int).Value = simulacion.CodigoPrestamo; command.Parameters.Add("@idCliente", SqlDbType.Int).Value = simulacion.CodigoCliente; command.Parameters.Add("@Monto", SqlDbType.Real).Value = simulacion.Monto; command.Parameters.Add("@Taza", SqlDbType.Real).Value = simulacion.TazaInteres; command.Parameters.Add("@Plazo", SqlDbType.Int).Value = simulacion.PlazoPago; command.Parameters.Add("@FechaIni", SqlDbType.Date).Value = simulacion.FechaIncio.ToString("yyyy/MM/dd"); return Conexion.EjecutarComando(command); } public DataSet ListaSimulaciones() { return Conexion.EjecutarSentencia(new SqlCommand("select idPrestamo, Clientes.idCliente ,Nombre, Monto, TazaInteres, Plazo, FechaInicio from Simulaciones inner join Clientes on Simulaciones.idCliente1 = Clientes.idCliente")); } public SimulacionBO BuscarSimulacion(int id) { SimulacionBO simulacion = new SimulacionBO(); SqlCommand Comando = new SqlCommand("Select * from Simulaciones where idPrestamo ='" + id + "'"); SqlDataReader Reader; Comando.Connection = Conexion.ConectarBD(); Conexion.Abrir(); Reader = Comando.ExecuteReader(); if(Reader.Read()) { simulacion.CodigoPrestamo = int.Parse(Reader[0].ToString()); simulacion.CodigoCliente = int.Parse(Reader[1].ToString()); simulacion.Monto = double.Parse(Reader[2].ToString()); simulacion.TazaInteres = double.Parse(Reader[3].ToString()); simulacion.PlazoPago = int.Parse(Reader[4].ToString()); simulacion.FechaIncio = DateTime.Parse(Reader[5].ToString()); } Conexion.Cerrar(); return simulacion; } public void GenerarPDF(int id, string ruta) { FileStream PFD = new FileStream(ruta, FileMode.Create); //Instancia de la clase clientes DAO para poder buscar al cliente que hace el prestamo ClientesDAO clientes = new ClientesDAO(); //Buscamos el registro de la simulacion SimulacionBO simulacion = BuscarSimulacion(id); //Buscamos el cliente al que se le hizo la simulacion ClientesBO cliente = clientes.BuscarCliente(simulacion.CodigoCliente); //Creamos un nuevo documento de ITextSharp y le pasamos como parametro que queremos que sea de tamaño carta Document Reporte = new Document(PageSize.LETTER); PdfWriter Writer = PdfWriter.GetInstance(Reporte, PFD); //Agregamos un titulo Reporte.AddTitle("Simulacion Prestamo " + simulacion.CodigoPrestamo); //Agregarmos Al creador del documento Reporte.AddCreator("PrestamosUTM"); //Y lo abrimos para editar Reporte.Open(); //Intanciamos la fuente que tendra nuestro documento Font Fuente = new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL, BaseColor.BLACK); //Agregamos un parrafo nuevo para que sea nuestra cabecera Reporte.Add(new Paragraph("Simulacion de prestamo N." + simulacion.CodigoPrestamo)); Reporte.Add(Chunk.NEWLINE); //Hacemos lo mismp para los datos del cliente Reporte.Add(new Paragraph("Numero de cliente: " + cliente.CodigoCliente + "\nCliente: " + cliente.Nombre + " " + cliente.Apellido)); Reporte.Add(Chunk.NEWLINE); //Creamos una nueva tabla y le pasamos como parametro el numero de columnas PdfPTable tablaPrestamo = new PdfPTable(6); tablaPrestamo.WidthPercentage = 100; //Configuaramos el titulo de las columnas PdfPCell CellNumeroPago = new PdfPCell(new Phrase("No. Pago", Fuente)); CellNumeroPago.BorderWidth = 0; CellNumeroPago.BorderWidthBottom = 0.75f; PdfPCell CellFecha = new PdfPCell(new Phrase("Fecha", Fuente)); CellFecha.BorderWidth = 0; CellFecha.BorderWidthBottom = 0.75f; PdfPCell CellPrincial = new PdfPCell(new Phrase("Principal", Fuente)); CellPrincial.BorderWidth = 0; CellPrincial.BorderWidthBottom = 0.75f; PdfPCell CellInteres = new PdfPCell(new Phrase("Interés", Fuente)); CellInteres.BorderWidth = 0; CellInteres.BorderWidthBottom = 0.75f; PdfPCell CellIVA = new PdfPCell(new Phrase("IVA(16%)", Fuente)); CellIVA.BorderWidth = 0; CellIVA.BorderWidthBottom = 0.75f; PdfPCell CellPago = new PdfPCell(new Phrase("Pago Total", Fuente)); CellPago.BorderWidth = 0; CellPago.BorderWidthBottom = 0.75f; //Agregamos las celdas a la tabla tablaPrestamo.AddCell(CellNumeroPago); tablaPrestamo.AddCell(CellFecha); tablaPrestamo.AddCell(CellPrincial); tablaPrestamo.AddCell(CellInteres); tablaPrestamo.AddCell(CellIVA); tablaPrestamo.AddCell(CellPago); //Pasamos el total a una variable double Monto = simulacion.Monto; DateTime Fecha = simulacion.FechaIncio; for (int i = simulacion.PlazoPago, j = 1; i > 0; i--, j++) { //calculamos los datos que se va a usar double InteresMensual = Monto * simulacion.TazaInteres; double IVA = (Monto + InteresMensual) * .16; double TotalPago = (Monto + InteresMensual + IVA) / i; CellNumeroPago = new PdfPCell(new Phrase(j.ToString(), Fuente)); CellNumeroPago.BorderWidth = 1; CellFecha = new PdfPCell(new Phrase(Fecha.ToShortDateString(), Fuente)); CellFecha.BorderWidth = 1; CellPrincial = new PdfPCell(new Phrase(Math.Round(Monto, 2).ToString(), Fuente)); CellPrincial.BorderWidth = 1; CellInteres = new PdfPCell(new Phrase(Math.Round(InteresMensual,2).ToString(), Fuente)); CellInteres.BorderWidth = 1; CellIVA = new PdfPCell(new Phrase(Math.Round(IVA,2).ToString(), Fuente)); CellIVA.BorderWidth = 1; CellPago = new PdfPCell(new Phrase(Math.Round(TotalPago,2).ToString(), Fuente)); CellPago.BorderWidth = 1; //Añadimos las celdas a la tabla tablaPrestamo.AddCell(CellNumeroPago); tablaPrestamo.AddCell(CellFecha); tablaPrestamo.AddCell(CellPrincial); tablaPrestamo.AddCell(CellInteres); tablaPrestamo.AddCell(CellIVA); tablaPrestamo.AddCell(CellPago); Monto = Monto - TotalPago; Fecha = Fecha.AddMonths(1); } Reporte.Add(tablaPrestamo); Reporte.Close(); PFD.Close(); Writer.Close(); } } }
using HardcoreHistoryBlog.Data; using HardcoreHistoryBlog.Models.Blog_Models; using HardcoreHistoryBlog.Models.Comments; using HardcoreHistoryBlog.Models.Likes; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace HardcoreHistoryBlog.Models { public class Users { public class Client : ApplicationUser { public virtual ApplicationUser Author { get; set; } public virtual ApplicationRole Role { get; set; } public virtual ICollection<Post> Posts { get; set; } } public class Customer : ApplicationUser { public virtual ApplicationRole Role { get; set; } public virtual ICollection<Post> Posts { get; set; } public virtual ICollection<Like> Likes { get; set; } public virtual ICollection<Comment> Comments { get; set; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameManager { public void Spawn(string path) { GameObject player = Managers.Resource.Instantiate(path); player.transform.position = new Vector2(-5, 2); } public void HpUpdate(Image hpBar) { if (Managers.Data.Hp > Managers.Data.MaxHp) { Managers.Data.Hp = Managers.Data.MaxHp; } hpBar.fillAmount = Managers.Data.Hp / Managers.Data.MaxHp; if (!Managers.Data.GameOver) { Managers.Data.Hp -= 1 * Time.deltaTime; } else { Managers.Data.Hp = 0f; } if (Managers.Data.Hp < 0) { Managers.Data.GameOver = true; } } public void ScoreUpdate(Text txt) { txt.text = $"Score : {Managers.Data.Score}"; } private void GameOver() { Managers.Data.Stage = 0; Managers.Data.RecordBestScore(); Managers.Sound.StopBgm(); Transform gameOver = GameObject.Find("@UI_Root").transform.Find("UI_GameOver"); if (gameOver != null) gameOver.gameObject.SetActive(true); } public IEnumerator ChangeStage() { while (true) { yield return new WaitForSeconds(30.0f); if (Managers.Data.Stage == 3) Managers.Data.Stage = 1; else Managers.Data.Stage++; } } public void OnUpdate() { if (Managers.Data.GameOver) GameOver(); } }
namespace MonoGame.Extended.Tiled { public enum TiledMapLayerType : byte { ImageLayer = 0, TileLayer = 1, ObjectLayer = 2, GroupLayer = 3 } }
using System.Collections.Generic; using ALTechTest.DataTransferObjects; namespace ALTechTest.Helpers { public class ArtistComparer : IEqualityComparer<ArtistDto> { public bool Equals(ArtistDto leftArtist, ArtistDto rightArtist) { Verify.NotNull(leftArtist, nameof(leftArtist)); Verify.NotNull(rightArtist, nameof(rightArtist)); return leftArtist.Id.Equals(rightArtist.Id); } public int GetHashCode(ArtistDto value) { return value.GetHashCode(); } } }
using Platformer.Mechanics; using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; using UnityEngine.UI; public class EquipmentUsing : MonoBehaviour { public int equipmentId; public EquipmentItem eItem; public Button button; private EquipmentItem GetThisEItem() { for (int i = 0; i < GameManager.instance.equipmentItems.Count; i++) { if (equipmentId == i) { eItem = GameManager.instance.equipmentItems[i]; } } return eItem; } public void UseEquipmentButton() { //if equiptment if (GetThisEItem().EquipmentID == 1) { Debug.Log("this happens 1" + GetThisEItem().itemName); for (int i = 0; i < GameManager.instance.equipmentItems.Count; i++) { if (GameManager.instance.equipmentItems[i].EquipmentID == 1 && GameManager.instance.equipmentItems[i].itemName == eItem.itemName) { GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().InsertEquipmentItemToPlayer(GetThisEItem()); button.enabled = false; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1); GameManager.instance.equipmentItems[i].eItemUsedByCharacter = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; Debug.Log("name: " + GameManager.instance.equipmentItems[i].eItemUsedByCharacter); GameManager.instance.equipmentItems[i].eUsing = true; Debug.Log(eItem.itemName); for (int j = 0; j < GameManager.instance.equipmentHelmets.Count; j++) { if (!(GameManager.instance.equipmentHelmets[j].itemName == eItem.itemName) && GameManager.instance.equipmentHelmets[j].eItemUsedByCharacter == eItem.eItemUsedByCharacter) { for (int k = 0; k < GameManager.instance.equipmentSlots.Length; k++) { if (k < GameManager.instance.equipmentItems.Count) { if (GameManager.instance.equipmentHelmets[j].itemName == GameManager.instance.equipmentItems[k].itemName) { Debug.Log("Item Name: " + GameManager.instance.equipmentItems[k].itemName); GameManager.instance.equipmentSlots[k].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = " "; GameManager.instance.equipmentSlots[k].transform.GetChild(2).GetComponent<Button>().enabled = true; GameManager.instance.equipmentItems[k].eItemUsedByCharacter = null; GameManager.instance.equipmentItems[k].eUsing = false; } } } } } } } } else if (GetThisEItem().EquipmentID == 2) { Debug.Log("this happens 2" + GetThisEItem().itemName); for (int i = 0; i < GameManager.instance.equipmentItems.Count; i++) { if (GameManager.instance.equipmentItems[i].EquipmentID == 2 && GameManager.instance.equipmentItems[i].itemName == eItem.itemName) { GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().InsertEquipmentItemToPlayer(GetThisEItem()); // Debug.Log("Name: " + GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().name); button.enabled = false; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1); GameManager.instance.equipmentItems[i].eItemUsedByCharacter = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; Debug.Log("name: " + GameManager.instance.equipmentItems[i].eItemUsedByCharacter); GameManager.instance.equipmentItems[i].eUsing = true; Debug.Log(eItem.itemName); for (int j = 0; j < GameManager.instance.equipmentChest.Count; j++) { if (!(GameManager.instance.equipmentChest[j].itemName == eItem.itemName) && GameManager.instance.equipmentChest[j].eItemUsedByCharacter == eItem.eItemUsedByCharacter) { for (int k = 0; k < GameManager.instance.equipmentSlots.Length; k++) { if (k < GameManager.instance.equipmentItems.Count) { if (GameManager.instance.equipmentChest[j].itemName == GameManager.instance.equipmentItems[k].itemName) { Debug.Log("Item Name: " + GameManager.instance.equipmentItems[k].itemName); GameManager.instance.equipmentSlots[k].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = " "; GameManager.instance.equipmentSlots[k].transform.GetChild(2).GetComponent<Button>().enabled = true; GameManager.instance.equipmentItems[k].eItemUsedByCharacter = null; GameManager.instance.equipmentItems[k].eUsing = false; } } } } } } } } else if (GetThisEItem().EquipmentID == 3) { Debug.Log("this happens 3" + GetThisEItem().itemName); for (int i = 0; i < GameManager.instance.equipmentItems.Count; i++) { if (GameManager.instance.equipmentItems[i].EquipmentID == 3 && GameManager.instance.equipmentItems[i].itemName == eItem.itemName) { GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().InsertEquipmentItemToPlayer(GetThisEItem()); // Debug.Log("Name: " + GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().name); button.enabled = false; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1); GameManager.instance.equipmentItems[i].eItemUsedByCharacter = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; Debug.Log("name: " + GameManager.instance.equipmentItems[i].eItemUsedByCharacter); GameManager.instance.equipmentItems[i].eUsing = true; Debug.Log(eItem.itemName); for (int j = 0; j < GameManager.instance.equipmentPants.Count; j++) { if (!(GameManager.instance.equipmentPants[j].itemName == eItem.itemName) && GameManager.instance.equipmentPants[j].eItemUsedByCharacter == eItem.eItemUsedByCharacter) { for (int k = 0; k < GameManager.instance.equipmentSlots.Length; k++) { if (k < GameManager.instance.equipmentItems.Count) { if (GameManager.instance.equipmentPants[j].itemName == GameManager.instance.equipmentItems[k].itemName) { Debug.Log("Item Name: " + GameManager.instance.equipmentItems[k].itemName); GameManager.instance.equipmentSlots[k].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = " "; GameManager.instance.equipmentSlots[k].transform.GetChild(2).GetComponent<Button>().enabled = true; GameManager.instance.equipmentItems[k].eItemUsedByCharacter = null; GameManager.instance.equipmentItems[k].eUsing = false; } } } } } } } } else if (GetThisEItem().EquipmentID == 4) { Debug.Log("this happens 4" + GetThisEItem().itemName); for (int i = 0; i < GameManager.instance.equipmentItems.Count; i++) { if (GameManager.instance.equipmentItems[i].EquipmentID == 4 && GameManager.instance.equipmentItems[i].itemName == eItem.itemName) { GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().InsertEquipmentItemToPlayer(GetThisEItem()); // Debug.Log("Name: " + GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().name); button.enabled = false; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1); GameManager.instance.equipmentItems[i].eItemUsedByCharacter = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; Debug.Log("name: " + GameManager.instance.equipmentItems[i].eItemUsedByCharacter); GameManager.instance.equipmentItems[i].eUsing = true; Debug.Log(eItem.itemName); for (int j = 0; j < GameManager.instance.equipmentBoots.Count; j++) { if (!(GameManager.instance.equipmentBoots[j].itemName == eItem.itemName) && GameManager.instance.equipmentBoots[j].eItemUsedByCharacter == eItem.eItemUsedByCharacter) { for (int k = 0; k < GameManager.instance.equipmentSlots.Length; k++) { if (k < GameManager.instance.equipmentItems.Count) { if (GameManager.instance.equipmentBoots[j].itemName == GameManager.instance.equipmentItems[k].itemName) { Debug.Log("Item Name: " + GameManager.instance.equipmentItems[k].itemName); GameManager.instance.equipmentSlots[k].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = " "; GameManager.instance.equipmentSlots[k].transform.GetChild(2).GetComponent<Button>().enabled = true; GameManager.instance.equipmentItems[k].eItemUsedByCharacter = null; GameManager.instance.equipmentItems[k].eUsing = false; } } } } } } } } else if (GetThisEItem().EquipmentID == 5) { Debug.Log("this happens 5" + GetThisEItem().itemName); for (int i = 0; i < GameManager.instance.equipmentItems.Count; i++) { if (GameManager.instance.equipmentItems[i].EquipmentID == 5 && GameManager.instance.equipmentItems[i].itemName == eItem.itemName) { if (GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerDetectShoot>().bulletShoot1 == null) { GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerDetectShoot>().bulletShootDamage1 += GetThisEItem().value; GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerDetectShoot>().bulletShoot1 = GetThisEItem().shootingPng; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1); button.enabled = false; GameManager.instance.equipmentItems[i].eItemUsedByCharacter = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentItems[i].eUsing = true; GameManager.instance.equipmentItems[i].bullet1 = true; GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerController>().playerCurrentEitems.Add(GetThisEItem()); } else if (GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerDetectShoot>().bulletShoot2 == null) { GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerDetectShoot>().bulletShootDamage2 += GetThisEItem().value; GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerDetectShoot>().bulletShoot2 = GetThisEItem().shootingPng; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1); button.enabled = false; GameManager.instance.equipmentItems[i].eItemUsedByCharacter = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; GameManager.instance.equipmentItems[i].eUsing = true; GameManager.instance.equipmentItems[i].bullet2 = true; GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerController>().playerCurrentEitems.Add(GetThisEItem()); } } // GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<PlayerAttributes>().playerDamage += GetThisEItem().value; // Debug.Log("Name: " + GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Health>().GetComponent<PlayerController>().name); // button.enabled = false; // GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; //GameManager.instance.equipmentSlots[i].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().color = new Color(1, 1, 1, 1); //GameManager.instance.equipmentItems[i].eItemUsedByCharacter = GameManager.instance.playerC.GetComponent<CharacterSwapping>().currentCharacter.GetComponent<Character>().characterName; /* for (int j = 0; j < GameManager.instance.equipmentWeapon.Count; j++) { if (!(GameManager.instance.equipmentWeapon[j].itemName == eItem.itemName) && GameManager.instance.equipmentWeapon[j].eItemUsedByCharacter == eItem.eItemUsedByCharacter) { for (int k = 0; k < GameManager.instance.equipmentSlots.Length; k++) { if (k < GameManager.instance.equipmentItems.Count) { if (GameManager.instance.equipmentWeapon[j].itemName == GameManager.instance.equipmentItems[k].itemName) { Debug.Log("Item Name: " + GameManager.instance.equipmentItems[k].itemName); GameManager.instance.equipmentSlots[k].transform.GetChild(2).transform.GetChild(0).GetComponent<Text>().text = " "; GameManager.instance.equipmentSlots[k].transform.GetChild(2).GetComponent<Button>().enabled = true; GameManager.instance.equipmentItems[k].eItemUsedByCharacter = null; } } } } }*/ } } } }
using NUnit.Framework; using FileImporter; using System.Collections.Generic; namespace FileAggregator.Tests { [TestFixture] public class Test { private FlatFileHeader header; private ICollection<FlatFileDataRow> dataRows; private string[] expectedAggregated; [SetUp] public void Setup() { header = new FlatFileHeader("CurrencyPair,Date,Type,Amount"); dataRows = new List<FlatFileDataRow> { new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-01,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,D,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,D,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-02,Q,100000"), new FlatFileDataRow("EUR/USD,2010-02-02,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("GBP/USD,2010-02-03,Q,100000"), new FlatFileDataRow("SGD/USD,2010-02-03,Q,100000") }; expectedAggregated = new[] { "[CurrencyPair=GBP/USD, Date=2010-02-01, Amount=2600000]", "[CurrencyPair=EUR/USD, Date=2010-02-01, Amount=300000]", "[CurrencyPair=GBP/USD, Date=2010-02-02, Amount=2400000]", "[CurrencyPair=EUR/USD, Date=2010-02-02, Amount=1500000]", "[CurrencyPair=GBP/USD, Date=2010-02-03, Amount=1000000]", "[CurrencyPair=SGD/USD, Date=2010-02-03, Amount=100000]" }; } [Test] public void TestThatAggregatorWorks() { var keyFields = new[] {"CurrencyPair", "Date"}; var valueField = "Amount"; var aggregator = new FileAggregator(); var results = aggregator.AggregateRows<long>(header, dataRows, keyFields, valueField); var output = new List<string>(); foreach (var res in results) { output.Add(res.ToString()); } Assert.AreEqual(expectedAggregated, output.ToArray()); } } }
namespace MooshakPP.Models.Entities { public class Milestone { public int ID { get; set; } public int assignmentID { get; set; } public string name { get; set; } public string description { get; set; } public string language { get; set; } } }
using JCFruit.WeebChat.Server.Tcp; using MediatR; namespace JCFruit.WeebChat.Server.ServerEvents { public class UserConnected : INotification { public ConnectedClient Client { get; } public UserConnected(ConnectedClient client) { Client = client; } } }
using System; using System.Collections.Generic; using System.IO; namespace LiveSplit.Yono { public enum LogObject { CurrentSplit, Pointers, Version, Loading, SceneName, SaveData, SaveCount } public class LogManager { public const string LOG_FILE = "Yono.txt"; private Dictionary<LogObject, string> currentValues = new Dictionary<LogObject, string>(); private Dictionary<string, SaveData> currentSaveData = new Dictionary<string, SaveData>(StringComparer.OrdinalIgnoreCase); private bool enableLogging; public bool EnableLogging { get { return enableLogging; } set { if (value != enableLogging) { enableLogging = value; if (value) { AddEntryUnlocked(new EventLogEntry("Initialized")); } } } } public LogManager() { EnableLogging = false; Clear(); } public void Clear(bool deleteFile = false) { lock (currentValues) { if (deleteFile) { try { File.Delete(LOG_FILE); } catch { } } foreach (LogObject key in Enum.GetValues(typeof(LogObject))) { currentValues[key] = null; } } } public void AddEntry(ILogEntry entry) { lock (currentValues) { AddEntryUnlocked(entry); } } private void AddEntryUnlocked(ILogEntry entry) { string logEntry = entry.ToString(); if (EnableLogging) { try { using (StreamWriter sw = new StreamWriter(LOG_FILE, true)) { sw.WriteLine(logEntry); } } catch { } Console.WriteLine(logEntry); } } public void Update(LogicManager logic, SplitterSettings settings) { if (!EnableLogging) { return; } lock (currentValues) { DateTime date = DateTime.Now; bool updateLog = true; foreach (LogObject key in Enum.GetValues(typeof(LogObject))) { string previous = currentValues[key]; string current = null; switch (key) { case LogObject.CurrentSplit: current = $"{logic.CurrentSplit} ({GetCurrentSplit(logic, settings)})"; break; case LogObject.Pointers: current = logic.Memory.GamePointers(); break; case LogObject.Version: current = MemoryManager.Version.ToString(); break; case LogObject.Loading: current = logic.Memory.IsLoading().ToString(); break; case LogObject.SceneName: current = updateLog ? logic.Memory.SceneName() : previous; break; case LogObject.SaveCount: current = updateLog ? logic.Memory.SaveDataCount().ToString() : previous; break; case LogObject.SaveData: if (updateLog) { CheckItems<SaveData>(key, currentSaveData, logic.Memory.SaveData()); } break; } if (previous != current) { AddEntryUnlocked(new ValueLogEntry(date, key, previous, current)); currentValues[key] = current; } } } } private void CheckItems<T>(LogObject type, Dictionary<string, T> currentItems, Dictionary<string, T> newItems) { DateTime date = DateTime.Now; foreach (KeyValuePair<string, T> pair in newItems) { string key = pair.Key; T state = pair.Value; T oldState; if (!currentItems.TryGetValue(key, out oldState) || !state.Equals(oldState)) { AddEntryUnlocked(new ValueLogEntry(date, type, oldState, state)); currentItems[key] = state; } } List<string> itemsToRemove = new List<string>(); foreach (KeyValuePair<string, T> pair in currentItems) { string key = pair.Key; T state = pair.Value; if (!newItems.ContainsKey(key)) { AddEntryUnlocked(new ValueLogEntry(date, type, state, null)); itemsToRemove.Add(key); } } for (int i = 0; i < itemsToRemove.Count; i++) { currentItems.Remove(itemsToRemove[i]); } } private string GetCurrentSplit(LogicManager logic, SplitterSettings settings) { if (logic.CurrentSplit >= settings.Autosplits.Count) { return "N/A"; } return settings.Autosplits[logic.CurrentSplit].ToString(); } } public interface ILogEntry { } public class ValueLogEntry : ILogEntry { public DateTime Date; public LogObject Type; public object PreviousValue; public object CurrentValue; public ValueLogEntry(DateTime date, LogObject type, object previous, object current) { Date = date; Type = type; PreviousValue = previous; CurrentValue = current; } public override string ToString() { return string.Concat( Date.ToString(@"HH\:mm\:ss.fff"), ": (", Type.ToString(), ") ", PreviousValue, " -> ", CurrentValue ); } } public class EventLogEntry : ILogEntry { public DateTime Date; public string Event; public EventLogEntry(string description) { Date = DateTime.Now; Event = description; } public EventLogEntry(DateTime date, string description) { Date = date; Event = description; } public override string ToString() { return string.Concat( Date.ToString(@"HH\:mm\:ss.fff"), ": ", Event ); } } }
using BigEndian.IO; namespace nuru.IO.NUI.Cell.Color { public class ColorUInt4Writer : IColorWriter { public virtual void Write(BigEndianBinaryWriter writer, ColorData pair) { writer.Write((byte)((pair.Foreground << 4) | (pair.Background & 0x0f))); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace POTM { public class LightColorPicker : MonoBehaviour { public LightColors colors; // Start is called before the first frame update void Awake() { Renderer rend = GetComponent<Renderer>(); rend.material = colors.col[Random.Range(0, colors.col.Count)]; } } }
using System; using System.Collections.Generic; using System.Data.Common; using System.Linq; using System.Text; using System.Threading.Tasks; using Caliburn.Micro; using Voronov.Nsudotnet.BuildingCompanyIS.Entities; using Voronov.Nsudotnet.BuildingCompanyIS.Entities.RelationTables; using Voronov.Nsudotnet.BuildingCompanyIS.Logic.DbInterfaces; namespace Voronov.Nsudotnet.BuildingCompanyIS.UI.ViewModels { public class BuildingAttributeValueViewModel : AbstractAttributeValueViewModel { public BuildingAttributeValueViewModel(BuildingAttributeValue entity) { BuildingAttributeValueEntity = entity; BuildingAttributeViewModel = new BuildingAttributeViewModel(entity.BuildingCategoryAttributes.BuildingAttribute); } public BuildingAttributeValue BuildingAttributeValueEntity { get; private set; } public BuildingAttributeViewModel BuildingAttributeViewModel { get; private set; } public override string AttributeName { get { return BuildingAttributeViewModel.AttributeName; } } public override DataTypes DataType { get { return BuildingAttributeViewModel.DataTypesViewModel.Type; } } public override string Value { get { return BuildingAttributeValueEntity.Value; } set { if (value == BuildingAttributeValueEntity.Value) return; BuildingAttributeValueEntity.Value = value; NotifyOfPropertyChange(() => Value); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _2C2PAssignment.Business.Dtos { public class ValidateResultDto { public CardType? Type { get; set; } public bool? IsValid { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SqlJobHub { public partial class JobPanel : UserControl { private String JobName; private String StepName; public JobPanel() { InitializeComponent(); } public JobPanel(String JobName, String StepName) { InitializeComponent(); this.JobName = JobName; this.StepName = StepName; this.JobNameLbl.Text = this.JobName; this.StepNameLbl.Text = this.StepName; this.ActionBtn.Enabled = false; } private void RefreshBtn_Click(object sender, EventArgs e) { } private void ActionBtn_Click(object sender, EventArgs e) { } } }
using System.Threading.Tasks; using Business.Abstract; using Entities.Concrete; using Microsoft.AspNetCore.Mvc; namespace WebAPI.Controllers { [Route("api/[controller]")] [ApiController] public class AddressesController : ControllerBase { private IAddressService _addressService; public AddressesController(IAddressService addressService) { _addressService = addressService; } [HttpGet("getall")] public async Task<IActionResult> GetAllAsync() { var result = await _addressService.GetAll(); if (result.Success) { return Ok(result); } return BadRequest(result); } [HttpGet("getallbyuserid")] public async Task<IActionResult> GetAllByUserId(int userId) { var result = await _addressService.GetAllByUserId(userId); if (result.Success) { return Ok(result); } return BadRequest(result); } [HttpGet("getbyid")] public async Task<IActionResult> GetById(int id) { var result = await _addressService.GetById(id); if (result.Success) { return Ok(result); } return BadRequest(result); } [HttpPost("getidadd")] public async Task<IActionResult> GetIdAdd(Address address) { var result = await _addressService.GetIdAdd(address); if (result.Success) { return Ok(result); } return BadRequest(result); } [HttpPost("add")] public async Task<IActionResult> Add(Address address) { var result = await _addressService.Add(address); if (result.Success) { return Ok(result); } return BadRequest(result); } [HttpPost("delete")] public async Task<IActionResult> Delete(Address address) { var result = await _addressService.Delete(address); if (result.Success) { return Ok(result); } return BadRequest(result); } [HttpPost("update")] public async Task<IActionResult> Update(Address address) { var result = await _addressService.Update(address); if (result.Success) { return Ok(result); } return BadRequest(result); } } }
using Microsoft.AspNetCore.Builder; using System; using System.Linq; using Utils; using Utils.Localization; using Utils.Localization.Configuration; using Utils.Localization.Dictionaries; using Utils.Localization.Dictionaries.Json; using Utils.Localization.Dictionaries.Xml; // ReSharper disable once CheckNamespace namespace Microsoft.Extensions.DependencyInjection { public static class LocalizationBuilderExtensions { /// <summary> /// /// </summary> /// <param name="app"></param> /// <param name="options"></param> /// <example> /// app.UseI18n(options => { /// options.LocalizationSourceName = "Tiny"; /// options.Localizations.Add(new LocalizationFile { Assembly = typeof(DisposeAction).GetAssembly(), RootNamespace = "Utils.Localization.Sources.XmlSource", LocalizationFileType = LocalizationFileType.XmlEmbeddedFile }); /// }); /// </example> /// <returns></returns> public static IApplicationBuilder UseI18N(this IApplicationBuilder app, Action<LocalizationOptions> options) { if (app == null) { throw new ArgumentNullException(nameof(app)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } LocalizationIocManager.ServiceProvider = app.ApplicationServices; var localizationOptions = new LocalizationOptions(); options.Invoke(localizationOptions); if (!localizationOptions.Localizations.Any()) { throw new ArgumentNullException(nameof(localizationOptions.Localizations), "本地化文件不能为空"); } IServiceProvider provider = app.ApplicationServices; var localizationConfiguration = provider.GetService<ILocalizationConfiguration>(); if (localizationConfiguration == null) { throw new InvalidOperationException( "AddI18N() must be called on the service collection. eg: services.AddI18N(...)"); } foreach (LocalizationFile item in localizationOptions.Localizations) { switch (item.LocalizationFileType) { case LocalizationFileType.JsonEmbeddedFile: localizationConfiguration.Sources.Add( new DictionaryBasedLocalizationSource( localizationOptions.LocalizationSourceName, new JsonEmbeddedFileLocalizationDictionaryProvider( item.Assembly, item.RootNamespace ))); break; case LocalizationFileType.JsonFile: Check.NotNullOrEmpty(item.DirectoryPath, nameof(item.DirectoryPath)); localizationConfiguration.Sources.Add( new DictionaryBasedLocalizationSource( localizationOptions.LocalizationSourceName, new JsonFileLocalizationDictionaryProvider( item.DirectoryPath ))); break; case LocalizationFileType.XmlFile: Check.NotNullOrEmpty(item.DirectoryPath, nameof(item.DirectoryPath)); localizationConfiguration.Sources.Add( new DictionaryBasedLocalizationSource( localizationOptions.LocalizationSourceName, new XmlFileLocalizationDictionaryProvider( item.DirectoryPath ))); break; case LocalizationFileType.XmlEmbeddedFile: localizationConfiguration.Sources.Add( new DictionaryBasedLocalizationSource( localizationOptions.LocalizationSourceName, new XmlEmbeddedFileLocalizationDictionaryProvider( item.Assembly, item.RootNamespace ))); break; } } var localizationManager = provider.GetService<ILocalizationManager>(); if (localizationManager == null) { throw new InvalidOperationException( "AddI18N() must be called on the service collection. eg: services.AddI18N(...)"); } localizationManager.Initialize(); return app; } } }
using Elementary.Compare; using LiteDB; using Moq; using System; using System.IO; using System.Linq; using TreeStore.Messaging; using TreeStore.Model; using Xunit; namespace TreeStore.LiteDb.Test { public class TagRepositoryTest : IDisposable { private readonly LiteRepository liteDb; private readonly Mock<IChangedMessageBus<ITag>> eventSource; private readonly TagRepository repository; private readonly ILiteCollection<BsonDocument> tags; private readonly MockRepository mocks = new MockRepository(MockBehavior.Strict); public TagRepositoryTest() { this.liteDb = new LiteRepository(new MemoryStream()); this.eventSource = this.mocks.Create<IChangedMessageBus<ITag>>(); this.repository = new TagRepository(this.liteDb, this.eventSource.Object); this.tags = this.liteDb.Database.GetCollection("tags"); } #pragma warning disable CA1063 // Implement IDisposable Correctly public void Dispose() => this.mocks.VerifyAll(); #pragma warning restore CA1063 // Implement IDisposable Correctly [Fact] public void TagRepository_writes_Tag_to_repository() { // ARRANGE var tag = new Tag("tag"); this.eventSource .Setup(s => s.Modified(tag)); // ACT this.repository.Upsert(tag); // ASSERT var readTag = this.tags.FindById(tag.Id); Assert.NotNull(readTag); Assert.Equal(tag.Id, readTag.AsDocument["_id"].AsGuid); } [Fact] public void TagRepository_writes_and_reads_Tag_with_Facet_from_repository() { // ARRANGE var tag = new Tag("tag", new Facet("facet", new FacetProperty("prop", FacetPropertyTypeValues.Long))); this.eventSource .Setup(s => s.Modified(tag)); // ACT this.repository.Upsert(tag); var result = this.repository.FindById(tag.Id); // ASSERT var comp = tag.DeepCompare(result); Assert.True(tag.NoPropertyHasDefaultValue()); Assert.False(comp.Different.Any()); } [Fact] public void TagRepository_updates_and_reads_Tag_with_Facet_from_repository() { // ARRANGE var tag = new Tag("tag", new Facet("facet", new FacetProperty("prop", FacetPropertyTypeValues.Guid))); this.eventSource .Setup(s => s.Modified(tag)); this.repository.Upsert(tag); // ACT tag.Name = "name2"; tag.AssignFacet(new Facet("facet2", new FacetProperty("prop2", FacetPropertyTypeValues.Double))); this.repository.Upsert(tag); // ASSERT Assert.True(tag.NoPropertyHasDefaultValue()); Assert.False(tag.DeepCompare(this.repository.FindById(tag.Id)).Different.Any()); } [Fact] public void TagRepository_rejects_duplicate_name() { // ARRANGE var tag = new Tag("tag", new Facet("facet", new FacetProperty("prop"))); this.eventSource .Setup(s => s.Modified(tag)); this.repository.Upsert(tag); // ACT var result = Assert.Throws<LiteException>(() => this.repository.Upsert(new Tag("TAG"))); // ASSERT // notification was sent only once this.eventSource.Verify(s => s.Modified(It.IsAny<Tag>()), Times.Once()); Assert.Equal("Cannot insert duplicate key in unique index 'Name'. The duplicate value is '\"tag\"'.", result.Message); Assert.Single(this.tags.FindAll()); } [Fact] public void TagRepository_finds_all_tags() { // ARRANGE var tag = new Tag("tag", new Facet("facet", new FacetProperty("prop", FacetPropertyTypeValues.Bool))); this.eventSource .Setup(s => s.Modified(tag)); this.repository.Upsert(tag); // ACT var result = this.repository.FindAll(); // ASSERT Assert.Equal(tag, result.Single()); var comp = tag.DeepCompare(result.Single()); Assert.True(tag.NoPropertyHasDefaultValue()); Assert.False(comp.Different.Any()); } [Fact] public void TagRepository_finding_tag_by_id_returns_null() { // ACT var result = this.repository.FindById(Guid.NewGuid()); // ASSERT Assert.Null(result); } [Fact] public void TagRepository_removes_tag_from_repository() { // ARRANGE var tag = new Tag("tag"); this.eventSource .Setup(s => s.Modified(tag)); this.repository.Upsert(tag); this.eventSource .Setup(s => s.Removed(tag)); // ACT var result = this.repository.Delete(tag); // ASSERT Assert.True(result); Assert.Null(this.tags.FindById(tag.Id)); } [Fact] public void TagRepository_removing_unknown_tag_returns_false() { // ARRANGE var tag = new Tag("tag"); // ACT var result = this.repository.Delete(tag); // ASSERT Assert.False(result); } [Fact] public void TagRepository_finds_by_name() { // ARRANGE var tag = new Tag("tag", new Facet("facet", new FacetProperty("prop", FacetPropertyTypeValues.Decimal))); this.eventSource .Setup(s => s.Modified(tag)); this.repository.Upsert(tag); // ACT var result = this.repository.FindByName("tag"); // ASSERT Assert.Equal(tag, result); var comp = tag.DeepCompare(result); Assert.True(tag.NoPropertyHasDefaultValue()); Assert.False(comp.Different.Any()); } [Fact] public void TagRepository_finding_by_name_returns_null_on_missing_tag() { // ARRANGE var tag = new Tag("tag", new Facet("facet", new FacetProperty("prop"))); this.eventSource .Setup(s => s.Modified(tag)); this.repository.Upsert(tag); // ACT var result = this.repository.FindByName("unknown"); // ASSERT Assert.Null(result); } } }
using System.Collections.Generic; namespace ReliableDbProvider.Tests.Entities { public class User { public int Id { get; set; } public string Name { get; set; } public ICollection<UserProperty> Properties { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace VinesaucePlayer { public partial class TwitchChat : Form { frmPlayer parent; public string Channel; public string ProperChannel { get { return parent.toProperCase(Channel); } } public TwitchChat(frmPlayer _parent, string _channel) { InitializeComponent(); parent = _parent; Channel = _channel; } private void TwitchChat_Load(object sender, EventArgs e) { if (parent.AlwaysOnTop) this.TopMost = true; Twitch.ScrollBarsEnabled = false; Twitch.ScriptErrorsSuppressed = true; Twitch.NewWindow3 += new EventHandler<NewWindow3EventArgs>(parent.WebBrowser_NewWindow3); this.Text = "Twitch Chat : " + ProperChannel; Twitch.Url = new Uri("http://perso.maskatel.net/lib/EZTWAPI/GETCHAT.php?channel=" + Channel); } private void Twitch_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { try { Twitch.Document.Body.Style = "overflow:hidden; background-color:black; margin:0 0 0 0; padding:0 0 0 0;"; } catch { } Twitch.Visible = true; } private void ChatangoChat_FormClosed(object sender, FormClosedEventArgs e) { parent.twitch.Remove(this); } } }
using ConsoleAppNoOpenClose.Model.Entities; using ConsoleAppNoOpenClose.Model.Repositories; using System; using System.Collections.Generic; using System.Text; namespace ConsoleAppNoOpenClose.Model.Services { public class StudentPersistService { public void Save(Student student) { var repo = new StudentRepository(); repo.Add(student); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(MoveAgent))] [RequireComponent(typeof(Animator))] [RequireComponent(typeof(Collider))] public class Unit : Attackable { public UnitData data; public float Health { get; private set; } public Transform heart; public LayerMask enemyMask; [HideInInspector] public Transform firePoint; [HideInInspector] public Transform impactSpot; [HideInInspector] public LayerMask comradeMask; public GameObject deathEffect; public float deathEffectLifetime = 5; public bool IsDead { get; private set; } public override Transform Center => heart; public bool isDefense; bool patrols = false; bool setToGoHome; Vector3 patrolPoint; float seeRange = 10000000; MoveAgent agent; Animator anim; Collider col; bool ready = true; public override bool IsAlive => !IsDead; public override Collider BoundsCollider => col; Attackable target; const float updateTargetDelta = 0.5f; public Vector3 ClosestPointToTarget => target.BoundsCollider.ClosestPointOnBounds(transform.position); public float DistanceFromClosestPoint => Vector3.Distance(transform.position, ClosestPointToTarget); public bool IsInAttackRange => target == null ? false : DistanceFromClosestPoint < data.attackRange; void Awake() { Health = data.health; col = GetComponent<Collider>(); anim = GetComponent<Animator>(); agent = GetComponent<MoveAgent>(); InvokeRepeating("UpdateTarget", 0.2f, updateTargetDelta); } void UpdateTarget() { float minDist = float.MaxValue; target = null; foreach(var col in Physics.OverlapSphere(transform.position, seeRange, enemyMask)) { float dist = Vector3.SqrMagnitude(col.transform.position - transform.position); if (dist >= minDist) continue; var attackable = col.GetComponent<Attackable>(); if (!attackable.IsAlive) continue; minDist = dist; target = attackable; } if (target == null) return; setToGoHome = false; agent.FollowTargetAtDist(target.Center, data.attackRange - 0.2f); } void Update() { if (target == null) { if (!patrols) return; if (setToGoHome) return; setToGoHome = true; agent.SetDestination(patrolPoint); return; } if (ready && IsInAttackRange) { Attack(); StartCoroutine(GetReadyRoutine()); } } [ContextMenu("To Walking")] void ConvertToWalking() { DestroyImmediate(GetComponent<Collider>()); DestroyImmediate(GetComponent<MoveAgent>()); gameObject.AddComponent<CampMoveAgent>(); DestroyImmediate(this); } public void ApplyDefenseData(Vector3 patrolSpot, float seeRange) { patrols = true; patrolPoint = patrolSpot; this.seeRange = seeRange; } public override void TakeDamage(float damage) { if (IsDead) return; anim.SetTrigger("Take Damage"); Health -= damage; if (Health <= 0) Die(); } public override void HealBy(float value) { if (IsDead) return; Health = Mathf.Clamp(Health + value, 0, data.health); } public void Attack() { if (IsDead) return; if (!ready) return; switch (data.type) { case UnitData.UnitType.Melee: MeleeAttack(); break; case UnitData.UnitType.Range: RangeAttack(); break; case UnitData.UnitType.Kamikaze: KamikazeAttack(); break; case UnitData.UnitType.Magic: MagicalAttack(); break; case UnitData.UnitType.Healer: HealerHeal(); break; } } IEnumerator GetReadyRoutine() { ready = false; float waitTime = 10; switch (data.type) { case UnitData.UnitType.Melee: case UnitData.UnitType.Range: case UnitData.UnitType.Magic: waitTime = 1f / data.attackSpeed; break; case UnitData.UnitType.Healer: waitTime = data.healDelta; break; } yield return new WaitForSeconds(waitTime); ready = true; } #region Attack void SplashAction(Vector3 center, bool heal = false) { if (!data.splashAttack) return; LayerMask mask = heal ? comradeMask : enemyMask; foreach (var col in Physics.OverlapSphere(center, data.splashRadius, mask)) { var attackable = col.GetComponent<Attackable>(); if (attackable == null) continue; if (heal) attackable.HealBy(data.splashHeal); else attackable.TakeDamage(data.splashDamage); } } void MeleeAttack() { anim.SetTrigger("Attack"); target.TakeDamage(data.damage); SplashAction(transform.position); } void KamikazeAttack() { anim.SetTrigger("Kaboom!"); SplashAction(transform.position); Die(); } void RangeAttack() { anim.SetTrigger("Attack"); var prefab = isDefense ? data.defenseProjectile : data.attackProjectile; var projectile = Instantiate(prefab, firePoint.position, firePoint.rotation); projectile.transform.LookAt(target.Center); } void MagicalAttack() { anim.SetTrigger("Attack"); //to do invoke from special script } void HealerHeal() { anim.SetTrigger("Heal"); target.HealBy(data.healAmount); SplashAction(target.transform.position, true); } #endregion void DeathEffectStuff() { if (deathEffect == null) return; var effect = Instantiate(deathEffect, transform.position, transform.rotation); effect.name = name + " Corpse"; Destroy(effect, deathEffectLifetime); } void Die() { IsDead = true; DeathEffectStuff(); Destroy(gameObject); } void OnValidate() { if (heart == null) heart = transform; } void OnGizmosDrawSelected() { if (data == null) return; Gizmos.color = Color.red; Gizmos.DrawWireSphere(heart.position, data.attackRange); } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; public class Movimiento_Mouse : MonoBehaviour { public float movementSpeed; public float speed = 0.0f, duration = 0.0f; public GameObject playerMovePoint; private GameObject Obj_personaje; private GameObject triggeringPMR; private Transform pmr ; private bool pmrSpawned; private bool moving; private Animator anim; //private NavMeshAgent navAgent; Vector3 mousePosition, target; public Vector3 targetPos; public LayerMask groundLayer; private void Awake() { //navAgent = GetComponent<NavMeshAgent>(); anim = GetComponentInChildren<Animator>(); } // Update is called once per frame void Update() { //anim.SetFloat("velo", navAgent.velocity.sqrMagnitude); if (Input.GetButtonDown("Fire1")) { MoveTowardsClick(); } //Player movement Plane playerPlane = new Plane(Vector3.up, transform.position); Ray ray = UnityEngine.Camera.main.ScreenPointToRay(Input.mousePosition); Obj_personaje = GameObject.Find("Player"); if (playerPlane.Raycast(ray, out float hitDistance)) { mousePosition = ray.GetPoint(hitDistance); if (Input.GetMouseButtonDown(0)) { moving = true; if (pmrSpawned) { pmr = null; pmr = Instantiate(playerMovePoint.transform, mousePosition, Quaternion.identity); } else { pmr = Instantiate(playerMovePoint.transform, mousePosition, Quaternion.identity); } } } if (pmr) pmrSpawned = true; else pmrSpawned = false; if (moving) Move(); } private void MoveTowardsClick() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit, Mathf.Infinity, groundLayer)) { if (targetPos != hit.point) { targetPos = hit.point; } //navAgent.SetDestination(targetPos); } } public void Move() { if (pmr) { transform.position = Vector3.MoveTowards(transform.position, pmr.transform.position, movementSpeed); this.transform.LookAt(pmr.transform); ///Dibuja trayectoria del muñeco al mouse /*transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime); Debug.DrawLine(transform.position, mousePosition, Color.black, duration = 0.0f);*/ } } void OnTriggerEnter(Collider other) { if(other.CompareTag("PMR")) { triggeringPMR = other.gameObject; triggeringPMR.GetComponent<PMR>().DestroyPMR(); } } }
using System; using System.Collections.Generic; using System.Text; namespace AgentStoryComponents { public class PostMan { AgentStoryComponents.core.utils ute = new AgentStoryComponents.core.utils(); private string _conn; public string conn { get { return _conn; } } public PostMan(string asConn) { //read off config this._conn = asConn; aspNetEmail.EmailMessage.LoadLicenseFile(config.aspNetEmailLicensePath ); } public void SendMessages(EmailStates state) { StoryLog sl = new StoryLog(config.conn); Emails emails = new Emails(this._conn); List<EmailMsg> messagesToSend = emails.getEmailMessages(state); foreach (EmailMsg emsg in messagesToSend) { try { sendMail(emsg); //$TODO: LOG EASIER string successMsg = "EMAIL [" + emsg.ID + "] to [ " + emsg.to + " ] was SENT "; sl.AddToLog(successMsg); emsg.LastError = ute.encode64(successMsg); emsg.Save(); } catch (Exception ex) { //$TODO: LOG EASIER string errMsg = "EMAIL [" + emsg.ID + "] to [ "+emsg.to+" ] was NOT SENT :" + ex.Message; sl.AddToLog(errMsg); emsg.LastError = ute.encode64(errMsg); emsg.Save(); } } sl = null; } private void sendMail( EmailMsg emsg) { aspNetEmail.EmailMessage msg = new aspNetEmail.EmailMessage(config.smtpServer); msg.ValidateAddress = false; User from = null; try { from = new User(config.conn, emsg.from); } catch (Exception ex) { throw new UserDoesNotExistException("Invalid sender [" + emsg.from + "]. Can only send emails from users that are registered on this system"); } User reply = null; try { reply = new User(config.conn, emsg.ReplyToAddress); } catch (Exception ex) { throw new UserDoesNotExistException("Invalid replyto [" + emsg.ReplyToAddress + "]. Can only reply to emails from users that are registered on this system"); } User to = null; try { to = new User(config.conn, emsg.to); } catch (Exception ex) { throw new UserDoesNotExistException("Invalid recipient [" + emsg.to + "]. Can only send emails to users that are registered on this system"); } msg.BodyFormat = aspNetEmail.MailFormat.Text; //if (to.NotificationTypes.IndexOf("html") != -1) //{ // msg.BodyFormat = aspNetEmail.MailFormat.Html; //} msg.AddTo(to.Email,"<" + to.FirstName + ", " + to.LastName + "> "); // msg.ReturnReceipt = true; //msg.ReturnReceiptAddress = emsg.ReplyToAddress; msg.FromAddress = emsg.from; //msg.FromName = from.FirstName + " " + from.LastName + " ( aka. " + from.UserName + " ) "; msg.FromName = reply.FirstName + " " + reply.LastName + " ( aka. " + reply.UserName + " ) "; msg.ReplyTo = emsg.ReplyToAddress; msg.Importance = aspNetEmail.MailPriority.High; msg.Priority = aspNetEmail.MailPriority.High; msg.Organization = config.Orginization; if (emsg.ReplyToAddress.Trim().ToLower() == config.anonEmailReplyTo.Trim().ToLower()) { //ANON REPLY TO msg.Subject = "[" + from.UserName + " | " + from.UserGUID + "] " + ute.decode64(emsg.subject); msg.Body = ute.decode64(emsg.body) + config.AnonEmailBodyFooter + " " + config.GeneralEmailBodyFooter + config.HelpEmailBodyFooter; } else { //NON ANON REPLY TO msg.Subject = ute.decode64(emsg.subject); msg.Body = ute.decode64(emsg.body) + config.GeneralEmailBodyFooter + config.HelpEmailBodyFooter; } msg.Username = config.smtpUser; msg.Password = config.smtpPwd; try { emsg.changeState(EmailStates.sending); msg.Send(); emsg.changeState(EmailStates.sent); } catch (Exception ex) { //$TODO: LOG EASIER string errMsg = "EMAIL [" + emsg.ID + "] was NOT SENT :" + ex.Message; StoryLog sl = new StoryLog(config.conn); sl.AddToLog(errMsg); sl = null; emsg.LastError = ute.encode64(errMsg); emsg.Save(); throw new MessageNotSentException(errMsg); } } public void SendMessage(int msgID) { EmailMsg msgToSend = new EmailMsg(config.conn, msgID); sendMail(msgToSend); } } }
using Microsoft.Xna.Framework; namespace MonoGame.Extended { public interface IMovable { Vector2 Position { get; set; } } }
using Hayalpc.Fatura.Common.Enums; using Hayalpc.Library.Repository; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Text; namespace Hayalpc.Fatura.Data.Models { [Table("roles", Schema = "panel")] public class Role : HpModel { [Required] [Updatable] public UserType Type { get; set; } [Required] [StringLength(64)] [Updatable] public string Name { get; set; } [Required] [StringLength(64)] [Updatable] public string Description { get; set; } [Updatable] public Library.Common.Enums.Status Status { get; set; } } }
namespace Triton.Game.Mono { using GreyMagic; using log4net; using ns26; using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using Triton.Common; using Triton.Game; public class MonoClass : IDisposable { private static readonly AllocatedMemory[] allocatedMemory_0 = new AllocatedMemory[0x20]; private bool bool_0; internal static readonly Dictionary<string, Type> dictionary_0 = new Dictionary<string, Type>(); internal static Dictionary<string, IntPtr> dictionary_1; internal static Dictionary<string, IntPtr> dictionary_2; private static readonly Dictionary<IntPtr, Dictionary<string, List<Class269>>> dictionary_3 = new Dictionary<IntPtr, Dictionary<string, List<Class269>>>(); private static readonly Dictionary<IntPtr, Dictionary<string, IntPtr>> dictionary_4 = new Dictionary<IntPtr, Dictionary<string, IntPtr>>(); private static readonly Dictionary<string, Dictionary<string, IntPtr>> dictionary_5 = new Dictionary<string, Dictionary<string, IntPtr>>(); private static readonly ILog ilog_0 = Logger.GetLoggerInstanceForType(); private const int int_0 = 0x20; [CompilerGenerated] private IntPtr intptr_0; private static readonly List<uint> list_0 = new List<uint>(); private IntPtr? nullable_0; private IntPtr? nullable_1; public static readonly object OutLock = new object(); [CompilerGenerated] private string string_0; [CompilerGenerated] private string string_1; [CompilerGenerated] private string string_2; [CompilerGenerated] private string string_3; [CompilerGenerated] private uint uint_0; static MonoClass() { foreach (Type type in Assembly.GetExecutingAssembly().GetTypes()) { if (type.IsClass) { foreach (Attribute38 attribute in type.GetCustomAttributes(typeof(Attribute38), false)) { dictionary_0.Add(attribute.ClassName, type); } } } } internal MonoClass(IntPtr address, string className) : this(TritonHs.MainAssemblyPath, "", className) { if (address == IntPtr.Zero) { throw new InvalidOperationException("Cannot create an instance of MonoClass with a backing pointer of Zero."); } this.Address = address; this.UInt32_0 = Class272_0.method_10(address, true); this.RealClassName = Class272_0.method_45(this.IntPtr_0); } internal MonoClass(string assembly, string classNamespace, string className) { this.AssemblyPath = assembly; this.ClassNamespace = classNamespace; this.ClassName = className; } public void Dispose() { this.Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (!this.bool_0) { if (disposing) { List<uint> list = list_0; lock (list) { if (this.UInt32_0 != 0) { list_0.Add(this.UInt32_0); this.UInt32_0 = 0; } } } this.bool_0 = true; } } ~MonoClass() { this.Dispose(true); } public virtual IntPtr GetClassInstance() { return this.Address; } public static bool IsOutParam(int index, out IntPtr addr) { addr = IntPtr.Zero; if (((index >= 0) && (index < 0x20)) && (allocatedMemory_0[index] != null)) { addr = allocatedMemory_0[index].Address; return true; } return false; } internal IntPtr method_0(string string_4, Class272.Enum20[] enum20_0) { if (this.IntPtr_0 == IntPtr.Zero) { throw new InvalidOperationException("Cannot get a method pointer on an object that has no MonoClass pointer."); } return smethod_4(this.IntPtr_0, string_4, enum20_0); } internal IntPtr method_1(string string_4) { Dictionary<string, IntPtr> dictionary; IntPtr ptr; if (!dictionary_4.TryGetValue(this.IntPtr_0, out dictionary)) { dictionary_4.Add(this.IntPtr_0, new Dictionary<string, IntPtr>()); dictionary = dictionary_4[this.IntPtr_0]; } if (!dictionary.TryGetValue(string_4, out ptr)) { ptr = Class272_0.method_34(this.IntPtr_0, string_4); if (ptr != IntPtr.Zero) { dictionary.Add(string_4, ptr); } } return ptr; } internal T method_10<T>(string string_4, Class272.Enum20[] enum20_0, params object[] object_0) where T: struct { IntPtr ptr = this.method_7(string_4, enum20_0, object_0); if (ptr == IntPtr.Zero) { return default(T); } if (typeof(T) == typeof(bool)) { IntPtr addr = Class272_0.method_26(ptr); return (T) (ExternalProcessMemory_0.Read<byte>(addr) > 0); } return ExternalProcessMemory_0.Read<T>(Class272_0.method_26(ptr)); } internal T method_11<T>(string string_4, params object[] object_0) where T: struct { return this.method_10<T>(string_4, null, object_0); } internal string method_12(string string_4, Class272.Enum20[] enum20_0, params object[] object_0) { IntPtr ptr = this.method_7(string_4, enum20_0, object_0); if (ptr == IntPtr.Zero) { return null; } return Class272_0.method_24(ptr); } internal string method_13(string string_4, params object[] object_0) { return this.method_12(string_4, null, object_0); } internal T method_14<T>(string string_4, params object[] object_0) where T: class { return this.method_15<T>(string_4, null, object_0); } internal T method_15<T>(string string_4, Class272.Enum20[] enum20_0, params object[] object_0) where T: class { if (!typeof(T).IsClass) { object[] objArray1 = new object[] { typeof(T), " is not a class type. Please fix the method invocation for ", this.ClassName, ".", string_4, " to use Get<T> or GetString instead." }; throw new InvalidOperationException(string.Concat(objArray1)); } IntPtr ptr = this.method_7(string_4, enum20_0, object_0); if (ptr == IntPtr.Zero) { return default(T); } return FastObjectFactory.CreateObjectInstance<T>(ptr); } private int method_16() { return Class272_0.method_8(Class272_0.method_23(this.Address)); } internal int method_17() { return Class272_0.method_7(this.Address); } private IntPtr method_18(int int_1) { return Class272_0.method_9(this.Address, this.method_16(), int_1); } private T method_19<T>(IntPtr intptr_1) where T: class { if (intptr_1 == IntPtr.Zero) { return default(T); } return FastObjectFactory.CreateObjectInstance<T>(intptr_1); } internal T method_2<T>(string string_4) where T: struct { IntPtr ptr = this.method_5(string_4); if (ptr == IntPtr.Zero) { return default(T); } return ExternalProcessMemory_0.Read<T>(Class272_0.method_26(ptr)); } private T method_20<T>(IntPtr intptr_1) where T: struct { if (intptr_1 == IntPtr.Zero) { return default(T); } if (typeof(T) == typeof(bool)) { IntPtr addr = Class272_0.method_26(intptr_1); return (T) (ExternalProcessMemory_0.Read<byte>(addr) > 0); } return ExternalProcessMemory_0.Read<T>(Class272_0.method_26(intptr_1)); } internal T method_21<T>(int int_1) where T: class { if ((int_1 < 0) || (int_1 >= this.method_17())) { throw new InvalidOperationException(string.Format("The index {0} is invalid for this array.", int_1)); } IntPtr addr = this.method_18(int_1); IntPtr ptr2 = ExternalProcessMemory_0.Read<IntPtr>(addr); return this.method_19<T>(ptr2); } internal T method_22<T>(int int_1) where T: struct { if ((int_1 < 0) || (int_1 >= this.method_17())) { throw new InvalidOperationException(string.Format("The index {0} is invalid for this array.", int_1)); } IntPtr addr = this.method_18(int_1); return ExternalProcessMemory_0.Read<T>(addr); } internal string method_23(int int_1) { if ((int_1 < 0) || (int_1 >= this.method_17())) { throw new InvalidOperationException(string.Format("The index {0} is invalid for this array.", int_1)); } IntPtr addr = this.method_18(int_1); IntPtr ptr2 = ExternalProcessMemory_0.Read<IntPtr>(addr); return Class272_0.method_24(ptr2); } internal T method_3<T>(string string_4) where T: class { IntPtr ptr = this.method_5(string_4); if (ptr == IntPtr.Zero) { return default(T); } return FastObjectFactory.CreateObjectInstance<T>(ptr); } internal string method_4(string string_4) { IntPtr ptr = this.method_5(string_4); if (ptr == IntPtr.Zero) { return null; } return Class272_0.method_24(ptr); } internal IntPtr method_5(string string_4) { IntPtr classInstance = this.GetClassInstance(); if (classInstance == IntPtr.Zero) { throw new Exception("Cannot call a method on an object instance that has no address!"); } IntPtr ptr2 = this.method_1(string_4); if (ptr2 == IntPtr.Zero) { throw new MissingFieldException(this.ClassName, string_4); } return Class272_0.method_22(classInstance, ptr2); } internal IntPtr method_6(string string_4, params object[] object_0) { return this.method_7(string_4, null, object_0); } internal IntPtr method_7(string string_4, Class272.Enum20[] enum20_0, params object[] object_0) { IntPtr classInstance = this.GetClassInstance(); if (classInstance == IntPtr.Zero) { throw new Exception("Cannot call a method on an object instance that has no address!"); } IntPtr ptr2 = this.method_0(string_4, enum20_0); if (ptr2 == IntPtr.Zero) { throw new MissingMethodException(this.ClassName, string_4); } return Class272_0.method_43(ptr2, classInstance, object_0); } internal void method_8(string string_4, params object[] object_0) { this.method_9(string_4, null, object_0); } internal void method_9(string string_4, Class272.Enum20[] enum20_0, params object[] object_0) { this.method_7(string_4, enum20_0, object_0); } public static T ReadOutParam<T>(int index) where T: struct { if ((index < 0) || (index >= 0x20)) { throw new Exception(string.Format("index({0}) < 0 || index({0}) >= MaxOutParams({1})", index, 0x20)); } return allocatedMemory_0[index].Read<T>(0); } public static IntPtr ReflectionTypeGetType(string type) { IntPtr ptr = smethod_2(type); if (ptr == IntPtr.Zero) { return IntPtr.Zero; } return Class272_0.method_5(ptr); } public static void ResetOutParams() { for (int i = 0; i < 0x20; i++) { if (allocatedMemory_0[i] != null) { allocatedMemory_0[i].Dispose(); allocatedMemory_0[i] = null; } } } public static void SetOutParam(int index, int size) { if ((index < 0) || (index >= 0x20)) { throw new Exception(string.Format("index({0}) < 0 || index({0}) >= MaxOutParams({1})", index, 0x20)); } allocatedMemory_0[index] = new AllocatedMemory(ExternalProcessMemory_0, size); } internal static void smethod_0() { List<uint> list = list_0; lock (list) { int count = list_0.Count; foreach (uint num in list_0) { Class272_0.method_11(num); } list_0.Clear(); } } private static void smethod_1() { if (dictionary_1 == null) { dictionary_1 = new Dictionary<string, IntPtr>(); } else { dictionary_1.Clear(); } if (dictionary_2 == null) { dictionary_2 = new Dictionary<string, IntPtr>(); } else { dictionary_2.Clear(); } foreach (KeyValuePair<string, IntPtr> pair in TritonHs.Class272_0.method_20(TritonHs.UnityEngineAssemblyPath, ref dictionary_1)) { dictionary_2.Add(pair.Key, pair.Value); } foreach (KeyValuePair<string, IntPtr> pair2 in TritonHs.Class272_0.method_20(TritonHs.MainAssemblyPath, ref dictionary_1)) { dictionary_2.Add(pair2.Key, pair2.Value); } } internal static IntPtr smethod_10(string string_4, string string_5, string string_6, string string_7, Class272.Enum20[] enum20_0, params object[] object_0) { IntPtr ptr; string[] textArray1 = new string[] { string_4, "~", string_5, ".", string_6 }; string key = string.Concat(textArray1); if (!Dictionary_1.TryGetValue(key, out ptr)) { ptr = Class272_0.method_21(string_4, string_5, string_6); Dictionary_1.Add(key, ptr); } IntPtr ptr2 = smethod_4(ptr, string_7, enum20_0); if (ptr2 == IntPtr.Zero) { return IntPtr.Zero; } return Class272_0.method_43(ptr2, IntPtr.Zero, object_0); } internal static T smethod_11<T>(string string_4, string string_5, string string_6, string string_7, Class272.Enum20[] enum20_0, params object[] object_0) where T: struct { IntPtr ptr = smethod_10(string_4, string_5, string_6, string_7, enum20_0, object_0); if (ptr == IntPtr.Zero) { return default(T); } if (typeof(T) == typeof(bool)) { IntPtr addr = Class272_0.method_26(ptr); return (T) (ExternalProcessMemory_0.Read<byte>(addr) > 0); } return ExternalProcessMemory_0.Read<T>(Class272_0.method_26(ptr)); } internal static string smethod_12(string string_4, string string_5, string string_6, string string_7, params object[] object_0) { return smethod_13(string_4, string_5, string_6, string_7, null, object_0); } internal static string smethod_13(string string_4, string string_5, string string_6, string string_7, Class272.Enum20[] enum20_0, params object[] object_0) { IntPtr ptr = smethod_10(string_4, string_5, string_6, string_7, enum20_0, object_0); if (ptr == IntPtr.Zero) { return null; } return Class272_0.method_24(ptr); } internal static T smethod_14<T>(string string_4, string string_5, string string_6, string string_7, params object[] object_0) where T: struct { return smethod_11<T>(string_4, string_5, string_6, string_7, null, object_0); } internal static T smethod_15<T>(string string_4, string string_5, string string_6, string string_7, params object[] object_0) where T: MonoClass { return smethod_16<T>(string_4, string_5, string_6, string_7, null, object_0); } internal static T smethod_16<T>(string string_4, string string_5, string string_6, string string_7, Class272.Enum20[] enum20_0, params object[] object_0) where T: MonoClass { IntPtr ptr = smethod_10(string_4, string_5, string_6, string_7, enum20_0, object_0); if (ptr == IntPtr.Zero) { return default(T); } return FastObjectFactory.CreateObjectInstance<T>(ptr); } internal static void smethod_17(string string_4, string string_5, string string_6, string string_7) { smethod_10(string_4, string_5, string_6, string_7, null, Array.Empty<object>()); } internal static void smethod_18(string string_4, string string_5, string string_6, string string_7, params object[] object_0) { smethod_10(string_4, string_5, string_6, string_7, null, object_0); } internal static void smethod_19(string string_4, string string_5, string string_6, string string_7, Class272.Enum20[] enum20_0, params object[] object_0) { smethod_10(string_4, string_5, string_6, string_7, enum20_0, object_0); } private static IntPtr smethod_2(string string_4) { IntPtr ptr; if (Dictionary_0.TryGetValue(TritonHs.UnityEngineAssemblyPath + "~" + string_4, out ptr)) { return ptr; } if (Dictionary_0.TryGetValue(TritonHs.MainAssemblyPath + "~." + string_4, out ptr)) { return ptr; } return IntPtr.Zero; } internal static IntPtr smethod_3(string string_4, string string_5, string string_6) { IntPtr ptr; string[] textArray1 = new string[] { string_4, "~", string_5, ".", string_6 }; string key = string.Concat(textArray1); if (!Dictionary_1.TryGetValue(key, out ptr)) { ptr = Class272_0.method_21(string_4, string_5, string_6); if (ptr != IntPtr.Zero) { Dictionary_1.Add(key, ptr); } } return ptr; } private static IntPtr smethod_4(IntPtr intptr_1, string string_4, Class272.Enum20[] enum20_0) { Dictionary<string, List<Class269>> dictionary; List<Class269> list; Class270 class2 = new Class270 { string_0 = string_4, enum20_0 = enum20_0 }; if (!dictionary_3.TryGetValue(intptr_1, out dictionary)) { dictionary_3.Add(intptr_1, new Dictionary<string, List<Class269>>()); dictionary = dictionary_3[intptr_1]; } if (!dictionary.TryGetValue(class2.string_0, out list)) { dictionary.Add(class2.string_0, new List<Class269>()); list = dictionary[class2.string_0]; } Class269 item = list.FirstOrDefault<Class269>(new Func<Class269, bool>(class2.method_0)); if (item == null) { IntPtr address = Class272_0.method_33(intptr_1, class2.string_0, class2.enum20_0); if (address != IntPtr.Zero) { item = new Class269(class2.string_0, address, class2.enum20_0); list.Add(item); } } if (item == null) { return IntPtr.Zero; } return item.IntPtr_0; } internal static IntPtr smethod_5(string string_4, string string_5, string string_6, string string_7) { Dictionary<string, IntPtr> dictionary; IntPtr ptr2; string key = string_6 + "." + string_7; if (!dictionary_5.TryGetValue(key, out dictionary)) { dictionary_5.Add(key, new Dictionary<string, IntPtr>()); dictionary = dictionary_5[key]; } IntPtr ptr = smethod_3(string_4, string_5, string_6); if (!dictionary.TryGetValue(string_7, out ptr2)) { ptr2 = Class272_0.method_34(ptr, string_7); if (ptr2 != IntPtr.Zero) { dictionary.Add(string_7, ptr2); } } return ptr2; } internal static T smethod_6<T>(string string_4, string string_5, string string_6, string string_7) where T: struct { IntPtr ptr = smethod_9(string_4, string_5, string_6, string_7); if (ptr == IntPtr.Zero) { return default(T); } return ExternalProcessMemory_0.Read<T>(Class272_0.method_26(ptr)); } internal static T smethod_7<T>(string string_4, string string_5, string string_6, string string_7) where T: class { IntPtr ptr = smethod_9(string_4, string_5, string_6, string_7); if (ptr == IntPtr.Zero) { return default(T); } return FastObjectFactory.CreateObjectInstance<T>(ptr); } internal static string smethod_8(string string_4, string string_5, string string_6, string string_7) { IntPtr ptr = smethod_9(string_4, string_5, string_6, string_7); if (ptr == IntPtr.Zero) { return null; } return Class272_0.method_24(ptr); } internal static IntPtr smethod_9(string string_4, string string_5, string string_6, string string_7) { IntPtr ptr = smethod_5(string_4, string_5, string_6, string_7); if (ptr == IntPtr.Zero) { throw new MissingFieldException(string_6, string_7); } return Class272_0.method_22(IntPtr.Zero, ptr); } internal virtual IntPtr vmethod_0(string string_4, string string_5, string string_6) { if (this.Address != IntPtr.Zero) { return Class272_0.method_23(this.Address); } return smethod_3(string_4, string_5, string_6); } public IntPtr Address { [CompilerGenerated] get { return this.intptr_0; } [CompilerGenerated] internal set { this.intptr_0 = value; } } public string AssemblyPath { [CompilerGenerated] get { return this.string_0; } [CompilerGenerated] private set { this.string_0 = value; } } internal static Class272 Class272_0 { get { return TritonHs.Class272_0; } } public string ClassName { [CompilerGenerated] get { return this.string_2; } [CompilerGenerated] private set { this.string_2 = value; } } public string ClassNamespace { [CompilerGenerated] get { return this.string_1; } [CompilerGenerated] private set { this.string_1 = value; } } private static Dictionary<string, IntPtr> Dictionary_0 { get { if (dictionary_1 == null) { smethod_1(); } return dictionary_1; } } private static Dictionary<string, IntPtr> Dictionary_1 { get { if (dictionary_2 == null) { smethod_1(); } return dictionary_2; } } internal static ExternalProcessMemory ExternalProcessMemory_0 { get { return TritonHs.Memory; } } internal IntPtr IntPtr_0 { get { IntPtr? nullable = this.nullable_0; if (!nullable.HasValue) { IntPtr? nullable2; this.nullable_0 = nullable2 = new IntPtr?(this.vmethod_0(this.AssemblyPath, this.ClassNamespace, this.ClassName)); return nullable2.Value; } return nullable.GetValueOrDefault(); } } internal IntPtr IntPtr_1 { get { IntPtr? nullable = this.nullable_1; if (!nullable.HasValue) { IntPtr? nullable2; this.nullable_1 = nullable2 = new IntPtr?(this.vmethod_0(TritonHs.UnityEngineAssemblyPath, "UnityEngine", this.ClassName)); return nullable2.Value; } return nullable.GetValueOrDefault(); } } public virtual bool IsNull { get { return (this.GetClassInstance() == IntPtr.Zero); } } public string RealClassName { [CompilerGenerated] get { return this.string_3; } [CompilerGenerated] private set { this.string_3 = value; } } internal uint UInt32_0 { [CompilerGenerated] get { return this.uint_0; } [CompilerGenerated] set { this.uint_0 = value; } } internal class Class269 { [CompilerGenerated] private Class272.Enum20[] enum20_0; [CompilerGenerated] private IntPtr intptr_0; [CompilerGenerated] private string string_0; public Class269(string name, IntPtr address, Class272.Enum20[] parameters) { this.Name = name; this.IntPtr_0 = address; this.Enum20_0 = parameters; } public bool method_0(string string_1, params Class272.Enum20[] enum20_1) { if (this.Name != string_1) { return false; } if (enum20_1 == null) { if ((this.Enum20_0 != null) && (this.Enum20_0.Length != 0)) { return false; } return true; } if (enum20_1.Length != this.Enum20_0.Length) { return false; } for (int i = 0; i < enum20_1.Length; i++) { if (enum20_1[i] != this.Enum20_0[i]) { return false; } } return true; } public Class272.Enum20[] Enum20_0 { [CompilerGenerated] get { return this.enum20_0; } [CompilerGenerated] set { this.enum20_0 = value; } } public IntPtr IntPtr_0 { [CompilerGenerated] get { return this.intptr_0; } [CompilerGenerated] set { this.intptr_0 = value; } } public string Name { [CompilerGenerated] get { return this.string_0; } [CompilerGenerated] internal set { this.string_0 = value; } } } [CompilerGenerated] private sealed class Class270 { public Class272.Enum20[] enum20_0; public string string_0; internal bool method_0(MonoClass.Class269 class269_0) { return class269_0.method_0(this.string_0, this.enum20_0); } } } }
using System; namespace RO { [CustomLuaClass] [Serializable] public class ToBornPointTeleportPathInfo { public BornPoint bp; public ExitPoint nextEP; public float totalCost; public ToBornPointTeleportPathInfo(BornPoint b, ExitPoint e, float c) { this.bp = b; this.nextEP = e; this.totalCost = c; } } }
using FacultyV3.Core.Constants; using FacultyV3.Core.Interfaces; using FacultyV3.Core.Interfaces.IServices; using FacultyV3.Core.Models.Entities; using FacultyV3.Web.Common; using FacultyV3.Web.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace FacultyV3.Web.Areas.Admin.Controllers { public class ConferenceController : BaseController { private readonly IConferenceService conferenceService; public ConferenceController(IConferenceService conferenceService, IDataContext context) : base(context) { this.conferenceService = conferenceService; } [HasCredential(RoleID = Constant.ADMIN)] public ActionResult ConferenceView() { return View(); } [HttpGet] public ActionResult LoadTable(string search, int page = 1, int pageSize = 10) { var model = conferenceService.PageList(search, page, pageSize); return PartialView("ConferenceTablePartialView", model); } public ActionResult AddOrEdit(string Id = "") { try { var data = conferenceService.GetConferenceByID(Id); if (data != null) { var model = new ConferenceViewModel(); model.Title = data.Title; model.Url_Image = data.Url_Image; model.Url_Link = data.Url_Link; model.Serial = data.Serial; return PartialView("CRUDConference", model); } } catch (Exception) { } return PartialView("CRUDConference", new ConferenceViewModel()); } [HttpPost] public ActionResult AddOrUpdate(ConferenceViewModel model) { if (model.Id == null) { Conference conference = new Conference() { Title = model.Title, Url_Image = model.Url_Image, Url_Link = model.Url_Link, Serial = model.Serial, Create_At = DateTime.Now, Update_At = DateTime.Now }; try { context.Conferences.Add(conference); context.SaveChanges(); TempData[Constant.MessageViewBagName] = new GenericMessageViewModel { Message = "Thêm thành công", MessageType = GenericMessages.success }; } catch (Exception) { TempData[Constant.MessageViewBagName] = new GenericMessageViewModel { Message = "Thêm thất bại", MessageType = GenericMessages.error }; } } else { try { var banner = conferenceService.GetConferenceByID(model.Id); banner.Title = model.Title; banner.Url_Image = model.Url_Image; banner.Url_Link = model.Url_Link; banner.Serial = model.Serial; banner.Update_At = DateTime.Now; context.SaveChanges(); TempData[Constant.MessageViewBagName] = new GenericMessageViewModel { Message = "Cập nhật thành công!", MessageType = GenericMessages.success }; } catch (Exception) { TempData[Constant.MessageViewBagName] = new GenericMessageViewModel { Message = "Cập nhật thất bại!", MessageType = GenericMessages.error }; } } return RedirectToAction("ConferenceView", "Conference"); } [HttpPost] public ActionResult Delete(string Id) { try { var conference = context.Conferences.Find(new Guid(Id)); context.Conferences.Remove(conference); context.SaveChanges(); return Json(new { success = true }, JsonRequestBehavior.AllowGet); } catch (Exception) { } return Json(new { success = false }, JsonRequestBehavior.AllowGet); } } }
// ------------------------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------------------------------------------ using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading.Tasks; using Microsoft.PSharp.IO; using Microsoft.PSharp.Runtime; using Microsoft.PSharp.TestingServices.Runtime; using Microsoft.PSharp.TestingServices.Scheduling.Strategies; namespace Microsoft.PSharp.TestingServices.Scheduling { /// <summary> /// Provides methods for controlling the schedule of asynchronous operations. /// </summary> internal sealed class BugFindingScheduler { /// <summary> /// The P# testing runtime. /// </summary> private readonly SystematicTestingRuntime Runtime; /// <summary> /// The scheduling strategy to be used for state-space exploration. /// </summary> private readonly ISchedulingStrategy Strategy; /// <summary> /// Map from unique ids to asynchronous operations. /// </summary> private readonly Dictionary<ulong, AsyncOperation> OperationMap; /// <summary> /// The scheduler completion source. /// </summary> private readonly TaskCompletionSource<bool> CompletionSource; /// <summary> /// Checks if the scheduler is running. /// </summary> private bool IsSchedulerRunning; /// <summary> /// The currently scheduled asynchronous operation. /// </summary> internal AsyncOperation ScheduledOperation { get; private set; } /// <summary> /// Number of scheduled steps. /// </summary> internal int ScheduledSteps => this.Strategy.GetScheduledSteps(); /// <summary> /// Checks if the schedule has been fully explored. /// </summary> internal bool HasFullyExploredSchedule { get; private set; } /// <summary> /// True if a bug was found. /// </summary> internal bool BugFound { get; private set; } /// <summary> /// Bug report. /// </summary> internal string BugReport { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="BugFindingScheduler"/> class. /// </summary> internal BugFindingScheduler(SystematicTestingRuntime runtime, ISchedulingStrategy strategy) { this.Runtime = runtime; this.Strategy = strategy; this.OperationMap = new Dictionary<ulong, AsyncOperation>(); this.CompletionSource = new TaskCompletionSource<bool>(); this.IsSchedulerRunning = true; this.BugFound = false; this.HasFullyExploredSchedule = false; } /// <summary> /// Schedules the next asynchronous operation. /// </summary> internal void ScheduleNextOperation(AsyncOperationType type, AsyncOperationTarget target, ulong targetId) { int? taskId = Task.CurrentId; // If the caller is the root task, then return. if (taskId != null && taskId == this.Runtime.RootTaskId) { return; } if (!this.IsSchedulerRunning) { this.Stop(); throw new ExecutionCanceledException(); } // Checks if concurrency not controlled by the runtime was used. this.Runtime.AssertNoExternalConcurrencyUsed(); // Checks if the scheduling steps bound has been reached. this.CheckIfSchedulingStepsBoundIsReached(); AsyncOperation current = this.ScheduledOperation; current.SetNextOperation(type, target, targetId); // Get and order the operations by their id. var ops = this.OperationMap.Values.OrderBy(op => op.SourceId).Select(op => op as IAsyncOperation).ToList(); if (!this.Strategy.GetNext(out IAsyncOperation next, ops, current)) { // Checks if the program has livelocked. this.CheckIfProgramHasLivelocked(ops.Select(op => op as AsyncOperation)); Debug.WriteLine("<ScheduleDebug> Schedule explored."); this.HasFullyExploredSchedule = true; this.Stop(); throw new ExecutionCanceledException(); } this.ScheduledOperation = next as AsyncOperation; this.Runtime.ScheduleTrace.AddSchedulingChoice(next.SourceId); Debug.WriteLine($"<ScheduleDebug> Schedule '{next.SourceName}' with task id '{this.ScheduledOperation.Task.Id}'."); if (current != next) { current.IsActive = false; lock (next) { this.ScheduledOperation.IsActive = true; System.Threading.Monitor.PulseAll(next); } lock (current) { if (!current.IsInboxHandlerRunning) { return; } while (!current.IsActive) { Debug.WriteLine($"<ScheduleDebug> Sleep '{current.SourceName}' with task id '{current.Task.Id}'."); System.Threading.Monitor.Wait(current); Debug.WriteLine($"<ScheduleDebug> Wake up '{current.SourceName}' with task id '{current.Task.Id}'."); } if (!current.IsEnabled) { throw new ExecutionCanceledException(); } } } } /// <summary> /// Returns the next nondeterministic boolean choice. /// </summary> internal bool GetNextNondeterministicBooleanChoice(int maxValue, string uniqueId = null) { // Checks if concurrency not controlled by the runtime was used. this.Runtime.AssertNoExternalConcurrencyUsed(); // Checks if the scheduling steps bound has been reached. this.CheckIfSchedulingStepsBoundIsReached(); if (!this.Strategy.GetNextBooleanChoice(maxValue, out bool choice)) { Debug.WriteLine("<ScheduleDebug> Schedule explored."); this.Stop(); throw new ExecutionCanceledException(); } if (uniqueId is null) { this.Runtime.ScheduleTrace.AddNondeterministicBooleanChoice(choice); } else { this.Runtime.ScheduleTrace.AddFairNondeterministicBooleanChoice(uniqueId, choice); } return choice; } /// <summary> /// Returns the next nondeterministic integer choice. /// </summary> internal int GetNextNondeterministicIntegerChoice(int maxValue) { // Checks if concurrency not controlled by the runtime was used. this.Runtime.AssertNoExternalConcurrencyUsed(); // Checks if the scheduling steps bound has been reached. this.CheckIfSchedulingStepsBoundIsReached(); if (!this.Strategy.GetNextIntegerChoice(maxValue, out int choice)) { Debug.WriteLine("<ScheduleDebug> Schedule explored."); this.Stop(); throw new ExecutionCanceledException(); } this.Runtime.ScheduleTrace.AddNondeterministicIntegerChoice(choice); return choice; } /// <summary> /// Waits for the specified asynchronous operation to start. /// </summary> internal void WaitForOperationToStart(AsyncOperation op) { lock (op) { if (this.OperationMap.Count == 1) { op.IsActive = true; System.Threading.Monitor.PulseAll(op); } else { while (!op.IsInboxHandlerRunning) { System.Threading.Monitor.Wait(op); } } } } /// <summary> /// Notify that the specified asynchronous operation has been created. /// </summary> internal void NotifyOperationCreated(AsyncOperation op) { if (!this.OperationMap.ContainsKey(op.SourceId)) { if (this.OperationMap.Count == 0) { this.ScheduledOperation = op; } this.OperationMap.Add(op.SourceId, op); } Debug.WriteLine($"<ScheduleDebug> Created '{op.SourceName}' with task id '{op.Task.Id}'."); } /// <summary> /// Notify that the specified asynchronous operation has started. /// </summary> internal static void NotifyOperationStarted(AsyncOperation op) { Debug.WriteLine($"<ScheduleDebug> Started '{op.SourceName}' with task id '{op.Task.Id}'."); lock (op) { op.IsInboxHandlerRunning = true; System.Threading.Monitor.PulseAll(op); while (!op.IsActive) { Debug.WriteLine($"<ScheduleDebug> Sleep '{op.SourceName}' with task id '{op.Task.Id}'."); System.Threading.Monitor.Wait(op); Debug.WriteLine($"<ScheduleDebug> Wake up '{op.SourceName}' with task id '{op.Task.Id}'."); } if (!op.IsEnabled) { throw new ExecutionCanceledException(); } } } /// <summary> /// Notify that a monitor was registered. /// </summary> internal void NotifyMonitorRegistered(AsyncOperation op) { this.OperationMap.Add(op.SourceId, op); Debug.WriteLine($"<ScheduleDebug> Created monitor of '{op.SourceName}'."); } /// <summary> /// Notify that an assertion has failed. /// </summary> internal void NotifyAssertionFailure(string text, bool killTasks = true, bool cancelExecution = true) { if (!this.BugFound) { this.BugReport = text; this.Runtime.LogWriter.OnError($"<ErrorLog> {text}"); this.Runtime.LogWriter.OnStrategyError(this.Runtime.Configuration.SchedulingStrategy, this.Strategy.GetDescription()); this.BugFound = true; if (this.Runtime.Configuration.AttachDebugger) { System.Diagnostics.Debugger.Break(); } } if (killTasks) { this.Stop(); } if (cancelExecution) { throw new ExecutionCanceledException(); } } /// <summary> /// Returns the enabled schedulable ids. /// </summary> internal HashSet<ulong> GetEnabledSchedulableIds() { var enabledSchedulableIds = new HashSet<ulong>(); foreach (var machineInfo in this.OperationMap.Values) { if (machineInfo.IsEnabled) { enabledSchedulableIds.Add(machineInfo.SourceId); } } return enabledSchedulableIds; } /// <summary> /// Returns a test report with the scheduling statistics. /// </summary> internal TestReport GetReport() { TestReport report = new TestReport(this.Runtime.Configuration); if (this.BugFound) { report.NumOfFoundBugs++; report.BugReports.Add(this.BugReport); } if (this.Strategy.IsFair()) { report.NumOfExploredFairSchedules++; report.TotalExploredFairSteps += this.ScheduledSteps; if (report.MinExploredFairSteps < 0 || report.MinExploredFairSteps > this.ScheduledSteps) { report.MinExploredFairSteps = this.ScheduledSteps; } if (report.MaxExploredFairSteps < this.ScheduledSteps) { report.MaxExploredFairSteps = this.ScheduledSteps; } if (this.Strategy.HasReachedMaxSchedulingSteps()) { report.MaxFairStepsHitInFairTests++; } if (this.ScheduledSteps >= report.Configuration.MaxUnfairSchedulingSteps) { report.MaxUnfairStepsHitInFairTests++; } } else { report.NumOfExploredUnfairSchedules++; if (this.Strategy.HasReachedMaxSchedulingSteps()) { report.MaxUnfairStepsHitInUnfairTests++; } } return report; } /// <summary> /// Checks for a livelock. This happens when there are no more enabled operations, /// but there is one or more blocked operations that are waiting to receive an event /// or for a task to complete. /// </summary> private void CheckIfProgramHasLivelocked(IEnumerable<AsyncOperation> ops) { var blockedOnReceiveOperations = ops.Where(op => op.IsWaitingToReceive).ToList(); if (blockedOnReceiveOperations.Count == 0) { return; } string message = "Livelock detected."; if (blockedOnReceiveOperations.Count > 0) { for (int i = 0; i < blockedOnReceiveOperations.Count; i++) { message += string.Format(CultureInfo.InvariantCulture, " '{0}'", blockedOnReceiveOperations[i].SourceName); if (i == blockedOnReceiveOperations.Count - 2) { message += " and"; } else if (i < blockedOnReceiveOperations.Count - 1) { message += ","; } } message += blockedOnReceiveOperations.Count == 1 ? " is " : " are "; message += "waiting to receive an event, but no other controlled tasks are enabled."; } this.Runtime.Scheduler.NotifyAssertionFailure(message); } /// <summary> /// Checks if the scheduling steps bound has been reached. If yes, /// it stops the scheduler and kills all enabled machines. /// </summary> private void CheckIfSchedulingStepsBoundIsReached() { if (this.Strategy.HasReachedMaxSchedulingSteps()) { int bound = this.Strategy.IsFair() ? this.Runtime.Configuration.MaxFairSchedulingSteps : this.Runtime.Configuration.MaxUnfairSchedulingSteps; string message = $"Scheduling steps bound of {bound} reached."; if (this.Runtime.Configuration.ConsiderDepthBoundHitAsBug) { this.Runtime.Scheduler.NotifyAssertionFailure(message); } else { Debug.WriteLine($"<ScheduleDebug> {message}"); this.Stop(); throw new ExecutionCanceledException(); } } } /// <summary> /// Waits until the scheduler terminates. /// </summary> internal Task WaitAsync() => this.CompletionSource.Task; /// <summary> /// Stops the scheduler. /// </summary> private void Stop() { this.IsSchedulerRunning = false; this.KillRemainingMachines(); // Check if the completion source is completed. If not synchronize on // it (as it can only be set once) and set its result. if (!this.CompletionSource.Task.IsCompleted) { lock (this.CompletionSource) { if (!this.CompletionSource.Task.IsCompleted) { this.CompletionSource.SetResult(true); } } } } /// <summary> /// Kills any remaining machines at the end of the schedule. /// </summary> private void KillRemainingMachines() { foreach (var machine in this.OperationMap.Values) { machine.IsActive = true; machine.IsEnabled = false; if (machine.IsInboxHandlerRunning) { lock (machine) { System.Threading.Monitor.PulseAll(machine); } } } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Reflection; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Data; using UGCS.Example.Enums; namespace UGCS.Example.Helpers { public class GPSFixUtility : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { if (string.IsNullOrEmpty(value.ToString())) return GPSFixStatus.NO_FIX; return (StringToEnum<GPSFixStatus>(value.ToString())).GetDescription(); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { if (string.IsNullOrEmpty(value.ToString())) return GPSFixStatus.NO_FIX; return StringToEnum<GPSFixStatus>(value.ToString()); } public static T StringToEnum<T>(string name) { T str; try { str = (T)Enum.Parse(typeof(T), name); } catch { str = default(T); } return str; } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Grisaia.Extensions; using Grisaia.Utils; namespace Grisaia.Asmodean { partial class Kifint { #region Decrypt /// <summary> /// Decrypts the KIFINT archives using the wildcard search, install directory, and name of executable with the /// V_CODE2 used to decrypt.<para/> /// Using this will initialize with <see cref="KifintType.Unknown"/>. /// </summary> /// <param name="wildcard">The wildcard name of the files to look for and merge.</param> /// <param name="installDir">The installation directory for both the archives and executable.</param> /// <param name="vcode2">The V_CODE2 key obtained from the exe, used to decrypt the file names.</param> /// <param name="callback">The optional callback for progress made during decryption.</param> /// <returns>The <see cref="KifintLookup"/> merged with all loaded archives.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="wildcard"/>, <paramref name="installDir"/>, or <paramref name="vcode2"/> is null. /// </exception> public static KifintLookup Decrypt(string wildcard, string installDir, string vcode2, KifintProgressCallback callback = null) { if (vcode2 == null) throw new ArgumentNullException(nameof(vcode2)); KifintType type = KifintType.Unknown; KifintLookup lookup = new KifintLookup(type); string[] files = Directory.GetFiles(installDir, wildcard); KifintProgressArgs progress = new KifintProgressArgs { ArchiveType = type, ArchiveIndex = 0, ArchiveCount = files.Length, }; foreach (string kifintPath in files) { progress.ArchiveName = Path.GetFileName(kifintPath); using (Stream stream = File.OpenRead(kifintPath)) lookup.Merge(Decrypt(type, stream, kifintPath, vcode2, progress, callback)); progress.ArchiveIndex++; } progress.EntryIndex = 0; progress.EntryCount = 0; callback?.Invoke(progress); return lookup; } /// <summary> /// Decrypts the KIFINT archives using the known archive type, install directory, and name of executable with /// the V_CODE2 used to decrypt. /// </summary> /// <param name="type">The type of archive to look for and decrypt.</param> /// <param name="installDir">The installation directory for both the archives and executable.</param> /// <param name="vcode2">The V_CODE2 key obtained from the exe, used to decrypt the file names.</param> /// <param name="callback">The optional callback for progress made during decryption.</param> /// <returns>The <see cref="KifintLookup"/> merged with all loaded archives.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="installDir"/> or <paramref name="vcode2"/> is null. /// </exception> /// <exception cref="ArgumentException"> /// <paramref name="type"/> is <see cref="KifintType.Unknown"/>. /// </exception> public static KifintLookup Decrypt(KifintType type, string installDir, string vcode2, KifintProgressCallback callback = null) { if (vcode2 == null) throw new ArgumentNullException(nameof(vcode2)); if (type == KifintType.Unknown) throw new ArgumentException($"{nameof(type)} cannot be {nameof(KifintType.Unknown)}!", nameof(type)); KifintLookup lookup = new KifintLookup(type); string wildcard = EnumInfo<KifintType>.GetAttribute<KifintWildcardAttribute>(type).Wildcard; string[] files = Directory.GetFiles(installDir, wildcard); KifintProgressArgs progress = new KifintProgressArgs { ArchiveType = type, ArchiveIndex = 0, ArchiveCount = files.Length, }; foreach (string kifintPath in files) { progress.ArchiveName = Path.GetFileName(kifintPath); using (Stream stream = File.OpenRead(kifintPath)) lookup.Merge(Decrypt(type, stream, kifintPath, vcode2, progress, callback)); progress.ArchiveIndex++; } progress.EntryIndex = 0; progress.EntryCount = 0; callback?.Invoke(progress); return lookup; } #endregion #region IdentifyFileTypes public static string[] IdentifyFileTypes(string kifintPath, string vcode2) { using (Stream stream = File.OpenRead(kifintPath)) return IdentifyFileTypes(stream, kifintPath, vcode2); } private static string[] IdentifyFileTypes(Stream stream, string kifintPath, string vcode2) { BinaryReader reader = new BinaryReader(stream); KIFHDR hdr = reader.ReadUnmanaged<KIFHDR>(); if (hdr.Signature != "KIF") // It's really a KIF INT file throw new UnexpectedFileTypeException(kifintPath, "KIF"); KIFENTRY[] entries = reader.ReadUnmanagedArray<KIFENTRY>(hdr.EntryCount); uint tocSeed = GenTocSeed(vcode2); uint fileKey = 0; bool decrypt = false; // Obtain the decryption file key if one exists for (int i = 0; i < hdr.EntryCount; i++) { if (entries[i].FileName == "__key__.dat") { fileKey = MersenneTwister.GenRand(entries[i].Length); decrypt = true; break; } } HashSet<string> extensions = new HashSet<string>(); // Decrypt the KIFINT entries using the file key if (decrypt) { for (uint i = 0; i < hdr.EntryCount; i++) { if (entries[i].FileName == "__key__.dat") continue; // Give the entry the correct name UnobfuscateFileName(entries[i].FileNameRaw, tocSeed + i); } } for (uint i = 0; i < hdr.EntryCount; i++) { string entryFileName = entries[i].FileName; if (entryFileName == "__key__.dat") continue; extensions.Add(Path.GetExtension(entryFileName)); } return extensions.ToArray(); } #endregion #region ExtractHg3 /// <summary> /// Extracts the HG-3 image information from the KIFINT entry and saves all images to the output /// <paramref name="directory"/>. /// </summary> /// <param name="entry">The KIFINT entry information used to extract the HG-3 file.</param> /// <param name="directory">The output directory to save the images to.</param> /// <param name="expand">True if the images are expanded to their full size when saving.</param> /// <returns>The extracted <see cref="Hg3"/> information.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="entry"/> or <paramref name="directory"/> is null. /// </exception> public static Hg3 ExtractHg3AndImages(KifintEntry entry, string directory, bool expand) { if (entry == null) throw new ArgumentNullException(nameof(entry)); using (KifintStream kifintStream = new KifintStream()) return ExtractHg3AndImages(kifintStream, entry, directory, expand); } /// <summary> /// Extracts the HG-3 image information from the KIFINT entry's open KIFINT archive stream and saves all /// images to the output <paramref name="directory"/>. /// </summary> /// <param name="kifintStream">The stream to the open KIFINT archive.</param> /// <param name="entry">The KIFINT entry information used to extract the HG-3 file.</param> /// <param name="directory">The output directory to save the images to.</param> /// <param name="expand">True if the images are expanded to their full size when saving.</param> /// <returns>The extracted <see cref="Hg3"/> information.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="kifintStream"/>, <paramref name="entry"/>, or <paramref name="directory"/> is null. /// </exception> public static Hg3 ExtractHg3AndImages(KifintStream kifintStream, KifintEntry entry, string directory, bool expand) { if (directory == null) throw new ArgumentNullException(nameof(directory)); byte[] buffer = Extract(kifintStream, entry); using (MemoryStream ms = new MemoryStream(buffer)) return Hg3.ExtractImages(ms, entry.FileName, directory, expand); } /// <summary> /// Extracts the HG-3 image information ONLY and does not extract the actual images. /// </summary> /// <param name="entry">The KIFINT entry to open the KIFINT archive from and locate the file.</param> /// <returns>The extracted <see cref="Hg3"/> information.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="entry"/> is null. /// </exception> public static Hg3 ExtractHg3(KifintEntry entry) { if (entry == null) throw new ArgumentNullException(nameof(entry)); using (KifintStream kifintStream = new KifintStream()) return ExtractHg3(kifintStream, entry); } /// <summary> /// Extracts the HG-3 image information ONLY from open KIFINT archive stream and does not extract the actual /// images. /// </summary> /// <param name="kifintStream">The stream to the open KIFINT archive.</param> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <returns>The extracted <see cref="Hg3"/> information.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="kifintStream"/> or <paramref name="entry"/> is null. /// </exception> public static Hg3 ExtractHg3(KifintStream kifintStream, KifintEntry entry) { byte[] buffer = Extract(kifintStream, entry); using (MemoryStream ms = new MemoryStream(buffer)) return Hg3.Extract(ms, entry.FileName); } #endregion #region Extract Anm /// <summary> /// Extracts the ANM animation information from the entry. /// </summary> /// <param name="entry">The KIFINT entry to open the KIFINT archive from and locate the file.</param> /// <returns>The extracted <see cref="Anm"/> animation information.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="entry"/> is null. /// </exception> public static Anm ExtractAnm(KifintEntry entry) { if (entry == null) throw new ArgumentNullException(nameof(entry)); using (KifintStream kifintStream = new KifintStream()) return ExtractAnm(kifintStream, entry); } /// <summary> /// Extracts the ANM animation information from the open KIFINT archive stream. /// </summary> /// <param name="kifintStream">The stream to the open KIFINT archive.</param> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <returns>The extracted <see cref="Anm"/> animation information.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="kifintStream"/> or <paramref name="entry"/> is null. /// </exception> public static Anm ExtractAnm(KifintStream kifintStream, KifintEntry entry) { byte[] buffer = Extract(kifintStream, entry); using (MemoryStream ms = new MemoryStream(buffer)) return Anm.Extract(ms, entry.FileName); } #endregion #region ExtractToFile /// <summary> /// Extracts the KIFINT entry file from the the entry's KIFINT archive and saves it to the output /// <paramref name="filePath"/>. /// </summary> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <param name="filePath">The path to save the file to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="entry"/> or <paramref name="filePath"/> is null. /// </exception> public static void ExtractToFile(KifintEntry entry, string filePath) { if (entry == null) throw new ArgumentNullException(nameof(entry)); using (KifintStream kifintStream = new KifintStream()) ExtractToFile(kifintStream, entry, filePath); } /// <summary> /// Extracts the KIFINT entry file from the the entry's open KIFINT archive stream and saves it to the output /// <paramref name="filePath"/>. /// </summary> /// <param name="kifintStream">The stream to the open KIFINT archive.</param> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <param name="filePath">The path to save the file to.</param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="kifintStream"/>, <paramref name="entry"/>, or <paramref name="filePath"/> is null. /// </exception> public static void ExtractToFile(KifintStream kifintStream, KifintEntry entry, string filePath) { if (kifintStream == null) throw new ArgumentNullException(nameof(kifintStream)); if (entry == null) throw new ArgumentNullException(nameof(entry)); if (filePath == null) throw new ArgumentNullException(nameof(filePath)); var kifint = entry.Kifint; kifintStream.Open(kifint); BinaryReader reader = new BinaryReader(kifintStream); kifintStream.Position = entry.Offset; byte[] buffer = reader.ReadBytes(entry.Length); if (kifint.IsEncrypted) { DecryptData(buffer, entry.Length, kifint.FileKey); } File.WriteAllBytes(filePath, buffer); } #endregion #region ExtractToDirectory /// <summary> /// Extracts the KIFINT entry file from the the entry's KIFINT archive and saves it to the output /// <paramref name="directory"/>. /// </summary> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <param name="directory"> /// The directory to save the file to. The file name will be <see cref="KifintEntry.FileName"/>. /// </param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="entry"/> or <paramref name="directory"/> is null. /// </exception> public static void ExtractToDirectory(KifintEntry entry, string directory) { if (entry == null) throw new ArgumentNullException(nameof(entry)); using (KifintStream kifintStream = new KifintStream()) ExtractToDirectory(kifintStream, entry, directory); } /// <summary> /// Extracts the KIFINT entry file from the the entry's open KIFINT archive stream and saves it to the output /// <paramref name="directory"/>. /// </summary> /// <param name="kifintStream">The stream to the open KIFINT archive.</param> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <param name="directory"> /// The directory to save the file to. The file name will be <see cref="KifintEntry.FileName"/>. /// </param> /// /// <exception cref="ArgumentNullException"> /// <paramref name="kifintStream"/>, <paramref name="entry"/>, or <paramref name="directory"/> is null. /// </exception> public static void ExtractToDirectory(KifintStream kifintStream, KifintEntry entry, string directory) { if (kifintStream == null) throw new ArgumentNullException(nameof(kifintStream)); if (entry == null) throw new ArgumentNullException(nameof(entry)); if (directory == null) throw new ArgumentNullException(nameof(directory)); var kifint = entry.Kifint; kifintStream.Open(kifint); BinaryReader reader = new BinaryReader(kifintStream); kifintStream.Position = entry.Offset; byte[] buffer = reader.ReadBytes(entry.Length); if (kifint.IsEncrypted) { DecryptData(buffer, entry.Length, kifint.FileKey); } File.WriteAllBytes(Path.Combine(directory, entry.FileName), buffer); } #endregion #region ExtractToStream /// <summary> /// Extracts the KIFINT entry file from the the entry's KIFINT archive and returns a stream. /// </summary> /// <param name="entry">The KIFINT entry to open the KIFINT archive from and locate the file.</param> /// <returns>A stream of the extracted KIFINT entry's file data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="entry"/> is null. /// </exception> public static MemoryStream ExtractToStream(KifintEntry entry) { if (entry == null) throw new ArgumentNullException(nameof(entry)); using (KifintStream kifintStream = new KifintStream()) return ExtractToStream(kifintStream, entry); } /// <summary> /// Extracts the KIFINT entry file from the the entry's KIFINT archive and returns a stream. /// </summary> /// <param name="kifintStream">The stream to the open KIFINT archive.</param> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <returns>A stream of the extracted KIFINT entry's file data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="kifintStream"/> or <paramref name="entry"/> is null. /// </exception> public static MemoryStream ExtractToStream(KifintStream kifintStream, KifintEntry entry) { if (kifintStream == null) throw new ArgumentNullException(nameof(kifintStream)); if (entry == null) throw new ArgumentNullException(nameof(entry)); var kifint = entry.Kifint; kifintStream.Open(kifint); BinaryReader reader = new BinaryReader(kifintStream); kifintStream.Position = entry.Offset; byte[] buffer = reader.ReadBytes(entry.Length); if (kifint.IsEncrypted) { DecryptData(buffer, entry.Length, kifint.FileKey); } return new MemoryStream(buffer); } #endregion #region Extract /// <summary> /// Extracts the KIFINT entry file from the the entry's KIFINT archive. /// </summary> /// <param name="entry">The KIFINT entry to open the KIFINT archive from and locate the file.</param> /// <returns>A byte array containing the extracted KIFINT entry's file data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="entry"/> is null. /// </exception> public static byte[] Extract(KifintEntry entry) { if (entry == null) throw new ArgumentNullException(nameof(entry)); using (KifintStream kifintStream = new KifintStream()) return Extract(kifintStream, entry); } /// <summary> /// Extracts the KIFINT entry file from the the entry's KIFINT archive. /// </summary> /// <param name="kifintStream">The stream to the open KIFINT archive.</param> /// <param name="entry">The KIFINT entry used to locate the file.</param> /// <returns>A byte array containing the extracted KIFINT entry's file data.</returns> /// /// <exception cref="ArgumentNullException"> /// <paramref name="kifintStream"/> or <paramref name="entry"/> is null. /// </exception> public static byte[] Extract(KifintStream kifintStream, KifintEntry entry) { if (kifintStream == null) throw new ArgumentNullException(nameof(kifintStream)); if (entry == null) throw new ArgumentNullException(nameof(entry)); var kifint = entry.Kifint; kifintStream.Open(kifint); BinaryReader reader = new BinaryReader(kifintStream); kifintStream.Position = entry.Offset; byte[] buffer = reader.ReadBytes(entry.Length); if (kifint.IsEncrypted) { DecryptData(buffer, entry.Length, kifint.FileKey); } return buffer; } #endregion } }
using System; using System.Web; namespace SKT.MES.Web { public class Global : Systems.Web.HttpApplication { protected void Application_Error(object sender, EventArgs e) { try { Exception ex = this.Server.GetLastError(); WebHelper.WriteException(ex); } catch(Exception ex) { WebHelper.ShowMessage(ex.Message); } } } }
using Microsoft.EntityFrameworkCore.Migrations; namespace Async_Inn.Migrations { public partial class dataseeding : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.InsertData( table: "Amenities", columns: new[] { "AmenitiesID", "Name" }, values: new object[,] { { 1, "Coffee Maker" }, { 2, "Air Conditioning" }, { 3, "Waterfront View" }, { 4, "Mini-bar" }, { 5, "Personal Chef" } }); migrationBuilder.InsertData( table: "Hotel", columns: new[] { "HotelID", "Address", "Name", "Phone" }, values: new object[,] { { 1, "123 Forest Dr", "Evergreen Inn", "206-555-5555" }, { 2, "123 Tree St", "Birch Inn", "206-555-4444" }, { 3, "123 Branch St", "Oak Hotel", "206-555-6666" }, { 4, "123 Fir Dr", "Pine Inn", "206-555-7777" }, { 5, "123 Needle St", "Douglas Fir Hotel", "206-555-8888" } }); migrationBuilder.InsertData( table: "Room", columns: new[] { "RoomID", "Layout", "Name" }, values: new object[,] { { 1, 1, "Cedar" }, { 2, 2, "Redwood" }, { 3, 0, "Maple" }, { 4, 1, "Juniper" }, { 5, 2, "Maple" } }); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DeleteData( table: "Amenities", keyColumn: "AmenitiesID", keyValue: 1); migrationBuilder.DeleteData( table: "Amenities", keyColumn: "AmenitiesID", keyValue: 2); migrationBuilder.DeleteData( table: "Amenities", keyColumn: "AmenitiesID", keyValue: 3); migrationBuilder.DeleteData( table: "Amenities", keyColumn: "AmenitiesID", keyValue: 4); migrationBuilder.DeleteData( table: "Amenities", keyColumn: "AmenitiesID", keyValue: 5); migrationBuilder.DeleteData( table: "Hotel", keyColumn: "HotelID", keyValue: 1); migrationBuilder.DeleteData( table: "Hotel", keyColumn: "HotelID", keyValue: 2); migrationBuilder.DeleteData( table: "Hotel", keyColumn: "HotelID", keyValue: 3); migrationBuilder.DeleteData( table: "Hotel", keyColumn: "HotelID", keyValue: 4); migrationBuilder.DeleteData( table: "Hotel", keyColumn: "HotelID", keyValue: 5); migrationBuilder.DeleteData( table: "Room", keyColumn: "RoomID", keyValue: 1); migrationBuilder.DeleteData( table: "Room", keyColumn: "RoomID", keyValue: 2); migrationBuilder.DeleteData( table: "Room", keyColumn: "RoomID", keyValue: 3); migrationBuilder.DeleteData( table: "Room", keyColumn: "RoomID", keyValue: 4); migrationBuilder.DeleteData( table: "Room", keyColumn: "RoomID", keyValue: 5); } } }
using System; using System.Collections.Generic; namespace ClassesExercise { class Program { static void Main(string[] args) { Author stavros = new Author("Stavros", "Kyriacou"); Author someone = new Author("Someone", "Somebody"); List<Book> books = new List<Book>(); books.Add(new Book("idk", 1234, 2000, stavros, false)); books.Add(new Book("yes", 4567, 2001, stavros, false)); books.Add(new Book("nope", 8901, 1999, stavros, false)); books.Add(new Book("ahahaha", 1111, 500, someone, false)); books.Add(new Book("<(O_O)>", 2222, 600, someone, false)); Library library = new Library("Big Library", "Earth?", books); Book b1 = new Book("this is a book title", 1111, 321093210, stavros, false); library.AddBookToCollection(b1); library.PrintBookTitles(); library.books[0].Borrow(); library.books[1].Borrow(); library.books[0].Return(); library.books[1].Return(); } } }
using System; using KelpNet.Common; using KelpNet.Common.Functions.Type; namespace KelpNet.Functions.Activations { [Serializable] public class ELU : SingleInputFunction { const string FUNCTION_NAME = "ELU"; private readonly Real _alpha; public ELU(double alpha = 1, string name = FUNCTION_NAME, string[] inputNames = null, string[] outputNames = null) : base(name, inputNames, outputNames) { this._alpha = alpha; SingleInputForward = NeedPreviousForwardCpu; SingleOutputBackward = NeedPreviousBackwardCpu; } private NdArray NeedPreviousForwardCpu(NdArray x) { Real[] result = new Real[x.Data.Length]; for (int i = 0; i < x.Data.Length; i++) { if (x.Data[i] >= 0) { result[i] = x.Data[i]; } else { result[i] = this._alpha * (Math.Exp(x.Data[i]) - 1); } } return NdArray.Convert(result, x.Shape, x.BatchCount, this); } private void NeedPreviousBackwardCpu(NdArray y, NdArray x) { for (int i = 0; i < y.Grad.Length; i++) { if (x.Data[i] >= 0) { x.Grad[i] += y.Grad[i]; } else { x.Grad[i] += y.Grad[i] * this._alpha * Math.Exp(x.Data[i]); } } } } }
using Aliencube.ConfigurationValueConverter.Configs; using Aliencube.ConfigurationValueConverter.Configs.Interfaces; using Aliencube.ConfigurationValueConverter.Tests.Fixtures; using FluentAssertions; using Xunit; namespace Aliencube.ConfigurationValueConverter.Tests { /// <summary> /// This represents the test entity for the <see cref="ConverterSettings"/> class. /// </summary> public class ConverterSettingsTest : IClassFixture<ConverterSettingsFixture> { private readonly IConverterSettings _settings; /// <summary> /// Initialises a new instance of the <see cref="ConverterSettingsTest"/> class. /// </summary> /// <param name="fixture"><see cref="ConverterSettingsFixture"/> instance.</param> public ConverterSettingsTest(ConverterSettingsFixture fixture) { this._settings = fixture.ConverterSettings; } [Fact] public void Given_AppConfig_Settings_ShouldReturn_Result() { this._settings.Product.Status.Should().Be(ProductStatus.Active); this._settings.Product.ProductIds.Should().Contain(1); this._settings.Product.ProductIds.Should().Contain(2); this._settings.Product.ProductIds.Should().Contain(3); this._settings.Product.Types.Should().HaveFlag(ProductTypes.ProductA); this._settings.Product.Types.Should().HaveFlag(ProductTypes.ProductC); } } }
using System; using UnityEngine; using System.Collections; using System.Collections.Generic; using Object = UnityEngine.Object; namespace UMA { public abstract class UMAGeneratorBase : MonoBehaviour { public bool fitAtlas; public bool usePRO; public bool AtlasCrop; [NonSerialized] public TextureMerge textureMerge; public int maxPixels; public bool convertRenderTexture; public bool convertMipMaps; public int atlasResolution; public string[] textureNameList; public abstract void addDirtyUMA(UMAData umaToAdd); public abstract bool IsIdle(); private struct AnimationState { public int stateHash; public float stateTime; } public virtual void UpdateAvatar(UMAData umaData) { if (umaData) { AnimationState[] snapshot = null; if (umaData.animationController) { var animator = umaData.animator; bool animating = false; bool applyRootMotion = false; bool animatePhysics = false; AnimatorCullingMode cullingMode = AnimatorCullingMode.AlwaysAnimate; if (animator) { animating = animator.enabled; applyRootMotion = animator.applyRootMotion; animatePhysics = animator.animatePhysics; cullingMode = animator.cullingMode; if (umaData.animationController == animator.runtimeAnimatorController) { snapshot = new AnimationState[animator.layerCount]; for (int i = 0; i < animator.layerCount; i++) { var state = animator.GetCurrentAnimatorStateInfo(i); snapshot[i].stateHash = state.nameHash; snapshot[i].stateTime = Mathf.Max(0, state.normalizedTime - Time.deltaTime / state.length); } } Object.DestroyImmediate(animator); } var oldParent = umaData.umaRoot.transform.parent; umaData.umaRoot.transform.parent = null; animator = CreateAnimator(umaData, umaData.umaRecipe.raceData.TPose, umaData.animationController, applyRootMotion, animatePhysics, cullingMode); umaData.animator = animator; umaData.umaRoot.transform.parent = oldParent; if (snapshot != null) { for (int i = 0; i < animator.layerCount; i++) { animator.Play(snapshot[i].stateHash, i, snapshot[i].stateTime); } animator.Update(0); animator.enabled = animating; } } } } public static Animator CreateAnimator(UMAData umaData, UmaTPose umaTPose, RuntimeAnimatorController controller, bool applyRootMotion, bool animatePhysics, AnimatorCullingMode cullingMode) { var animator = umaData.umaRoot.AddComponent<Animator>(); switch (umaData.umaRecipe.raceData.umaTarget) { case RaceData.UMATarget.Humanoid: umaTPose.DeSerialize(); animator.avatar = CreateAvatar(umaData, umaTPose); break; case RaceData.UMATarget.Generic: animator.avatar = CreateGenericAvatar(umaData); break; } animator.runtimeAnimatorController = controller; animator.applyRootMotion = applyRootMotion; animator.animatePhysics = animatePhysics; animator.cullingMode = cullingMode; return animator; } public static void DebugLogHumanAvatar(GameObject root, HumanDescription description) { Debug.Log("***", root); Dictionary<String, String> bones = new Dictionary<String, String>(); foreach (var sb in description.skeleton) { Debug.Log(sb.name); bones[sb.name] = sb.name; } Debug.Log("----"); foreach (var hb in description.human) { string boneName; if (bones.TryGetValue(hb.boneName, out boneName)) { Debug.Log(hb.humanName + " -> " + boneName); } else { Debug.LogWarning(hb.humanName + " !-> " + hb.boneName); } } Debug.Log("++++"); } public static Avatar CreateAvatar(UMAData umaData, UmaTPose umaTPose) { umaTPose.DeSerialize(); HumanDescription description = CreateHumanDescription(umaData, umaTPose); //DebugLogHumanAvatar(umaData.umaRoot, description); Avatar res = AvatarBuilder.BuildHumanAvatar(umaData.umaRoot, description); return res; } public static Avatar CreateGenericAvatar(UMAData umaData) { Avatar res = AvatarBuilder.BuildGenericAvatar(umaData.umaRoot, umaData.umaRecipe.GetRace().genericRootMotionTransformName); return res; } public static HumanDescription CreateHumanDescription(UMAData umaData, UmaTPose umaTPose) { var res = new HumanDescription(); res.armStretch = 0; res.feetSpacing = 0; res.legStretch = 0; res.lowerArmTwist = 0.2f; res.lowerLegTwist = 1f; res.upperArmTwist = 0.5f; res.upperLegTwist = 0.1f; var animatedBones = umaData.GetAnimatedBones(); if (animatedBones.Length > 0) { List<SkeletonBone> animatedSkeleton = new List<SkeletonBone>(umaTPose.boneInfo); foreach (var animatedBoneHash in animatedBones) { var animatedBone = umaData.GetBoneGameObject(animatedBoneHash).transform; var sb = new SkeletonBone(); sb.name = animatedBone.name; sb.position = animatedBone.localPosition; sb.rotation = animatedBone.localRotation; sb.scale = animatedBone.localScale; animatedSkeleton.Add(sb); } res.skeleton = animatedSkeleton.ToArray(); } else { res.skeleton = umaTPose.boneInfo; } // List<HumanBone> animatedHuman = new List<HumanBone>(); // foreach (HumanBone bone in umaTPose.humanInfo) { // int animIndex = System.Array.IndexOf(umaData.animatedBones, bone.boneName); // if (animIndex > -1) { // animatedHuman.Add(bone); // } // else { // int traitIndex = System.Array.IndexOf(HumanTrait.BoneName, bone.humanName); // if (HumanTrait.RequiredBone(traitIndex)) { // animatedHuman.Add(bone); // } // } // } // List<SkeletonBone> animatedSkeleton = new List<SkeletonBone>(); // foreach (SkeletonBone bone in umaTPose.boneInfo) { // int animIndex = System.Array.IndexOf(umaData.animatedBones, bone.name); // if (animIndex > -1) { // animatedSkeleton.Add(bone); // } // } // res.human = animatedHuman.ToArray(); // res.skeleton = animatedSkeleton.ToArray(); res.human = umaTPose.humanInfo; res.skeleton[0].name = umaData.umaRoot.name; SkeletonModifier(umaData, ref res.skeleton); return res; } private static void SkeletonModifier(UMAData umaData, ref SkeletonBone[] bones) { Dictionary<Transform, Transform> animatedBones = new Dictionary<Transform,Transform>(); for (var i = 0; i < umaData.animatedBones.Length; i++) { animatedBones.Add(umaData.animatedBones[i], umaData.animatedBones[i]); } for (var i = 0; i < bones.Length; i++) { var skeletonbone = bones[i]; UMAData.BoneData entry; if (umaData.boneHashList.TryGetValue(UMASkeleton.StringToHash(skeletonbone.name), out entry)) { //var entry = umaData.boneList[skeletonbone.name]; skeletonbone.position = entry.boneTransform.localPosition; //skeletonbone.rotation = entry.boneTransform.localRotation; skeletonbone.scale = entry.boneTransform.localScale; bones[i] = skeletonbone; animatedBones.Remove(entry.boneTransform); } } if (animatedBones.Count > 0) { var newBones = new List<SkeletonBone>(bones); // iterate original list rather than dictionary to ensure that relative order is preserved for (var i = 0; i < umaData.animatedBones.Length; i++) { var animatedBone = umaData.animatedBones[i]; if (animatedBones.ContainsKey(animatedBone)) { var newBone = new SkeletonBone(); newBone.name = animatedBone.name; newBone.position = animatedBone.localPosition; newBone.rotation = animatedBone.localRotation; newBone.scale = animatedBone.localScale; newBones.Add(newBone); } } bones = newBones.ToArray(); } } } }
using System; namespace ClassLibrarySample { public class MathSample { public void Fibonacci() { int n1 = 0, n2 = 1, n3, i, number; Console.Write("Enter the number of elements: "); number = int.Parse(Console.ReadLine()); Console.Write(n1 + " " + n2 + " "); //printing 0 and 1 for (i = 2; i < number; ++i) //loop starts from 2 because 0 and 1 are already printed { n3 = n1 + n2; Console.Write(n3 + " "); n1 = n2; n2 = n3; } } public void PrimeNumber() { int n, i, m = 0, flag = 0; Console.Write("Enter the Number to check Prime: "); n = int.Parse(Console.ReadLine()); m = n / 2; for (i = 2; i <= m; i++) { if (n % i == 0) { Console.Write("Number is not Prime."); flag = 1; break; } } if (flag == 0) Console.Write("Number is Prime."); } public void Factorial() { int i, fact = 1, number; Console.Write("Enter any Number: "); number = int.Parse(Console.ReadLine()); for (i = 1; i <= number; i++) { fact = fact * i; } Console.Write("Factorial of " + number + " is: " + fact); } public void ArmstrongNumber() { int n, r, sum = 0, temp; Console.Write("Enter the Number= "); n = int.Parse(Console.ReadLine()); temp = n; while (n > 0) { r = n % 10; sum = sum + (r * r * r); n = n / 10; } if (temp == sum) Console.Write("Armstrong Number."); else Console.Write("Not Armstrong Number."); } } }
using System.Collections.Generic; using System.Linq; using AgGateway.ADAPT.ApplicationDataModel.ADM; using AgGateway.ADAPT.ApplicationDataModel.Equipment; using AgGateway.ADAPT.ApplicationDataModel.LoggedData; using AgGateway.ADAPT.ApplicationDataModel.Shapes; using AgGateway.ADAPT.ISOv4Plugin.ExtensionMethods; using AgGateway.ADAPT.Representation.RepresentationSystem; namespace ADAPT_Sample_App { public class LogDataProcessor { /* * Note the use of foreach loops here. The underlying IEnumerable's often use deferred execution to reduce memory usage. * This means anything that causes multiple iterations of an IEnumerable will have a severe performance impact. * For instance, adaptDataModel.Documents.LoggedData.Count() will be extremely slow. Additionally, loading everything into * memory at once using adaptDataModel.Documents.LoggedData.ToList() or similar will consume a very large amount of memory. */ public void Process(ApplicationDataModel adaptDataModel) { //An ADAPT LoggedData is roughly analogous to an EIC LogStream foreach (var loggedData in adaptDataModel.Documents.LoggedData) { //An ADAPT OperationData is roughly analogous to an EIC LogBlock foreach (var operationData in loggedData.OperationData) { ProcessEquipmentDefinitionForOperation(operationData, adaptDataModel.Catalog); ProcessOperationData(operationData, adaptDataModel.Catalog); } //This is similar to EIC's stream.Release() method that releases underlying resources from memory. //This is the only place in ADAPT where this concept exists. loggedData.ReleaseSpatialData.Invoke(); } } private void ProcessEquipmentDefinitionForOperation(OperationData operationData, Catalog catalog) { var equipmentConfigurations = catalog.EquipmentConfigurations.Where(config => operationData.EquipmentConfigurationIds.Contains(config.Id.ReferenceId)); foreach (var config in equipmentConfigurations) { var connector = catalog.Connectors.Single(c => c.Id.ReferenceId == config.Connector1Id); var deviceElementConfig = catalog.DeviceElementConfigurations.Single(c => c.Id.ReferenceId == connector.DeviceElementConfigurationId); //Once we have the DeviceElementConfiguration's, we can start to store equipment offsets. if (deviceElementConfig is MachineConfiguration machineConfiguration) { //Not a typo: The X-axis is inline and the Y-axis is lateral. This is consistent with ISO offsets. var gpsReceiverLateralOffset = machineConfiguration.GpsReceiverYOffset; var gpsReceiverInlineOffset = machineConfiguration.GpsReceiverXOffset; var gpsReceiverVerticalOffset = machineConfiguration.GpsReceiverZOffset; } if (deviceElementConfig is ImplementConfiguration implementConfiguration) { var controlPoint = implementConfiguration.ControlPoint; var implementWidth = implementConfiguration.Width; } } } private static void ProcessOperationData(OperationData operationData, Catalog catalog) { var sections = ProcessImplementSections(operationData, catalog); var metersBySection = GetMetersBySection(sections); //Each SpatialRecord is equivalent to one row from an EIC LogBlock's SpatialLayer. foreach (var spatialRecord in operationData.GetSpatialRecords.Invoke()) { var point = spatialRecord.Geometry as Point; //The SpatialRecord has a value for each available meter (called WorkingData in ADAPT). //Note that section status is treated as a WorkingData. Each controllable section will have a meter with representation of SectionStatus. foreach (var section in metersBySection.Keys) { foreach (var meter in metersBySection[section]) { var meterValue = spatialRecord.GetMeterValue(meter); } } } } /* * Implement sections (called DeviceElementUses) are hierarchical. A section at depth 0 represents the entire width of the implement. * A greater depth indicates a more granular division of the implement. Deere's plugins interpret this as: * 0: Master level. This represents the entire implement. * 1: Meter level. This usually represents one half of the implement. * 2: Section level. This represents one controllable section of the implement. * 3: Row level. This represents a single row. * Not every level will be present in every datacard. For example, you may have Master level and Section level data but no Meter level data. */ private static List<DeviceElementUse> ProcessImplementSections(OperationData operationData, Catalog catalog) { var maxImplementSectionDepth = operationData.MaxDepth; for (int i = 0; i <= maxImplementSectionDepth; ++i) { IEnumerable<DeviceElementUse> sectionsAtThisDepth = operationData.GetDeviceElementUses.Invoke(i); foreach (var section in sectionsAtThisDepth) { //The order indicates the section's relative position on the implement. 0 is the left-most section, 1 is next to it, etc. var sectionOrder = section.Order; var equipmentConfiguration = catalog.DeviceElementConfigurations.Single(config => config.Id.ReferenceId == section.DeviceConfigurationId); var sectionConfiguration = equipmentConfiguration as SectionConfiguration; var sectionWidth = sectionConfiguration.SectionWidth; var lateralOffset = sectionConfiguration.LateralOffset; var inlineOffset = sectionConfiguration.InlineOffset; } } //If you don't care about any of this, you can get all the sections at once and ignore the hierarchy: return operationData.GetAllSections(); } private static Dictionary<DeviceElementUse, List<WorkingData>> GetMetersBySection(List<DeviceElementUse> sections) { /* * Note the .ToList() invocation here. Since we will iterate through the meters (WorkingData) for every SpatialRecord that we process, * we need to avoid multiple iterations of an IEnumerable. It makes a large performance difference. */ return sections.ToDictionary(section => section, section => section.GetWorkingDatas.Invoke().ToList()); /* * If you are only interested in specific Representations, this is a good place to filter them so you do not need to sort through * all of the data. */ // return sections.ToDictionary(section => section, // section => section.GetWorkingDatas.Invoke().Where( // meter => meter.Representation.Code == RepresentationInstanceList.dtRecordingStatus.DomainId || // meter.Representation.Code == RepresentationInstanceList.vrDistanceTraveled.DomainId) // .ToList()); } } }
namespace SchoolClasses { using System; using System.Collections.Generic; public class Teacher : People { private List<Discipline> disciplines; public List<Discipline> Disciplines { get { return this.disciplines; } set { this.disciplines = value; } } } }
using System; using System.Globalization; namespace Stundenplan.Services { public class CalendarService { private readonly PositionService pService = new PositionService(); public int GetWeekOfYear(DateTime time) { DayOfWeek day = CultureInfo.InvariantCulture.Calendar.GetDayOfWeek(time); if (day >= DayOfWeek.Monday && day <= DayOfWeek.Wednesday) { time = time.AddDays(3); } return CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(time, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); } public DateTime FirstDateOfWeek(int year, int weekOfYear) { DateTime jan1 = new DateTime(year, 1, 1); int daysOffset = DayOfWeek.Thursday - jan1.DayOfWeek; // Use first Thursday in January to get first week of the year as // it will never be in Week 52/53 DateTime firstThursday = jan1.AddDays(daysOffset); var cal = CultureInfo.CurrentCulture.Calendar; int firstWeek = cal.GetWeekOfYear(firstThursday, CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday); var weekNum = weekOfYear; // As we're adding days to a date in Week 1, // we need to subtract 1 in order to get the right date for week #1 if (firstWeek == 1) { weekNum -= 1; } // Using the first Thursday as starting week ensures that we are starting in the right year // then we add number of weeks multiplied with days var result = firstThursday.AddDays(weekNum * 7); // Subtract 3 days from Thursday to get Monday, which is the first weekday in ISO8601 return result.AddDays(-3); } public int GetTurnusForDate(string text, DateTime date) { int thisWeekNumber = this.GetWeekOfYear(date); DateTime firstDayOfWeek = this.FirstDateOfWeek(date.Year, thisWeekNumber); DateTime lastDayOfWeek = firstDayOfWeek.AddDays(4); string year = lastDayOfWeek.Year.ToString().Substring(2); string firstDay = firstDayOfWeek.Day.ToString(); string lastDay = lastDayOfWeek.Day.ToString(); if (firstDay.Length == 1) { firstDay = "0" + firstDay; } if (lastDay.Length == 1) { lastDay = "0" + lastDay; } string firstMonth = firstDayOfWeek.Month.ToString(); string lastMonth = lastDayOfWeek.Month.ToString(); if (firstMonth.Length == 1) { firstMonth = "0" + firstMonth; } if (lastMonth.Length == 1) { lastMonth = "0" + lastMonth; } string searchDate = firstDay + "." + firstMonth + ". - " + lastDay + "." + lastMonth + "." + year; int index = text.IndexOf(searchDate, StringComparison.InvariantCultureIgnoreCase); if (index == -1) { throw new Exception("Datum gibts nicht im aktuellen Plan"); } text = text.Substring(index); int turnusIndex = this.pService.GetPositonOfTurnus(text); string turnusText = text.Substring(turnusIndex); var splited = turnusText.Split('/'); turnusText = splited[0].Substring(splited[0].Length - 1); switch (turnusText) { case "I": return 1; case "II": return 2; case "III": return 3; case "IV": return 4; case "V": return 5; case "VI": return 6; case "VII": return 7; case "VIII": return 8; case "IX": return 9; case "X": return 10; case "XI": return 11; case "XII": return 12; case "XIII": return 13; default: return 0; } } } }
namespace K4AdotNet.NativeHandles { // Defined in k4atypes.h: // K4A_DECLARE_HANDLE(k4a_transformation_t); // /// <summary>Handle to an Azure Kinect transformation context.</summary> /// <remarks>Handles are created with <c>k4a_transformation_create()</c>.</remarks> internal sealed class TransformationHandle : HandleBase { private TransformationHandle() { } protected override bool ReleaseHandle() { NativeApi.TransformationDestroy(handle); return true; } public static readonly TransformationHandle Zero = new TransformationHandle(); } }
namespace MusicPlayer.ViewModels { public partial class ArtistsViewModel { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteAlways] public class SphereCollision : MonoBehaviour { //Max distance for detecting collisions and drawing the ray public float maxDistance; public float radius; private void Update() { raycasting(); } void raycasting() { // Bit shift the index of the layer (8) to get a bit mask int layerMask = 1 << 8; /* This would cast rays only against colliders in layer 8. But if you want to do the oposite(collide against everything except layer 8). The ~ operator does this, it inverts a bitmask. Example: layerMask = ~layerMask; */ //Create a ray at this object's position aiming to the rigth direction Ray ray = new Ray(transform.position, Vector3.right); //Store information about the object colliding with the ray RaycastHit hit; //Draw the ray Debug.DrawRay(ray.origin, ray.direction * maxDistance, Color.magenta); /* Physics.SphereCast return true if something collides with the ray. Think at this as a ray which you can specify how thick you want it to be If we pass the maxDistance as parameter it will only detects sollisions in between that distance Passing the layermask the ray will detects only objects in the layer number 8 */ if (Physics.SphereCast(ray, radius, out hit, maxDistance, layerMask)) { Debug.Log(hit.collider.name); } } private void OnDrawGizmos() { Gizmos.color = Color.magenta; Gizmos.DrawWireSphere(transform.position + (Vector3.right * maxDistance), radius); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "ServerProperties", menuName = "ScriptableObjects/ServerProperties", order = 1)] public class ServerProperties : ScriptableObject { [SerializeField] private byte RoomMaxPlayer; public byte roomMaxPlayer { get { return RoomMaxPlayer; } private set { RoomMaxPlayer = value; } } [SerializeField] private bool ServerIsOpen; public bool serverIsOpen { get { return ServerIsOpen; } private set { ServerIsOpen = value; } } [SerializeField] private bool ServerIsVisible; public bool serverIsVisible { get { return ServerIsVisible; } private set { ServerIsVisible = value; } } }