text
stringlengths
13
6.01M
using System.ComponentModel.DataAnnotations; using System; using System.Collections.Generic; using System.Runtime.Serialization; namespace GistackWAPService.models { /// <summary> /// Model class to hold cloud detail /// </summary> [DataContract] public class Cloud { [DataMember] public Guid id { get; set; } [DataMember] public string name { get; set; } } /// <summary> /// Model class to hold list of cloud /// </summary> public class CloudList : List<Cloud> { /// <summary> /// Initializes a new instance of the Cloud class. /// </summary> public CloudList() : base() { } /// <summary> /// Initializes a new instance of the Cloud class. /// </summary> /// <param name="records">The records.</param> public CloudList(IEnumerable<Cloud> records) : base(records) { } } }
using System.Collections.Generic; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Actions { public class ActionTakenType : Entity { public virtual string ActionTakenTypeName { get; set; } public virtual bool Archive { get; set; } public virtual string Notes { get; set; } public virtual bool IsRemedial { get; set; } public virtual bool IsDisciplinary { get; set; } public virtual IList<ActionTaken> ActionsTaken { get; set; } public ActionTakenType() { this.ActionsTaken = new List<ActionTaken>(); } public override string ToString() { return this.ActionTakenTypeName; } public virtual object ToJSON() { return new { Id = this.Id, Name = this.ActionTakenTypeName, IsRemedial = this.IsRemedial, IsDisciplinary = this.IsDisciplinary }; } } }
using CEMAPI.Models; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Web; using CEMAPI.DAL; namespace CEMAPI.BAL { public class BroadcastBAL { TETechuvaDBContext context = new TETechuvaDBContext(); string errorMsg = string.Empty; SuccessInfo sinfo = new SuccessInfo(); FailInfo finfo = new FailInfo(); GenericDAL genDAL = new GenericDAL(); int count = 0; HttpResponseMessage hrm = new HttpResponseMessage(); public BroadcastBAL() { context.Configuration.ProxyCreationEnabled = false; } public HttpResponseMessage SaveBroadCast(TEBroadcastUserDefined broadcastUDObj) { try { int tempBroadcastId = 0; TEBroadcast broadcast = new TEBroadcast(); broadcast.CreatedBy = broadcastUDObj.CreatedBy; broadcast.CreatedOn = DateTime.Now; broadcast.Title = broadcastUDObj.Title; broadcast.IsActive = true; broadcast.LastModifiedBy = broadcastUDObj.LastModifiedBy; broadcast.LastModifiedOn = DateTime.Now; broadcast.Message = broadcastUDObj.Message; broadcast.ValidFrom = broadcastUDObj.ValidFrom; broadcast.ValidTo = broadcastUDObj.ValidTo; context.TEBroadcasts.Add(broadcast); context.SaveChanges(); tempBroadcastId = broadcast.UniqueID; if(tempBroadcastId>0) { foreach(int roleid in broadcastUDObj.RoleIds) { if(roleid != 0) { TEBroadcastDetail broadcastdetail = new TEBroadcastDetail(); broadcastdetail.BroadcastID = tempBroadcastId; broadcastdetail.RoleID = roleid; context.TEBroadcastDetails.Add(broadcastdetail); context.SaveChanges(); } } } sinfo.errorcode = 0; sinfo.errormessage = "Successfully Saved"; hrm.Content = new JsonContent(new { info = sinfo }); } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Fail to Save"; hrm.Content = new JsonContent(new { info = finfo }); } return hrm; } public HttpResponseMessage DeleteBroadCast(TEBroadcastUserDefined broadcastUDObj) { try { TEBroadcast broadcast = new TEBroadcast(); broadcast = context.TEBroadcasts.Where(a => a.UniqueID == broadcastUDObj.UniqueID && a.IsActive == true).FirstOrDefault(); if(broadcast!=null) { broadcast.IsActive = false; broadcast.LastModifiedBy = broadcastUDObj.LastModifiedBy; broadcast.LastModifiedOn = DateTime.Now; context.Entry(broadcast).CurrentValues.SetValues(broadcast); context.SaveChanges(); sinfo.errorcode = 0; sinfo.errormessage = "Successfully Deleted"; hrm.Content = new JsonContent(new { info = sinfo }); } else { finfo.errorcode = 1; finfo.errormessage = "Unable to Delete"; hrm.Content = new JsonContent(new { info = finfo }); } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Fail to Delete"; hrm.Content = new JsonContent(new { info = finfo }); } return hrm; } public HttpResponseMessage GetAllMessageswithPagination(JObject json) { try { int count = 0; int pagenumber = json["page_number"].ToObject<int>(); int pagepercount = json["pagepercount"].ToObject<int>(); List<TEBroadcastUserDefined> broadcastList = new List<TEBroadcastUserDefined>(); broadcastList = (from bc in context.TEBroadcasts join prof in context.UserProfiles on bc.LastModifiedBy equals prof.UserId join creator in context.UserProfiles on bc.LastModifiedBy equals creator.UserId where bc.IsActive == true select new TEBroadcastUserDefined { Message = bc.Message, LastModifiedBy_Name = prof.CallName, CreatedOn = bc.CreatedOn, ValidFrom = bc.ValidFrom, ValidTo = bc.ValidTo, Title=bc.Title, CreatedBy = bc.CreatedBy, CreatedBy_Name = creator.CallName, UniqueID = bc.UniqueID, LastModifiedBy = bc.LastModifiedBy, LastModifiedOn = bc.LastModifiedOn }).OrderByDescending(a=>a.ValidFrom).ToList(); foreach (var bcdata in broadcastList) { string tempRole = string.Empty; var bcDetailsList = (from bcd in context.TEBroadcastDetails join role in context.webpages_Roles on bcd.RoleID equals role.RoleId where bcd.BroadcastID == bcdata.UniqueID select new { bcd.RoleID, role.RoleName }).ToList(); foreach(var bcdData in bcDetailsList) { tempRole += bcdData.RoleName + ","; } // to remove ',' at the end of the string if (!string.IsNullOrEmpty(tempRole)) { char getLastChar = tempRole[tempRole.Length - 1]; if (getLastChar == ',') { tempRole = tempRole.Remove(tempRole.Length - 1); } } bcdata.RolesNames = tempRole; } count = broadcastList.Count; if (count > 0) { if (pagenumber == 0) { pagenumber = 1; } int iPageNum = pagenumber; int iPageSize = pagepercount; int start = iPageNum - 1; start = start * iPageSize; var finalResult = broadcastList.Skip(start).Take(iPageSize).ToList(); sinfo.errorcode = 0; sinfo.errormessage = "Success"; sinfo.fromrecords = (start == 0) ? 1 : start + 1; sinfo.torecords = finalResult.Count + start; sinfo.totalrecords = count; sinfo.listcount = finalResult.Count; sinfo.pages = "1"; if (finalResult.Count > 0) { hrm.Content = new JsonContent(new { result = finalResult, info = sinfo }); return hrm; } else { finfo.errorcode = 0; finfo.errormessage = "No Records"; finfo.listcount = 0; hrm.Content = new JsonContent(new { result = finalResult, info = finfo }); return hrm; } } else { finfo.errorcode = 0; finfo.errormessage = "No Records"; finfo.listcount = 0; hrm.Content = new JsonContent(new { result = broadcastList, info = finfo }); return hrm; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to Get Data"; hrm.Content = new JsonContent(new { info = finfo }); return hrm; } } public HttpResponseMessage GetBroadcastMessages(JObject json, int logInUserId) { try { DateTime currentdate = DateTime.Now.Date; DateTime tomorrowdate = DateTime.Now.AddDays(1).Date; var messageList = (from bc in context.TEBroadcasts join bcd in context.TEBroadcastDetails on bc.UniqueID equals bcd.BroadcastID join usrole in context.webpages_UsersInRoles on bcd.RoleID equals usrole.RoleId join user in context.UserProfiles on bc.CreatedBy equals user.UserId where bc.IsActive == true && usrole.UserId == logInUserId && bc.ValidFrom <= tomorrowdate && bc.ValidTo >= currentdate select new { bc.Message,bc.Title,bc.ValidFrom,bc.ValidTo,user.CallName }).Distinct().ToList(); count = messageList.Count; if (count > 0) { sinfo.errorcode = 0; sinfo.errormessage = "Success"; sinfo.fromrecords = count; sinfo.torecords = count; sinfo.totalrecords = count; sinfo.listcount = count; sinfo.pages = "1"; hrm.Content = new JsonContent(new { result = messageList, info = sinfo }); return hrm; } else { finfo.errorcode = 0; finfo.errormessage = "No Records"; finfo.listcount = 0; hrm.Content = new JsonContent(new { result = messageList, info = finfo }); return hrm; } } catch (Exception ex) { genDAL.RecordUnHandledException(ex); finfo.errorcode = 1; finfo.errormessage = "Unable to Get Data"; hrm.Content = new JsonContent(new { info = finfo }); return hrm; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class start_builder : MonoBehaviour { void OnTriggerEnter2D(Collider2D other) { if(other.CompareTag("Player")) other.GetComponent<player_controller>().transitioning = false; } void OnTriggerExit2D(Collider2D other) { if(other.CompareTag("Player")) other.GetComponent<player_controller>().transitioning = true; } }
using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Html; namespace WebSport.Tools { public static class HTMLHelperExtensions { public static MvcHtmlString CustomEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { var htmlString = ""; TagBuilder div = new TagBuilder("div"); div.AddCssClass("form-group"); var htmlStringLabel = html.LabelFor<TModel, TValue>(expression, new { @class = "control-label col-md-2" }); TagBuilder divCol = new TagBuilder("div"); divCol.AddCssClass("col-md-10"); htmlString += html.EditorFor<TModel, TValue>(expression, new { htmlAttributes = new { @class = "form-control" } }); htmlString += html.ValidationMessageFor<TModel, TValue>(expression, "", new { @class = "text-danger" }); divCol.InnerHtml = htmlString; div.InnerHtml = htmlStringLabel + divCol.ToString(); return MvcHtmlString.Create(div.ToString());; } public static MvcHtmlString CustomDropDownFor<TModel, TValueLabel, TValueSelected>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValueLabel>> expression, Expression<Func<TModel, TValueSelected>> selected, IEnumerable<SelectListItem> liste) { var htmlString = ""; TagBuilder div = new TagBuilder("div"); div.AddCssClass("form-group"); var htmlStringLabel = html.LabelFor<TModel, TValueLabel>(expression, new { @class = "control-label col-md-2" }); TagBuilder divCol = new TagBuilder("div"); divCol.AddCssClass("col-md-10"); htmlString += html.DropDownListFor<TModel, TValueSelected>(selected, liste, "Aucune course", new { @class = "form-control" }); divCol.InnerHtml = htmlString; div.InnerHtml = htmlStringLabel + divCol.ToString(); return MvcHtmlString.Create(div.ToString()); ; } } }
using CommonMark.Syntax; using MarkdownUtils.MdDoc; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MarkdownUtils.Core { /// <summary> /// Flattens out the MdBlock via recursion /// </summary> public class MdBlockFlattener { public IEnumerable<MdInlineFlat> FlattenBlock(MdBlock para) { var result = new List<MdInlineFlat>(); RecurseMdBlock(para, result); return result; } private void RecurseMdBlock(MdBlock para, List<MdInlineFlat> list) { if (para.StringContent != null) list.Add(new MdInlineFlat(para.StringContent, para.Tag)); foreach (var childPara in para.SubBlocks) { RecurseMdBlock(childPara, list); } foreach (var inline in para.Inline) { RecurseInline(inline, list); } // .... when block ends any chain of inlines should be closed with a line break for our purposes if (para.Inline.Any()) list.Add(new MdInlineFlat("\n", InlineTag.LineBreak)); } private void RecurseInline(MdInline inline, List<MdInlineFlat> list) { if (inline.Text != null) list.Add(new MdInlineFlat(inline.Text, inline.Tag)); foreach (var inlineSub in inline.SubInline) { RecurseInline(inlineSub, list); } } } }
using GFW; using System; using System.Collections.Generic; using System.IO; namespace CodeX { public class Pathtool { public static string CombinePath(string path1, string path2) { string[] paths = path1.Split(new char[] { '/' }); string[] paths2 = path2.Split(new char[] { '/' }); List<string> paths1_list = new List<string>(); foreach (string value in paths) { paths1_list.Add(value); } for (int i = 0; i < paths2.Length; i++) { bool flag = paths2[i] == ".."; if (flag) { paths1_list.RemoveAt(paths1_list.Count - 1); } else { bool flag2 = paths2[i] != "."; if (flag2) { paths1_list.Add(paths2[i]); } } } string out_path = ""; for (int j = 0; j < paths1_list.Count; j++) { bool flag3 = j == 0; if (flag3) { out_path = paths1_list[0]; } else { bool flag4 = out_path.EndsWith("/"); if (flag4) { out_path += paths1_list[j]; } else { out_path = out_path + "/" + paths1_list[j]; } } } return out_path; } public static void CreatePath(string path) { string NewPath = path.Replace("\\", "/"); string[] strs = NewPath.Split(new char[] { '/' }); string p = ""; for (int i = 0; i < strs.Length; i++) { p += strs[i]; bool flag = i != strs.Length - 1; if (flag) { p += "/"; } bool flag2 = !Path.HasExtension(p); if (flag2) { bool flag3 = !Directory.Exists(p); if (flag3) { Directory.CreateDirectory(p); } } } } public static bool SaveDataToFile(string path, byte[] buffer) { if (path.IndexOf(AppConst.StreamingAssets) != -1 && AppConst.UpdateMode) { if (File.Exists(path)) { File.Delete(path); } if (Directory.Exists(path)) { Directory.Delete(path); } } if ((!File.Exists(path) && path.IndexOf(AppConst.StreamingAssets) == -1) || !AppConst.UpdateMode) { Pathtool.CreatePath(path); } try { FileStream fs = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(buffer, 0, buffer.Length); fs.Close(); } catch (Exception ex) { LogMgr.LogError("Can't create local resource" + path); return false; } return true; } public static void DeleteToFile(string path) { bool flag = File.Exists(path); if (flag) { File.Delete(path); Pathtool.CreatePath(path); } } public static bool GetDataToFile(string path, out byte[] buffer) { buffer = null; if (File.Exists(path)) { try { FileStream fs = new FileStream(path, FileMode.Open); int nLength = (int)fs.Length; byte[] buffs = new byte[nLength]; fs.Read(buffs, 0, nLength); fs.Close(); buffer = buffs; return true; } catch (Exception ex) { LogMgr.LogError("Can't create local resource" + path); return false; } } return false; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; namespace 校园卡管理系统 { public partial class Form4 : Form { public Form4() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { stuform.account = textBox1.Text; stuxgmm.account = textBox1.Text; Form9.account = textBox1.Text; stuxf.account = textBox1.Text; Form21.account = textBox1.Text; Form23.account = textBox1.Text; Form25.account = textBox1.Text; SqlConnection connection = new SqlConnection(); connection.ConnectionString = "Data Source= GATEWAY-PC;Initial Catalog=xiaoyuanka;User ID=sa;Password=niit#1234"; connection.Open(); SqlCommand cmd = new SqlCommand("select * from student", connection); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) { if (textBox1.Text == ""||textBox2.Text =="") { MessageBox.Show("账户或密码不能为空!"); return; } if (textBox1.Text == dr[0].ToString().Trim() && textBox2.Text == dr[1].ToString().Trim()) { stuform f = new stuform(); f.Show(); break; } else { MessageBox.Show("账户或密码输入错误!"); return; } } connection.Close(); this.Close(); } private void button2_Click(object sender, EventArgs e) { this.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace HTB.Database.Views { public class qryCustInkAkt : tblCustInkAkt { #region Property Declaration tblKlient private int _klientID; private string _klientName1; private string _klientName2; private string _klientName3; private string _klientStrasse; private string _klientLKZ; private string _klientPLZ; private string _klientOrt; private string _klientEMail; private string _klientOldID; public int KlientID { get { return _klientID; } set { _klientID = value; } } public string KlientName1 { get { return _klientName1; } set { _klientName1 = value; } } public string KlientName2 { get { return _klientName2; } set { _klientName2 = value; } } public string KlientName3 { get { return _klientName3; } set { _klientName3 = value; } } public string KlientStrasse { get { return _klientStrasse; } set { _klientStrasse = value; } } public string KlientLKZ { get { return _klientLKZ; } set { _klientLKZ = value; } } public string KlientPLZ { get { return _klientPLZ; } set { _klientPLZ = value; } } public string KlientOrt { get { return _klientOrt; } set { _klientOrt = value; } } public string KlientEMail { get { return _klientEMail; } set { _klientEMail = value; } } public string KlientOldID { get { return _klientOldID; } set { _klientOldID = value; } } #endregion #region Property Declaration tblUser private int _userID; private string _userVorname; private string _userNachname; private string _userEMailOffice; public int UserID { get { return _userID; } set { _userID = value; } } public string UserVorname { get { return _userVorname; } set { _userVorname = value; } } public string UserNachname { get { return _userNachname; } set { _userNachname = value; } } public string UserEMailOffice { get { return _userEMailOffice; } set { _userEMailOffice = value; } } #endregion #region Property Declaration tblAuftraggeber private string _auftraggeberName1; private string _auftraggeberName2; private string _auftraggeberStrasse; private string _auftraggeberLKZ; private string _auftraggeberPLZ; private string _auftraggeberOrt; public string AuftraggeberName1 { get { return _auftraggeberName1; } set { _auftraggeberName1 = value; } } public string AuftraggeberName2 { get { return _auftraggeberName2; } set { _auftraggeberName2 = value; } } public string AuftraggeberStrasse { get { return _auftraggeberStrasse; } set { _auftraggeberStrasse = value; } } public string AuftraggeberLKZ { get { return _auftraggeberLKZ; } set { _auftraggeberLKZ = value; } } public string AuftraggeberPLZ { get { return _auftraggeberPLZ; } set { _auftraggeberPLZ = value; } } public string AuftraggeberOrt { get { return _auftraggeberOrt; } set { _auftraggeberOrt = value; } } #endregion #region Property Declaration tblGegner private int _gegnerID; private string _gegnerAnrede; private string _gegnerName1; private string _gegnerName2; private string _gegnerStrasse; private string _gegnerZipPrefix; private string _gegnerZip; private string _gegnerOrt; private DateTime _gegnerGebDat; private string _gegnerOldID; private int _gegnerVVZ; private DateTime _gegnerVVZDate; private string _gegnerLastZipPrefix; private string _gegnerLastZip; private string _gegnerLastOrt; private string _gegnerLastStrasse; private string _gegnerLastName1; private int _gegnerType; private string _gegnerAnsprechAnrede; private string _gegnerAnsprechVorname; private string _gegnerAnsprech; public int GegnerID { get { return _gegnerID; } set { _gegnerID = value; } } public string GegnerAnrede { get { return _gegnerAnrede; } set { _gegnerAnrede = value; } } public string GegnerName1 { get { return _gegnerName1; } set { _gegnerName1 = value; } } public string GegnerName2 { get { return _gegnerName2; } set { _gegnerName2 = value; } } public string GegnerStrasse { get { return _gegnerStrasse; } set { _gegnerStrasse = value; } } public string GegnerZipPrefix { get { return _gegnerZipPrefix; } set { _gegnerZipPrefix = value; } } public string GegnerZip { get { return _gegnerZip; } set { _gegnerZip = value; } } public string GegnerOrt { get { return _gegnerOrt; } set { _gegnerOrt = value; } } public DateTime GegnerGebDat { get { return _gegnerGebDat; } set { _gegnerGebDat = value; } } public string GegnerOldID { get { return _gegnerOldID; } set { _gegnerOldID = value; } } public int GegnerVVZ { get { return _gegnerVVZ; } set { _gegnerVVZ = value; } } public DateTime GegnerVVZDate { get { return _gegnerVVZDate; } set { _gegnerVVZDate = value; } } public string GegnerLastZipPrefix { get { return _gegnerLastZipPrefix; } set { _gegnerLastZipPrefix = value; } } public string GegnerLastZip { get { return _gegnerLastZip; } set { _gegnerLastZip = value; } } public string GegnerLastOrt { get { return _gegnerLastOrt; } set { _gegnerLastOrt = value; } } public string GegnerLastStrasse { get { return _gegnerLastStrasse; } set { _gegnerLastStrasse = value; } } public string GegnerLastName1 { get { return _gegnerLastName1; } set { _gegnerLastName1 = value; } } public string GegnerLastName2 { get; set; } public string GegnerLastName3 { get; set; } public int GegnerType { get { return _gegnerType; } set { _gegnerType = value; } } public string GegnerAnsprechAnrede { get { return _gegnerAnsprechAnrede; } set { _gegnerAnsprechAnrede = value; } } public string GegnerAnsprechVorname { get { return _gegnerAnsprechVorname; } set { _gegnerAnsprechVorname = value; } } public string GegnerAnsprech { get { return _gegnerAnsprech; } set { _gegnerAnsprech = value; } } #endregion #region Property Declaration tblKZ private string _kZKZ; private string _kZCaption; public string KZKZ { get { return _kZKZ; } set { _kZKZ = value; } } public string KZCaption { get { return _kZCaption; } set { _kZCaption = value; } } #endregion } }
using Pe.Stracon.SGC.Cross.Core.Base; using Pe.Stracon.SGC.Infraestructura.CommandModel.Contractual; using Pe.Stracon.SGC.Infraestructura.Core.CommandContract.Contractual; using Pe.Stracon.SGC.Infraestructura.Core.Context; using Pe.Stracon.SGC.Infraestructura.Repository.Base; using System; using System.Data; using System.Data.SqlClient; namespace Pe.Stracon.SGC.Infraestructura.Repository.Command.Contractual { /// <summary> /// Implementación del Repositorio de Contrato /// </summary> /// <remarks> /// Creación : GMD 20150527 <br /> /// Modificación : <br /> /// </remarks> public class ContratoEntityRepository : ComandRepository<ContratoEntity>, IContratoEntityRepository { /// <summary> /// Interfaz para el manejo de auditoría /// </summary> public IEntornoActualAplicacion entornoActualAplicacion { get; set; } /// <summary> /// Realiza la inserción de contratos /// </summary> /// <param name="data">Datos a registrar</param> /// <returns>Indicador con el resultado de la operación</returns> public int RegistrarContrato(ContratoEntity data) { SqlParameter[] parametros = new SqlParameter[] { new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoContrato ?? DBNull.Value}, new SqlParameter("CODIGO_UNIDAD_OPERATIVA",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoUnidadOperativa ?? DBNull.Value}, new SqlParameter("CODIGO_PROVEEDOR",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoProveedor ?? DBNull.Value}, new SqlParameter("NUMERO_CONTRATO",SqlDbType.NVarChar) { Value = (object)data.NumeroContrato ?? DBNull.Value}, new SqlParameter("DESCRIPCION",SqlDbType.NVarChar) { Value = (object)data.Descripcion ?? DBNull.Value}, new SqlParameter("NUMERO_ADENDA",SqlDbType.NVarChar) { Value = (object)data.NumeroAdenda ?? DBNull.Value}, new SqlParameter("NUMERO_ADENDA_CONCATENADO",SqlDbType.NVarChar) { Value = (object)data.NumeroAdendaConcatenado ?? DBNull.Value}, new SqlParameter("CODIGO_TIPO_SERVICIO",SqlDbType.NVarChar) { Value = (object)data.CodigoTipoServicio ?? DBNull.Value}, new SqlParameter("CODIGO_TIPO_REQUERIMIENTO",SqlDbType.NVarChar) { Value = (object)data.CodigoTipoRequerimiento ?? DBNull.Value}, new SqlParameter("CODIGO_TIPO_DOCUMENTO",SqlDbType.NVarChar) { Value = (object)data.CodigoTipoDocumento ?? DBNull.Value}, new SqlParameter("INDICADOR_VERSION_OFICIAL",SqlDbType.Bit) { Value = (object)data.IndicadorVersionOficial ?? DBNull.Value}, new SqlParameter("FECHA_INICIO_VIGENCIA",SqlDbType.DateTime) { Value = (object)data.FechaInicioVigencia ?? DBNull.Value}, new SqlParameter("FECHA_FIN_VIGENCIA",SqlDbType.DateTime) { Value = (object)data.FechaFinVigencia ?? DBNull.Value}, new SqlParameter("CODIGO_MONEDA",SqlDbType.NVarChar) { Value = (object)data.CodigoMoneda ?? DBNull.Value}, new SqlParameter("MONTO_CONTRATO",SqlDbType.Decimal) { Value = (object)data.MontoContrato ?? DBNull.Value}, new SqlParameter("MONTO_ACUMULADO",SqlDbType.Decimal) { Value = (object)data.MontoAcumulado ?? DBNull.Value}, new SqlParameter("CODIGO_ESTADO", SqlDbType.NVarChar){Value = (object)data.CodigoEstado ?? DBNull.Value}, new SqlParameter("CODIGO_PLANTILLA", SqlDbType.UniqueIdentifier){Value = (object)data.CodigoPlantilla ?? DBNull.Value}, new SqlParameter("CODIGO_CONTRATO_PRINCIPAL",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoContratoPrincipal ?? DBNull.Value}, new SqlParameter("CODIGO_ESTADO_EDICION", SqlDbType.NVarChar){Value = (object)data.CodigoEstadoEdicion ?? DBNull.Value}, new SqlParameter("COMENTARIO_MODIFICACION", SqlDbType.VarChar){Value = (object)data.ComentarioModificacion ?? DBNull.Value}, new SqlParameter("RESPUESTA_MODIFICACION", SqlDbType.NVarChar){Value = (object)data.RespuestaModificacion ?? DBNull.Value}, new SqlParameter("CODIGO_FLUJO_APROBACION", SqlDbType.UniqueIdentifier){Value = (object)data.CodigoFlujoAprobacion ?? DBNull.Value}, new SqlParameter("CODIGO_ESTADIO_ACTUAL", SqlDbType.UniqueIdentifier){Value = (object)data.CodigoEstadioActual ?? DBNull.Value}, new SqlParameter("ESTADO_REGISTRO", SqlDbType.Char){Value = (object)DatosConstantes.EstadoRegistro.Activo ?? DBNull.Value}, new SqlParameter("USUARIO_CREACION",SqlDbType.NVarChar) { Value = (object)entornoActualAplicacion.UsuarioSession ?? DBNull.Value}, new SqlParameter("FECHA_CREACION",SqlDbType.DateTime) { Value = (object)data.FechaCreacion ?? DBNull.Value}, new SqlParameter("TERMINAL_CREACION",SqlDbType.NVarChar) { Value = (object)entornoActualAplicacion.Terminal ?? DBNull.Value}, new SqlParameter("ES_FLEXIBLE",SqlDbType.Bit) { Value = (object)data.EsFlexible ?? DBNull.Value}, new SqlParameter("ES_CORPORATIVO",SqlDbType.Bit) { Value = (object)data.EsCorporativo ?? DBNull.Value}, new SqlParameter("CODIGO_CONTRATO_ORIGINAL",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoContratoOriginal ?? DBNull.Value} }; var result = this.dataBaseProvider.ExecuteStoreProcedureNonQuery("CTR.USP_CONTRATO_INS", parametros); return result; } /// <summary> /// Realiza la edición de un contrato /// </summary> /// <param name="data">Datos a registrar</param> /// <returns>Indicador con el resultado de la operación</returns> public int EditarContrato(ContratoEntity data) { SqlParameter[] parametros = new SqlParameter[] { new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoContrato ?? DBNull.Value}, new SqlParameter("CODIGO_ESTADO", SqlDbType.NVarChar){Value = (object)data.CodigoEstado ?? DBNull.Value}, new SqlParameter("CODIGO_ESTADO_EDICION", SqlDbType.NVarChar){Value = (object)data.CodigoEstadoEdicion ?? DBNull.Value}, new SqlParameter("NUMERO_CONTRATO", SqlDbType.NVarChar){Value = (object)data.NumeroContrato ?? DBNull.Value}, new SqlParameter("COMENTARIO_MODIFICACION", SqlDbType.VarChar){Value = (object)data.ComentarioModificacion ?? DBNull.Value}, new SqlParameter("USUARIO_MODIFICACION",SqlDbType.NVarChar) { Value = (object)entornoActualAplicacion.UsuarioSession ?? DBNull.Value}, new SqlParameter("FECHA_MODIFICACION",SqlDbType.DateTime) { Value = (object)data.FechaModificacion ?? DBNull.Value}, new SqlParameter("TERMINAL_MODIFICACION",SqlDbType.NVarChar) { Value = (object)entornoActualAplicacion.Terminal ?? DBNull.Value}, new SqlParameter("ES_FLEXIBLE",SqlDbType.Bit) { Value = (object)data.EsFlexible ?? DBNull.Value}, }; var result = this.dataBaseProvider.ExecuteStoreProcedureNonQuery("CTR.USP_CONTRATO_UPD", parametros); return result; } /// <summary> /// Metodo para consultar si el numero de contrato ya existe. /// </summary> /// <param name="data"></param> /// <returns></returns> public int ConsultaNumeroContrato(ContratoEntity data) { //int valorNumero = 0; //SqlParameter[] parametros = new SqlParameter[] //{ // new SqlParameter("NUMERO_CONTRATO", SqlDbType.NVarChar) {Value = (object)data.NumeroContrato ?? DBNull.Value}, // new SqlParameter("VALOR_NUMERO",SqlDbType.Int) { Value = (object)valorNumero ?? DBNull.Value}, //}; //this.dataBaseProvider.ExecuteStoreProcedureNonQuery("CTR.USP_NUMERO_CONTRATO_VALIDA_SEL", parametros); //var result = Convert.ToInt32(valorNumero); //return result; int valorNumero = 0; SqlParameter pIdUsuario = new SqlParameter("@VALOR_NUMERO", valorNumero); pIdUsuario.Direction = System.Data.ParameterDirection.Output; this.dataBaseProvider.ExecuteStoreProcedureNonQuery("EXEC CTR.USP_NUMERO_CONTRATO_VALIDA_SEL @NUMERO_CONTRATO, @VALOR_NUMERO output" , new SqlParameter("NUMERO_CONTRATO", data.NumeroContrato) , pIdUsuario ); var result = Convert.ToInt32(pIdUsuario.Value); return result; } public int Actualizar_Flujo_Contrato_Estadio(ContratoEntity data) { SqlParameter[] parametros = new SqlParameter[] { new SqlParameter("CODIGO_CONTRATO",SqlDbType.UniqueIdentifier) { Value = (object)data.CodigoContrato ?? DBNull.Value}, new SqlParameter("CODIGO_FLUJO_APROBACION", SqlDbType.UniqueIdentifier){Value = (object)data.CodigoFlujoAprobacion ?? DBNull.Value}, new SqlParameter("CODIGO_ESTADIO_ACTUAL", SqlDbType.UniqueIdentifier){Value = (object)data.CodigoEstadioActual ?? DBNull.Value} }; var result = this.dataBaseProvider.ExecuteStoreProcedureNonQuery("CTR.USP_ACTUALIZAR_FLUJO_APROBACION_ESTADIO", parametros); return result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; namespace pjank.BossaAPI { /// <summary> /// Lista bieżących zleceń na danym rachunku. /// </summary> public class BosOrders : IEnumerable<BosOrder> { /// <summary> /// Rachunek, którego dotyczą te zlecenia. /// </summary> public readonly BosAccount Account; /// <summary> /// Liczba bieżących zleceń dostępnych na tym rachunku. /// </summary> public int Count { get { return list.Count; } } /// <summary> /// Dostęp do konkretnego zlecenia z listy, po jego indeksie (licząc od zera). /// </summary> public BosOrder this[int index] { get { return list[index]; } } #region Generic list stuff private List<BosOrder> list = new List<BosOrder>(); public IEnumerator<BosOrder> GetEnumerator() { for (int i = 0; i < Count; i++) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } #endregion #region Internal library stuff // konstruktor, wywoływany z samej klasy BosAccount internal BosOrders(BosAccount account) { Account = account; } // aktualizacja danych na liście po odebraniu ich z sieci internal void Update(DTO.OrderData data) { var order = list.Where(o => o.Id == data.BrokerId).SingleOrDefault(); if (order != null) order.Update(data); else list.Add(new BosOrder(Account, data)); } #endregion } }
using System; namespace PatientWebApp.DTOs { public class PatientDTO { public string Name { get; set; } public string Surname { get; set; } public string Jmbg { get; set; } public int Gender { get; set; } public DateTime DateOfBirth { get; set; } public string Phone { get; set; } public int CountryId { get; set; } public string CountryName { get; set; } public int CityZipCode { get; set; } public string CityName { get; set; } public string HomeAddress { get; set; } public int PatientCardId { get; set; } public int BloodType { get; set; } public int RhFactor { get; set; } public string Lbo { get; set; } public string Allergies { get; set; } public string MedicalHistory { get; set; } public string Email { get; set; } public string Password { get; set; } } }
using System; using System.IO; using System.Text; namespace SerializationDemo { public class HttpRequest : IMessage { public HttpRequest(Uri url, string contents) { Url = url; var payload = Encoding.UTF8.GetBytes(contents); Contents = new MemoryStream(payload); } public Uri Url { get; private set; } public Stream Contents { get; private set; } } public class HttpResponse : IMessage { public HttpResponse() { Contents = new MemoryStream(); } public Stream Contents { get; private set; } public string GetText() { return Encoding.UTF8.GetString((Contents as MemoryStream).ToArray()); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Assignment1.Models; namespace Assignment1.Controllers { public class HomeController : Controller { public ViewResult Index() { return View(); } [HttpGet] public ViewResult AddRecipe() { return View(); } [HttpPost] public ViewResult AddRecipe(Recipe recipe) { if (ModelState.IsValid) { Repository.AddRecipes(recipe); return View("ThankYouRecipe", recipe); } else { return View(); } } public ViewResult RecipeList() { return View(Repository.Recipes.OrderBy(r => r.Name)); } [HttpGet] public ViewResult AddReview(string name) { //Review review = new Review //{ // RecipeName = name //} //; return View(new Review { RecipeName = name}); } [HttpPost] public ViewResult AddReview(Review review) { if (!(Repository.Recipes.Any( r => r.Name == review.RecipeName))) { ModelState.AddModelError("", "Reciepe doesn't exist"); } if (ModelState.IsValid) { //Recipe recipe = Repository.Recipes.FirstOrDefault(r => r.Name == rvName); //review.RecipeName = recipe; Repository.AddReviews(review); //TempData["review"] = "Thank you for adding your review!"; return View("ThankYouReview", review); } else { return View(); } } public ViewResult ViewRecipe( string name) { return View(Repository.Recipes.FirstOrDefault(r => r.Name == name)); } public ViewResult ReviewList() { return View(Repository.Reviews); } } }
using AutoMapper; using TimeTableApi.Application.Shared.RoleManagement.Dtos; using TimeTableApi.Core.Entities; namespace TimeTableApi.Application.AutoMapper { public class RoleProfile : Profile { public RoleProfile() { CreateMap<Role, CreateOrEditRoleInputDto>().ReverseMap(); CreateMap<Role, RoleDto>().ReverseMap(); } } }
using Project.Errors; using Project.Models; using Project.Services; using System; using System.Windows.Forms; namespace Project.Base { public class BaseScreen : Form { public virtual string GetHandle() { throw new NotImplementedException(); } public virtual bool IsDefault() { return false; } public virtual void Init() { } public virtual void OnShow() { } public virtual bool RequireLogin() { return true; } public virtual bool RequireAdmin() { return false; } } }
using Autofac; using EmberKernel.Plugins.Models; using EmberKernel.Services.UI.Mvvm.ViewComponent; using EmberKernel.Services.UI.Mvvm.ViewModel.Plugins; using EmberWpfCore.Components.PluginsManager.ViewModel; using Microsoft.Extensions.Logging; using System.ComponentModel; using System.Runtime.CompilerServices; using System.Threading.Tasks; using System.Windows.Controls; namespace EmberWpfCore.Components.PluginsManager.View { /// <summary> /// Interaction logic for PluginsTab.xaml /// </summary> [ViewComponentNamespace(@namespace: "CoreWpfTab")] [ViewComponentName(name: "Plugins")] public partial class PluginsTab : UserControl, IViewComponent { public PluginsTab() { InitializeComponent(); } public ValueTask Initialize(ILifetimeScope scope) { var logger = scope.Resolve<ILogger<PluginsTab>>(); if (scope.TryResolve<IPluginManagerViewModel>(out var pluginsViewModel)) { this.DataContext = new PluginsTabViewModel(pluginsViewModel); } else logger.LogError("Can't resolve 'IPluginManagerViewModel'"); return default; } public ValueTask Uninitialize(ILifetimeScope scope) { this.DataContext = null; return default; } public void Dispose() { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CloneState : State { public CloneState(StateController stateController) : base(stateController) { } public bool hasCloned = false; public override void CheckTransitions() { if (stateController.CheckIfInRange("enemy")) { stateController.SetState(new EscapeState(stateController)); } if (hasCloned) { stateController.SetState(new NPCWander(stateController)); } } public override void Act() { if (!hasCloned) { GameObject newAI = GameObject.Instantiate(stateController.self, stateController.transform); newAI.transform.SetParent(null); hasCloned = true; } } public override void OnStateEnter() { stateController.destination = stateController.GetNextNavPoint(); if (stateController.ai.agent != null) { stateController.ai.agent.speed = .2f; } stateController.ai.SetTarget(stateController.destination); stateController.ChangeColor(Color.cyan); } }
using System; using System.Collections.Generic; using System.Threading; using Framework.Core.Config; using NUnit.Framework; using Tests.Data.Oberon; using OpenQA.Selenium; using OpenQA.Selenium.Support.PageObjects; using Framework.Core.Common; namespace Tests.Pages.Oberon.ReportManager { //[TextFixture] public class ReportManagerCreate : ReportManagerBasePage { public ReportManagerCreate(Driver driver) : base(driver) { } #region Page Objects /// <summary> /// returns report title /// </summary> private IWebElement Title() { return Report.FindElement(By.CssSelector("div.actionTitle h2")); } /// <summary> /// returns method multi select IWebElement /// </summary> private IWebElement MethodMultiSelect() { return Report.FindElement(By.CssSelector("#xda06817509874b51a21843d525f423a8")); } /// <summary> /// returns method multi IWebElement select options /// </summary> private IWebElement MethodMultiSelectOptions() { string query = "#" + MethodMultiSelect().GetAttribute("id") + " + .multiSelectOptions"; return Report.FindElement(By.CssSelector("#" + MethodMultiSelect().GetAttribute("id") + " + .multiSelectOptions")); } /// <summary> /// returns method select IWebElement button /// </summary> private IWebElement MethodSelectButton() { if (_driver.InternetExplorer()) return MethodMultiSelect().FindElement(By.CssSelector(".button")); else return MethodMultiSelect().FindElement(By.CssSelector(".button.w3c")); } /// <summary> /// returns method select all IWebElement selector /// </summary> private IWebElement MethodSelectAll() { return MethodMultiSelectOptions().FindElement(By.CssSelector(".selectAll")); } /// <summary> /// returns run report IWebElement button /// </summary> private IWebElement RunReport() { return Report.FindElement(By.CssSelector(".action.formButtons button")); } #endregion #region Methods /// <summary> /// navigates to report manager page directly /// </summary> public void GoToPage() { _driver.GoToPage(AppConfig.OberonBaseUrl + "/ReportManager"); } /// <summary> /// waits until new report loads, default timeout is 30 seconds /// </summary> public void WaitUntilNewReportLoads() { int count = 0; do { if (_driver.IsElementPresentBy(By.CssSelector(".progress-indicator"))) { Assert.IsTrue(Title().Text.Contains("Unsaved Report")); break; } else { Thread.Sleep(1000); count++; } } while (count <= 30); } /// <summary> /// clicks method select button /// </summary> public void ClickMethodSelect() { _driver.Click(MethodSelectButton()); } /// <summary> /// clicks method select all checkbox option /// </summary> public void ClickMethodSelectAllCheckbox() { ClickMethodSelect(); _driver.Click(MethodSelectAll()); } /// <summary> /// returns true if method option is checked based on text parameter /// </summary> public bool VerifyMethodOptionChecked(string text) { //IWebElement methodMultiSelect = MethodMultiSelect().FindElement(By.CssSelector("#" + MethodMultiSelect().GetAttribute("id") + " + .multiSelectOptions")); IWebElement option = null; switch (text) { case "Select All": option = MethodSelectAll(); break; case "Check": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Credit Card": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Wire Transfer": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Cash": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Debit Card": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Electronic Pay System": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Money Order": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Other": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; case "Cashier's Check": option = MethodMultiSelectOptions().FindElement(By.Name("xda06817509874b51a21843d525f423a8[]")); break; } return option.Enabled; } /// <summary> /// clicks run report element /// </summary> public void ClickRunReport() { _driver.ScrollToBottomOfPage(); _driver.Click(RunReport()); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace CRL.CacheServer { public class CacheServer { public static string Query(string json) { var obj = LambdaQuery.CRLQueryExpression.FromJson(json); return Query(obj); } public static string Query(LambdaQuery.CRLQueryExpression queryExpression) { if (SettingConfig.ExpressionQueryData == null) { throw new Exception("请实现SettingConfig.ExpressionQueryData"); } var data = SettingConfig.ExpressionQueryData(queryExpression); var result = new ResultData() { Data = data, Total = queryExpression.Total }; return CoreHelper.StringHelper.SerializerToJson(result); } } }
using System.Collections.Concurrent; using BDTest.Maps; using BDTest.NetCore.Razor.ReportMiddleware.Interfaces; using BDTest.NetCore.Razor.ReportMiddleware.Models; using Microsoft.Extensions.Caching.Memory; namespace BDTest.NetCore.Razor.ReportMiddleware.Implementations; public class MemoryCacheBdTestDataStore : IMemoryCacheBdTestDataStore { private readonly IMemoryCache _testRecordCache; private readonly ConcurrentDictionary<string, TestRunSummary> _testRunSummariesDictionary = new(); private List<TestRunSummary> _testRunSummaries = new(); public MemoryCacheBdTestDataStore(IMemoryCache testRecordCache) { _testRecordCache = testRecordCache; } public Task<BDTestOutputModel> GetTestData(string id, CancellationToken cancellationToken) { if (_testRecordCache.TryGetValue<BDTestOutputModel>(id, out var model)) { return Task.FromResult(model); } return Task.FromResult<BDTestOutputModel>(null); } public Task DeleteTestData(string id) { _testRecordCache.Remove(id); return Task.CompletedTask; } public Task<IEnumerable<TestRunSummary>> GetAllTestRunRecords() { return Task.FromResult(_testRunSummaries.AsEnumerable()); } public Task StoreTestData(string id, BDTestOutputModel data) { _testRecordCache.Set(id, data, TimeSpan.FromHours(8)); return Task.CompletedTask; } public Task StoreTestRunRecord(TestRunSummary testRunSummary) { var testRunSummariesCopy = _testRunSummariesDictionary .Values .OrderByDescending(record => record.StartedAtDateTime) .ToList(); Interlocked.Exchange(ref _testRunSummaries, testRunSummariesCopy); _testRunSummariesDictionary.TryAdd(testRunSummary.RecordId, testRunSummary); return Task.CompletedTask; } public Task DeleteTestRunRecord(string id) { _testRunSummariesDictionary.TryRemove(id, out _); var testRunSummariesCopy = _testRunSummaries.ToList(); testRunSummariesCopy.RemoveAll(x => x.RecordId == id); Interlocked.Exchange(ref _testRunSummaries, testRunSummariesCopy); return Task.CompletedTask; } }
using System; using System.Collections; using System.IO; using System.Linq; namespace csqueue { public class RadixSort { enum DigitType {ones = 1, tens = 10} public static void RSort(int[] target, int size, int n_digits) { Queue[] bins = new Queue[10]; Console.WriteLine("in Radix."); n_digits=2; for(int d = 1; d <= n_digits; d++) { int pos; int tmp; Console.WriteLine("Sorting the "+ d + "-digit"); for(int i=0; i<size; i++) { tmp = target[i]; pos = ( (d == 1) ? tmp % 10 : tmp / 10 ); bins[pos].Enqueue(tmp); }//for each item in target[] int j=0; for(int bin_num = 0; bin_num < 10; bin_num++) while(bins[bin_num].Count > 0) target[j++] = Int32.Parse(bins[bin_num].Dequeue().ToString()); } } static void Main(string[] args) { //Queue [] numQueue = new Queue[10]; int [] nums = new int[] {91, 46, 85, 15, 92, 35, 31, 22}; // Display original list //for(int i = 0; i < 10; i++) // numQueue[i] = new Queue(); RSort(nums, nums.Length, (int) DigitType.ones); Console.WriteLine(); Console.WriteLine("First pass results: "); DisplayArray(nums); // Second pass sort RSort(nums, nums.Length, (int) DigitType.tens); Console.WriteLine(); Console.WriteLine("Second pass results: "); // Display final results DisplayArray(nums); Console.WriteLine(); Console.Write("Press enter to quit"); Console.ReadKey(); } static void DisplayArray(int [] n) { for(int x = 0; x <= n.GetUpperBound(0); x++) Console.Write(n[x] + " "); } } }
namespace Swan.Ldap.Test { using System; using System.Net.Sockets; using System.Threading.Tasks; using NUnit.Framework; public abstract class LdapTest { protected const string LdapServer = "localhost"; protected const string DefaultDn = "cn=root"; protected const string DefaultOrgDn = "dn=sample, o=unosquare"; protected const string DefaultPassword = "secret"; protected const int DefaultPort = 1089; protected const string DefaultUserDn = "cn=Simio, dn=sample, o=unosquare"; public LdapConnection Connection { get; private set; } [SetUp] public async Task Setup() { Connection = new LdapConnection(); await Connection.Connect(LdapServer, DefaultPort); await Connection.Bind(DefaultDn, DefaultPassword); } [TearDown] public void GlobalTeardown() => Connection?.Dispose(); } [TestFixture] public class Bind : LdapTest { [Test] public void ValidCredentials_ReturnsTrue() { Assert.IsNotNull(Connection.AuthenticationDn); } [Test] public void InvalidCredentials_ThrowsLdapException() { Assert.ThrowsAsync<LdapException>(async () => { var cn = new LdapConnection(); await cn.Connect(LdapServer, DefaultPort); await cn.Bind("cn=invalid", DefaultPassword); cn.Dispose(); }); } [Test] public async Task NullPassword_ReturnsNullAuthenticationDnProperty() { var cn = new LdapConnection(); await cn.Connect(LdapServer, DefaultPort); await cn.Bind(DefaultDn, null); Assert.IsNull(cn.AuthenticationDn); cn.Dispose(); } } [TestFixture] public class Connect : LdapTest { [Test] public async Task ValidHost_ReturnsTrue() { await Connection.Connect(LdapServer, DefaultPort); Assert.IsTrue(Connection.Connected); } [Test] public void InvalidHost_ThrowsSocketException() { Assert.CatchAsync<SocketException>(async () => { var cn = new LdapConnection(); await cn.Connect("invalid.local", DefaultPort); await cn.Bind(DefaultDn, DefaultPassword); cn.Dispose(); }); } [Test] public void InvalidPort_ThrowsSocketException() { Assert.CatchAsync<SocketException>(async () => { var cn = new LdapConnection(); await cn.Connect(LdapServer, 388); await cn.Bind(DefaultDn, DefaultPassword); cn.Dispose(); }); } [Test] public void Connected_ResetConnection() { Assert.IsTrue(Connection.Connected); Connection.Dispose(); Assert.IsFalse(Connection.Connected); } [Test] public void Default_ProtocolVersion() { Assert.AreEqual(3, Connection.ProtocolVersion, "The default protocol version is 3"); } [Test] public void Default_AuthenticationMethod() { Assert.AreEqual("simple", Connection.AuthenticationMethod, "The default Authentication Method is simple"); } } [TestFixture] public class Modify : LdapTest { [Test] public void ChangeUserProperty_LdapException() { var ex = Assert.CatchAsync(async () => { await Connection.Modify( "cn=Invalid, o=unosquare", new[] {new LdapModification(LdapModificationOp.Replace, "email", "new@unosquare.com")}); Connection.Disconnect(); }); if (ex is LdapException ldapEx) Assert.AreEqual(LdapStatusCode.NoSuchObject, ldapEx.ResultCode); else Assert.IsNotNull(ex); } [Test] public void Modify_DNNull() { Assert.ThrowsAsync<ArgumentNullException>(async () => { var mods = new LdapModification(LdapModificationOp.Replace, new LdapAttribute("ui")); await Connection.Modify(null, new[] {mods}); }); } } [TestFixture] public class Read : LdapTest { [Test] public async Task WithDefaultUser_MailShouldMatch() { var properties = await Connection.Read(DefaultUserDn); var mail = properties.GetAttribute("email"); Assert.AreEqual(mail.StringValue, "gperez@unosquare.com"); } [Test] public void Read_LdapException() { Assert.ThrowsAsync<LdapException>(async () => { await Connection.Read("ou=scientists,dc=example,dc=com"); }); } } [TestFixture] public class Search : LdapTest { [Test] public async Task MultipleSearchResults() { var lsc = await Connection.Search(DefaultOrgDn, LdapScope.ScopeSub); if (lsc.HasMore()) { var entry = lsc.Next(); var ldapAttributes = entry.GetAttributeSet(); Assert.IsNotNull(ldapAttributes["email"]?.StringValue); } Assert.AreNotEqual(lsc.Count, 0); Assert.IsTrue(lsc.HasMore()); } [Test] public async Task SingleSearchResult() { var lsc = await Connection.Search( DefaultOrgDn, LdapScope.ScopeSub, "(email=gperez@unosquare.com)"); if (lsc.HasMore()) { var entry = lsc.Next(); var ldapAttributes = entry.GetAttributeSet(); Assert.AreEqual("gperez@unosquare.com", ldapAttributes["email"]?.StringValue); } Assert.IsFalse(lsc.HasMore()); } [Test] public void UsingInvalidDN_ThrowsLdapException() { Assert.ThrowsAsync<LdapException>(async () => { await Connection.Search("ou=scientists,dc=com", LdapScope.ScopeSub); }); } [Test] public void SearchForMore_ThrowsLdapException() { Assert.ThrowsAsync<ArgumentOutOfRangeException>(async () => { var lsc = await Connection.Search( DefaultOrgDn, LdapScope.ScopeSub, $"(uniqueMember={DefaultUserDn})"); while (lsc.HasMore()) { lsc.Next(); } lsc.Next(); }); } } }
using UnityEngine; namespace DChild.Gameplay.Environment { public interface IPosition{ Vector3 position { get; } } }
using Allyn.Application.Dto.Manage.Front; using Allyn.Application.Front; using Allyn.Infrastructure; using Allyn.Infrastructure.Api.WeChat.Enties; using Allyn.Infrastructure.Api.WeChat.Js; using Microsoft.Practices.Unity; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; using System.Web; using System.Web.Mvc; using System.Web.Security; namespace Allyn.MvcApp.Areas.Shop.Controllers { public class HomeController : Controller { public ActionResult Index() { //获取JsApiConfig. string url = string.Format("http://{0}{1}", Request.Url.Host, Request.RawUrl); JsApiConfig jsApiConfig = JsApi.GetJsApiConfig(url); ViewBag.JsApiConfig = JsonConvert.SerializeObject(jsApiConfig); //获取总店. IShopService shopService = ServiceLocator.Instance.GetService<IShopService>(); ShopDto shop = shopService.GetHeadShop(); if (shop == null) { throw new Exception("系统还没有设置总店,请联系管理员."); } //获取总店的所有分类. ICategoryService categoryService = ServiceLocator.Instance.GetService<ICategoryService>(); List<CategorySelectItemDto> categoryList = categoryService.GetCategorySelectList(); //获取总店的所有产品和推荐产品. IProductService productService = ServiceLocator.Instance.GetService<IProductService>(); List<ProductDto> productList = productService.GetProducts(shop.Id, Guid.Empty); List<ProductDto> redProductList = productService.GetRedProducts(shop.Id); ViewBag.ShopKey = shop.Id.ToString(); ViewBag.CategoryArray = JsonConvert.SerializeObject(categoryList ?? new List<CategorySelectItemDto>()); ViewBag.ProductArray = JsonConvert.SerializeObject(productList??new List<ProductDto>()); ViewBag.RedProductArray = JsonConvert.SerializeObject(redProductList ?? new List<ProductDto>()); return View(); } //根据用户的定位,获取在范围内的店铺.范围是根据系统设定的结果. public JsonResult GetShop(decimal lng, decimal lat) { IShopService service = ServiceLocator.Instance.GetService<IShopService>(); int renge = 2000; // Todo 获取系统设置的马上送的范围. List<ShopDto> result = service.GetShops(lng, lat, renge); return Json(new { status = true, shopArray = result, msg = "获取成功!" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } //根据店铺标识,获取所有的类别. public JsonResult GetCategoryArray(Guid shopKey) { ICategoryService service = ServiceLocator.Instance.GetService<ICategoryService>(); List<CategorySelectItemDto> categoryList = service.GetCategorySelectList(); return Json(new { status = true, categoryArray = categoryList, msg = "获取成功!" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } //根据店铺标识和类别标识,获取该店铺产品. public JsonResult GetProductArray(Guid shopKey, Guid categoryKey) { ////浏览器访问,调试测试数据.真实发布需注释掉! //shopKey = new Guid("F3ADCAD1-9186-E711-8CAE-C86000C3027D"); if (shopKey == null || shopKey == Guid.Empty) { throw new ArgumentNullException("shopKey", "指定的店铺无效."); } IProductService service = ServiceLocator.Instance.GetService<IProductService>(); List<ProductDto> productList = service.GetProducts(shopKey,categoryKey); return Json(new { status = true, productArray = productList, msg = "获取成功!" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } //根据店铺标识,获取该店铺推荐的产品. public JsonResult GetRedProductArray(Guid shopKey) { ////浏览器访问,调试测试数据.真实发布需注释掉! //shopKey = new Guid("F3ADCAD1-9186-E711-8CAE-C86000C3027D"); IProductService service = ServiceLocator.Instance.GetService<IProductService>(); List<ProductDto> productList = service.GetRedProducts(shopKey); return Json(new { status = true, productArray = productList, msg = "获取成功!" }, "json", Encoding.UTF8, JsonRequestBehavior.DenyGet); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Client.Features.JobService.Models; namespace Client.Features.JobService { public class JobServiceRepository : IJobServiceRepository { private readonly Internal.ILogger _logger; private readonly DAL.IDBContext _dBContext; public JobServiceRepository() { _logger = (Internal.ILogger)Bootstrap.Instance.Services.GetService(typeof(Internal.ILogger)); _dBContext = (DAL.IDBContext)Bootstrap.Instance.Services.GetService(typeof(DAL.IDBContext)); } public async Task<bool> Delete(Models.PathCompareValue pathCompareValue) { try { if (pathCompareValue != null) { await _dBContext.Instance.DeleteAsync(pathCompareValue); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to delete PathCompareValue item"); } return false; } public async Task<Models.PathCompareValue> Find(string fullFileName) { return await _dBContext.Instance.Table<Models.PathCompareValue>().FirstOrDefaultAsync(x => x.FullFile == fullFileName.ToUpper()); } public async Task<List<Models.PathCompareValue>> Gets(params string[] directorys) { var retVal = new List<Models.PathCompareValue>(); foreach (var item in directorys) { var paths = await _dBContext.Instance.Table<Models.PathCompareValue>().Where(x => x.Directory == item.ToUpper()).ToListAsync(); if (paths?.Count > 0) retVal.AddRange(paths); } return retVal; } public async Task<List<Models.PathCompareValue>> GetsByDirectoryWithSubFolders(string directory) { return await _dBContext.Instance.Table<Models.PathCompareValue>().Where(x => x.Directory.StartsWith(directory)).ToListAsync(); } public async Task<List<Models.PathCompareValue>> GetsByDirectory(string directory) { return await _dBContext.Instance.Table<Models.PathCompareValue>().Where(x => x.Directory == directory.ToUpper()).ToListAsync(); } public async Task<bool> Insert(Models.PathCompareValue pathCompareValue) { try { if (pathCompareValue != null) { await _dBContext.Instance.InsertAsync(pathCompareValue); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to insert new PathCompareValue item"); } return false; } public async Task<bool> Update(Models.PathCompareValue pathCompareValue) { try { if (pathCompareValue != null) { await _dBContext.Instance.UpdateAsync(pathCompareValue); return true; } } catch (Exception ex) { _logger.Error(ex, "Failed to update new PathCompareValue item"); } return false; } public async Task<DuplicateValue> CreateDuplicateValue(int compareValue) { try { var duplicate = new DuplicateValue { CompareValue = compareValue, Id = Guid.NewGuid(), }; await _dBContext.Instance.InsertAsync(duplicate); return duplicate; } catch (Exception ex) { _logger.Error(ex, "Failed to create new DuplicateValue item"); } return null; } public async Task<bool> CreatePathDuplicate(Guid jobId, Guid duplicateValueId, string pathFullFileName) { try { var path = await Find(pathFullFileName.ToUpper()); if (path != null) { var pathDuplicate = new PathDuplicate { Id = Guid.NewGuid(), JobId = jobId, DuplicateValueId = duplicateValueId, PathCompareValueId = path.Id }; await _dBContext.Instance.InsertAsync(pathDuplicate); return true; } return false; } catch (Exception ex) { _logger.Error(ex, "Failed to create new PathDuplicate item"); } return false; } public async Task<bool> ClearPathDuplicate(Guid jobId) { try { var pathDuplicates = await _dBContext.Instance.Table<Models.PathDuplicate>().Where(x => x.JobId == jobId).ToListAsync(); foreach (var item in pathDuplicates) { var duplicateValues = await _dBContext.Instance.Table<Models.DuplicateValue>().FirstOrDefaultAsync(x => x.Id == item.DuplicateValueId); if (duplicateValues != null) await _dBContext.Instance.DeleteAsync(duplicateValues); await _dBContext.Instance.DeleteAsync(item); } return true; } catch (Exception ex) { _logger.Error(ex, "Failed to clear Duplicate items"); } return false; } public async Task<bool> ClearCachePathCompareValues() { try { await _dBContext.Instance.DeleteAllAsync<Models.PathCompareValue>(); return true; } catch (Exception ex) { _logger.Error(ex, "Failed to clear PathCompareValue items"); } return false; } public async Task<List<PathCompareValue>> GetAll() { return await _dBContext.Instance.Table<Models.PathCompareValue>().ToListAsync(); } public async Task<bool> ClearCachePathCompareValues(PathCompareValue compareValue) { try { await _dBContext.Instance.DeleteAsync<Models.PathCompareValue>(compareValue); return true; } catch (Exception ex) { _logger.Error(ex, "Failed to delete PathCompareValue items"); } return false; } public async Task<bool> CheckCacheFileExists() { try { var cache = await GetAll(); foreach (var item in cache) { if (!Compare.AccessControl.File(item.FullFile)) { await ClearCachePathCompareValues(item); } } return true; } catch (Exception ex) { _logger.Error(ex, "Failed to execute CheckCacheFileExists"); } return false; } public async Task<bool> ChangeDuplicateResultCache(DuplicateResultProgress duplicateResultProgress, List<DuplicateResultProgressIndex> indices) { try { var item = await GetDuplicateResultCache(duplicateResultProgress.JobId); if (item != null) { item.DateTime = duplicateResultProgress.DateTime; item.Cache = duplicateResultProgress.Cache; await _dBContext.Instance.UpdateAsync(item); } else { item = new DuplicateResultProgress { JobId = duplicateResultProgress.JobId, DateTime = duplicateResultProgress.DateTime, Cache = duplicateResultProgress.Cache }; await _dBContext.Instance.InsertAsync(item); } var index = await GetDuplicateResultIndexCache(duplicateResultProgress.JobId); foreach (var val in indices) { if (!index.Any(x => x.Value == val.Value && x.JobId == val.JobId)) { await _dBContext.Instance.InsertAsync( new DuplicateResultProgressIndex { Id = Guid.NewGuid(), JobId = duplicateResultProgress.JobId, Value = val.Value.ToUpper() }); } } return true; } catch (Exception ex) { _logger.Error(ex, "Failed to change ChangeDuplicateResultCache item"); } return false; } public async Task<bool> RemoveDuplicateResultCache(Guid jobId) { try { var caches = await _dBContext.Instance.Table<Models.DuplicateResultProgress>().Where(x => x.JobId == jobId).ToListAsync(); if (caches != null && caches.Count > 0) { foreach (var item in caches) { await _dBContext.Instance.DeleteAsync(item); } } var cachesIndex = await _dBContext.Instance.Table<Models.DuplicateResultProgressIndex>().Where(x => x.JobId == jobId).ToListAsync(); if (cachesIndex != null && cachesIndex.Count > 0) { foreach (var item in cachesIndex) { await _dBContext.Instance.DeleteAsync(item); } } return true; } catch (Exception ex) { _logger.Error(ex, "Failed to delete RemoveDuplicateResultCache items"); } return false; } public async Task<DuplicateResultProgress> GetDuplicateResultCache(Guid jobId) { return await _dBContext.Instance.Table<Models.DuplicateResultProgress>().FirstOrDefaultAsync(x => x.JobId == jobId); } public async Task<List<DuplicateResultProgressIndex>> GetDuplicateResultIndexCache(Guid jobId) { return await _dBContext.Instance.Table<Models.DuplicateResultProgressIndex>().Where(x => x.JobId == jobId).ToListAsync(); } } }
using System; using System.Collections.Generic; using System.Linq; namespace _02.Selection_Sort { class SelectionSortMain { static void Main(string[] args) { string input = Console.ReadLine(); int[] numbers = input.Split() .Select(int.Parse) .ToArray(); Console.WriteLine("Original array: {0}", string.Join(" ", numbers)); Console.WriteLine("Sorted array: {0}", string.Join(" ", SelectionSort(numbers))); } static int[] SelectionSort(int[] numbers) { List<int> sorted = new List<int>(), unsorted = new List<int>(numbers); for (int i = 0; i < numbers.Length; i++) { int min = unsorted[0]; for (int j = 0; j < unsorted.Count; j++) { if (unsorted[j] < min) { min = unsorted[j]; } } sorted.Add(min); unsorted.Remove(min); } return sorted.ToArray(); } } }
using Vlc.DotNet.Core.Interops; using Vlc.DotNet.Core.Interops.Signatures; namespace Vlc.DotNet.Core { internal sealed class ChapterManagement : IChapterManagement { private readonly VlcManager myManager; private readonly VlcMediaPlayerInstance myMediaPlayer; public ChapterManagement(VlcManager manager, VlcMediaPlayerInstance mediaPlayerInstance) { myManager = manager; myMediaPlayer = mediaPlayerInstance; } public int Count { get { return myManager.GetMediaChapterCount(myMediaPlayer); } } public void Previous() { myManager.SetPreviousMediaChapter(myMediaPlayer); } public void Next() { myManager.SetNextMediaChapter(myMediaPlayer); } public int Current { get { return myManager.GetMediaChapter(myMediaPlayer); } set { myManager.SetMediaChapter(myMediaPlayer, value); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CharacterController : MonoBehaviour { float moveSpeed; float jumpForce; public bool isJumping; bool facingRight; public GameObject rbo2, rbo3, rbo4; public AudioClip JumpSound1; Rigidbody2D rb; Rigidbody2D rb2; Rigidbody2D rb3; Rigidbody2D rb4; // Use this for initialization void Start() { rb = rbo2.GetComponent<Rigidbody2D>(); rb2 = GetComponent<Rigidbody2D>(); rb3 = rbo3.GetComponent<Rigidbody2D>(); rb4 = rbo4.GetComponent<Rigidbody2D>(); facingRight = true; } void FixedUpdate() { moveSpeed = gameObject.GetComponent<ChangeCharacter>().moveSpeed; jumpForce = gameObject.GetComponent<ChangeCharacter>().jumpForce; float xEingabe = Input.GetAxis("Horizontal"); float yEingabe = Input.GetAxis("Vertical"); if (yEingabe < 0 | yEingabe > 0) { return; } float xNeu = transform.position.x + xEingabe * moveSpeed * Time.deltaTime; float yNeu = transform.position.y + yEingabe * jumpForce * Time.deltaTime; transform.position = new Vector3(xNeu, yNeu, 0); Jump(); Flip(); } void Jump() { if (Input.GetKeyDown(KeyCode.Space) && !isJumping) { SoundManager.instance.RandomizeSfx(JumpSound1); isJumping = true; rb.AddForce(new Vector2(rb.velocity.x, jumpForce)); rb2.AddForce(new Vector2(rb2.velocity.x, jumpForce)); rb3.AddForce(new Vector2(rb3.velocity.x, jumpForce)); rb4.AddForce(new Vector2(rb4.velocity.x, jumpForce)); } } private void OnCollisionEnter2D(Collision2D other) { if (other.gameObject.CompareTag("Ground")) { isJumping = false; rb.velocity = Vector2.zero; rb2.velocity = Vector2.zero; rb3.velocity = Vector2.zero; rb4.velocity = Vector2.zero; } } private void Flip() { if ((Input.GetKeyDown(KeyCode.LeftArrow) && facingRight) || (Input.GetKeyDown(KeyCode.RightArrow) && !facingRight)) { facingRight = !facingRight; transform.Rotate(0f, 180f, 0f); } } }
namespace SoftuniNumerals { using System; using System.Numerics; using System.Text; public class Startup { public static void Main(string[] args) { Execute(); } private static void Execute() { var numerals = new string[5]; numerals[4] = "cdc"; numerals[3] = "cc"; numerals[2] = "bcc"; numerals[1] = "aba"; numerals[0] = "aa"; var builder = new StringBuilder(); var line = Console.ReadLine(); while (line.Length > 0) { var changed = false; for (int j = numerals.Length - 1; j >= 0; j--) { if (line.Length >= numerals[j].Length) { if (line.Substring(0, numerals[j].Length) == numerals[j]) { changed = true; line = line.Substring(numerals[j].Length); builder.Append(j.ToString()); } } } if (!changed) { break; } } Console.WriteLine(ConvertToDecimal(builder.ToString())); } private static BigInteger ConvertToDecimal(string base5Num) { BigInteger sum = 0; for (int i = 0; i < base5Num.Length; i++) { sum += int.Parse(base5Num[i].ToString()) * BigInteger.Pow(5, base5Num.Length - i - 1); } return sum; } } }
using System.Collections.Generic; using Zesty.Core.Entities; namespace Zesty.Core.Api.System { public class Languages : ApiHandlerBase { public override ApiHandlerOutput Process(ApiInputHandler input) { return GetOutput(new LanguagesResponse() { List = Business.Languages.List() }); } } public class LanguagesResponse { public List<Entities.Language> List { get; set; } } }
using gView.Framework.IO; using gView.Framework.system; using System; namespace gView.Framework.Symbology { public class SymbolRotation : IPersistable, IClone { private RotationType _rotType = RotationType.aritmetic; private RotationUnit _rotUnit = RotationUnit.deg; private string _rotationFieldName = ""; public RotationType RotationType { get { return _rotType; } set { _rotType = value; } } public RotationUnit RotationUnit { get { return _rotUnit; } set { _rotUnit = value; } } public string RotationFieldName { get { return _rotationFieldName; } set { _rotationFieldName = value; } } public double Convert2DEGAritmetic(double rotation) { //if (_rotType == RotationType.aritmetic && _rotUnit == RotationUnit.deg) // return -rotation; switch (_rotUnit) { case RotationUnit.rad: rotation *= 180.0 / Math.PI; break; case RotationUnit.gon: rotation /= 0.9; break; } switch (_rotType) { case RotationType.aritmetic: rotation = 90 - rotation; break; case RotationType.geographic: //rotation = 90 - rotation; break; } if (rotation < 0.0) { rotation += 360.0; } return rotation; } #region IPersistable Members public string PersistID { get { return ""; } } public void Load(IPersistStream stream) { _rotationFieldName = (string)stream.Load("RotationFieldname", ""); _rotType = (RotationType)stream.Load("RotationType", RotationType.aritmetic); _rotUnit = (RotationUnit)stream.Load("RotationUnit", RotationUnit.deg); } public void Save(IPersistStream stream) { if (_rotationFieldName == "") { return; } stream.Save("RotationFieldname", _rotationFieldName); stream.Save("RotationType", (int)_rotType); stream.Save("RotationUnit", (int)_rotUnit); } #endregion #region IClone Members public object Clone() { SymbolRotation rot = new SymbolRotation(); rot._rotationFieldName = _rotationFieldName; rot._rotType = _rotType; rot._rotUnit = _rotUnit; return rot; } #endregion } }
using HarmonyLib; using UnityEngine; using System.Reflection; using System.Collections.Generic; namespace Navinha { public static class Patches { public static void DoPatches() { Harmony harmonyInstance = new Harmony("com.locochoco.plugin.navinha"); #region VanishVolume MethodInfo VanishVolumeFixedUpdate = AccessTools.Method(typeof(VanishVolume), "FixedUpdate"); MethodInfo VanishVolumeOnTriggerEnter = AccessTools.Method(typeof(VanishVolume), "OnTriggerEnter"); HarmonyMethod fixedUpdatePrefix = new HarmonyMethod(typeof(Patches), nameof(Patches.FixedUpdatePrefix)); HarmonyMethod onTriggerEnterPrefix = new HarmonyMethod(typeof(Patches), nameof(Patches.OnTriggerEnterPrefix)); harmonyInstance.Patch(VanishVolumeFixedUpdate, prefix: fixedUpdatePrefix); harmonyInstance.Patch(VanishVolumeOnTriggerEnter, prefix: onTriggerEnterPrefix); #endregion #region DestructionVolume MethodInfo DestructionVolumeVanish = AccessTools.Method(typeof(DestructionVolume), "Vanish"); HarmonyMethod destructionVanishPrefix = new HarmonyMethod(typeof(Patches), nameof(Patches.DestructionVanishPrefix)); harmonyInstance.Patch(DestructionVolumeVanish, prefix: destructionVanishPrefix); #endregion #region BlackHoleVolume MethodInfo BlackHoleVolumeVanish = AccessTools.Method(typeof(BlackHoleVolume), "Vanish"); MethodInfo BlackHoleVolumeVanishPlayer = AccessTools.Method(typeof(BlackHoleVolume), "VanishPlayer"); HarmonyMethod blackHoleVanishPrefix = new HarmonyMethod(typeof(Patches), nameof(Patches.BlackHoleVanishPrefix)); HarmonyMethod vanishPlayerPrefix = new HarmonyMethod(typeof(Patches), nameof(Patches.VanishPlayerPrefix)); harmonyInstance.Patch(BlackHoleVolumeVanish, prefix: blackHoleVanishPrefix); harmonyInstance.Patch(BlackHoleVolumeVanishPlayer, prefix: vanishPlayerPrefix); #endregion #region WhiteHoleVolume MethodInfo WhiteHoleVolumeReceiveWarpedBody = AccessTools.Method(typeof(WhiteHoleVolume), "ReceiveWarpedBody"); MethodInfo WhiteHoleVolumeAddToGrowQueue = AccessTools.Method(typeof(WhiteHoleVolume), "AddToGrowQueue"); HarmonyMethod receiveWarpedBodyPrefix = new HarmonyMethod(typeof(Patches), nameof(Patches.ReceiveWarpedBodyPrefix)); HarmonyMethod addToGrowQueuePrefix = new HarmonyMethod(typeof(Patches), nameof(Patches.AddToGrowQueuePrefix)); harmonyInstance.Patch(WhiteHoleVolumeReceiveWarpedBody, prefix: receiveWarpedBodyPrefix); harmonyInstance.Patch(WhiteHoleVolumeAddToGrowQueue, prefix: addToGrowQueuePrefix); #endregion } static bool DestructionVanishPrefix(OWRigidbody bodyToVanish, DestructionVolume __instance) { var vanishableObjectComponent = bodyToVanish.GetComponentInChildren<ControlledVanishObject>(); if (vanishableObjectComponent != null) return vanishableObjectComponent.OnDestructionVanish(__instance); return true; } static bool BlackHoleVanishPrefix(OWRigidbody bodyToVanish, BlackHoleVolume __instance) { var vanishableObjectComponent = bodyToVanish.GetComponent<ControlledVanishObject>(); if (vanishableObjectComponent == null) vanishableObjectComponent = bodyToVanish.GetComponentInChildren<ControlledVanishObject>(); if (vanishableObjectComponent != null) return vanishableObjectComponent.OnBlackHoleVanish(__instance); return true; } public delegate bool ConditionsForPlayerToWarp(); public static event ConditionsForPlayerToWarp OnConditionsForPlayerToWarp; static bool VanishPlayerPrefix() { bool condition = true; foreach (var d in OnConditionsForPlayerToWarp.GetInvocationList()) condition &= ((ConditionsForPlayerToWarp)d).Invoke(); return condition; } static bool ReceiveWarpedBodyPrefix(OWRigidbody warpedBody, WhiteHoleVolume __instance) { var vanishableObjectComponent = warpedBody.GetComponent<ControlledVanishObject>(); if (vanishableObjectComponent == null) vanishableObjectComponent = warpedBody.GetComponentInChildren<ControlledVanishObject>(); if (vanishableObjectComponent != null) return vanishableObjectComponent.OnWhiteHoleReceiveWarped(__instance); return true; } static bool AddToGrowQueuePrefix(OWRigidbody bodyToGrow) { var vanishableObjectComponent = bodyToGrow.GetComponent<ControlledVanishObject>(); if (vanishableObjectComponent == null) vanishableObjectComponent = bodyToGrow.GetComponentInChildren<ControlledVanishObject>(); if (vanishableObjectComponent != null) return vanishableObjectComponent.DestroyComponentsOnGrow; return true; } private static Dictionary<VanishVolume, List<ControlledVanishObject>> controlledVanishObjectVolumeList = new Dictionary<VanishVolume, List<ControlledVanishObject>>(); public static void CheckControlledVanishObjectVolumeList() { var keys = controlledVanishObjectVolumeList.Keys; foreach (var key in keys) { if (key == null) controlledVanishObjectVolumeList.Remove(key); } } static bool OnTriggerEnterPrefix(Collider hitCollider, VanishVolume __instance) { if (hitCollider.attachedRigidbody != null) { var vanishableObjectComponent = hitCollider.attachedRigidbody.GetComponent<ControlledVanishObject>(); if (vanishableObjectComponent == null) vanishableObjectComponent = hitCollider.attachedRigidbody.GetComponentInChildren<ControlledVanishObject>(); if (vanishableObjectComponent != null) { if (controlledVanishObjectVolumeList.TryGetValue(__instance, out var list)) { list.Add(vanishableObjectComponent); } else { controlledVanishObjectVolumeList.Add(__instance, new List<ControlledVanishObject> { vanishableObjectComponent }); } return false; } } return true; } static void FixedUpdatePrefix(VanishVolume __instance) { if (controlledVanishObjectVolumeList.TryGetValue(__instance,out var list)) { foreach(var vanishObject in list) { __instance.Vanish(vanishObject.GetAttachedOWRigidbody()); } list.Clear(); } } } }
using System; namespace DelftTools.Utils { /// <summary> /// This class was introduced to support the most simple as possible support for tuples. /// the class DelftTools.DataObjects.Functions.Tuples.Pair has some restrictions. /// see http://luke.breuer.com/time/item/C_Tuple%5BT1,_T2%5D/219.aspx /// TODO in c# use dynamic type see: http://spellcoder.com/blogs/dodyg/archive/2008/10/30/16319.aspx /// </summary> /// <typeparam name="T1"></typeparam> /// <typeparam name="T2"></typeparam> public class Tuple<T1, T2> { public T1 First { get; set; } public T2 Second { get; set; } public Tuple() { } public Tuple(T1 first, T2 second) { if (first == null) throw new ArgumentNullException("first"); if (second == null) throw new ArgumentNullException("second"); First = first; Second = second; } public override int GetHashCode() { return First.GetHashCode() ^ Second.GetHashCode(); } public static bool operator ==(Tuple<T1, T2> a, Tuple<T1, T2> b) { return object.ReferenceEquals(a, b) || (object)a != null && a.Equals(b); } public static bool operator !=(Tuple<T1, T2> a, Tuple<T1, T2> b) { return !(a == b); } public override bool Equals(object obj) { var t = obj as Tuple<T1, T2>; return t != null && t.First.Equals(this.First) && t.Second.Equals(this.Second); } public override string ToString() { return string.Format("First: {0} Second: {1}", First, Second); } } }
namespace AGCompressedAir.Windows.Converters { public class IntToObjectConverter : ToObjectConverter<int> { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using Microsoft.Win32; using MaterialDesignThemes.Wpf; namespace Projet2Cpi { /// <summary> /// Logique d'interaction pour FormulaireAddEvent.xaml /// </summary> public partial class FormulaireAddEvent : UserControl { static int cpt_files; // Ce compteur est pour compter le nombre de fichiers ajoutés OpenFileDialog file; public WindowFormulaires windowParent; public FormulaireAddEvent() { InitializeComponent(); } //Cette fonction, est pour importer des fichiers à l'évènement , en cliquant sur l icon "ImportFile" private void Importfile_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { OpenFileDialog file = new OpenFileDialog(); file.Filter = "Pdf Files (*.pdf)|*.pdf|Excel Files (*.xls)|*.xls|Word Files (*.docx)|*.docx|All files (*.*)|*.*"; file.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); file.Multiselect = true; //On peut selectionner multiple fichiers if (file.ShowDialog() == true) { //Si l'utilisatuer selectionne aucun fichier if (file.FileNames.Length == 0) { cpt_files = 0; //un compteur qui compte le nombre des fichiers selectionnés AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; } //si il selectionne un ficher else if (file.FileNames.Length == 1) { AddfilesCard.Visibility = Visibility.Hidden; //On cache la carte d'ajout et on affiche la carte des chips FilesChipsCard.Visibility = Visibility.Visible; cpt_files = 1; //un compteur qui compte le nombre des fichiers selectionnés File1.Visibility = Visibility.Visible; //On affiche le premiers CHIPS , le seul fichier selectionné File1.Content = file.SafeFileName; //On nomme le chips, par le nom du fichier } // si il selectionne deux fichiers else if (file.FileNames.Length == 2) { AddfilesCard.Visibility = Visibility.Hidden; FilesChipsCard.Visibility = Visibility.Visible; cpt_files = 2; //un compteur qui compte le nombre des fichiers selectionnés File1.Visibility = Visibility.Visible; File2.Visibility = Visibility.Visible; //On GET les noms des deux fichiers selectionnés String[] MergedFile = new String[2]; int cpt = 0; foreach (string filename in file.SafeFileNames) { MergedFile[cpt] = filename; cpt++; } //On nomme les chips et leurs TOOLTIP par les noms des fichiers File1.Content = MergedFile[0]; File1.ToolTip = MergedFile[0]; File2.Content = MergedFile[1]; File2.ToolTip = MergedFile[1]; } // si il selectionne trois fichiers else if (file.FileNames.Length == 3) { AddfilesCard.Visibility = Visibility.Hidden; FilesChipsCard.Visibility = Visibility.Visible; cpt_files = 3; //un compteur qui compte le nombre des fichiers selectionnés File1.Visibility = Visibility.Visible; //On affiche tous les CHIPS File2.Visibility = Visibility.Visible; File3.Visibility = Visibility.Visible; //On GET les noms des deux fichiers selectionnés String[] MergedFile = new String[3]; int cpt = 0; foreach (string filename in file.SafeFileNames) { MergedFile[cpt] = filename; cpt++; } //On nomme les chips et leurs TOOLTIP par les noms des fichiers File1.Content = MergedFile[0]; File1.ToolTip = MergedFile[0]; File2.Content = MergedFile[1]; File2.ToolTip = MergedFile[1]; File3.Content = MergedFile[2]; File3.ToolTip = MergedFile[2]; } // s'il selectionne plus de trois fichiers else if (file.FileNames.Length > 3) { MessageBox.Show("You have to select just 3 files"); cpt_files = 0; //un compteur qui compte le nombre des fichiers selectionnés } } } private void Chip_Delete(object sender, RoutedEventArgs e) { } //Cette fonction est pour l'ajout des contactes en tappant sur clavier //Still needs to verify if the name typed is one of the contacts or no //still needs to make the list of the contacts beggins with the first letter appear while typing //Still needs to do the function of the delete click on it ! //Still needs to adapt the width of the chip according to the length of the contact' name private void CommentTextBox_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Enter) { Chip ch = new Chip(); ch.Height = 30; ch.Width = 120; Thickness margin = ch.Margin; margin.Right += 5; ch.Margin = margin; ch.Content = ((TextBox)sender).Text; try { //string ic = new String(((TextBox)sender).Text[0], 1); //ch.Icon = ic.ToUpper(); ch.IsDeletable = true; ((TextBox)sender).Text = ""; chips.Children.Add(ch); } catch (Exception) { } } } //Les trois fonctions ci dessous sont pour supprimer les Chips des fichiers selectionnés //En effet, pour le moment cettes fonctions manipulent seulement l affichage //Je propose lors la création de l objet event , on vérifie d'abord les CHIPS qui sont VISIBLES,puis on enregistre leurs données private void File1_DeleteClick(object sender, RoutedEventArgs e) { File1.Visibility = Visibility.Hidden; //Si le premier fichiers est supprimée, on cache son CHIP , puis on modifie le MARGIN GAUCHE du CHIP qui le suit Thickness margin = File2.Margin; margin.Left = -100; File2.Margin = margin; cpt_files -= 1; if (cpt_files == 0) //Si tous les fichiers sont supprimés, on cache la carte des fichiers ajoutés et on affiche la carte d'ajout des fichiers { AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; margin.Left += 105; File3.Margin = margin; margin = File2.Margin; margin.Left += 105; File2.Margin = margin; } } private void File2_DeleteClick(object sender, RoutedEventArgs e) { File2.Visibility = Visibility.Hidden; Thickness margin = File3.Margin; margin.Left = -100; File3.Margin = margin; cpt_files -= 1; if (cpt_files == 0) { AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; margin.Left += 105; File3.Margin = margin; margin = File2.Margin; margin.Left += 105; File2.Margin = margin; } } private void File3_DeleteClick(object sender, RoutedEventArgs e) { File3.Visibility = Visibility.Hidden; cpt_files -= 1; Thickness margin = File3.Margin; if (cpt_files == 0) { AddfilesCard.Visibility = Visibility.Visible; FilesChipsCard.Visibility = Visibility.Hidden; margin.Left += 105; File3.Margin = margin; margin = File2.Margin; margin.Left += 105; File2.Margin = margin; } } //Cette fonction,est pour l'ajout du deuxiéme alarme , en cliquant sur l icon d'ajout à droite private void AddAlarme1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (ComboBoxAlarmType1.SelectedIndex == -1 || DatePickeralarm1.SelectedDate == null || TimePickeralarm1.SelectedTime == null) { MessageBox.Show("Vous devez d'abord introduire toutes les données du la première alarme !"); } else { AddAlarme1.Visibility = Visibility.Hidden; DeleteAlarme1.Visibility = Visibility.Hidden; AlarmWrapPanel2.Visibility = Visibility.Visible; } } //Cette fonction , va supprimer les données déja entrés pour la première alarme //Les instructions de cette fonction, peuvent être comme des conditions à la création d objet EVENEMENT aprés ! private void DeleteAlarme1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { ComboBoxAlarmType1.SelectedIndex = -1; DatePickeralarm1.SelectedDate = null; TimePickeralarm1.SelectedTime = null; } //Cette fonction , va cacher le WRAPPANEL ayant les PICKERS de la deuxiéme alarme, et les mis à NULL //Lors la création d'objet EVENEMENT aprés, vous pouver également tester si le "AlarmWrapPanel2" est VISIBLE , ou si le PICKERS sont à null et le Comboboxselectedindex est à -1 private void DeleteAlarme2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { ComboBoxAlarmType2.SelectedIndex = -1; DatePickeralarm2.SelectedDate = null; TimePickeralarm2.SelectedTime = null; AlarmWrapPanel2.Visibility = Visibility.Hidden; AddAlarme1.Visibility = Visibility.Visible; DeleteAlarme1.Visibility = Visibility.Visible; } //Cette fonction,est pour l'ajout du troisiéme alarme , en cliquant sur l icon d'ajout à droite private void AddAlarme2_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (ComboBoxAlarmType2.SelectedIndex == -1 || DatePickeralarm2.SelectedDate == null || TimePickeralarm2.SelectedTime == null) { MessageBox.Show("Vous devez d'abord introduire toutes les données du la deuxième alarme !"); } else { AddAlarme2.Visibility = Visibility.Hidden; DeleteAlarme2.Visibility = Visibility.Hidden; AlarmWrapPanel3.Visibility = Visibility.Visible; } } //Cette fonction , va cacher le WRAPPANEL ayant les PICKERS de la troisiéme alarme, et les mis à NULL //Lors la création d'objet EVENEMENT aprés, vous pouver également tester si le "AlarmWrapPanel3" est HIDDEN , ou si le PICKERS sont à null et le Comboboxselectedindex est à -1 private void DeleteAlarme3_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { ComboBoxAlarmType3.SelectedIndex = -1; DatePickeralarm3.SelectedDate = null; TimePickeralarm3.SelectedTime = null; AlarmWrapPanel3.Visibility = Visibility.Hidden; AddAlarme2.Visibility = Visibility.Visible; DeleteAlarme2.Visibility = Visibility.Visible; } private void ButtonAddEvent_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { Evenement ev = new Evenement(); if (debutDatePicker.SelectedDate == null) { MessageBox.Show("Please select a day"); return; } ev.DateDebut = debutDatePicker.SelectedDate.Value; ev.Title = TextboxTitre.Text; ev.Description = TextBoxDescription.Text; DataSupervisor.ds.AddEvenement(ev); windowParent.Close(); } private void ButtonCancel_MouseLeftButtonDown(object sender, MouseButtonEventArgs e) { windowParent.Close(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Text; namespace ExceptionHandling { public class TryCatchFinally { public static void HandleWithTryCatchFinally() { var streamReader = new StreamReader(@"c:\file.zip"); try { Console.WriteLine(Calculator.Divide(56, 0)); } catch (Exception e) { Console.WriteLine("Sorry there was an unexpected error!"); Console.WriteLine(e); } finally { streamReader.Dispose(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Castle.Services.Transaction; using com.Sconit.Entity.ORD; using com.Sconit.Entity.Exception; using com.Sconit.Entity.INV; using com.Sconit.Utility; namespace com.Sconit.Service { public class SQLocationDetailMgrImpl : BaseMgr, ISQLocationDetailMgr { public ILocationDetailMgr locationDetailMgr { get; set; } public IGenericMgr genericMgr { get; set; } public INumberControlMgr numberControlMgr { get; set; } public IHuMgr huMgr { get; set; } [Transaction(TransactionMode.Requires)] public IList<Hu> MatchNewHuForRepack(IList<OrderDetail> orderDetailList, Boolean isJIT, BusinessException businessException) { #region 变量 // BusinessException businessException = new BusinessException(); List<Hu> huList = new List<Hu>(); List<InventoryOccupy> inventoryOccupyList = new List<InventoryOccupy>(); decimal totalQty = 0m; string oldHus = string.Empty; #endregion #region 检查发货单是否有占用的条码,有的话需要用当前数量减去已匹配数量 string hql = string.Empty; List<object> paras = new List<object>(); foreach (OrderDetail orderDetail in orderDetailList) { if (string.IsNullOrEmpty(hql)) { hql = "from HuMapping where IsEffective = 0 and OrderDetId in(?"; } else { hql += ", ?"; } paras.Add(orderDetail.Id); } hql += ")"; IList<HuMapping> huMappingList = this.genericMgr.FindAll<HuMapping>(hql, paras.ToArray()); if (huMappingList.Count > 0) { foreach (OrderDetail orderDetail in orderDetailList) { orderDetail.OrderedQty = orderDetail.OrderedQty - huMappingList.Where(o => o.OrderDetId == orderDetail.Id).Sum(o => o.Qty); } } #endregion #region 翻箱 orderDetailList = orderDetailList.Where(o => o.RemainShippedQty > 0).ToList(); if (orderDetailList.Count == 0) { businessException.AddMessage("没有需要打印翻箱标签得要货明细。"); return huList; } IList<string> itemList = orderDetailList.Select(o => o.Item).Distinct().ToList(); foreach (var item in itemList) { #region 查看库存是否满足要货需求 totalQty = 0m; oldHus = string.Empty; var groupOrderDetailList = orderDetailList.Where(o => o.Item == item).ToList(); var locationLotDetailList = genericMgr.FindAllWithNamedQuery<LocationLotDetail>("USP_Busi_GetAotuPickInventory", new Object[] { groupOrderDetailList[0].LocationFrom, groupOrderDetailList[0].Item, groupOrderDetailList[0].QualityType, 0, false, true }).OrderBy(l => l.Qty).ThenBy(l => l.LotNo).ToList(); var matchLocationLotDetailList = new List<LocationLotDetail>(); if (locationLotDetailList.Count == 0) { businessException.AddMessage("零件{0}在库位{1}中没有库存。", groupOrderDetailList[0].Item, groupOrderDetailList[0].LocationFrom); continue; } if (locationLotDetailList.Where(l => l.OccupyType == CodeMaster.OccupyType.None).Sum(l => l.Qty) < groupOrderDetailList.Sum(g => g.RemainShippedQty)) { businessException.AddMessage("物料{0}的库存数量{1}不满足本次要货数{2}。", item, locationLotDetailList.Where(l => l.OccupyType == CodeMaster.OccupyType.None).Sum(l => l.Qty).ToString("0.######"), groupOrderDetailList.Sum(g => g.RemainShippedQty).ToString("0.######")); } #endregion #region JIT件每条明细一张条码 if (isJIT == true) { try { //如果有数量能直接匹配上零头箱的,那么就直接将这个匹配 var oddMatchedlocationLotDetailList = (from l in locationLotDetailList from g in groupOrderDetailList where g.Item == l.Item && g.RemainShippedQty == l.Qty select new LocationLotDetail { Area = l.Area, BaseUom = l.BaseUom, Bin = l.Bin, BinSequence = l.BinSequence, ConsigementParty = l.ConsigementParty, CreateDate = l.CreateDate, CreateUserId = l.CreateUserId, CreateUserName = l.CreateUserName, FirstInventoryDate = l.FirstInventoryDate, HuId = l.HuId, HuQty = l.HuQty, HuUom = l.HuUom, Id = l.Id, IsATP = l.IsATP, IsConsignment = l.IsConsignment, IsFreeze = l.IsFreeze, IsOdd = l.IsOdd, Item = l.Item, ItemDescription = l.ItemDescription, LastModifyDate = l.LastModifyDate, LastModifyUserId = l.LastModifyUserId, LastModifyUserName = l.LastModifyUserName, Location = l.Location, LotNo = l.LotNo, ManufactureDate = l.ManufactureDate, ManufactureParty = l.ManufactureParty, OccupyReferenceNo = l.OccupyReferenceNo, OccupyType = l.OccupyType, PlanBill = l.PlanBill, Qty = l.Qty, QualityType = l.QualityType, ReferenceItemCode = l.ReferenceItemCode, UnitCount = l.UnitCount, UnitQty = l.UnitQty, Version = l.Version }); if (oddMatchedlocationLotDetailList.Count() > 0) { var oddMatchedlocationLotDetail = oddMatchedlocationLotDetailList.FirstOrDefault(); var oddMatchedOrderDetail = groupOrderDetailList.FirstOrDefault(o => o.RemainShippedQty == oddMatchedlocationLotDetail.Qty && o.Item == oddMatchedlocationLotDetail.Item); huList.AddRange(this.huMgr.CreateHu(oddMatchedOrderDetail, false, oddMatchedlocationLotDetail.ManufactureParty, oddMatchedlocationLotDetail.LotNo, oddMatchedlocationLotDetail.Qty, oddMatchedlocationLotDetail.Qty, oddMatchedlocationLotDetail.Qty, oddMatchedlocationLotDetail.HuId, oddMatchedOrderDetail.BinTo, true)); this.genericMgr.Update(oddMatchedlocationLotDetail); locationLotDetailList.Remove(oddMatchedlocationLotDetail); groupOrderDetailList.Remove(oddMatchedOrderDetail); } //将剩下的全部翻箱 var groupItemQty = groupOrderDetailList.Sum(g => g.RemainShippedQty); foreach (var locationLotDetail in locationLotDetailList) { totalQty += locationLotDetail.Qty; oldHus += locationLotDetail.HuId + ";"; InventoryOccupy inventoryOccupy = new InventoryOccupy(); inventoryOccupy.HuId = locationLotDetail.HuId; inventoryOccupy.Location = locationLotDetail.Location; inventoryOccupy.QualityType = locationLotDetail.QualityType; inventoryOccupy.OccupyType = CodeMaster.OccupyType.Pick; inventoryOccupy.OccupyReferenceNo = string.Empty; inventoryOccupyList.Add(inventoryOccupy); //locationLotDetail.OccupyType = CodeMaster.OccupyType.AutoPick; //this.genericMgr.Update(locationLotDetail); matchLocationLotDetailList.Add(locationLotDetail); if (totalQty >= groupItemQty) { break; } } foreach (var orderDetail in groupOrderDetailList) { if (totalQty - orderDetail.RemainShippedQty >= 0) { totalQty = totalQty - orderDetail.RemainShippedQty; huList.AddRange(this.huMgr.CreateHu(orderDetail, true, matchLocationLotDetailList[0].ManufactureParty, LotNoHelper.GenerateLotNo(DateTime.Now), orderDetail.RemainShippedQty, orderDetail.RemainShippedQty, orderDetail.RemainShippedQty, oldHus, orderDetail.BinTo, true)); } else { if (totalQty == 0m) { break; } else { huList.AddRange(this.huMgr.CreateHu(orderDetail, true, matchLocationLotDetailList[0].ManufactureParty, LotNoHelper.GenerateLotNo(DateTime.Now), totalQty, totalQty, totalQty, oldHus, orderDetail.BinTo, true)); totalQty = 0m; } } } if (totalQty > 0m) { huList.AddRange(this.huMgr.CreateHu(groupOrderDetailList[0], true, matchLocationLotDetailList[0].ManufactureParty, LotNoHelper.GenerateLotNo(DateTime.Now), totalQty, totalQty, totalQty, oldHus, string.Empty, false)); } } catch (BusinessException be) { businessException.AddMessage(be.GetMessages()[0].GetMessageString()); } } #endregion #region 看板件需求必须是UC的整数倍,零头不管 else { foreach (var orderDetail in groupOrderDetailList) { if (locationLotDetailList.Where(l => l.IsOdd == false && l.Qty == orderDetail.UnitCount).Count() <= 0) { businessException.AddMessage("零件{0}的包装数不满足要货的包装数。", orderDetail.Item ); } if (orderDetail.RemainShippedQty % orderDetail.UnitCount != 0) { businessException.AddMessage("要货单{0}中的看板件{1}的要货需求有零头数{2},系统无法自动翻箱。", orderDetail.OrderNo, orderDetail.Item, (orderDetail.RemainShippedQty % orderDetail.UnitCount).ToString()); } totalQty = 0m; oldHus = string.Empty; for (int i = 0; i < orderDetail.RemainShippedQty / orderDetail.UnitCount; ++i) { if (locationLotDetailList.Where(l => l.IsOdd == false && l.Qty == orderDetail.UnitCount).Count() > 0) { var oneIntPack = locationLotDetailList.FirstOrDefault(l => l.IsOdd == false && l.Qty == orderDetail.UnitCount); huList.AddRange(this.huMgr.CreateHu(orderDetail, false, oneIntPack.ManufactureParty, oneIntPack.LotNo, orderDetail.UnitCount, orderDetail.UnitCount, orderDetail.UnitCount, oneIntPack.HuId, orderDetail.BinTo, true)); InventoryOccupy inventoryOccupy = new InventoryOccupy(); inventoryOccupy.HuId = oneIntPack.HuId; inventoryOccupy.Location = oneIntPack.Location; inventoryOccupy.QualityType = oneIntPack.QualityType; inventoryOccupy.OccupyType = CodeMaster.OccupyType.Pick; inventoryOccupy.OccupyReferenceNo = string.Empty; inventoryOccupyList.Add(inventoryOccupy); locationLotDetailList.Remove(oneIntPack); //oneIntPack.OccupyType = CodeMaster.OccupyType.AutoPick; //this.genericMgr.Update(oneIntPack); } } } } #endregion #region 库存占用 try { if (inventoryOccupyList.Count > 0) { this.locationDetailMgr.InventoryOccupy(inventoryOccupyList); } } catch (BusinessException be) { businessException.AddMessage(be.GetMessages()[0].GetMessageString()); } #endregion } return huList; #endregion } [Transaction(TransactionMode.Requires)] public void DistributionLabelCancel(string HuId) { HuMapping hm = this.genericMgr.FindAll<HuMapping>("select h from HuMapping as h where HuId=?", HuId)[0]; if (hm.IsEffective) { throw new BusinessException("条码{0}已经配送,不能取消。", HuId); } this.genericMgr.Delete(hm); string[] oldHuIdArray = hm.OldHus.Split(';'); string hql = string.Empty; IList<object> parm = new List<object>(); foreach (string oldHuId in oldHuIdArray) { if (!string.IsNullOrEmpty(oldHuId)) { if (string.IsNullOrEmpty(hql)) { hql = "select l from LocationLotDetail as l where HuId in ( ?"; } else { hql += ",?"; } parm.Add(oldHuId); } } hql += ")"; IList<LocationLotDetail> locLotDetList = this.genericMgr.FindAll<LocationLotDetail>(hql, parm.ToArray()); foreach (LocationLotDetail item in locLotDetList) { item.OccupyType = 0; this.genericMgr.Update(item); } } } }
using System.Collections.Generic; using System.Net.Http; using Microsoft.Extensions.Configuration; using WebStore.DomainNew.Dto; using WebStore.DomainNew.ViewModels; using WebStore.Interfaces; namespace WebStore.Clients.Services { public class OrdersClient : BaseClient, IOrderService { public OrdersClient(IConfiguration configuration) : base(configuration) { ServiceAddress = "api/orders"; } public IEnumerable<OrderDto> GetUserOrders(string userName) { var orders = Get<List<OrderDto>>($"{ServiceAddress}/user/{userName}"); return orders; } public OrderDto GetOrderById(int id) { var order = Get<OrderDto>($"{ServiceAddress}/{id}"); return order; } public OrderDto CreateOrder(CreateOrderDto createOrderDto, string userName) { var response = Post($"{ServiceAddress}/{userName}", createOrderDto); return response.Content.ReadAsAsync<OrderDto>().Result; } } }
namespace Uintra.Features.Search.Extensions { public static class SearchExtensions { public static string CropText(this string text, int sizeToCrop) { if (!string.IsNullOrEmpty(text) && text.Length > sizeToCrop * 2 && !text.Contains(SearchConstants.Global.HighlightPreTag)) { return text.Substring(text.Length - sizeToCrop) + "..."; } return text; } } }
using System; namespace Apache.Shiro.Util { public abstract class AbstractFactory<T> : IFactory<T> { private T singletonInstance; public AbstractFactory() { Singleton = true; } public T Instance { get { T instance; if (Singleton) { if (singletonInstance == null) { singletonInstance = CreateInstance(); } instance = singletonInstance; } else { instance = CreateInstance(); } if (instance == null) { throw new NullReferenceException("AbstractFactory.CreateInstance() returned a null object"); } return instance; } } public bool Singleton { get; set; } protected abstract T CreateInstance(); } }
using LocusNew.Controllers; using LocusNew.Persistence; using LocusNew.Core.Models; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.EntityFramework; using System.Data.Entity; using System.Web.Http; using System.Web.Mvc; using Unity; using Unity.Injection; using Unity.WebApi; using LocusNew.Core; using LocusNew.Core.Repositories; using LocusNew.Persistence.Repositories; using Unity.Lifetime; using Microsoft.Owin.Security; using System.Web; namespace LocusNew { public static class UnityConfig { public static void RegisterComponents() { var container = new UnityContainer(); // register all your components with the container here // it is NOT necessary to register your controllers // e.g. container.RegisterType<ITestService, TestService>(); container.RegisterType<AccountController>(new InjectionConstructor()); container.RegisterType<DbContext, ApplicationDbContext>(new HierarchicalLifetimeManager()); container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager()); container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager()); container.RegisterType<IAuthenticationManager>( new InjectionFactory(o => System.Web.HttpContext.Current.GetOwinContext().Authentication)); container.RegisterType<IUnitOfWork, UnitOfWork>(); container.RegisterType<ICityPartsRepository, CityPartsRepository>(); container.RegisterType<IGlobalSettingsRepository, GlobalSettingsRepository>(); container.RegisterType<ILeadsRepository, LeadsRepository>(); container.RegisterType<IListingImagesRepository, ListingImagesRepository>(); container.RegisterType<IListingsRepository, ListingsRepository>(); container.RegisterType<IPropertyBuyersRepository, PropertyBuyersRepository>(); container.RegisterType<IPropertyOwnersRepository, PropertyOwnersRepository>(); container.RegisterType<IPropertyTypesRepository, PropertyTypesRepository>(); container.RegisterType<ISellerLeadsRepository, SellerLeadsRepository>(); container.RegisterType<IShowingsRepository, ShowingsRepository>(); container.RegisterType<IUsersRepository, UsersRepository>(); DependencyResolver.SetResolver(new Unity.Mvc5.UnityDependencyResolver(container)); GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container); } } }
using System; using System.Collections.Generic; namespace CollaborativeFiltering { public class DefaultVoting : PearsonCorrelation { private readonly double _defaultValue; public DefaultVoting(IEnumerable<IRating> ratings, double defaultValue) : base(ratings) { _defaultValue = defaultValue; } protected override IRatingService GetRatingService() { return new RatingHelperDefaulter(_defaultValue); } public override string ToString() { return "Default voting"; } } }
using AlgorithmProblems.Arrays.ArraysHelper; using AlgorithmProblems.matrix_problems.Helper; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AlgorithmProblems.Dynamic_Programming { /// <summary> /// Given the times taken by the jobs in an array and also the number of people to whom these jobs can be assigned. /// A group of consecutive jobs can be assigned to a person. /// Find the min time taken to finish all the jobs in the input array, given k people. /// /// Basically this problem can be restated as follows: /// Given the arr, divide the array into k partitions such that the max sum in any partion is the minimum. /// </summary> class JobSchedullingWithConstraints { #region RecursiveSolution with memoization /// <summary> /// In the recursive solution, We first assign task1 to p1 and call the recursive function with tasklist - task1 and personList - p1. /// Then we assign t1 and t2 to p1 and call the recursive function with tasklist - (t1,t2) and personList - (p1). /// We keep doing this till we assign all the tasks to person p1. /// Find the min and that would be the time taken to complete all the tasks with k people. /// /// Also use memoization for not calculating the same subproblems again and again. /// /// The running time is O(n^2*k) where n is the total number of jobs and k is the total number of people /// The space requirement is O(n*k) needed to save the matrix /// </summary> /// <param name="arr"></param> /// <param name="k"></param> /// <param name="currentIndex"></param> /// <param name="memoization"></param> /// <returns></returns> public static int GetMinTimeTaken(ref int[] arr, int k, int currentIndex, ref int[,] memoization) { if(currentIndex >= arr.Length && k>=0) { // People are left but the work is finished return 0; } else if(currentIndex <arr.Length && k<=0) { // No people, but the work is left return int.MaxValue; } if(memoization[k, currentIndex] != -1) { return memoization[k, currentIndex]; } int timeIfKthPersonWorks = 0; int minTimeTaken = int.MaxValue; for(int i= currentIndex; i<arr.Length; i++) { timeIfKthPersonWorks += arr[i]; int minTimeFromRemainigWork = GetMinTimeTaken(ref arr, k - 1, i+1, ref memoization); if(minTimeTaken > Math.Max(timeIfKthPersonWorks, minTimeFromRemainigWork)) { minTimeTaken = Math.Max(timeIfKthPersonWorks, minTimeFromRemainigWork); } } memoization[k, currentIndex] = minTimeTaken; return minTimeTaken; } #endregion #region Dynamic Programming /// <summary> /// In the dynamic programming approach: /// Initialize for case when we have only person. /// Then loop till we have considered all k people. /// Foreach person assign him tasks t1 to tn and get the min time taken and put it in the currentArr /// /// The running time is O(n^2*k) where n is the total number of jobs and k is the total number of people /// The space requirement is O(n) needed to save the pevious row for the p-1 people case. /// </summary> /// <param name="arr"></param> /// <param name="k"></param> /// <returns></returns> public static int GetMinTimeTakenDP(int[] arr, int k) { if(arr == null || arr.Length ==0) { // When we have no jobs return 0; } if (k <= 0) { // When we have no people to assign the job return int.MaxValue; } int p = 1; int[] arrForPPeople = new int[arr.Length]; for(int i=0; i<arr.Length; i++) { arrForPPeople[i] = (i - 1 >= 0) ? arrForPPeople[i - 1] + arr[i] : arr[i]; } while (p <= k) { int[] currentArr = new int[arr.Length]; currentArr.Populate(int.MaxValue); for(int i=0; i< arr.Length; i++) { int currentWork = 0; for(int j= i; j>=0; j--) { currentWork += arr[j]; int restWorkDoneByPreviousPeople = (j - 1 >= 0) ? arrForPPeople[j - 1] : 0; if(currentArr[i] > Math.Max(currentWork, restWorkDoneByPreviousPeople)) { currentArr[i] = Math.Max(currentWork, restWorkDoneByPreviousPeople); } } } arrForPPeople = currentArr; p++; } return arrForPPeople[arr.Length - 1]; } #endregion public static void TestJobSchedullingWithConstraints() { int[] arr = new int[] { 1, 3, 5 }; int k = 2; int[,] memoization = new int[k+1, arr.Length]; memoization.Populate(-1); Console.WriteLine("Recursive method: The min time taken is {0}. Expected:5", GetMinTimeTaken(ref arr, k, 0, ref memoization)); Console.WriteLine("DP method: The min time taken is {0}. Expected:5", GetMinTimeTakenDP(arr, k)); arr = new int[] { 1, 2, 3, 4, 5, 9 }; k = 3; memoization = new int[k + 1, arr.Length]; memoization.Populate(-1); Console.WriteLine("Recursive method: The min time taken is {0}. Expected:9", GetMinTimeTaken(ref arr, k, 0, ref memoization)); Console.WriteLine("DP method: The min time taken is {0}. Expected:9", GetMinTimeTakenDP(arr, k)); arr = new int[] { 1, 1,1,1,1,1,1,1,1, 4, 5, 9 }; k = 3; memoization = new int[k + 1, arr.Length]; memoization.Populate(-1); Console.WriteLine("Recursive method: The min time taken is {0}. Expected:9", GetMinTimeTaken(ref arr, k, 0, ref memoization)); Console.WriteLine("DP method: The min time taken is {0}. Expected:9", GetMinTimeTakenDP(arr, k)); arr = new int[] { }; k = 3; memoization = new int[k + 1, arr.Length]; memoization.Populate(-1); Console.WriteLine("Recursive method: The min time taken is {0}. Expected:0", GetMinTimeTaken(ref arr, k, 0, ref memoization)); Console.WriteLine("DP method: The min time taken is {0}. Expected:0", GetMinTimeTakenDP(arr, k)); arr = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 9 }; k = 0; memoization = new int[k + 1, arr.Length]; memoization.Populate(-1); Console.WriteLine("Recursive method: The min time taken is {0}. Expected:int.Max", GetMinTimeTaken(ref arr, k, 0, ref memoization)); Console.WriteLine("DP method: The min time taken is {0}. Expected:int.Max", GetMinTimeTakenDP(arr, k)); arr = new int[] { 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 5, 9 }; k = 100; memoization = new int[k + 1, arr.Length]; memoization.Populate(-1); Console.WriteLine("Recursive method: The min time taken is {0}. Expected:9", GetMinTimeTaken(ref arr, k, 0, ref memoization)); Console.WriteLine("DP method: The min time taken is {0}. Expected:9", GetMinTimeTakenDP(arr, k)); } } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace WebsiteManagerPanel.Migrations { public partial class UpdateMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.DropForeignKey( name: "FK_User_User_CreatedBy", table: "User"); migrationBuilder.DropForeignKey( name: "FK_User_User_ModifiedBy", table: "User"); migrationBuilder.DropTable( name: "AdditionalFieldValues"); migrationBuilder.DropIndex( name: "IX_User_CreatedBy", table: "User"); migrationBuilder.DropIndex( name: "IX_User_ModifiedBy", table: "User"); migrationBuilder.DropColumn( name: "CreateDate", table: "User"); migrationBuilder.DropColumn( name: "CreatedBy", table: "User"); migrationBuilder.DropColumn( name: "IsActive", table: "User"); migrationBuilder.DropColumn( name: "ModifiedBy", table: "User"); migrationBuilder.DropColumn( name: "ModifyDate", table: "User"); migrationBuilder.DropColumn( name: "IsArray", table: "AdditionalFields"); migrationBuilder.DropColumn( name: "IsSearchable", table: "AdditionalFields"); migrationBuilder.DropColumn( name: "ShowInGrid", table: "AdditionalFields"); migrationBuilder.DropColumn( name: "Sort", table: "AdditionalFields"); migrationBuilder.DropColumn( name: "Type", table: "AdditionalFields"); migrationBuilder.CreateTable( name: "Fields", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), DefinitionId = table.Column<int>(type: "int", nullable: true), Name = table.Column<string>(type: "nvarchar(max)", nullable: true), Type = table.Column<int>(type: "int", nullable: false), CreateDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "GETDATE()"), CreatedBy = table.Column<int>(type: "int", nullable: false), ModifyDate = table.Column<DateTime>(type: "datetime2", nullable: true), ModifiedBy = table.Column<int>(type: "int", nullable: true), IsActive = table.Column<bool>(type: "bit", nullable: false, defaultValue: true) }, constraints: table => { table.PrimaryKey("PK_Fields", x => x.Id); table.ForeignKey( name: "FK_Fields_AdditionalFields_DefinitionId", column: x => x.DefinitionId, principalTable: "AdditionalFields", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Fields_User_CreatedBy", column: x => x.CreatedBy, principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_Fields_User_ModifiedBy", column: x => x.ModifiedBy, principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateTable( name: "FieldValue", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), FieldId = table.Column<int>(type: "int", nullable: true), Value = table.Column<string>(type: "nvarchar(max)", nullable: true), CreateDate = table.Column<DateTime>(type: "datetime2", nullable: false), CreateUserId = table.Column<int>(type: "int", nullable: false), ModifyDate = table.Column<DateTime>(type: "datetime2", nullable: true), ModifyUserId = table.Column<int>(type: "int", nullable: true), IsActive = table.Column<bool>(type: "bit", nullable: false) }, constraints: table => { table.PrimaryKey("PK_FieldValue", x => x.Id); table.ForeignKey( name: "FK_FieldValue_Fields_FieldId", column: x => x.FieldId, principalTable: "Fields", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_FieldValue_User_CreateUserId", column: x => x.CreateUserId, principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Cascade); table.ForeignKey( name: "FK_FieldValue_User_ModifyUserId", column: x => x.ModifyUserId, principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_Fields_CreatedBy", table: "Fields", column: "CreatedBy"); migrationBuilder.CreateIndex( name: "IX_Fields_DefinitionId", table: "Fields", column: "DefinitionId"); migrationBuilder.CreateIndex( name: "IX_Fields_ModifiedBy", table: "Fields", column: "ModifiedBy"); migrationBuilder.CreateIndex( name: "IX_FieldValue_CreateUserId", table: "FieldValue", column: "CreateUserId"); migrationBuilder.CreateIndex( name: "IX_FieldValue_FieldId", table: "FieldValue", column: "FieldId"); migrationBuilder.CreateIndex( name: "IX_FieldValue_ModifyUserId", table: "FieldValue", column: "ModifyUserId"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "FieldValue"); migrationBuilder.DropTable( name: "Fields"); migrationBuilder.AddColumn<DateTime>( name: "CreateDate", table: "User", type: "datetime2", nullable: false, defaultValueSql: "GETDATE()"); migrationBuilder.AddColumn<int>( name: "CreatedBy", table: "User", type: "int", nullable: false, defaultValue: 0); migrationBuilder.AddColumn<bool>( name: "IsActive", table: "User", type: "bit", nullable: false, defaultValue: true); migrationBuilder.AddColumn<int>( name: "ModifiedBy", table: "User", type: "int", nullable: true); migrationBuilder.AddColumn<DateTime>( name: "ModifyDate", table: "User", type: "datetime2", nullable: true); migrationBuilder.AddColumn<bool>( name: "IsArray", table: "AdditionalFields", type: "bit", nullable: false, defaultValue: false); migrationBuilder.AddColumn<bool>( name: "IsSearchable", table: "AdditionalFields", type: "bit", nullable: false, defaultValue: false); migrationBuilder.AddColumn<bool>( name: "ShowInGrid", table: "AdditionalFields", type: "bit", nullable: false, defaultValue: false); migrationBuilder.AddColumn<byte>( name: "Sort", table: "AdditionalFields", type: "tinyint", nullable: true); migrationBuilder.AddColumn<int>( name: "Type", table: "AdditionalFields", type: "int", nullable: false, defaultValue: 0); migrationBuilder.CreateTable( name: "AdditionalFieldValues", columns: table => new { Id = table.Column<int>(type: "int", nullable: false) .Annotation("SqlServer:Identity", "1, 1"), AdditionalFieldId = table.Column<int>(type: "int", nullable: true), CreateDate = table.Column<DateTime>(type: "datetime2", nullable: false, defaultValueSql: "GETDATE()"), CreatedBy = table.Column<int>(type: "int", nullable: false), IsActive = table.Column<bool>(type: "bit", nullable: false, defaultValue: true), ModifyDate = table.Column<DateTime>(type: "datetime2", nullable: true), ModifiedBy = table.Column<int>(type: "int", nullable: true), Value = table.Column<string>(type: "nvarchar(max)", nullable: true) }, constraints: table => { table.PrimaryKey("PK_AdditionalFieldValues", x => x.Id); table.ForeignKey( name: "FK_AdditionalFieldValues_AdditionalFields_AdditionalFieldId", column: x => x.AdditionalFieldId, principalTable: "AdditionalFields", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_AdditionalFieldValues_User_CreatedBy", column: x => x.CreatedBy, principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); table.ForeignKey( name: "FK_AdditionalFieldValues_User_ModifiedBy", column: x => x.ModifiedBy, principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); }); migrationBuilder.CreateIndex( name: "IX_User_CreatedBy", table: "User", column: "CreatedBy"); migrationBuilder.CreateIndex( name: "IX_User_ModifiedBy", table: "User", column: "ModifiedBy"); migrationBuilder.CreateIndex( name: "IX_AdditionalFieldValues_AdditionalFieldId", table: "AdditionalFieldValues", column: "AdditionalFieldId"); migrationBuilder.CreateIndex( name: "IX_AdditionalFieldValues_CreatedBy", table: "AdditionalFieldValues", column: "CreatedBy"); migrationBuilder.CreateIndex( name: "IX_AdditionalFieldValues_ModifiedBy", table: "AdditionalFieldValues", column: "ModifiedBy"); migrationBuilder.AddForeignKey( name: "FK_User_User_CreatedBy", table: "User", column: "CreatedBy", principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); migrationBuilder.AddForeignKey( name: "FK_User_User_ModifiedBy", table: "User", column: "ModifiedBy", principalTable: "User", principalColumn: "Id", onDelete: ReferentialAction.Restrict); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using Docller.Core.Common; using Docller.Core.Models; using Microsoft.Practices.EnterpriseLibrary.Data; namespace Docller.Core.Repository.Mappers.StoredProcMappers { public class AttachmentMapper : IResultSetMapper<FileAttachment> { private readonly IRowMapper<FileAttachment> _fileAttachmentMapper; private readonly IRowMapper<FileAttachmentVersion> _fileAttachmentVersions; public AttachmentMapper() { _fileAttachmentMapper = DefaultMappers.ForFileAttachment; _fileAttachmentVersions = MapBuilder<FileAttachmentVersion>.MapNoProperties() .MapByName(x => x.FileId) .MapByName(x => x.RevisionNumber) .MapByName(x => x.VersionPath) .MapByName(x => x.FileName) .MapByName(x => x.FileExtension) .MapByName(x => x.ContentType) .MapByName(x=>x.CreatedDate) .Map(x => x.CreatedBy) .WithFunc( reader => new User() { FirstName = reader.GetNullableString(7), LastName = reader.GetNullableString(8) }) .Build(); } public IEnumerable<FileAttachment> MapSet(IDataReader reader) { FileAttachment attachment = null; using (reader) { if(reader.Read()) { attachment = _fileAttachmentMapper.MapRow(reader); } if (reader.NextResult() && attachment != null) { attachment.Versions = new List<FileAttachmentVersion>(); while (reader.Read()) { FileAttachmentVersion v = this._fileAttachmentVersions.MapRow(reader); v.ParentFile = attachment.ParentFile; v.Folder = attachment.Folder; v.Project = attachment.Project; if (!string.IsNullOrEmpty(v.VersionPath)) { attachment.Versions.Add(v); } } } } return new List<FileAttachment>() { attachment }; } } }
using _7DRL_2021.Behaviors; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _7DRL_2021.Cards { class CardHeal : Card { public CardHeal(int stack) : base("heal", stack) { Sprite = SpriteLoader.Instance.AddSprite("content/card_bubble"); Name = "Prolong"; Description = (textBuilder) => { textBuilder.AppendText("Restore "); textBuilder.AppendDescribe(Symbol.Heart, "all", Color.White); }; Value = 1500; } public override void Apply(SceneGame world, Vector2 cardPos) { var alive = world.PlayerCurio.GetBehavior<BehaviorAlive>(); alive.SetDamage(0); } public override void Destroy(SceneGame world, Vector2 cardPos) { throw new NotImplementedException(); } public override bool IsValid(SceneGame world) { var alive = world.PlayerCurio.GetBehavior<BehaviorAlive>(); return alive != null && alive.Damage > 0; } public override bool CanDestroy(SceneGame world) { return false; } } }
using BenchmarkDotNet.Running; using System.Reflection; namespace Bench.IPC { class Program { static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(GetAssembly()).Run(args); private static Assembly GetAssembly() => typeof(Program).GetTypeInfo().Assembly; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AgenciaBancaria.Dominio { public class Cliente //Conceito de emcapsulamento { public Cliente(string nome, string cpf, string rg, Endereco endereco) { /*if(string.IsNullOrWhiteSpace(nome)) Verifica se a string nome está vazia. { se válido, execulta uma excessão. throw new Exception("Campo *Nome* deve está preenchido corretamente. "); }*/ Nome = nome.ValidaStringVazia(); CPF = cpf.ValidaStringVazia(); RG = rg.ValidaStringVazia(); Endereco = endereco ?? throw new Exception("Endereço deve ser informado. "); } public string Nome { get; private set; } //Propriedade pode ser usada como variável. public string CPF { get; private set; } public string RG { get; private set; } public Endereco Endereco { get; private set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Door : MonoBehaviour { public static Door instance; private BoxCollider2D box; private Animator anim; [HideInInspector] public int collectiblesCount; // Use this for initialization void Awake () { MakeInstance(); anim = GetComponent<Animator>(); box = GetComponent<BoxCollider2D>(); } private void MakeInstance () { if(instance == null) { instance = this; } } public void DecrementCollectables () { collectiblesCount--; if(collectiblesCount == 0) { StartCoroutine(OpenDoor()); } } IEnumerator OpenDoor() { anim.Play("Open"); yield return new WaitForSeconds(.7f); box.isTrigger = true; } private void OnTriggerEnter2D(Collider2D target) { if(target.tag == "Player") { Debug.Log("game finished"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using EntityClasses; namespace MapClasses { [System.Serializable] public class LevelPrefab { [SerializeField] GameObject prefab; public GameObject Prefab { get { return prefab; } } [Range(0f, 1f)] [SerializeField] float weight; public float Weight { get { return weight; } } } // A map class that mainly serves as a container for the base level fields, properties, and methods. // Contains a list of Levels, the current level index, and methods for setting the current level and moving to new levels. [System.Serializable] public class LevelManager { // Just an arbitrary float which all cell instances' sizes are multiplied by. [SerializeField] float cellScale; public float CellScale { get { return cellScale; } } // The maximum width of the cell grid. This is arbitrary and is only used for defining the indices. [SerializeField] int maxWidth; public int MaxWidth { get { return maxWidth; } set { maxWidth = value; } } // The maximum depth of the cell grid. This is arbitrary and is only used for defining the indices. [SerializeField] int maxDepth; public int MaxDepth { get { return maxDepth; } set { maxDepth = value; } } // The index for the current level. public Level CurrentLevel { get; private set; } // This is a list of all levels. Hub area, biodome area, biodome boss, mechanical bay, mechanical bay boss, final boss. [SerializeField] public List<Level> levels; // Would work just as well anywhere else. public LevelManager() { CurrentLevel = null; } public void Reset() { CurrentLevel = null; } // Sets the current level index, as long as it's valid, and returns the level. public Level SetCurrentLevel(int index) { if (index < 0 || index >= levels.Count) return null; CurrentLevel = levels[index]; return CurrentLevel; } // Poorly named. // Gets the current level, verifies that it's not null and has been initialized, // Then gets the index of the Exit cell from the level's list of exits (if it's in the list), // Then gets the corresponding next level's index from the level's list of exit destination indices. // Then sets the current level and returns the level. public Level NextLevel(Cell exit) { if (CurrentLevel == null || !CurrentLevel.Initialized) return null; int exitIndex = CurrentLevel.ExitCells.IndexOf(exit); if (exitIndex < 0 || exitIndex >= CurrentLevel.ExitCells.Count) return null; int nextIndex = CurrentLevel.exitList[exitIndex]; if (nextIndex < 0 || nextIndex >= levels.Count) return null; return SetCurrentLevel(nextIndex); } // Returns the Vector3 position for the cell, using the cell's X and Z values and multiplying them by the CellScale. // Returns Vector3.zero if the cell is null. public Vector3 GetCellPosition(Cell cell) { if (cell == null) { Debug.LogError("ERROR: Cannot get cell position, cell is null."); return Vector3.zero; } float cellScale = CellScale; return new Vector3(cell.X * cellScale, 0, cell.Z * cellScale); } public Vector3 GetCellPosition(int x, int z) { float cellScale = CellScale; return new Vector3(x * cellScale, 0f, z * cellScale); } public GameObject GetRandomPrefab(List<LevelPrefab> prefabList) { if (prefabList == null || prefabList.Count == 0) return null; float totalWeight = 0f; foreach (LevelPrefab pref in prefabList) { totalWeight += pref.Weight; } GameObject prefab = null; float choice = Random.Range(0f, totalWeight); float cumulative = 0f; foreach (LevelPrefab pref in prefabList) { cumulative += pref.Weight; if (choice <= cumulative) { prefab = pref.Prefab; break; } } // If couldn't find one with the proper weight, just grab the first prefab. if (prefab == null) { prefab = prefabList[0].Prefab; } return prefab; } } }
namespace ostranauts_modding { public class GasRespire { public bool bAllowExternA { get; set; } public bool bAllowExternB { get; set; } public double fConvRate { get; set; } public double fSignalCheckRate { get; set; } public double fStatRate { get; set; } public double fVol { get; set; } public string strCTA { get; set; } public string strCTB { get; set; } public string strGasIn { get; set; } public string strGasOut { get; set; } public string strName { get; set; } public string strPtA { get; set; } public string strPtB { get; set; } public string strSignalCT { get; set; } public string strStat { get; set; } public bool? bSignalCheckA { get; set; } public bool? bSignalCheckB { get; set; } } }
using LMS.App_Code; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Text; using System.Web; using System.Web.Http; namespace LMS { public class AccessController : ApiController { [HttpPost] public HttpResponseMessage login(UserAccess useraccess) { //login(dynamic para_user_id, dynamic para_password) ReturnData rd = new ReturnData(); rd = useraccess.login(); string yourJson = JsonConvert.SerializeObject(rd); ; var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json"); return response; } [HttpPost] public HttpResponseMessage forgetPassword(UserAccess useraccess) { //login(dynamic para_user_id, dynamic para_password) ReturnData rd = new ReturnData(); rd = useraccess.forgetPassword(); string yourJson = JsonConvert.SerializeObject(rd); ; var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json"); return response; } [HttpPost] public HttpResponseMessage changeForgetPassword(UserAccess useraccess) { //login(dynamic para_user_id, dynamic para_password) ReturnData rd = new ReturnData(); rd = useraccess.changeForgetPassword(); string yourJson = JsonConvert.SerializeObject(rd); ; var response = this.Request.CreateResponse(HttpStatusCode.OK); response.Content = new StringContent(yourJson, Encoding.UTF8, "application/json"); return response; } // GET api/<controller> public IEnumerable<string> Get() { return new string[] { "value1", "value2" }; } // GET api/<controller>/5 public string Get(int id) { return "value"; } // POST api/<controller> public void Post([FromBody]string value) { } // PUT api/<controller>/5 public void Put(int id, [FromBody]string value) { } // DELETE api/<controller>/5 public void Delete(int id) { } } }
using System; using System.Collections.Generic; using TRPO_labe_5.States; namespace TRPO_labe_5.Model { class ServiceLift { private int _currentCarrying = 0; private IState _currentState; public int CurrentFloor { get; set; } public int Carrying { get; set; } public int ProbabilityOfPowerOutage { get; set; } public IState State { get => _currentState; private set { _currentState = value; _currentState.DoAction(); } } public ServiceLift() { State = new Rest(); } public void CallOnFloor(int floor) { var rnd = new Random(); if (State is Overload) { Console.WriteLine("Не получается поехать!"); } else { int randomInt = rnd.Next(0, 101); if (randomInt <= ProbabilityOfPowerOutage) State = new NoPower(); else { State = new Movement(); CurrentFloor = floor; } } } public void Load(int weight) { _currentCarrying += weight; if (_currentCarrying > Carrying) State = new Overload(); } public void Unload(int weight) { if (_currentCarrying - weight < 0) throw new Exception("Как лифт может сбросить вес, которого нет?!"); _currentCarrying -= weight; State = new Rest(); } public void RestorePowerSupply() { if (State is NoPower) State = new Rest(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SharpNexalogy.Model { public class Job { public string result { get; set; } public int time_it_took { get; set; } public string error_code { get; set; } public string error_detail { get; set; } public int type { get; set; } public int id { get; set; } public string command_url { get; set; } public string post_vars { get; set; } public string requested_at { get; set; } public int estimated_time { get; set; } public string error_link { get; set; } public string description { get; set; } public int priority { get; set; } public string error_message { get; set; } public string callback_url { get; set; } public int percent_completed { get; set; } public NexalogyUser nexalogy_user { get; set; } } }
using System; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using System.Runtime.InteropServices; namespace VoxelSpace { using IO; public class VoxelChunk : IDisposable, IBinaryReadWritable { public const int SIZE = 32; public const int VOXEL_COUNT = SIZE * SIZE * SIZE; public VoxelVolume Volume { get; private set; } public Coords Coords { get; private set; } public VoxelChunkMesh Mesh { get; private set; } public IndexedVoxels Voxels { get; private set; } public UnmanagedArray3<VoxelData> VoxelData { get; private set; } public VoxelChunkLightData LightData { get; private set; } public VoxelTypeIndex Index { get; private set; } public bool WasDisposed { get; private set; } public VoxelChunk(VoxelVolume volume, Coords coords) { Volume = volume; Coords = coords; Index = Volume.Index; VoxelData = new UnmanagedArray3<VoxelData>(); Voxels = new IndexedVoxels(this); LightData = new VoxelChunkLightData(); } ~VoxelChunk() { Dispose(); } void CheckDisposed() { if (WasDisposed) throw new ObjectDisposedException(GetType().Name); } public unsafe void ReadBinary(BinaryReader reader) { var curr = VoxelData[0]; var end = curr + SIZE * SIZE * SIZE; while (curr < end) { ushort header = reader.ReadUInt16(); if (header == 0) { // read data packet ushort data = reader.ReadUInt16(); while (data != 0xFFFF) { curr->TypeIndex = data; data = reader.ReadUInt16(); curr ++; } } else { // read rle packet ushort type = reader.ReadUInt16(); for (int i = 0; i < header; i ++) { curr->TypeIndex = type; curr ++; } } } curr = VoxelData[0]; while (curr < end) { var zcount = reader.ReadUInt16(); while (zcount > 0) { curr->Data = 0; curr ++; zcount --; } if (curr < end) { ushort data = reader.ReadUInt16(); while (curr < end && data != 0) { curr->Data = data; curr ++; data = reader.ReadUInt16(); } } } } public unsafe void WriteBinary(BinaryWriter writer) { var curr = VoxelData[0]; var end = curr + SIZE * SIZE * SIZE; // write type info while (curr < end) { var next = curr + 1; if (next == end) { // if this is the last voxel, just emit an RLE of length 1 writer.Write((ushort) 1); writer.Write((ushort) curr->TypeIndex); break; } if (next->TypeIndex == curr -> TypeIndex) { // if the next one is the same, emit an RLE var index = curr->TypeIndex; int count = 0; while (curr->TypeIndex == index && curr < end) { count ++; curr ++; } writer.Write((ushort) count); writer.Write((ushort) index); } else { // if the next one is different, emit data until the next one matches writer.Write((ushort) 0); writer.Write(curr->TypeIndex); while (curr->TypeIndex != next->TypeIndex && next < end) { writer.Write(next->TypeIndex); curr ++; next ++; } curr = next; writer.Write((ushort) 0xFFFF); } } // write data curr = VoxelData[0]; while (curr < end) { ushort count = 0; while (curr->Data == 0 && curr < end) { count ++; curr ++; } writer.Write(count); if (curr < end) { while (curr->Data != 0 && curr < end) { writer.Write(curr->Data); curr ++; } writer.Write((ushort) 0); } } } public override string ToString() { return $"Chunk {Coords}"; } public void SetMesh(VoxelChunkMesh mesh) { if (WasDisposed) { mesh.Dispose(); } if (!mesh.AreBuffersReady) { throw new ArgumentException($"Cannot update chunk mesh for chunk at {Coords}: Mesh buffers aren't ready!"); } if (Mesh != null && Mesh != mesh) { Mesh.Dispose(); } Mesh = mesh; } public void Dispose() { WasDisposed = true; VoxelData.Dispose(); Mesh?.Dispose(); LightData?.Dispose(); } public static bool AreLocalCoordsInBounds(Coords c) { var min = 0; var max = SIZE - 1; return c.X >= min && c.X < max && c.Y >= min && c.Y < max && c.Z >= min && c.Z < max; } public Coords LocalToVolumeCoords(Coords c) => Coords * SIZE + c; public Coords VolumeToLocalCoords(Coords c) => c - (Coords * SIZE); public Vector3 LocalToVolumeVector(Vector3 c) => Coords * SIZE + c; public Vector3 VolumeToLocalVector(Vector3 c) => c - (Coords * SIZE); public unsafe Voxel GetVoxelIncludingNeighbors(Coords c) { var data = GetVoxelDataIncludingNeighbors(c); if (data == null) { return Voxel.Empty; } else { return new Voxel(*data, Index); } } public Voxel GetVoxelIncludingNeighbors(int i, int j, int k) => GetVoxelIncludingNeighbors(new Coords(i, j, k)); public unsafe VoxelData* GetVoxelDataIncludingNeighbors(Coords c) { if (AreLocalCoordsInBounds(c)) { return VoxelData[c]; } else { return Volume.GetVoxelData(LocalToVolumeCoords(c)); } } public unsafe VoxelData* GetVoxelDataIncludingNeighbors(int i, int j, int k) => GetVoxelDataIncludingNeighbors(new Coords(i, j, k)); public VoxelLight GetVoxelLightIncludingNeighbors(Coords c) { if (AreLocalCoordsInBounds(c)) { return LightData.GetVoxelLight(c); } else { return Volume?.GetVoxelLight(LocalToVolumeCoords(c)) ?? VoxelLight.NULL; } } public VoxelLight GetVoxelLightIncludingNeighbors(int i, int j, int k) => GetVoxelLightIncludingNeighbors(new Coords(i, j, k)); public unsafe byte* GetVoxelLightDataIncludingNeighbors(Coords c, int channel) { if (AreLocalCoordsInBounds(c)) { return LightData[channel][c]; } else { return Volume.GetVoxelLightData(LocalToVolumeCoords(c), channel); } } public unsafe byte* GetVoxelLightDataIncludingNeighbors(Coords c, VoxelLightChannel channel) => GetVoxelLightDataIncludingNeighbors(c, (int) channel); public unsafe byte* GetVoxelLightDataIncludingNeighbors(int i, int j, int k, int channel) => GetVoxelLightDataIncludingNeighbors(new Coords(i, j, k), channel); public unsafe byte* GetVoxelLightDataIncludingNeighbors(int i, int j, int k, VoxelLightChannel channel) => GetVoxelLightDataIncludingNeighbors(new Coords(i, j, k), (int) channel); /// <summary> /// Utility class to access voxels, auto translating from the stored indicies /// </summary> public class IndexedVoxels { VoxelTypeIndex _index; UnmanagedArray3<VoxelData> _data; public IndexedVoxels(VoxelChunk chunk) { _data = chunk.VoxelData; _index = chunk.Index; } public unsafe Voxel this[Coords c] { get => new Voxel(*_data[c], _index); set => *_data[c] = new VoxelData(_index.Add(value.Type), value.Data); } public unsafe Voxel this[int i, int j, int k] { get => new Voxel(*_data[i, j, k], _index); set => *_data[i, j, k] = new VoxelData(_index.Add(value.Type), value.Data); } } public unsafe class UnmanagedArray3<T> : IDisposable where T : unmanaged { public bool WasDisposed { get; private set; } T* data; public T* this[int x, int y, int z] { get { CheckDisposed(); return &data[x + y * SIZE + z * SIZE * SIZE]; } } public T* this[Coords c] { get { CheckDisposed(); return &data[c.X + c.Y * SIZE + c.Z * SIZE * SIZE]; } } public T* this[int offset] { get { CheckDisposed(); return &data[offset]; } } public UnmanagedArray3() { int size = Marshal.SizeOf<T>() * SIZE * SIZE * SIZE; data = (T*) Marshal.AllocHGlobal(size); while (size > 0) { ((byte*) data)[--size] = 0; } } ~UnmanagedArray3() { Dispose(); } public void Dispose() { WasDisposed = true; if (data != null) { Marshal.FreeHGlobal((IntPtr) data); data = null; } } void CheckDisposed() { if (WasDisposed) throw new ObjectDisposedException(GetType().Name); } public static int GetIndex(int x, int y, int z) => x + y * SIZE + z * SIZE * SIZE; public static int GetIndex(Coords c) => c.X + c.Y * SIZE + c.Z * SIZE * SIZE; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace Bus_Stop { class Calculation { public static void Calculate(string filenamebusadtime, int m, string str, string buscode) { /****************计算数据段**************************/ if (m > 1) { List<string> busadreread = IOTool.ReadText(filenamebusadtime); string lstline = busadreread[busadreread.Count - 2]; string[] lastline = busadreread[busadreread.Count - 2].Split(' '); string lastad = lastline[3] + " " + lastline[4]; DateTime ladtime = Convert.ToDateTime(lastad); string lservice = Convert.ToString(lastline[5]); int lstopnum = Convert.ToInt32(lastline[1]); int ladflag = Convert.ToInt32(lastline[2]); string[] adcontent = busadreread[busadreread.Count - 1].Split(' '); string contentad = adcontent[3] + " " + adcontent[4]; DateTime cadtime = Convert.ToDateTime(contentad); string cservice = Convert.ToString(adcontent[5]); int cstopnum = Convert.ToInt32(adcontent[1]); int cadflag = Convert.ToInt32(adcontent[2]); TimeSpan DeltaT = cadtime - ladtime; int DeltaStop = Math.Abs(lstopnum - cstopnum); if (lservice.Equals(cservice) && adcontent[0].Equals(lastline[0]))//判断是否同向且是否同线路,如果不同向,则两个数据无法计算 { /*****************全数据分析*************************************/ if (DeltaStop == 0 && ladflag < cadflag && DeltaT.TotalSeconds < 700)//A进A出、B进B出的情况 { string filenamewt = "Stopwaittime_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else if (DeltaStop == 1 && DeltaT.TotalSeconds < 1000) { string filename3 = "Stopruntime_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filename3, strd); } /****************************************************************/ /*****************时间段分析*************************************/ if (DeltaStop == 0 && ladflag < cadflag && DeltaT.TotalSeconds < 700)//A进A出、B进B出的情况 { if (cadtime.Hour > 6 && cadtime.Hour < 9) { string filenamewt = "Stopwaittime_" + "time_" + "7-9am_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else if (cadtime.Hour > 16 && cadtime.Hour < 19) { string filenamewt = "Stopwaittime_" + "time_" + "5-7pm_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else { string filenamewt = "Stopwaittime_" + "time_" + "other_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } } else if (DeltaStop == 1 && ladflag > cadflag && DeltaT.TotalSeconds < 1000) { if (cadtime.Hour > 6 && cadtime.Hour < 9) { string filenamewt = "Stopruntime_" + "time_" + "7-9am_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else if (cadtime.Hour > 16 && cadtime.Hour < 19) { string filenamewt = "Stopruntime_" + "time_" + "5-7pm_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else { string filenamewt = "Stopruntime_" + "time_" + "other_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } } /****************************************************************/ /*****************线路分析***************************************/ if (DeltaStop == 0 && ladflag < cadflag && DeltaT.TotalSeconds < 700)//A进A出、B进B出的情况 { string filenamewt = "Stopwaittime_" + "route_" + adcontent[0] + "_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else if (DeltaStop == 1 && DeltaT.TotalSeconds < 1000) { string filename3 = "Stopruntime_" + "route_" + adcontent[0] + "_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filename3, strd); } /****************************************************************/ /*****************线路时间分析***************************************/ if (DeltaStop == 0 && ladflag < cadflag && DeltaT.TotalSeconds < 700)//A进A出、B进B出的情况 { if (cadtime.Hour > 6 && cadtime.Hour < 9) { string filenamewt = "Stopwaittime_" + "route_" + adcontent[0] + "_time_" + "7-9am_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else if (cadtime.Hour > 16 && cadtime.Hour < 19) { string filenamewt = "Stopwaittime_" + "route_" + adcontent[0] + "_time_" + "5-7pm_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else { string filenamewt = "Stopwaittime_" + "route_" + adcontent[0] + "_time_" + "other_" + lastline[1] + "_" + cservice + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } } else if (DeltaStop == 1 && DeltaT.TotalSeconds < 1000) { if (cadtime.Hour > 6 && cadtime.Hour < 9) { string filenamewt = "Stopruntime_" + "route_" + adcontent[0] + "_time_" + "7-9am_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else if (cadtime.Hour > 16 && cadtime.Hour < 19) { string filenamewt = "Stopruntime_" + "route_" + adcontent[0] + "_time_" + "5-7pm_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } else { string filenamewt = "Stopruntime_" + "route_" + adcontent[0] + "_time_" + "other_" + lastline[1] + "_" + cstopnum + ".txt"; string strd = adcontent[0] + " " + lastline[1] + "," + cstopnum + " " + lastline[2] + cadflag + " " + DeltaT.TotalSeconds + " " + lstline + " " + str + " " + buscode;//记录的格式,转换为字符串,可以再加个cservice IOTool.WriteFile(filenamewt, strd); } } /****************************************************************/ } } /******************************************************************/ } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace GerenciamentoLivrosMVC.Models { [Table("Livros")] public class Livro { public int Id { get; set; } [Required(ErrorMessage = "O título é obrigatório", AllowEmptyStrings = false)] [Display(Name = "Título")] [StringLength(100)] public string Titulo { get; set; } [Required(ErrorMessage = "O gênero é obrigatório")] [Display(Name = "Gênero Id")] public int GeneroId { get; set; } public virtual Genero Genero { get; set; } [Required(ErrorMessage = "A data da publicação é obrigatório")] [Display(Name = "Data Publicação")] [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:d}")] public DateTime DataPublicacao { get; set; } [Required(ErrorMessage = "A quantidade de páginas é obrigatório")] [Display(Name = "Páginas")] public int Paginas { get; set; } [Required(ErrorMessage = "O autor é obrigatório", AllowEmptyStrings = false)] [Display(Name = "Autor")] [StringLength(100)] public string Autor { get; set; } [Required(ErrorMessage = "A editora é obrigatório", AllowEmptyStrings = false)] [Display(Name = "Editora")] [StringLength(100)] public string Editora { get; set; } [Required(ErrorMessage = "A descricao é obrigatório", AllowEmptyStrings = false)] [Display(Name = "Descrição")] [StringLength(150)] public string Descricao { get; set; } [Required(ErrorMessage = "A sinopse é obrigatório", AllowEmptyStrings = false)] [Display(Name = "Sinope")] [StringLength(150)] public string Sinopse { get; set; } [Required(ErrorMessage = "A capa é obrigatório")] [Display(Name = "Capa")] public byte[] Capa { get; set; } [Display(Name = "Link")] [StringLength(255)] public string Link { get; set; } public List<Genero> Lista() { return new List<Genero>(); } } }
using System; using System.Threading; using Framework.Core.Common; using OpenQA.Selenium; using Tests.Pages.Van.Main.Common.DefaultPage; namespace Tests.Pages.Van.Main.List { public class CanvassResultsSurveyQuestionListPage : CanvassListPage { #region Elements public string AFLCanvassResultsSurveyQuestionHeaderText = "Canvass Results by County"; public By CanvassResultsSurveyQuestionDropdownLocator = By.Id("ctl00_ContentPlaceHolderVANPage_VANCanvassFilterPanelInstance_VANInputItemQuestions"); public IWebElement CanvassResultsSurveyQuestionDropdown { get { return _driver.FindElement(CanvassResultsSurveyQuestionDropdownLocator); } } public By CanvassResultsCommitteeDropdownLocator = By.Id("ctl00_ContentPlaceHolderVANPage_VANCanvassFilterPanelInstance_VanInputItemFilterCommittee_VanInputItemFilterCommittee"); public IWebElement CanvassResultsCommitteeDropdown { get { return _driver.FindElement(CanvassResultsCommitteeDropdownLocator); } } #endregion public CanvassResultsSurveyQuestionListPage(Driver driver) : base(driver) { } #region Methods /// <summary> /// Click Survey Question Summary Link /// </summary> public void ClickSurveyQuestionSummaryLink() { var homePage = new VoterDefaultPage(_driver); // here twice because it's not waiting long enough _driver.WaitForElementToDisplayBy(homePage.ViewCanvassResultsAccordionHeaderLocator); _driver.WaitForElementToDisplayBy(homePage.ViewCanvassResultsAccordionHeaderLocator); _driver.Click(homePage.ViewCanvassResultsAccordionHeader); _driver.WaitForElementToDisplayBy(homePage.CanvassResultsOpenPanelLocator); _driver.Click(homePage.SurveyQuestionSummaryLink); _driver.WaitForElementToDisplayBy(RefreshButtonLocator); } #endregion } }
using System.Drawing; namespace Layout { /// <summary> /// A simple box with a specified fill and border. /// A parent element can be assigned and it can be positioned and sized in relation to it. /// </summary> public class Box : ActiveElement { /******** Variables ********/ private SizeF _relativeSize; private Rectangle _area; private Anchor _anchor; private Box _parent; /// <summary> /// An identifier to later retrieve the element when assigned to a Layout. /// </summary> public string identifier { get; private set; } /// <summary> /// The brush used to fill the box. /// </summary> public Brush fill; /// <summary> /// The pen to draw the boundary of the box. /// </summary> public Pen borderLine; /// <summary> /// Indicating if the draw method should be skipped. /// </summary> public bool visible; /******** Functions ********/ /// <summary> /// Full constructor. /// If no identifier is used, you may not retrieve the element after assigning it to a layout. /// </summary> /// <param name="area">The rectangle corresponding to the box.</param> /// <param name="fill">The brush used to fill the box.</param> /// <param name="borderLine">The pen to draw the boundary of the box.</param> /// <param name="identifier">An optional identifier to later retrieve the element.</param> public Box(Rectangle area, Brush fill, Pen borderLine, string identifier = "") { this.parent = null; this._area = area; this.fill = fill; this.borderLine = borderLine; this.identifier = identifier; this.visible = true; } /// <summary> /// Extended constructor. Will use the standard fill and borderLine set in the Layout class. /// If no identifier is used, you may not retrieve the element after assigning it to a layout. /// </summary> /// <param name="area">The rectangle corresponding to the box.</param> /// <param name="identifier">An optional identifier to later retrieve the element.</param> public Box(Rectangle area, string identifier = "") : this(area, (Brush)Layout.defaultFill.Clone(), (Pen)Layout.defaultBorderLine.Clone(), identifier) { } /// <summary> /// Standard constructor. Will use an empty rectangle and the standard fill and borderLine set in the Layout class. /// If no identifier is used, you may not retrieve the element after assigning it to a layout. /// </summary> /// <param name="identifier">An optional identifier to later retrieve the element.</param> public Box(string identifier = "") : this(new Rectangle(), identifier) { } /// <summary> /// Adapt position and size to the changing parent element. /// </summary> public override void Update() { base.Update(); } /// <summary> /// Draws the element with the given Graphics object. /// </summary> /// <param name="g">The graphics object to be rendered to.</param> public override void Draw(Graphics g) { if (visible) { g.FillRectangle(fill, area); g.DrawRectangle(borderLine, area); } } /******** Getter & Setter ********/ /// <summary> /// A parent element. You may position and size the element in relation to any parent box. /// Default is null (no parent, respectively the entire formular). /// </summary> public Box parent { get { if(_parent == null) { Box tempBox = new Box("form"); #warning Link to Program, but should be independent of software the library is used in tempBox.size = RectangleGame.Program.mainForm.ClientSize; return (tempBox); } else { return (_parent); } } set { _parent = value; if (_parent != null) { _area.X = _parent.absoluteX; _area.Y = _parent.absoluteY; // Adapt relative positioning to new parent. if (anchor != Anchor.None) { anchor = anchor; } else { percentageLocation = percentageLocation; } } else { _area.X = 0; _area.Y = 0; } } } // Setting position and size of the rectangle representing the box // Just a wrapper around the getters and setter for x, y, width and height public Rectangle area { get { return (_area); } set { x = value.X; y = value.Y; width = value.Width; height = value.Height; } } /// <summary> /// The x position in relation to the parent, in pixels. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public int x { get { return (_area.X - parent.absoluteX); } set { _area.X = value + parent.absoluteX; // Remove horizontal part of the anchor. anchor ^= (anchor & Anchor.CenterX); } } /// <summary> /// The y position in relation to the set parent, in pixels. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public int y { get { return (_area.Y - parent.absoluteY); } set { _area.Y = value + parent.absoluteY; // Remove vertical part of the anchor. anchor ^= (anchor & Anchor.CenterY); } } /// <summary> /// The location in relation to the set parent, in pixels. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public Point location { get { Point tempPoint = new Point(x, y); return (tempPoint); } set { x = value.X; y = value.Y; } } /// <summary> /// The x position in relation to the set parent, in percent of the parent's width. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public float percentageX { get { float tempPercentageX; tempPercentageX = (float)x / (float)parent.width * 100; return (tempPercentageX); } set { int tempX; tempX = (int)(value * parent.width / 100); x = tempX; // Remove horizontal part of the anchor. anchor ^= (anchor & Anchor.CenterX); } } /// <summary> /// The y position in relation to the set parent, in percent of the parent's height. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public float percentageY { get { float tempPercentageY; tempPercentageY = (float)y / (float)parent.height * 100; return (tempPercentageY); } set { int tempY; tempY = (int)(value * parent.height / 100); y = tempY; // Remove vertical part of the anchor. anchor ^= (anchor & Anchor.CenterY); } } /// <summary> /// The position in relation to the set parent, in percent of the parent's size. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public PointF percentageLocation { get { PointF tempPercentageLocation = new PointF(percentageX, percentageY); return (tempPercentageLocation); } set { percentageX = value.X; percentageY = value.Y; } } /// <summary> /// The absolute x position in relation to the formular, in pixels. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public int absoluteX { get { return (_area.X); } set { _area.X = value; // Remove horizontal part of the anchor. anchor ^= (anchor & Anchor.CenterX); } } /// <summary> /// The absolute x position in relation to the formular, in pixels. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public int absoluteY { get { return (_area.Y); } set { _area.Y = value; // Remove vertical part of the anchor. anchor ^= (anchor & Anchor.CenterY); } } /// <summary> /// The absolute location in relation to the formular, in pixels. /// Setting the location this way will remove any anchor that was previously set. /// </summary> public Point absoluteLocation { get { Point tempPoint = new Point(absoluteX, absoluteY); return (tempPoint); } set { x = value.X; y = value.Y; } } /// <summary> /// The width of the element, in pixels. /// </summary> public int width { get { return (_area.Width); } set { if (value > 0) _area.Width = value; else _area.Width = 0; } } /// <summary> /// The height of the element, in pixels. /// </summary> public int height { get { return (_area.Height); } set { if (value > 0) _area.Height = value; else _area.Height = 0; } } /// <summary> /// The size of the element. Implicitly uses the width and height properties. /// </summary> public Size size { get { return (new Size(width, height)); } set { width = value.Width; height = value.Height; } } /// <summary> /// The percentage width of the of the element in relation to its parent. /// -1 indicating that the value won't be used. /// </summary> public float percentageWidth { get { return (_relativeSize.Width); } set { if (value < 0) { _relativeSize.Width = -1; } else { // Setting width _area.Width = (int)(value / 100 * parent.width); _relativeSize.Width = value; } } } /// <summary> /// The percentage height of the of the element in relation to its parent. /// -1 indicating that the value won't be used. /// </summary> public float percentageHeight { get { return (_relativeSize.Height); } set { if (value < 0) { _relativeSize.Height = -1; } else { // Setting height _area.Height = (int)(value / 100 * parent.height); _relativeSize.Height = value; } } } /// <summary> /// The percentage size of the of the element in relation to its parent. /// Implicitly uses the relativeWidth and relativeHeight properties. /// -1 for either width or height indicating that the value won't be used. /// </summary> public SizeF percentageSize { get { return (_relativeSize); } set { percentageWidth = value.Width; percentageHeight = value.Height; } } /// <summary> /// You may center the element or set its position to the top, left, right or bottom using an anchor. /// You may combine them using the | operator. /// Combining the top, left, right and bottom anchor will result in centering the element. /// </summary> public Anchor anchor { get { return(_anchor); } set { // Aligned right if ((value & Anchor.Right) == Anchor.Right) { _area.X = parent.x + parent.width - width; } // Aligned Down if ((value & Anchor.Bottom) == Anchor.Bottom) { _area.Y = parent.y + parent.height - height; } // Aligned left if ((value & Anchor.Left) == Anchor.Left) { _area.X = parent.x; } // Aligned up if ((value & Anchor.Top) == Anchor.Top) { _area.Y = parent.y; } // Box centered on x axis if ((value & Anchor.CenterX) == Anchor.CenterX) { _area.X = parent.x + (parent.width / 2) - (width / 2); } // Box centered on y axis if ((value & Anchor.CenterY) == Anchor.CenterY) { _area.Y = parent.y + (parent.height / 2) - (height / 2); } _anchor = value; } } } }
using Microsoft.EntityFrameworkCore; using senai_hroads_webApi.Contexts; using senai_hroads_webApi.Domains; using senai_hroads_webApi.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace senai_hroads_webApi.Repositories { public class PersonagemRepository : IPersonagemRepository { HroadsContext _context = new HroadsContext(); public void Atualizar(int id, Personagem personagemAtualizado) { Personagem personagemBuscado = _context.Personagens.Find(id); if (personagemAtualizado.Nome != null) { personagemBuscado.Nome = personagemAtualizado.Nome; personagemBuscado.IdClasse = personagemAtualizado.IdClasse; personagemBuscado.CapMaxVida = personagemAtualizado.CapMaxVida; personagemBuscado.CapMaxMana = personagemAtualizado.CapMaxMana; personagemBuscado.DataAtualizacao = DateTime.Now; } _context.Personagens.Update(personagemBuscado); _context.SaveChanges(); } public Personagem BuscarPorId(int id) { return _context.Personagens.FirstOrDefault(e => e.IdPersonagem == id); } public void Cadastrar(Personagem novoPersonagem) { _context.Personagens.Add(novoPersonagem); } public void Deletar(int id) { Personagem personagemBuscado = _context.Personagens.Find(id); _context.Personagens.Remove(personagemBuscado); _context.SaveChanges(); } public List<Personagem> Listar() { return _context.Personagens.Include(e => e.IdClasseNavigation).ToList(); } } }
namespace Properties.Infrastructure.Data.Migrations { using System; using System.Data.Entity.Migrations; public partial class PropertyRelationshipFix : DbMigration { public override void Up() { DropForeignKey("dbo.Properties", "Landlord_LandlordId1", "dbo.Landlords"); DropIndex("dbo.Properties", new[] { "Landlord_LandlordId1" }); DropColumn("dbo.Properties", "Landlord_LandlordId1"); } public override void Down() { AddColumn("dbo.Properties", "Landlord_LandlordId1", c => c.Int()); CreateIndex("dbo.Properties", "Landlord_LandlordId1"); AddForeignKey("dbo.Properties", "Landlord_LandlordId1", "dbo.Landlords", "LandlordId1"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StraightLevelPieceScript : LevelPieceSuperClass { [Header("Bones")] public Transform FrontParent; public Transform RearParent; public Transform FrontLeftBone; public Transform FrontRightBone; public Transform RearLeftBone; public Transform RearRightBone; [Tooltip("Bones on the left side, in order. 0 is front, grows towards rear")] public List<Transform> LeftBones; [Tooltip("Bones on the right side, in order. 0 is front, grows towards rear")] public List<Transform> RightBones; }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Windows.Forms; using DevExpress.XtraEditors; using IRAP.Global; using IRAP.Client.SubSystem; namespace IRAP.Client.GUI.MESPDC.Actions { /// <summary> /// 万能表单 OutputStr 返回值中定义的操作: /// /// </summary> public class SelectChoiceAction : CustomAction, IUDFAction { int t107LeafID = 0; int t102LeafID = 0; public SelectChoiceAction(XmlNode actionParams, ExtendEventHandler extendAction, ref object tag) : base(actionParams, extendAction, ref tag) { t107LeafID = Tools.ConvertToInt32(actionParams.Attributes["T107LeafID"].Value); t102LeafID = Tools.ConvertToInt32(actionParams.Attributes["T102LeafID"].Value); } public void DoAction() { try { if (t107LeafID == 0) AvailableWIPStations.Instance.Options.RefreshOptionOne( CurrentOptions.Instance.OptionOne.T107LeafID); else AvailableWIPStations.Instance.Options.RefreshOptionOne(t107LeafID); if (t102LeafID != 0) AvailableWIPStations.Instance.Options.RefreshOptionTwo(t102LeafID); } catch (Exception error) { XtraMessageBox.Show( error.Message, "系统信息", MessageBoxButtons.OK, MessageBoxIcon.Error); } } } public class SelectChoiceFactory : CustomActionFactory, IUDFActionFactory { public IUDFAction CreateAction(XmlNode actionParams, ExtendEventHandler extendAction, ref object tag) { return new SelectChoiceAction(actionParams, extendAction, ref tag); } } }
using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ServiceA.Controllers { [Route("api/[controller]")] [ApiController] public class ServiceAController : ControllerBase { [HttpGet] [ActionName("ServiceName")] public string GetServiceName() { return "ServiceA"; } } }
using OrgMan.DomainObjects.Session; using System; using System.Collections.Generic; namespace OrgMan.DomainContracts.Session { public class CreateSessionQuery { public SessionDomainModel Session { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class PlayerCamera : MonoBehaviour { // Start is called before the first frame update void Start() { } public Transform _player; public Transform _cameraPivot; public Transform _cameraTarget; public float _lerpMove; public float _lerpLook; public float _mouseSensitivity = 1.0f; public float _cameraCollisionOfset = 0.3f; // Update is called once per frame void Update() { Vector3 pivot = _cameraPivot.rotation.eulerAngles; pivot.x = 0.0f; pivot.z = 0.0f; pivot.y += InputManager.getMouse().x * _mouseSensitivity * Time.deltaTime; _cameraPivot.rotation = Quaternion.Euler(pivot); _cameraPivot.transform.position = _player.transform.position; float smooth = 1.0f - Mathf.Pow(_lerpMove, Time.deltaTime); transform.position = Vector3.Lerp(transform.position, _cameraTarget.position, smooth); smooth = smooth = 1.0f - Mathf.Pow(_lerpLook, Time.deltaTime); transform.forward = Vector3.Lerp(transform.forward, (_player.position - transform.position).normalized, smooth); RaycastHit hit; if(Physics.Raycast(_player.position, (transform.position - _player.position), out hit, (_cameraTarget.position - _player.position).magnitude)) { transform.position = hit.point + ((_player.position - transform.position) * _cameraCollisionOfset); } } }
using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebAPI_Connection_ReExam.Custom { [JsonObject("item")] public class Item { [JsonProperty("id")] private string id { get; set; } //型番 [JsonProperty("name")] private string name { get; set; } //型番名 public Item(string id,string name) { this.id = id; this.name = name; } } }
using System; using System.Windows.Forms; using System.IO; using System.Diagnostics; using SessionSettings; using System.Reflection; using Common.Presentation; using Spelling; using System.Drawing; using System.Collections.Generic; using System.Linq; using Common; namespace FormTester { public partial class ScratchForm : Form { private Size originalSize = new Size(0, 0); //private float originalFontSize = 0f; public ScratchForm() { InitializeComponent(); } private void ScratchForm_Load(object sender, EventArgs e) { titleBar1.SetTitleImages(@"C:\Program Files\CSB\MoviesEh\Skin9"); //List<FontFamily> list = FontFamily.Families.Where(x => !x.IsStyleAvailable(FontStyle.Regular)).ToList(); //foreach(FontFamily f in list) //{ // System.Diagnostics.Debug.WriteLine(f.Name); //} } private void ScratchForm_FormClosing(object sender, FormClosingEventArgs e) { } private void ok_Click(object sender, EventArgs e) { Utilities.LaunchProcess(@"c:\Program Files\CSB\MoviesEh\"); //Spelling.Spelling spelling = new Spelling.Spelling(); //spelling.SetText("The qik browd fox jumped over the laxy dog."); //spelling.Show(); //string movieInfoPath = Path.Combine(Assembly.GetCallingAssembly().Location, "MovieInfo1EXE.exe"); //movieInfoPath = @"C:\Program Files\CSB\MoviesEh_NEW\bin\MovieInfo1EXE.exe"; //Process process = new Process(); //process.StartInfo = new ProcessStartInfo(movieInfoPath); //process.StartInfo.Arguments = "movie_rebuild_a_don,DTHUMIM,00332707"; //process.Start(); // photoImageViewer1.AddFolder(@"\\nfmfiles\photosmark2\Actors\"); } private void CreateMyListView() { // Create a new ListView control. ListView listView1 = new ListView(); listView1.Bounds = new Rectangle(new Point(10, 200), new Size(300, 200)); // Set the view to show details. listView1.View = View.Details; // Allow the user to edit item text. listView1.LabelEdit = true; // Allow the user to rearrange columns. listView1.AllowColumnReorder = true; // Display check boxes. listView1.CheckBoxes = true; // Select the item and subitems when selection is made. listView1.FullRowSelect = true; // Display grid lines. listView1.GridLines = true; // Sort the items in the list in ascending order. listView1.Sorting = SortOrder.Ascending; // Create three items and three sets of subitems for each item. ListViewItem item1 = new ListViewItem("item1", 0); // Place a check mark next to the item. item1.Checked = true; item1.SubItems.Add("1"); item1.SubItems.Add("2"); item1.SubItems.Add("3"); ListViewItem item2 = new ListViewItem("item2", 1); item2.SubItems.Add("4"); item2.SubItems.Add("5"); item2.SubItems.Add("6"); ListViewItem item3 = new ListViewItem("item3", 0); // Place a check mark next to the item. item3.Checked = true; item3.SubItems.Add("7"); item3.SubItems.Add("8"); item3.SubItems.Add("9"); // Create columns for the items and subitems. // Width of -2 indicates auto-size. listView1.Columns.Add("Item Column", -2, HorizontalAlignment.Left); listView1.Columns.Add("Column 2", -2, HorizontalAlignment.Left); listView1.Columns.Add("Column 3", -2, HorizontalAlignment.Left); listView1.Columns.Add("Column 4", -2, HorizontalAlignment.Center); //Add the items to the ListView. listView1.Items.AddRange(new ListViewItem[] { item1, item2, item3 }); // Add the ListView to the control collection. this.Controls.Add(listView1); } private void ScratchForm_Resize(object sender, EventArgs e) { //ResizeControls(this); foreach (Control c in Controls) { ResizeControls(c); } originalSize = Size; } private void ResizeControls(Control c) { float newWidth = (float)Size.Width / (float)originalSize.Width; float newHeight = (float)Size.Height / (float)originalSize.Height; //System.Diagnostics.Debug.WriteLine("newWidth=" + newWidth + "; originalSize.Width = " + originalSize.Width + "; Size.Width =" + Size.Width); //System.Diagnostics.Debug.WriteLine("newHeight=" + newHeight + "; originalSize.Height = " + originalSize.Height + "; Size.Height =" + Size.Height); if (newWidth == 0) newWidth = 1; if (newHeight == 0) newHeight = 1; c.Font = new Font(c.Font.Name, c.Font.Size * newWidth* newHeight, c.Font.Style); //System.Diagnostics.Debug.WriteLine("Font size in points=" + c.Font.Size); //c.Scale(new SizeF(newWidth, newHeight)); //System.Diagnostics.Debug.WriteLine("Control name=" + c.Name + "; Location=" + c.Location.ToString()); int newLeft = Convert.ToInt32((float)c.Left * newWidth); int newTop = Convert.ToInt32((float)c.Top * newHeight); //System.Diagnostics.Debug.WriteLine("newLeft=" + newLeft + "; newTop=" + newTop); //c.SetBounds(newLeft, newTop, c.Width * (int)newWidth, c.Height * (int)newHeight, BoundsSpecified.Location); //System.Diagnostics.Debug.WriteLine("Location after scale =" + c.Location.ToString()); c.Left = Convert.ToInt32((float)c.Left * newWidth); c.Top = Convert.ToInt32((float)c.Top * newHeight); c.Width = Convert.ToInt32((float)c.Width * newWidth); c.Height = Convert.ToInt32((float)c.Height * newHeight); foreach (Control ctrl in c.Controls) { ResizeControls(ctrl); } } private void ScratchForm_Shown(object sender, EventArgs e) { originalSize = Size; } /*protected override void ResizeControls(Control c) { float panelWidth = (float)Size.Width / (float)mOriginalSize.Width; float panelHeight = (float)(Size.Height - (clipboardControl.splitter.SplitterDistance + clipboardControl.splitter.SplitterWidth)) / (float)mOriginalSize.Height; float newFontScale = (panelWidth < panelHeight ? panelWidth : panelHeight); if (panelWidth == 0) panelWidth = 1; if (panelHeight == 0) panelHeight = 1; if (newFontScale == 0) newFontScale = 1; c.Font = new Font(c.Font.Name, c.Font.Size * newFontScale, c.Font.Style); int newLeft = Convert.ToInt32((float)c.Left * panelWidth); int newTop = Convert.ToInt32((float)c.Top * panelHeight); c.SetBounds(newLeft, newTop, c.Width * (int)panelWidth, c.Height * (int)panelHeight, BoundsSpecified.Location); foreach (Control ctrl in c.Controls) { ResizeControls(ctrl); } } protected virtual void DoResize() { foreach (Control c in Controls) { ResizeControls(c); } mOriginalSize = Size; } * * protected virtual void ResizeControls(Control c) { if (c is TitleBar || c is GradientProgressBar) return; if (c is Panel || c is TabPage) { foreach (Control ctrl in c.Controls) { ResizeControls(ctrl); } return; } float newWidth = (float)Size.Width / (float)mOriginalSize.Width; float newHeight = (float)Size.Height / (float)mOriginalSize.Height; float newFontScale = (newWidth < newHeight ? newWidth : newHeight); if (newWidth == 0) newWidth = 1; if (newHeight == 0) newHeight = 1; if (newFontScale == 0) newFontScale = 1; c.Font = new Font(c.Font.Name, c.Font.Size * newFontScale, c.Font.Style); int newLeft = Convert.ToInt32((float)c.Left * newWidth); int newTop = Convert.ToInt32((float)c.Top * newHeight); c.SetBounds(newLeft, newTop, c.Width * (int)newWidth, c.Height * (int)newHeight, BoundsSpecified.Location); foreach (Control ctrl in c.Controls) { ResizeControls(ctrl); } } */ } }
namespace Demo.Implementations { public class TeacherCredentialTransformer { List<TeacherCredential> TransformLines(List<string> lines) { // implementation specifics } } }
using System; using System.Collections.Generic; using System.Text; using System.Linq; namespace ConsoleApplication { public class Program { public static bool CheckIfSumIsX2(int n, int x){ int sum = 0; while (n != 0) { sum += n % 10; n /= 10; } if(sum == x){ return true; }else{ return false; } } public int GetSmallestSum(List<int> input) { int smallest = 0; for(int i=input[0]; i<=input[1]; i++){ if(CheckIfSumIsX2(i, input[2]) == true){ smallest += i; break; } } return smallest; } public int GetHighestSum(List<int> input) { int highest = 0; for(int i=input[1]; i>=input[0]; i--){ if(CheckIfSumIsX2(i, input[2]) == true){ highest += i; break; } } return highest; } public static void Main(string[] args) { Program p = new Program(); // int smallest = 0; // int highest = 0; var input = new List<int>(); for(int i=0;i<3;i++){ string x = Console.ReadLine(); input.Add(Convert.ToInt32(x)); } Console.WriteLine(p.GetSmallestSum(input)); Console.WriteLine(p.GetHighestSum(input)); } } }
using System; using System.Collections.Generic; using System.Text; using Hayaa.DataAccess; using Hayaa.BaseModel; using Hayaa.Security.Service.Config; namespace Hayaa.Security.Service.Dao { internal partial class AppGrantDal { } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.Events; using UnityEngine.EventSystems; namespace BanSupport { public static class ButtonExtension { private static bool CreateButtonExIfNotExist(GameObject go, out ButtonEx buttonEx) { if (go == null) { Debug.LogWarning("call 'CreateButtonEx' function with null GameObject param !"); buttonEx = null; return false; } else { buttonEx = go.GetComponent<ButtonEx>(); if (buttonEx == null) { buttonEx = go.AddComponent<ButtonEx>(); } return true; } } private static bool CreateButtonExIfNotExist(Button button, out ButtonEx buttonEx) { if (button == null) { Debug.LogWarning("call 'CreateButtonEx' function with null Button param !"); buttonEx = null; return false; } return CreateButtonExIfNotExist(button.gameObject, out buttonEx); } #region GameObject.AddClick public static ButtonEx AddClick(this GameObject gameObject, Action action, float cdTime = 0) { if (CreateButtonExIfNotExist(gameObject, out ButtonEx buttonEx)) { buttonEx.AddClick(action, cdTime); } return buttonEx; } public static ButtonEx RemoveClick(this GameObject gameObject) { if (CreateButtonExIfNotExist(gameObject, out ButtonEx buttonEx)) { buttonEx.RemoveClick(); } return buttonEx; } #endregion #region GameObject.AddHold public static ButtonEx AddHold(this GameObject gameObject, Action action, float cdTime) { if (CreateButtonExIfNotExist(gameObject, out ButtonEx buttonEx)) { buttonEx.AddHold(action, cdTime); } return buttonEx; } public static ButtonEx RemoveHold(this GameObject gameObject) { if (CreateButtonExIfNotExist(gameObject, out ButtonEx buttonEx)) { buttonEx.RemoveHold(); } return buttonEx; } #endregion #region GameObject.AddRepeat public static ButtonEx AddRepeat(this GameObject gameObject, Action action, float cdTime) { if (CreateButtonExIfNotExist(gameObject, out ButtonEx buttonEx)) { buttonEx.AddRepeat(action, cdTime); } return buttonEx; } public static ButtonEx RemoveRepeat(this GameObject gameObject) { if (CreateButtonExIfNotExist(gameObject, out ButtonEx buttonEx)) { buttonEx.RemoveRepeat(); } return buttonEx; } #endregion #region Button.AddClick public static ButtonEx AddClick(this Button button, Action action, float cdTime = 0) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.AddClick(action, cdTime); } return buttonEx; } public static ButtonEx RemoveClick(this Button button) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.RemoveClick(); } return buttonEx; } #endregion #region Button.AddHold public static ButtonEx AddHold(this Button button, Action action, float cdTime) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.AddHold(action, cdTime); } return buttonEx; } public static ButtonEx RemoveHold(this Button button) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.RemoveHold(); } return buttonEx; } #endregion #region Button.AddRepeat public static ButtonEx AddRepeat(this Button button, Action action, float cdTime) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.AddRepeat(action, cdTime); } return buttonEx; } public static ButtonEx RemoveRepeat(this Button button) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.RemoveRepeat(); } return buttonEx; } #endregion #region Others public static ButtonEx SetInteractable(this Button button, bool b) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.SetInteractable(b); } return buttonEx; } public static ButtonEx SetInteractable(this GameObject go, bool b) { if (CreateButtonExIfNotExist(go, out ButtonEx buttonEx)) { buttonEx.SetInteractable(b); } return buttonEx; } public static bool IsInteractable(this GameObject go) { if (CreateButtonExIfNotExist(go, out ButtonEx buttonEx)) { return buttonEx.IsInteractable(); } return false; } public static bool IsInteractable(this Button button) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { return buttonEx.IsInteractable(); } return false; } public static ButtonEx LoadStyleSetting(this GameObject go, List<ButtonStyle> styles) { if (CreateButtonExIfNotExist(go, out ButtonEx buttonEx)) { buttonEx.LoadStyleSetting(styles); } return buttonEx; } public static ButtonEx LoadStyleSetting(this Button button, List<ButtonStyle> styles) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.LoadStyleSetting(styles); } return buttonEx; } public static ButtonEx SetStyle(this GameObject go, string styleName) { if (CreateButtonExIfNotExist(go, out ButtonEx buttonEx)) { buttonEx.SetStyle(styleName); } return buttonEx; } public static ButtonEx SetStyle(this Button button, string styleName) { if (CreateButtonExIfNotExist(button, out ButtonEx buttonEx)) { buttonEx.SetStyle(styleName); } return buttonEx; } #endregion } public class ButtonEx : ExBase, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler { /// <summary> /// 本脚本事件逻辑层的隔断 /// </summary> private bool interactable = true; #region AddClick public ButtonEx AddClick(Action action, float cdTime) { AddWidget(new ButtonClickWidget(this, action, cdTime)); return this; } public ButtonEx RemoveClick() { RemoveWidget<ButtonClickWidget>(); return this; } #endregion #region AddHold public ButtonEx AddHold(Action mainAction, float cdTime) { AddWidget(new ButtonHoldWidget(this, mainAction, cdTime)); return this; } public ButtonEx RemoveHold() { RemoveWidget<ButtonHoldWidget>(); return this; } #endregion #region AddRepeat public ButtonEx AddRepeat(Action mainAction, float cdTime) { AddWidget(new ButtonRepeatWidget(this, mainAction, cdTime)); return this; } public ButtonEx RemoveRepeat() { RemoveWidget<ButtonRepeatWidget>(); return this; } #endregion #region Others /// <summary> /// 目前Style是Style,Interactable是Interactable,彼此分离,互不影响 /// </summary> public ButtonEx LoadStyleSetting(List<ButtonStyle> styles) { AddWidget(new ButtonStyleWidget(this, styles), true); return this; } public ButtonEx SetStyle(string styleName) { SendEvent("OnStyle", styleName); return this; } /// <summary> /// 目前Style是Style,Interactable是Interactable,彼此分离,互不影响 /// </summary> public ButtonEx SetInteractable(bool b) { this.interactable = b; if (this.TryGetComponent(out Button aButton)) { aButton.interactable = b; } return this; } public bool IsInteractable() { return this.interactable; } #endregion #region 系统函数 public void OnPointerClick(PointerEventData eventData) { if (this.interactable) { SendEvent("OnClick", eventData); } } public void OnPointerDown(PointerEventData eventData) { if (this.interactable) { SendEvent("OnPointDown", eventData); } } public void OnPointerUp(PointerEventData eventData) { if (this.interactable) { SendEvent("OnPointUp", eventData); } } #endregion } }
using System; public class BlockModel : IBlockModel { private Action UpdateEvent; private BlockData blockData; public BlockModel(BlockData data) { blockData = data; } public BlockData GetBlockData() { return blockData; } public void SubscribeToUpdateModel(Action action) { UpdateEvent += action; } public void UpdateModel() { UpdateEvent?.Invoke(); } }
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc.Razor; namespace CustomServiceRegistration.Configurations { public class AngularAppViewLocationExpander : IViewLocationExpander { public void PopulateValues(ViewLocationExpanderContext context) { context.Values["customviewlocation"] = nameof(AngularAppViewLocationExpander); } public IEnumerable<string> ExpandViewLocations( ViewLocationExpanderContext context, IEnumerable<string> viewLocations) { var viewLocationFormats = new[] { "~/wwwroot/app/components/{1}/{0}.html", "~/wwwroot/app/{1}/{0}.html", "~/wwwroot/app/{0}.html", "~/wwwroot/{0}.html" }; return viewLocationFormats; } } }
//Triangle Area public void TriangleArea(List<string> passInList) { StringBuilder sb = new StringBuilder(); foreach (string s in passInList) { string[] trianglesSides = s.Split(' '); int x1 = Convert.ToInt32(trianglesSides[0]); int y1 = Convert.ToInt32(trianglesSides[1]); int x2 = Convert.ToInt32(trianglesSides[2]); int y2 = Convert.ToInt32(trianglesSides[3]); int x3 = Convert.ToInt32(trianglesSides[4]); int y3 = Convert.ToInt32(trianglesSides[5]); const double ONE_HALF = .5; double solution = ONE_HALF * (Math.Abs((x1 - x3) * (y2 - y1) - (x1 - x2) * (y3 - y1))); Console.Write(solution + " "); sb.Append(solution + " "); } Console.WriteLine(); }
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using MuggleTranslator.Runtime; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Input; namespace MuggleTranslator.ViewModel { public class UserConfigViewModel : ViewModelBase { #region BindingProperty private bool _enableScreenshotTranlate; public bool EnableScreenshotTranlate { get => _enableScreenshotTranlate; set { _enableScreenshotTranlate = value; RaisePropertyChanged(nameof(EnableScreenshotTranlate)); } } private string _clientId; public string ClientId { get => _clientId; set { _clientId = value; RaisePropertyChanged(nameof(ClientId)); } } private string _clientSecret; public string ClientSecret { get => _clientSecret; set { _clientSecret = value; RaisePropertyChanged(nameof(ClientSecret)); } } #endregion #region BindingCommand private RelayCommand _updateUserConfigCommand; public ICommand UpdateUserConfigCommand { get { if (_updateUserConfigCommand == null) _updateUserConfigCommand = new RelayCommand(() => UpdateUserConfig()); return _updateUserConfigCommand; } } private void UpdateUserConfig() { UserConfig.Update(_enableScreenshotTranlate, _clientId, _clientSecret); MessageBox.Show("保存成功", "提示"); } private RelayCommand<RoutedEventArgs> _windowLoaded; public ICommand WindowLoadedCommand { get { if (_windowLoaded == null) _windowLoaded = new RelayCommand<RoutedEventArgs>(OnWindowLoaded); return _windowLoaded; } } private void OnWindowLoaded(RoutedEventArgs e) { EnableScreenshotTranlate = UserConfig.Current.EnableScreenshotTranlate; ClientId = UserConfig.Current.ClientId; ClientSecret = UserConfig.Current.ClientSecret; } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Strategy { class Program { static void Main(string[] args) { //Estrategia 1 GuardarPDF pdf = new GuardarPDF(); //Estrategia 2 GuardarHTML html = new GuardarHTML(); EditorDeTexto e = new EditorDeTexto(pdf); e.TextoContenido = "Este es el texto a guardar"; e.GuardarTexto(); Console.ReadKey(); } } }
//@Author Justin Scott Bieshaar. //For further questions please read comments or reach me via mail contact@justinbieshaar.com using System.Collections; using System.Collections.Generic; using UnityEngine; public class DashHitCharacter : Character { [SerializeField] [Tooltip("Stun length in seconds")] private float _stunTime = 2.0f; [SerializeField] private AudioClip _dashHitClip; private float _playerHeight = 2.0f; // stun particle position private float _time = 0.0f; private ParticleManager _particleManager; private SoundController _soundController; void Start() { //init _particleManager = ParticleManager.Instance; _soundController = SoundController.Instance; } void OnDashHit(float iImpulse) { if (pIsStunned) // DONT STUN WHEN ALREADY STUNNED! return; pIsStunned = true; if (_dashHitClip != null) _soundController.PlaySound(_dashHitClip, false); StartCoroutine(Stunned()); } void Update() { Stun(); // updat stun if (pIsStunned) { Vector3 tParticlePosition = transform.position; tParticlePosition.y += _playerHeight; _particleManager.SpawnParticle(ParticleType.STUNNED + pPlayerInformation.PlayerID, tParticlePosition); } } /// <summary> /// Stun player /// </summary> void Stun() { Character[] tCharacters = GetComponentsInChildren<Character>(); for (int i = 0; i < tCharacters.Length; i++) { tCharacters[i].Stun(pIsStunned); // stun all character classes } } /// <summary> /// Stop stun after _stunTime /// </summary> /// <returns></returns> IEnumerator Stunned() { yield return new WaitForSeconds(_stunTime); pIsStunned = false; } }
using Machine.Learning.Models; using Machine.Learning.Training; using Newtonsoft.Json; using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Machine.Learning { //class Program //{ // static void Main(string[] args) // { // Random rand = new Random(); // Console.WriteLine("Machine Learning test"); // TestNetwork testNetwork = new TestNetwork(); // testNetwork.Initialize(new int[] { 1, 16, 1 }); // double rssi = -76; // var value = (rssi * -1) / 100; // double[] input = new double[] { value }; // var output = testNetwork.FeedForward(input); // Console.WriteLine("Output:"); // for (var i = 0; i < output.Length; i++) // { // Console.WriteLine(output[i].Value); // } // Console.ReadLine(); // } //} class Program { //This reperesnts the Layers and how many neurons per layer [Input Neurons - (Hidden Layers) - Output Neurons] static int[] NETWORK_LAYOUT = new int[] { 4, 36, 3 }; static Stores.IStore store; static void Main(string[] args) { store = new Stores.JsonStore(); Random rand = new Random(); //Number of iterations for training... int numberOfIterations = 10000; string irisTrainingSet = File.ReadAllText(Path.Combine(Environment.CurrentDirectory, @"Training\DataSets\iris_dataset.json")).Replace(Environment.NewLine, ""); var trainingSetObj = JsonConvert.DeserializeObject<TrainingSetObj>(irisTrainingSet); var trainingSets = trainingSetObj.TrainingSets; if (trainingSets == null || trainingSets.Count <= 0) { Console.WriteLine("Incorrect Training Data.."); return; } NeuralNetwork network = null; //------ Loading Pre-existing (trained) network... if (File.Exists(Path.Combine(Environment.CurrentDirectory, "saved_network.json"))) network = NeuralNetworkFactory.LoadNetwork(store); else //---- Generating the network using the predefined NETWORK_LAYOUT... network = NeuralNetworkFactory.GenrateNewNetwork(NETWORK_LAYOUT); StringBuilder builder = new StringBuilder("Creating Network"); for (var i = 0; i < NETWORK_LAYOUT.Length; i++) builder.Append($"{NETWORK_LAYOUT[i]}-"); Console.WriteLine(builder.ToString()); //--------------------TESTING THE NETWORK BEFORE BEING TRAINIED-------------------------- Console.WriteLine("----BEFORE TRAINING-----"); Console.WriteLine("A New Test Set of {0} is Tested", trainingSets.Count); foreach (var item in trainingSets) { var output = network.FeedForward(item.input.ToArray()); Console.WriteLine("Expected: {0} Output: {1}", item.expected.ToArray().PrintDouble(), output.PrintNeuronValue()); } Console.WriteLine(); //------------------------- PERFORMING THE TRAINING NOW--------------------- Console.WriteLine("Training Networking using {0} training sets", trainingSets.Count); Stopwatch watch; watch = Stopwatch.StartNew(); for (var i = 0; i < numberOfIterations; i++) { // var index = i % trainingSets.Count; var item = trainingSets[rand.Next(0, trainingSets.Count)]; //Training the network by passing in the input/s and what the "Expected Output/s should be... var output = network.Train(item.input.ToArray(), item.expected.ToArray()); } watch.Stop(); Console.WriteLine("Completed Training in {0}", watch.Elapsed); Console.WriteLine(); store.Add(network.Layers); //-------------------------TESTING THE NETWORK AFTER THE TRAINING-------------------------- Console.WriteLine("----AFTER TRAINING-----"); Console.WriteLine("A New Test Set of {0} is Tested", trainingSets.Count); foreach (var item in trainingSets) { var output = network.FeedForward(item.input.ToArray()); Console.WriteLine("Expected: {0} Output: {1}", item.expected.ToArray().PrintHighestWeightedValue(), output.PrintHighestWeightedValue()); } Console.ReadLine(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WorkWithInterface { class Stationery : IProduction { public int Volume { get; set; } public int DefectiveVolume { get; set; } public string Name { get; set; } public Stationery() { Volume = 0; DefectiveVolume = 0; Name = "Неизвестный продукт"; } public Stationery(int volume, int defectiveVolume, string name) { Volume = volume; DefectiveVolume = defectiveVolume; Name = name; } public double PercentOfDefectiveProduct(int volume, int defectiveVolume) { Volume = volume; DefectiveVolume = defectiveVolume; if (Volume > 0) return DefectiveVolume * 100 / Volume; else return 0; } public void DisplayInfo() { Console.WriteLine($"Название канцелярского товара: {Name} \n" + $"Объем продукции: {Volume}\n" + $"Объем бракованной продукции: {DefectiveVolume}"); if (!double.IsNaN(PercentOfDefectiveProduct(Volume, DefectiveVolume))) { Console.WriteLine("Процент бракованной продукции: " + PercentOfDefectiveProduct(Volume, DefectiveVolume) + "%\n"); } } } }
using EntMob_Uni.Services; using EntMob_Uni.Utility; using EntMob_Uni.View; using Jogging.Model; using System; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace EntMob_Uni.ViewModel { public class DetailViewModel : INotifyPropertyChanged { public ICommand BackCommand { get; set; } private ISessionService sessionService; public event PropertyChangedEventHandler PropertyChanged; private Session selectedSession { get; set; } public Session SelectedSession { get { return selectedSession; } set { selectedSession = value; RaisePropertyChanged("SelectedSession"); } } private void RaisePropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } public DetailViewModel(ISessionService sessionService) { this.sessionService = sessionService; LoadCommands(); RegisterForMessages(); } private void RegisterForMessages() { Messenger.Default.Register<Session>(this, OnSessionReceived); } private void OnSessionReceived(Session session) { SelectedSession = session; LoadSessionAverages(); } private async void LoadSessionAverages() { var result = await sessionService.GetAverageForSession(selectedSession); SelectedSession = result; } private void LoadCommands() { BackCommand = new CustomCommand(Back, null); } private void Back(object o) { NavigationService.Default.Navigate(typeof(ValuesPage)); } } }
using System; namespace ObserverExample { public class RandomNumberGenerator : NumberGenerator { private int _number; private Random _rand = new Random(); public override void Execute() { for (int i = 0; i < 20; i++) { _number = _rand.Next(0, 50); NotifyObservers(); } } public override int GetNumber() { return _number; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Cs_Notas.Dominio.ValuesObject { public class SituacaoCpfCnpj { public int Codigo { get; set; } public string Descricao { get; set; } public List<SituacaoCpfCnpj> ObterListaSituacaoCpfCnpj() { var listaSituacao = new List<SituacaoCpfCnpj>(); var situacao = new SituacaoCpfCnpj(); situacao.Codigo = 0; situacao.Descricao = "Inscrito no Cpf/Cnpj "; listaSituacao.Add(situacao); situacao = new SituacaoCpfCnpj(); situacao.Codigo = 1; situacao.Descricao = "Sem CPF/CNPJ - Decisão Judicial"; listaSituacao.Add(situacao); situacao = new SituacaoCpfCnpj(); situacao.Codigo = 2; situacao.Descricao = "Sem CNPJ - Anterior a IN 200"; listaSituacao.Add(situacao); situacao = new SituacaoCpfCnpj(); situacao.Codigo = 3; situacao.Descricao = "Sem CPF - Anterio a IN 190"; listaSituacao.Add(situacao); return listaSituacao; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using ShootingGame.Models; using ShootingGame.GameUtil; using GameData; using ShootingGame; namespace ShootingGame { public class TankModel : DrawableModel { #region Fields // The XNA framework Model object that we are going to display. private bool isMoving; private double currentTurnedAngle; private Mode currentState; private int[,] cityMap; private Vector3 targetDestination; private bool enableAutoSearch; private LinkedList<Vector2> pathToTargetDestination; private PathFinder finder; private bool cannonMovingUp; private bool enableAttack; public TankStatusMode tankStaus; private static int healthGlobe; private float produceHealthGlobeCD; private float timeSinceLastHealthGlobeProduced; public enum Mode{ WANDER, FOLLOW, STOP } // Shortcut references to the bones that we are going to animate. // We could just look these up inside the Draw method, but it is more // efficient to do the lookups while loading and cache the results. ModelBone leftBackWheelBone; ModelBone rightBackWheelBone; ModelBone leftFrontWheelBone; ModelBone rightFrontWheelBone; ModelBone leftSteerBone; ModelBone rightSteerBone; ModelBone turretBone; ModelBone cannonBone; ModelBone hatchBone; // Store the original transform matrix for each animating bone. Matrix leftBackWheelTransform; Matrix rightBackWheelTransform; Matrix leftFrontWheelTransform; Matrix rightFrontWheelTransform; Matrix leftSteerTransform; Matrix rightSteerTransform; Matrix turretTransform; Matrix cannonTransform; Matrix hatchTransform; // Array holding all the bone transform matrices for the entire model. // We could just allocate this locally inside the Draw method, but it // is more efficient to reuse a single array, as this avoids creating // unnecessary garbage. // Current animation positions. float wheelRotationValue; float steerRotationValue; float turretRotationValue; float cannonRotationValue; float hatchRotationValue; #endregion #region Properties /// <summary> /// Gets or sets the wheel rotation amount. /// </summary> public float WheelRotation { get { return wheelRotationValue; } set { wheelRotationValue = value; } } /// <summary> /// Gets or sets the steering rotation amount. /// </summary> public float SteerRotation { get { return steerRotationValue; } set { steerRotationValue = value; } } /// <summary> /// Gets or sets the turret rotation amount. /// </summary> public float TurretRotation { get { return turretRotationValue; } set { turretRotationValue = value; } } /// <summary> /// Gets or sets the cannon rotation amount. /// </summary> public float CannonRotation { get { return cannonRotationValue; } set { cannonRotationValue = value; } } /// <summary> /// Gets or sets the entry hatch rotation amount. /// </summary> public float HatchRotation { get { return hatchRotationValue; } set { hatchRotationValue = value; } } #endregion public TankModel(TankStatusMode tankStaus, Model inModel, Matrix inWorldMatrix, Vector3 newDirection, int[,] cityMap) : base(inModel, inWorldMatrix, newDirection) { leftBackWheelBone = inModel.Bones["l_back_wheel_geo"]; rightBackWheelBone = inModel.Bones["r_back_wheel_geo"]; leftFrontWheelBone = inModel.Bones["l_front_wheel_geo"]; rightFrontWheelBone = inModel.Bones["r_front_wheel_geo"]; leftSteerBone = inModel.Bones["l_steer_geo"]; rightSteerBone = inModel.Bones["r_steer_geo"]; turretBone = inModel.Bones["turret_geo"]; cannonBone = inModel.Bones["canon_geo"]; hatchBone = inModel.Bones["hatch_geo"]; // Store the original transform matrix for each animating bone. leftBackWheelTransform = leftBackWheelBone.Transform; rightBackWheelTransform = rightBackWheelBone.Transform; leftFrontWheelTransform = leftFrontWheelBone.Transform; rightFrontWheelTransform = rightFrontWheelBone.Transform; leftSteerTransform = leftSteerBone.Transform; rightSteerTransform = rightSteerBone.Transform; turretTransform = turretBone.Transform; cannonTransform = cannonBone.Transform; hatchTransform = hatchBone.Transform; // Allocate the transform matrix array. worldMatrix = inWorldMatrix; this.direction = newDirection; this.cityMap = cityMap; this.tankStaus = tankStaus; //targetDestination = new Vector3(700,0,-700); finder = new PathFinder(); finder.SetUpMap(cityMap); pathToTargetDestination = new LinkedList<Vector2>(); isMoving = false; currentTurnedAngle = 0; ActivateWanderMode(); cannonMovingUp = true; enableAttack = false; produceHealthGlobeCD = 30000; timeSinceLastHealthGlobeProduced = 0; healthGlobe = 0; } public void DeductHealthGlobe() { healthGlobe = healthGlobe > 1 ? healthGlobe - 1 : 0; } public void EnableAttack() { this.enableAttack = true; } public void DisableAttack() { this.enableAttack = false; } private void EnableAutoSearch() { this.enableAutoSearch = true; } private void DisableAutoSearch() { this.enableAutoSearch = false; } public void ActivateWanderMode() { EnableAutoSearch(); this.currentState = Mode.WANDER; } public void ActivateFollowMode() { pathToTargetDestination.Clear(); this.currentState= Mode.FOLLOW; } public void DeactiveActionMode() { this.enableAutoSearch = false; this.currentState = Mode.STOP; } public void yawRotate(float rawRotate) { rotation *= Matrix.CreateFromYawPitchRoll(rawRotate, 0, 0); } public void DoTranslation(Vector3 translation) { worldMatrix *= Matrix.CreateTranslation(translation); } public void setDirection(Vector3 direction) { direction.Normalize(); this.direction = direction; } public void SetDestination(Vector3 destination) { this.targetDestination = destination; } public Vector2 PickRandomPosition(Random rnd) { int xIndex = rnd.Next(cityMap.GetLength(0)); int yIndex = rnd.Next(cityMap.GetLength(1)); if (cityMap[xIndex, yIndex] == 0) return new Vector2(xIndex, yIndex); else PickRandomPosition(rnd); return new Vector2(0,0); } public int GetHealthGlobe() { return healthGlobe; } public void Update(GameTime gameTime, Player player, Random rnd) { if (healthGlobe <= 3) { timeSinceLastHealthGlobeProduced += gameTime.ElapsedGameTime.Milliseconds; { if (timeSinceLastHealthGlobeProduced >= produceHealthGlobeCD) { timeSinceLastHealthGlobeProduced = 0; healthGlobe++; } } } if (this.currentState.ToString().Equals(this.tankStaus.Status_wander )) { if (enableAutoSearch) { targetDestination = MapIndexToWorldCorrd(PickRandomPosition(rnd)); DisableAutoSearch(); } StartMoving(player, rnd); } else if (this.currentState.ToString().Equals(this.tankStaus.Status_FOLLOW)) { targetDestination = player.Position; StartMoving(player, rnd); } else if (this.currentState.ToString().Equals(this.tankStaus.Status_STOP)) { } if (enableAttack) { UpdateCannonRotation(); TurretRotation += 0.02f; if (TurretRotation > Math.PI * 2) TurretRotation -= (float)Math.PI * 2; } } private void UpdateCannonRotation() { if (cannonMovingUp) { CannonRotation -= 0.005f; if (CannonRotation <= -1.5f) cannonMovingUp = false; } else { CannonRotation += 0.005f; if (CannonRotation >-0.2f) cannonMovingUp = true; } } private void StartMoving(Player player, Random rnd) { if (isMoving) { WheelRotation += 0.05f; } if (Position != targetDestination) { if (Math.Abs(Position.X - targetDestination.X) <= 25 && Math.Abs(Position.Z - targetDestination.Z) <= 25) { Position = targetDestination; isMoving = false; pathToTargetDestination.Clear(); if (this.currentState.ToString().Equals(tankStaus.Status_wander)) EnableAutoSearch(); else if (this.currentState.ToString().Equals(tankStaus.Status_FOLLOW)) DeactiveActionMode(); } else { if (null == pathToTargetDestination || pathToTargetDestination.Count == 0) CalculatePath(); if (null != pathToTargetDestination && pathToTargetDestination.Count > 0) { Vector2 targetPoint = pathToTargetDestination.First(); Vector3 targetPoint1 = MapIndexToWorldCorrd(targetPoint); if (Math.Abs(Position.X - targetPoint1.X) <= 25 && Math.Abs(Position.Z - targetPoint1.Z) <= 25) { Position = targetPoint1; pathToTargetDestination.RemoveFirst(); } else { double angleToTurn = MathUtil.AngleToTurn(Position, targetPoint1); isMoving = true; if (Math.Abs(currentTurnedAngle - angleToTurn) >= Math.PI / 50f) { if (currentTurnedAngle > angleToTurn) { SteerRotation -= (float)Math.PI / 500f; yawRotate(-(float)Math.PI / 360f); currentTurnedAngle -= Math.PI / 360; } else { SteerRotation += (float)Math.PI / 500f; yawRotate((float)Math.PI / 360f); currentTurnedAngle += Math.PI / 360; } if (Math.Abs(currentTurnedAngle - angleToTurn) <= Math.PI / 100f) { SteerRotation = 0; yawRotate((float)(angleToTurn - currentTurnedAngle)); currentTurnedAngle = angleToTurn; } } else { if (CheckIsCollidingWithPlayer(Matrix.CreateTranslation(direction), player.Position)) isMoving = false; else { isMoving = true; SteerRotation = 0; setDirection((targetPoint1 - position)); WorldMatrix = worldMatrix * Matrix.CreateTranslation(direction); } } } } } } } public bool IsAttackEnabled() { return this.enableAttack; } private bool CheckIsCollidingWithPlayer(Matrix translation, Vector3 playerPosition) { Matrix nextFrameWorldMatrix = WorldMatrix * translation; return DetectPlayerCollision(nextFrameWorldMatrix , playerPosition); } private bool IsTurnedToTarget(Vector3 targetPoint) { return true; } private void CalculatePath() { pathToTargetDestination = finder.FindPath(MapWorldCorrdToIndex(Position), MapWorldCorrdToIndex(targetDestination)); } private Vector3 MapWorldCorrdToIndex(Vector3 worldCoord) { float xIndex = (worldCoord.X - worldCoord.X % 50)/50; float zIndex = -(worldCoord.Z - worldCoord.Z % 50)/50; return new Vector3(xIndex, 0 , zIndex); } private Vector3 MapIndexToWorldCorrd(Vector2 mapIndex) { float xCoord = mapIndex.X * 50 + 25; float zCoord = mapIndex.Y * 50 + 25; return new Vector3(xCoord, 0, -zCoord); } public Vector3 GetDirection() { return direction; } public bool DetectPlayerCollision(Vector3 playerPosition) { BoundingSphere playerSphere = new BoundingSphere(playerPosition, 10f); foreach (ModelMesh myModelMeshes in model.Meshes) { if (myModelMeshes.BoundingSphere.Transform(worldMatrix).Intersects(playerSphere)) return true; } return false; } public bool DetectPlayerCollision(Matrix newWorld, Vector3 playerPosition) { BoundingSphere playerSphere = new BoundingSphere(playerPosition, 10f); foreach (ModelMesh myModelMeshes in model.Meshes) { if (myModelMeshes.BoundingSphere.Transform(newWorld).Intersects(playerSphere)) return true; } return false; } public override void Draw(Matrix viewMatrix, Matrix projectionMatrix) { Matrix wheelRotation = Matrix.CreateRotationX(wheelRotationValue); Matrix steerRotation = Matrix.CreateRotationY(steerRotationValue); Matrix turretRotation = Matrix.CreateRotationY(turretRotationValue); Matrix cannonRotation = Matrix.CreateRotationX(cannonRotationValue); Matrix hatchRotation = Matrix.CreateRotationX(hatchRotationValue); // Apply matrices to the relevant bones. leftBackWheelBone.Transform = wheelRotation * leftBackWheelTransform; rightBackWheelBone.Transform = wheelRotation * rightBackWheelTransform; leftFrontWheelBone.Transform = wheelRotation * leftFrontWheelTransform; rightFrontWheelBone.Transform = wheelRotation * rightFrontWheelTransform; leftSteerBone.Transform = steerRotation * leftSteerTransform; rightSteerBone.Transform = steerRotation * rightSteerTransform; turretBone.Transform = turretRotation * turretTransform; cannonBone.Transform = cannonRotation * cannonTransform; hatchBone.Transform = hatchRotation * hatchTransform; // Look up combined bone matrices for the entire model. model.CopyAbsoluteBoneTransformsTo(modelTransforms); //Matrix tankview = Matrix.CreateLookAt(tankPosition, camera.cameraPosition+camera.cameraDirection, Vector3.Up); // Vector3 tankDirection = camera.cameraPosition + camera.cameraDirection; //System.Diagnostics.Debug.WriteLine("Tank"+ tankDirection); // Draw the model. foreach (ModelMesh mesh in model.Meshes) { foreach (BasicEffect effect in mesh.Effects) { effect.EnableDefaultLighting(); effect.World = modelTransforms[mesh.ParentBone.Index] *rotation * worldMatrix; effect.View = viewMatrix; effect.Projection = projectionMatrix; } mesh.Draw(); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CLCommonCore.DTO { class PublisherDTO { public int PublisherID { get; set; } // Primary Key Property public string Name { get; set; } public string Address { get; set; } public string City { get; set; } public string state { get; set; } public int Zip { get; set; } } }
namespace Thingy.GraphicsPlusGui { public interface IElementStrategy { int Priority { get; } bool CanCreateElementFor(string elementType); IElement Create(string elementType); } public interface IElementStrategy<T> : IElementStrategy { }; }
namespace Bridge { public class Xamarin { protected readonly IMobileDevelopmentKit _framework; public Xamarin(IMobileDevelopmentKit framework) { _framework = framework; } } }
using AppointmentManagement.Entities.Concrete; using System; using System.Collections.Generic; using System.Text; namespace AppointmentManagement.Business.Abstract { public interface IOrderWarehouseService { List<OrderWarehouse> GetOrderWarehouses(); } }
using System; namespace Day3Exercise { public class D2 { static void Main() { // input a Console.Write("Input first integer: "); int a = Int32.Parse(Console.ReadLine()); int a1 = a; // input b Console.Write("Input second integer: "); int b = Int32.Parse(Console.ReadLine()); int b1 = b; // if a does not equals b, larger number - smaller number while (a != b) { if (a > b) { a = a - b; } else { b = b - a; } } Console.WriteLine("HCF is {0}", a); int lCm = (a1 * b1 / a); Console.WriteLine("LCM is {0}", lCm); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TaskScheduler { public interface ITaskScheduler { List<Task> RunTasks(List<Task> inTasks); void CheckDependency(Task inTask); } }
using OpHomeSecurity.Web.Database; using OpHomeSecurity.Web.ViewModels; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace OpHomeSecurity.Web.Controllers { public class HomeController : Controller { public ActionResult Index() { DatabaseService service = new DatabaseService(); var results = service.GetImages(); GalleryViewModel model = new GalleryViewModel(); model.Albums = results.Where(a => a.IsFeatured == true).ToList(); return View(model); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using CommonLibrary.Framework; using CommonLibrary.Framework.Tracing; using CommonLibrary.Framework.Validation; using EpisodeGrabber.Library.Entities; namespace EpisodeGrabber.Library.Services { public abstract class EntityServiceBase { #region Constants protected const string SaveFileName = "grabber.xml"; protected const string OldSaveFileName = "show.xml"; #endregion public static IEntityService GetService(EntityBase entity) { ValidationUtility.ThrowIfNullOrEmpty(entity, "entity"); IEntityService service = null; if (entity is Show) service = new ShowService(); else if (entity is Episode) service = new EpisodeService(); else if (entity is Season) service = new SeasonService(); else if (entity is Movie) service = new MovieService(); return service; } public static void DeleteCache(string directoryPath) { if (Directory.Exists(directoryPath)) { var files = Directory.GetFiles(directoryPath, SaveFileName, SearchOption.AllDirectories); files.ForEach(f => File.Delete(f)); } } public static List<EntityBase> ScanDirectory(string directoryPath, IEnumerable<string> mediaTypes) { List<EntityBase> entities = new List<EntityBase>(); DirectoryInfo directory = new DirectoryInfo(directoryPath); if (directory.Exists) { // Rename the old-named files FileInfo[] oldFiles = directory.GetFiles(EntityServiceBase.OldSaveFileName); if (oldFiles.Count() == 1) { string oldName = oldFiles[0].FullName; string newName = System.IO.Path.Combine(directory.FullName, EntityServiceBase.SaveFileName); if (!File.Exists(newName)) { TraceManager.Trace(string.Format("Old file name {0} found, renaming to {1}.", oldName, newName)); oldFiles[0].MoveTo(newName); } else { TraceManager.Trace(string.Format("Old file {0} exists and new file {1} is already there - deleting the old file.", oldName, newName)); oldFiles[0].Delete(); } } FileInfo[] grabberFiles = directory.GetFiles(EntityServiceBase.SaveFileName); if (grabberFiles.Count() == 1) { TraceManager.Trace(string.Format("{0} file found at {1}.", EntityServiceBase.SaveFileName, directory.FullName), (int)TraceVerbosity.Verbose); EntityBase entity = null; string filepath = grabberFiles[0].FullName; Type type = null; XmlDocument doc = new XmlDocument(); try { doc.Load(grabberFiles[0].FullName); } catch (Exception) { TraceManager.Trace(string.Format("Unable to load file {0}.", grabberFiles[0].FullName), TraceTypes.Error); } if (doc.DocumentElement != null) { string typeName = doc.DocumentElement.Name; switch (typeName.ToLowerInvariant()) { case "show": type = typeof(Show); break; case "movie": type = typeof(Movie); break; } if (type != null) { try { XmlSerializer serializer = new XmlSerializer(type); using (FileStream fs = new FileStream(grabberFiles[0].FullName, FileMode.Open)) { entity = (EntityBase)serializer.Deserialize(fs); } } catch (Exception) { // Pass silently } } } if (entity != null) { entity.Path = directory.FullName; entities.Add(entity); } } // If there was no configuration file, try to figure out what kind of item this is. if (entities.IsNullOrEmpty()) { DirectoryInfo seasonDirectory = directory.GetDirectories("Season *").FirstOrDefault(); if (seasonDirectory != null) { string showName = seasonDirectory.Parent.Name; entities.Add(new Show() { Path = directory.FullName, Name = showName }); } } if (entities.IsNullOrEmpty()) { FileInfo[] videoFiles = directory.GetFilesPattern("*.avi|*.mp4|*.divx|*.m4v"); if (videoFiles.Count() > 0) { bool isAllShows = true; bool isNoneShows = true; foreach (FileInfo videoFile in videoFiles) { if (!ShowService.IsShowFile(videoFile.FullName)) { isAllShows = false; } else { isNoneShows = false; } } if (isAllShows) { // If all the video files in the directory have the season/episode type file naming convention, then // the directory that houses these files must be the show directory. TraceManager.Trace(string.Format("Show found at {0}", directory.FullName), TraceVerbosity.Verbose); entities.Add(new Show() { Path = directory.FullName, Name = directory.Name }); } else if (isNoneShows) { // If none of the video files in the directory have the season/episode type file naming convention, then // the directory that houses these files is assumed to be a movie directory. TraceManager.Trace(string.Format("Movie found at {0}", directory.FullName), TraceVerbosity.Verbose); Match match = Regex.Match(directory.Name, @"(.*?)\((\d{4})\)(.*?)"); if (match.Success) { int year = int.Parse(match.Groups[2].Value); string name = string.Concat(match.Groups[1].Value, " ", match.Groups[3].Value).Trim(); entities.Add(new Movie() { Path = directory.FullName, Name = name, Created = new DateTime(year, 1, 1) }); } else { entities.Add(new Movie() { Path = directory.FullName, Name = directory.Name }); } } } } if (entities.IsNullOrEmpty()) { if (directory.GetDirectories().Count() > 0) { TraceManager.Trace(string.Format("Nothing found at {0}, looking deeper ...", directory.FullName), TraceVerbosity.Verbose); foreach (DirectoryInfo subDirectory in directory.GetDirectories()) { entities.AddRange(EntityServiceBase.ScanDirectory(subDirectory.FullName, mediaTypes)); } } else { TraceManager.Trace(string.Format("Nothing found at {0}", directory.FullName), TraceVerbosity.Verbose); } } // Initialize the shows ... hacking here ... entities.Where(e => e is Show).ForEach(e => new ShowService().Initialize(e, mediaTypes)); } return entities; } public void Save(EntityBase entity) { string filePath = System.IO.Path.Combine(entity.Path, EntityServiceBase.SaveFileName); XmlSerializer serializer = new XmlSerializer(entity.GetType()); TraceManager.Trace(string.Format("Writing file '{0}'", filePath), TraceVerbosity.Verbose, TraceTypes.Information); using (XmlWriter writer = XmlWriter.Create(filePath, new XmlWriterSettings() { Indent = true })) { serializer.Serialize(writer, entity); } } public void Delete(EntityBase entity) { string filePath = System.IO.Path.Combine(entity.Path, EntityServiceBase.SaveFileName); if (File.Exists(filePath)) { File.Delete(filePath); } } public virtual Image GetBannerImage(EntityBase entity) { return entity.Images.FirstOrDefault(); } protected string ParseName(string name) { // Remove the year value in parenthesis string value = Regex.Replace(name, @"\(\d{4}\)", string.Empty); value = value.Replace('_', ' '); value.Trim(); return value; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Data; using System.Diagnostics; using System.Linq; using System.ServiceProcess; using System.Text; using System.Threading.Tasks; using System.Timers; namespace LLU_Service2 { public partial class Scheduler : ServiceBase { private Timer timer1 = null; public Scheduler() { InitializeComponent(); } protected override void OnStart(string[] args) { timer1 = new Timer(); this.timer1.Interval = 3000; //this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Tick); this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.Timer1_SQLValidate); timer1.Enabled = true; timer1.Start(); //Library.WriteErrorLog(ConfigurationManager.AppSettings["AP_Comment"]); } private void Timer1_SQLValidate(object sender, ElapsedEventArgs e) { LibrarySQL.ExecSQLfromAppConfig(); // LibrarySQL.ShowActiveStatements_exec(); } private void timer1_Tick(object sender, ElapsedEventArgs e) { Library.WriteErrorLog("Timer has done a succesfull job"); Library.ReadEventlog(DateTime.Now); } protected override void OnStop() { timer1.Enabled = false; Library.WriteErrorLog("LLU_Service2 stopped 15"); Library.WriteErrorLog(ConfigurationManager.AppSettings["AP_Comment"]); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using WeifenLuo.WinFormsUI.Docking; using Kingdee.CAPP.Common; using System.Reflection; using Kingdee.CAPP.Componect; namespace Kingdee.CAPP.UI { /// <summary> /// 类型说明:单元格属性导航窗体 /// 作 者:jason.tang /// 完成时间:2013-01-07 /// </summary> public partial class PropertiesNavigate : DockContent { #region 变量声明 /// <summary> /// 定义一个窗体传值的委托 /// </summary> /// <param name="pParam">传递的对象</param> public delegate void DelegateProperty(object pParam); public event DelegateProperty InvokePropertyEvent; /// <summary> /// 保存Visible属性名 /// </summary> private List<string> listVisiblePropertyName; public static BaseForm CurrentForm { get; set; } #endregion #region 属性声明 private Dictionary<string, object> _dicProperties; public Dictionary<string, object> PropertyGridValues { get { return _dicProperties; } } #endregion #region 窗体控件的事件 protected virtual void OnSetPropertyEvent(object obj) { if (InvokePropertyEvent != null) { InvokePropertyEvent(obj); } } /// <summary> /// PropertyGrid属性变化时,动态改变单元格的属性 /// </summary> private void pgrdCellProperty_PropertyValueChanged(object s, PropertyValueChangedEventArgs e) { object obj = pgrdCellProperty.SelectedObject; if (obj != null) { if (obj.GetType() == typeof(DataGridViewTextBoxCellEx)) { bool readOnly = ((DataGridViewTextBoxCellEx)obj).CellEditType != (ComboBoxSourceHelper.CellType)Enum.Parse(typeof(ComboBoxSourceHelper.CellType), "0"); bool deailReadOnly = ((DataGridViewTextBoxCellEx)obj).CellEditType != (ComboBoxSourceHelper.CellType)Enum.Parse(typeof(ComboBoxSourceHelper.CellType), "2"); if (readOnly) { ((DataGridViewTextBoxCellEx)obj).CellContent = (ComboBoxSourceHelper.CellContent)Enum.Parse(typeof(ComboBoxSourceHelper.CellContent), "0"); } //固定单元格时显示内容选项 PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); foreach (PropertyDescriptor pd in props) { if (pd.Name == "LeftTopRightBottom" || pd.Name == "CellContent" || pd.Name == "LeftBottomRightTop") { SetPropertyReadOnly(obj, pd.Name, readOnly); } if (pd.Name == "SerialStep" || pd.Name == "SpaceRows") { SetPropertyReadOnly(obj, pd.Name, deailReadOnly); } } #region 如果设置了宽度,默认给设置颜色值 Color color = ((DataGridViewTextBoxCellEx)obj).TopBorderColor; int width = ((DataGridViewTextBoxCellEx)obj).TopBorderWidth; if (e.ChangedItem.Label == "上边框宽度") { if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0)) && width > 0) { ((DataGridViewTextBoxCellEx)obj).TopBorderColor = Color.Black; } else if (width == 0) { ((DataGridViewTextBoxCellEx)obj).TopBorderColor = Color.Empty; } } if (e.ChangedItem.Label == "下边框宽度") { color = ((DataGridViewTextBoxCellEx)obj).BottomBorderColor; width = ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0)) && width > 0) { ((DataGridViewTextBoxCellEx)obj).BottomBorderColor = Color.Black; } else if (width == 0) { ((DataGridViewTextBoxCellEx)obj).BottomBorderColor = Color.Empty; } } if (e.ChangedItem.Label == "左边框宽度") { color = ((DataGridViewTextBoxCellEx)obj).LeftBorderColor; width = ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0)) && width > 0) { ((DataGridViewTextBoxCellEx)obj).LeftBorderColor = Color.Black; } else if (width == 0) { ((DataGridViewTextBoxCellEx)obj).LeftBorderColor = Color.Empty; } } if (e.ChangedItem.Label == "右边框宽度") { color = ((DataGridViewTextBoxCellEx)obj).RightBorderColor; width = ((DataGridViewTextBoxCellEx)obj).RightBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0)) && width > 0) { ((DataGridViewTextBoxCellEx)obj).RightBorderColor = Color.Black; } else if (width == 0) { ((DataGridViewTextBoxCellEx)obj).RightBorderColor = Color.Empty; } } #endregion #region 如果设置了线条样式,默认设置颜色和宽度 if (e.ChangedItem.Label == "上边框线条样式") { color = ((DataGridViewTextBoxCellEx)obj).TopBorderColor; width = ((DataGridViewTextBoxCellEx)obj).TopBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).TopBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = 1; } } if (e.ChangedItem.Label == "下边框线条样式") { color = ((DataGridViewTextBoxCellEx)obj).BottomBorderColor; width = ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).BottomBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = 1; } } if (e.ChangedItem.Label == "左边框线条样式") { color = ((DataGridViewTextBoxCellEx)obj).LeftBorderColor; width = ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).LeftBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = 1; } } if (e.ChangedItem.Label == "右边框线条样式") { color = ((DataGridViewTextBoxCellEx)obj).RightBorderColor; width = ((DataGridViewTextBoxCellEx)obj).RightBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).RightBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = 1; } } #endregion #region 如果设置了颜色,默认给宽度设置值 color = ((DataGridViewTextBoxCellEx)obj).TopBorderColor; width = ((DataGridViewTextBoxCellEx)obj).TopBorderWidth; if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = 0; } color = ((DataGridViewTextBoxCellEx)obj).LeftBorderColor; width = ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth; if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = 0; } color = ((DataGridViewTextBoxCellEx)obj).RightBorderColor; width = ((DataGridViewTextBoxCellEx)obj).RightBorderWidth; if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = 0; } color = ((DataGridViewTextBoxCellEx)obj).BottomBorderColor; width = ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth; if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = 0; } color = ((DataGridViewTextBoxCellEx)obj).AllBorderColor; width = ((DataGridViewTextBoxCellEx)obj).AllBorderWidth; System.Drawing.Drawing2D.DashStyle dashstyle = ((DataGridViewTextBoxCellEx)obj).AllBorderStyle; //if (color != Color.Empty && color != Color.FromArgb(0,0,0,0) && width == 0) //{ // ((DataGridViewTextBoxCellEx)obj).AllBorderWidth = 1; // ((DataGridViewTextBoxCellEx)obj).AllBorderColor = Color.Empty; // ((DataGridViewTextBoxCellEx)obj).AllBorderStyle = System.Drawing.Drawing2D.DashStyle.Solid; // color = Color.Empty; // width = 1; // dashstyle = System.Drawing.Drawing2D.DashStyle.Solid; //} //else if (color.IsEmpty || color == Color.FromArgb(0, 0, 0, 0)) //{ // if (width > 0) // { // ((DataGridViewTextBoxCellEx)obj).AllBorderColor = Color.Black; // color = Color.Black; // } // else // { // ((DataGridViewTextBoxCellEx)obj).AllBorderWidth = 0; // width = 0; // } //} if (e.ChangedItem.PropertyDescriptor.Category == "全边框") { if (e.OldValue.GetType() == typeof(Color) && (Color)e.OldValue != color) { ((DataGridViewTextBoxCellEx)obj).TopBorderColor = color; ((DataGridViewTextBoxCellEx)obj).LeftBorderColor = color; ((DataGridViewTextBoxCellEx)obj).RightBorderColor = color; ((DataGridViewTextBoxCellEx)obj).BottomBorderColor = color; if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = 0; } if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = 0; } if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = 0; } if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = 0; } if (color != Color.Empty && width == 0) { ((DataGridViewTextBoxCellEx)obj).AllBorderWidth = 1; } else if (color.IsEmpty) { ((DataGridViewTextBoxCellEx)obj).AllBorderWidth = 0; } } if (e.OldValue.GetType() == typeof(int) && (int)e.OldValue != width) { ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = width; ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = width; ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = width; ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = width; color = ((DataGridViewTextBoxCellEx)obj).TopBorderColor; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).TopBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).TopBorderColor = Color.Empty; ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).BottomBorderColor; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).BottomBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).BottomBorderColor = Color.Empty; ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).LeftBorderColor; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).LeftBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).LeftBorderColor = Color.Empty; ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).RightBorderColor; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).RightBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).RightBorderColor = Color.Empty; ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).AllBorderColor; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).AllBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).AllBorderColor = Color.Empty; ((DataGridViewTextBoxCellEx)obj).AllBorderWidth = 1; } } if (e.OldValue.GetType() == typeof(System.Drawing.Drawing2D.DashStyle) && (System.Drawing.Drawing2D.DashStyle)e.OldValue != dashstyle) { ((DataGridViewTextBoxCellEx)obj).TopBorderStyle = dashstyle; ((DataGridViewTextBoxCellEx)obj).LeftBorderStyle = dashstyle; ((DataGridViewTextBoxCellEx)obj).RightBorderStyle = dashstyle; ((DataGridViewTextBoxCellEx)obj).BottomBorderStyle = dashstyle; color = ((DataGridViewTextBoxCellEx)obj).TopBorderColor; width = ((DataGridViewTextBoxCellEx)obj).TopBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).TopBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).TopBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).BottomBorderColor; width = ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).BottomBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).BottomBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).LeftBorderColor; width = ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).LeftBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).LeftBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).RightBorderColor; width = ((DataGridViewTextBoxCellEx)obj).RightBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).RightBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).RightBorderWidth = 1; } color = ((DataGridViewTextBoxCellEx)obj).AllBorderColor; width = ((DataGridViewTextBoxCellEx)obj).AllBorderWidth; if ((color == Color.Empty || color == Color.FromArgb(0, 0, 0, 0))) { ((DataGridViewTextBoxCellEx)obj).AllBorderColor = Color.Black; } if (width == 0) { ((DataGridViewTextBoxCellEx)obj).AllBorderWidth = 1; } } } #endregion } else if (obj.GetType() == typeof(DataGridViewCustomerCellStyle)) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); foreach (PropertyDescriptor pd in props) { if (pd.Name == "CardName") { SetPropertyVisibility(obj, pd.Name, true); } } } pgrdCellProperty.SelectedObject = obj; } ////如果当前事件不为空,则注销该事件,防止多次注册事件 //if (this.InvokePropertyEvent != null) //{ // this.InvokePropertyEvent = null; //} //注册事件,并传入当前窗体的委托 if (this.InvokePropertyEvent == null) { this.InvokePropertyEvent += new DelegateProperty(CurrentForm.SetPropertyEvent); } else { this.InvokePropertyEvent = null; //this.InvokePropertyEvent -= new DelegateProperty(CurrentForm.SetPropertyEvent); this.InvokePropertyEvent += new DelegateProperty(CurrentForm.SetPropertyEvent); } OnSetPropertyEvent(pgrdCellProperty.SelectedObject); } /// <summary> /// 窗体Load事件 /// </summary> private void PropertiesNavigate_Load(object sender, EventArgs e) { #region 列举DataGridViewTextBoxCellEx的所有自定义属性 listVisiblePropertyName = new List<string>(); listVisiblePropertyName.Add("CellEditType"); listVisiblePropertyName.Add("CellContent"); listVisiblePropertyName.Add("CellTag"); //listPropertyName.Add("CellBorderLeft"); //listPropertyName.Add("CellBorderTop"); //listPropertyName.Add("CellBorderRight"); //listPropertyName.Add("CellBorderBottom"); listVisiblePropertyName.Add("LeftBorderColor"); listVisiblePropertyName.Add("TopBorderColor"); listVisiblePropertyName.Add("RightBorderColor"); listVisiblePropertyName.Add("BottomBorderColor"); listVisiblePropertyName.Add("LeftBorderWidth"); listVisiblePropertyName.Add("TopBorderWidth"); listVisiblePropertyName.Add("RightBorderWidth"); listVisiblePropertyName.Add("BottomBorderWidth"); listVisiblePropertyName.Add("LeftBorderStyle"); listVisiblePropertyName.Add("TopBorderStyle"); listVisiblePropertyName.Add("RightBorderStyle"); listVisiblePropertyName.Add("BottomBorderStyle"); listVisiblePropertyName.Add("DetailProperty"); listVisiblePropertyName.Add("LeftTopRightBottom"); listVisiblePropertyName.Add("LeftBottomRightTop"); listVisiblePropertyName.Add("AllBorderColor"); listVisiblePropertyName.Add("AllBorderStyle"); listVisiblePropertyName.Add("AllBorderWidth"); listVisiblePropertyName.Add("CellSource"); listVisiblePropertyName.Add("SerialStep"); listVisiblePropertyName.Add("SpaceRows"); #endregion } #endregion #region 方法 /// <summary> /// 方法说明:从单元格的属性设置PropertyGrid /// 作 者:jason.tang /// 完成时间:2013-01-10 /// </summary> /// <param name="obj">对象</param> /// <param name="multiselect">是否多个对象</param> public void SetPropertyGrid(object obj, bool multiselect, bool cardOrModule) { try { if (obj != null) { if (!cardOrModule) { bool readOnly = ((DataGridViewTextBoxCellEx)obj).CellEditType != (ComboBoxSourceHelper.CellType)Enum.Parse(typeof(ComboBoxSourceHelper.CellType), "0"); bool deailReadOnly = ((DataGridViewTextBoxCellEx)obj).CellEditType != (ComboBoxSourceHelper.CellType)Enum.Parse(typeof(ComboBoxSourceHelper.CellType), "2"); //多选时,只显示单元格基本样式属性 PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); foreach (PropertyDescriptor pd in props) { if (pd.Name != "CustStyle" && pd.Name != "CellEditType" && PropertyExists(pd.Name)) { SetPropertyVisibility(obj, pd.Name, !multiselect); } if (pd.Name == "LeftTopRightBottom" || pd.Name == "CellContent" || pd.Name == "LeftBottomRightTop") { SetPropertyReadOnly(obj, pd.Name, readOnly); } if (pd.Name == "SerialStep" || pd.Name == "SpaceRows") { SetPropertyReadOnly(obj, pd.Name, deailReadOnly); } } } else { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); int type = 0; if (obj.GetType() == typeof(DataGridViewCustomerCellStyle)) { type = ((DataGridViewCustomerCellStyle)obj).CellType; } foreach (PropertyDescriptor pd in props) { if (pd.Name == "CardName") { SetPropertyVisibility(obj, pd.Name, true); } if (type == 2) { if (pd.Name == "Alignment") { SetPropertyReadOnly(obj, pd.Name, true); } if (pd.Name == "RichAlignment") { SetPropertyReadOnly(obj, pd.Name, false); } } else if (type == 1) { if (pd.Name == "Alignment") { SetPropertyReadOnly(obj, pd.Name, false); } if (pd.Name == "RichAlignment") { SetPropertyReadOnly(obj, pd.Name, true); } } } } } pgrdCellProperty.SelectedObject = obj; } catch { } } /// <summary> /// 方法说明:提供给外围主窗体调用 /// 作 者:jason.tang /// 完成时间:2013-01-11 /// </summary> public void CellOperator(object merge) { if (pgrdCellProperty.SelectedObject != null) { ((DataGridViewTextBoxCellEx)pgrdCellProperty.SelectedObject).Merge = (int)merge; //如果当前事件不为空,则注销该事件,防止多次注册事件 if (this.InvokePropertyEvent != null) { this.InvokePropertyEvent = null; } //注册事件,并传入当前窗体的委托 this.InvokePropertyEvent += new DelegateProperty(CurrentForm.SetPropertyEvent); OnSetPropertyEvent(pgrdCellProperty.SelectedObject); } //pgrdCellProperty_PropertyValueChanged(pgrdCellProperty, null); } /// <summary> /// 方法说明:在自定义属性中是否存在 /// 作 者:jason.tang /// 完成时间:2013-01-11 /// </summary> /// <param name="propertyName">属性名</param> /// <returns>True/False</returns> private bool PropertyExists(string propertyName) { if (listVisiblePropertyName.Contains(propertyName)) { return true; } return false; } /// <summary> /// 方法说明:动态设置指定属性是否只读 /// 作者:jason.tang /// 完成时间:2013-01-10 /// </summary> /// <param name="obj">当前对象</param> /// <param name="propertyName">属性名</param> /// <param name="readOnly">是否只读</param> private void SetPropertyReadOnly(object obj, string propertyName, bool readOnly) { Type type = typeof(System.ComponentModel.ReadOnlyAttribute); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); AttributeCollection attrs = props[propertyName].Attributes; FieldInfo fld = type.GetField("isReadOnly", BindingFlags.Instance | BindingFlags.NonPublic); fld.SetValue(attrs[type], readOnly); } /// <summary> /// 方法说明:动态设置指定属性是否可见 /// 作者:jason.tang /// 完成时间:2013-01-11 /// </summary> /// <param name="obj">当前对象</param> /// <param name="propertyName">属性名</param> /// <param name="visible">是否可见</param> private void SetPropertyVisibility(object obj, string propertyName, bool visible) { Type type = typeof(BrowsableAttribute); PropertyDescriptorCollection props = TypeDescriptor.GetProperties(obj); AttributeCollection attrs = props[propertyName].Attributes; FieldInfo fld = type.GetField("browsable", BindingFlags.Instance | BindingFlags.NonPublic); fld.SetValue(attrs[type], visible); } #endregion } }
using Terraria.ModLoader; using Terraria.ID; namespace Intalium.Items.Tools { public class MagicAlloyHamaxe : ModItem { public override void SetStaticDefaults() { DisplayName.SetDefault("Magic Alloy Hamaxe"); } public override void SetDefaults() { item.value = 95000; item.useStyle = 1; item.useAnimation = 14; item.useTime = 12; item.useTurn = true; item.autoReuse = true; item.rare = 6; item.width = 40; item.height = 40; item.UseSound = SoundID.Item1; item.damage = 100; item.knockBack = 6.25f; item.melee = true; item.scale = 1.2f; item.axe = 50; item.hammer = 150; item.tileBoost = 3; item.crit = 5; } public override void AddRecipes() { ModRecipe recipe = new ModRecipe(mod); recipe.AddIngredient(null, "MagicAlloy", 12); recipe.AddIngredient(null, "Shine", 2); recipe.AddTile(TileID.AdamantiteForge); recipe.SetResult(this); recipe.AddRecipe(); } } }
using DataAccesLayer; using DataAccesLayer.Repositorys; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace ContentManagementSystem { public partial class ReadArticleDetail : System.Web.UI.Page { public Articles article; ContentManagementEntities db; public static int myArticleid; public int myAuthorId; public bool isAdminLogin; protected void Page_Load(object sender, EventArgs e) { db = new ContentManagementEntities(); int id = Convert.ToInt32(Request.QueryString["id"]); myArticleid = id; myAuthorId = AddArticle.myid; article = db.Articles.Where(c => c.Id == myArticleid).FirstOrDefault(); isAdminLogin = AdminLogin.isAdmin; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Model.IntelligenceDiningTable.ResponseResult { /// <summary> /// 菜品元素含量 /// </summary> public class E_DishNutrition: E_Response { /// <summary> /// 菜品元素含量 /// </summary> public List<E_Nutrition> nutrition { get; set; } } }
namespace NeuroLinker.Enumerations { /// <summary> /// Season for shows /// </summary> public enum Seasons { /// <summary> /// Winter season /// </summary> Winter, /// <summary> /// Fall season /// </summary> Fall, /// <summary> /// Spring season /// </summary> Spring, /// <summary> /// Summer season /// </summary> Summer } }
using System; /*Find online more information about ASCII (American Standard Code for Information Interchange) and write a program that prints the entire ASCII table of characters on the console (characters from 0 to 255).*/ class PrintTheASCIITable { static void Main() { for(int i = 0; i <= 255; i++) { char c = (char) i; Console.Write(c + " "); } Console.WriteLine(); } }