text
stringlengths
13
6.01M
namespace OptGui.Services { /// <summary> /// Defines the <see cref="IKnapsackRow" />. /// </summary> public interface IKnapsackRow { /// <summary> /// Gets or sets the Name. /// </summary> string Name { get; set; } /// <summary> /// Gets or sets the Weight. /// </summary> double? Weight { get; set; } /// <summary> /// Gets or sets the Value. /// </summary> double? Value { get; set; } } /// <summary> /// Defines the <see cref="KnapsackRow" />. /// </summary> public class KnapsackRow : IKnapsackRow { /// <summary> /// Gets or sets the Name. /// </summary> public string Name { get; set; } /// <summary> /// Gets or sets the Weight. /// </summary> public double? Weight { get; set; } /// <summary> /// Gets or sets the Value. /// </summary> public double? Value { get; set; } /// <summary> /// Initializes a new instance of the <see cref="KnapsackRow"/> class. /// </summary> /// <param name="name">The name<see cref="string"/>.</param> /// <param name="weight">The weight<see cref="double"/>.</param> /// <param name="value">The value<see cref="double"/>.</param> public KnapsackRow(string name, double? weight, double? value) { this.Name = name; this.Weight = weight; this.Value = value; } /// <summary> /// Initializes a new instance of the <see cref="KnapsackRow"/> class. /// </summary> public KnapsackRow() { this.Name = null; this.Weight = null; this.Value = null; } } }
using ALM.ServicioAdminEmpresas.Entidades; using MySql.Data.MySqlClient; using System.Data; namespace ALM.ServicioAdminEmpresas.Datos { public class DSuperAdministrador : Conexion { public void ValidarSuperUsuario(ref ESuperAdministrador validar) { Utilerias.Utilerias utileria = null; DataTable dt = null; try { utileria = new Utilerias.Utilerias(); utileria.Clave = ""; utileria.Clave = utileria.Descifrar(System.Configuration.ConfigurationManager.AppSettings["ALMCL01"]); AbrirConexion(); accesoDatos.LimpiarParametros(); accesoDatos.TipoComando = CommandType.StoredProcedure; accesoDatos.Consulta = accesoDatos.ObtenerConsultaXml(Constante.RutaSP, "SPValidarSuperUsuario"); accesoDatos.ListaParametros.Add(new MySqlParameter("pDominio", validar.Dominio)); accesoDatos.ListaParametros.Add(new MySqlParameter("pLogin", validar.Login)); accesoDatos.ListaParametros.Add(new MySqlParameter("pContrasenia", utileria.Cifrar(validar.Contraseña))); dt = accesoDatos.CargarTabla(); if (dt != null && dt.Rows.Count > 0) { validar.Email = dt.Rows[0]["Valor"].ToString(); } else { validar.Email = null; } } finally { dt = null; CerrarConexion(); accesoDatos.LimpiarParametros(); } } } }
using Newtonsoft.Json; namespace WeatherApp.Models { public class Forecast { [JsonProperty(PropertyName = "currently")] public DayForecast Currently { get; set; } [JsonProperty(PropertyName = "daily")] public DailyForecast Daily { get; set; } [JsonProperty(PropertyName = "timezone")] public string TimeZone { get; set; } } }
using UnityEngine; using System.Collections.Generic; using System; [Serializable] public class VisualTree { private Phylogeny _phylogeny; private Node _root; private List<Node> _leaves; private string _name; private float _xScale = 0.1f; private float _distBetweenLeaves = 0.3f; /// <summary> /// Constructs a visual representation of the Phylogeny. /// </summary> /// <param name="p"></param> public VisualTree(Phylogeny p, string treeName="unnamed") { _phylogeny = p; _leaves = new List<Node>(); _name = treeName; SetUpNodeHierarchy(); PositionNodes(); AdjustNodes(); PositionBranches(); } // Creates the raw nodes. Makes the parent-child structure of the nodes match that of their genotypes. private void SetUpNodeHierarchy() { Stack<Genotype> genoParents = new Stack<Genotype>(); Stack<Node> nodeParents = new Stack<Node>(); genoParents.Push(_phylogeny.GetRoot()); _root = new Node(_phylogeny.GetRoot()); nodeParents.Push(_root); while (genoParents.Count != 0) { Genotype currentGeno = genoParents.Pop(); Node currentNode = nodeParents.Pop(); foreach (Genotype genoChild in currentGeno.Children) { Node childNode = new Node(genoChild); childNode.SetParent(currentNode); nodeParents.Push(childNode); genoParents.Push(genoChild); } } } public void Activate() { _root.GameObject.SetActive(true); } public void Deactivate() { _root.GameObject.SetActive(false); } // Determine the X and Y positions of the nodes. // Does a post order to determine the y values of the tree nodes. private void PositionNodes() { TreeIterator itr = new TreeIterator(_root, TreeIterator.Traversal.POST_ORDER); // The y position for leaves float yLeaves = 0; float yIntermediates = 0; while (itr.HasNext()) { Node current = itr.Next() as Node; float x = current.Genotype.TimeBorn * _xScale; // If it is a parent of 2 or more children then center in between the children. if (current.Children.Count > 1) { int last = current.Children.Count - 1; // Get the outermost children positions float yA = (current.Children[0] as Node).GameObject.transform.position.y; float yB = (current.Children[last] as Node).GameObject.transform.position.y; // (YA + YB) / 2. Divide each one first to avoid overflow, just in case. float yMid = yA / 2 + yB / 2; current.GameObject.transform.position = new Vector3(x, yMid); yIntermediates = yMid; } // A node with 1 child else if (current.Children.Count == 1) { current.GameObject.transform.position = new Vector3(x, yIntermediates, 0); } // A leaf node else { current.GameObject.transform.position = new Vector3(x, yLeaves, 0); yIntermediates = yLeaves; yLeaves += _distBetweenLeaves; _leaves.Add(current); } } } // Do a pre-order traversal. To determine where to place branches and which nodes are intermediates. private void PositionBranches() { TreeIterator itr = new TreeIterator(_root, TreeIterator.Traversal.PRE_ORDER); List<Node> currentIntermediates = new List<Node>(); while (itr.HasNext()) { Node current = itr.Next() as Node; // Intermediate node if (current.Children.Count == 1) { currentIntermediates.Add(current); } else { // Determine start position of the line. Vector3 start = CalcBranchStartPos(current, currentIntermediates); Vector3 currentPos = current.GameObject.transform.position; if (current.Children.Count > 1) { DrawVerticalLine(current); // Draw horizontal dummy line - Between two nodes with multiple children. Vector3 end = currentPos; if (currentIntermediates.Count == 0) { Vector3[] points = new Vector3[2]; points[0] = start; points[1] = end; Vectrosity.VectorLine line = new Vectrosity.VectorLine("line", points, null, 1f); line.SetColor(current.Color); line.Draw3DAuto(); } // Make a branch else { new Branch(currentIntermediates, start, end); currentIntermediates.Clear(); } } // Leaf else { currentIntermediates.Add(current); Vector3 end = new Vector3(_phylogeny.CutoffTime * _xScale, start.y); new Branch(currentIntermediates, start, end); currentIntermediates.Clear(); } } } } private Vector3 CalcBranchStartPos(Node current, List<Node> currentIntermediates) { // Determine start position of the line. float xStart; if (currentIntermediates.Count != 0) { // xStart is the 1st collected intermediate's parent x-position if (currentIntermediates[0].Parent != null) xStart = (currentIntermediates[0].Parent as Node).GameObject.transform.position.x; // Handle root case else xStart = currentIntermediates[0].GameObject.transform.position.x; } // Handles case where there are no intermediates between nodes. else if (current.Parent != null) { xStart = (current.Parent as Node).GameObject.transform.position.x; } // Handle root. else { xStart = current.GameObject.transform.position.x; } return new Vector3(xStart, current.GameObject.transform.position.y); } // Vertical lines are drawn on nodes with two or more children. private void DrawVerticalLine(Node current) { // Get the positions of the outermost children. int last = current.Children.Count - 1; float yA = (current.Children[0] as Node).GameObject.transform.position.y; float yB = (current.Children[last] as Node).GameObject.transform.position.y; float x = current.GameObject.transform.position.x; Vector3[] points = new Vector3[2]; points[0] = new Vector3(x, yA); points[1] = new Vector3(x, yB); Vectrosity.VectorLine line = new Vectrosity.VectorLine("line", points, null, 1f); line.SetColor(current.Color); line.Draw3DAuto(); } // Keep the tree tight, avoid being too long relative to the height. private void AdjustNodes() { float height = HeightBound; float width = WidthBound; // Scale up all the Y values of each node. if (height < width / 4) { float scaleFactor = (width / height) / 2; TreeIterator itr = new TreeIterator(_root); while (itr.HasNext()) { Node current = itr.Next() as Node; Vector3 pos = current.GameObject.transform.position; pos.y *= scaleFactor; current.GameObject.transform.position = pos; } _distBetweenLeaves *= scaleFactor; } } public Phylogeny Phylogeny { get { return _phylogeny; } } public Node Root { get { return _root; } } public float xScale { get { return _xScale; } } public float DistBetweenLeaves { get { return _distBetweenLeaves; } } /// <summary> /// How much space in the Y axis the tree takes up. /// </summary> public float HeightBound { get { return _distBetweenLeaves * _leaves.Count; } } /// <summary> /// How much space in the X axis the tree takes up. /// </summary> public float WidthBound { get { return _phylogeny.CutoffTime * _xScale; } } public List<Node> Leaves { get { return _leaves; } } public string Name { get { return _name; } set { _name = value; } } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace POS_SP.Models { public class Sale { public int Id { get; set; } [Display(Name = "Order Number")] public string OrderNumber { get; set; } [Required, Display(Name = "Order Reference No")] public string OrderRefNo { get; set; } [Required, Display(Name = "Sales Date"), DataType(DataType.Date)] public DateTime SalesDate { get; set; } [Display(Name = "Tax Amount")] public double TaxAmount { get; set; } [Display(Name = "Tax In Percent")] public double TaxPercent { get; set; } [Display(Name = "Vat Amount")] public double VatAmount { get; set; } [Display(Name = "Vat In Percent")] public double VatPercent { get; set; } [Display(Name = "Discount Amount")] public double DiscountAmount { get; set; } [Display(Name = "Dsicount In Percent")] public double DiscountPercent { get; set; } [Display(Name = "Payment Type")] public string PaymentType { get; set; } [Display(Name = "Down Payment")] public double DownPayment { get; set; } [Display(Name ="Installment Period")] public int InstallmentPeriod { get; set; } [Display(Name = "Payment Amount")] public double PaymentAmount { get; set; } [Display(Name = "Due Amount")] public double DueAmount { get; set; } [Display(Name = "Total Number")] public double TotalAmount { get; set; } [Display(Name = "Referenced Customer")] public int ReferenceId { get; set; } [Display(Name = "Customer")] public int CustomerId { get; set; } [ForeignKey("CustomerId")] public Customer Customer { get; set; } public List<SalesDetail> SalesDetails { get; set; } public List<InstallmentSchedulePayment> InstallmentSchedulePayments { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using EsMo.Sina.Model.Person; using EsMo.Sina.SDK.Storage; namespace EsMo.Sina.SDK.Service { public class ApplicationService:IApplicationService { IAccountService accountService; public ResourceCache ResourceCache { get; private set; } public ApplicationService(IAccountService accountService) { this.accountService = accountService; this.ResourceCache = new ResourceCache(); } public Account Account { get; set; } } }
using CDSShareLib.Helper; using CDSShareLib.ServiceBus; using Newtonsoft.Json; using sfShareLib; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace sfAPIService.Models { public class BackendTaskModel { public class Format_Base { [Required] public string Requester { get; set; } [Required] public string requesterEmail { get; set; } } //Company's CosmosDBCollection public void CreateCompanyCosmosDBCollection(int companyId, Format_Base parseData) { CDSShareLib.ServiceBus.Model.CosmosDBCollectionCreateModel message = new CDSShareLib.ServiceBus.Model.CosmosDBCollectionCreateModel(); message.content = new CDSShareLib.ServiceBus.Model.CosmosDBCollectionCreateModel.ContentFormat(); //ServiceBus - Content message.content.companyId = companyId; message.content.partitionKey = "/messageContent/equipmentId"; //temporarily fixed using (CDStudioEntities dbEntity = new CDStudioEntities()) { //Find company's unexpired and latest subscription var subscription = (from c in dbEntity.CompanyInSubscriptionPlan.AsNoTracking() where c.CompanyID == companyId && c.ExpiredDate > DateTime.UtcNow orderby c.ExpiredDate descending select c).FirstOrDefault(); if (subscription == null) throw new CDSException(10201); message.content.collectionRU = subscription.CosmosDBCollectionReservedUnits.ToString(); message.content.collectionTTL = subscription.CosmosDBCollectionTTL.ToString(); //ServiceBus - Flexible parameter message.cosmosDBConnectionString = subscription.CosmosDBConnectionString; } //ServiceBus - Base parameter message.entityId = companyId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } public void UpdateCompanyCosmosDBCollection(int companyId, Format_Base parseData) { CDSShareLib.ServiceBus.Model.CosmosDBCollectionUpdateModel message = new CDSShareLib.ServiceBus.Model.CosmosDBCollectionUpdateModel(); message.content = new CDSShareLib.ServiceBus.Model.CosmosDBCollectionUpdateModel.ContentFormat(); //ServiceBus - Content message.content.companyId = companyId; using (CDStudioEntities dbEntity = new CDStudioEntities()) { //Find company's unexpired and latest subscription var subscription = (from c in dbEntity.CompanyInSubscriptionPlan.AsNoTracking() where c.CompanyID == companyId && c.ExpiredDate > DateTime.UtcNow orderby c.ExpiredDate descending select c).FirstOrDefault(); if (subscription == null) throw new CDSException(10201); message.content.collectionRU = subscription.CosmosDBCollectionReservedUnits.ToString(); message.content.collectionTTL = subscription.CosmosDBCollectionTTL.ToString(); //ServiceBus - Flexible parameter message.cosmosDBConnectionString = subscription.CosmosDBConnectionString; } //ServiceBus - Base parameter message.entityId = companyId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } public void DeleteCompanyCosmosDBCollection(int companyId, Format_Base parseData) { CDSShareLib.ServiceBus.Model.CosmosDBCollectionDeleteModel message = new CDSShareLib.ServiceBus.Model.CosmosDBCollectionDeleteModel(); message.content = new CDSShareLib.ServiceBus.Model.CosmosDBCollectionDeleteModel.ContentFormat(); //ServiceBus - Content message.content.companyId = companyId; using (CDStudioEntities dbEntity = new CDStudioEntities()) { //Find company's latest subscription var subscription = (from c in dbEntity.CompanyInSubscriptionPlan.AsNoTracking() where c.CompanyID == companyId orderby c.ExpiredDate descending select c).FirstOrDefault(); if (subscription == null) throw new CDSException(10201); //ServiceBus - Flexible parameter message.cosmosDBConnectionString = subscription.CosmosDBConnectionString; } //ServiceBus - Base parameter message.entityId = companyId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } //IoTHub public class Format_LaunchIoTHubReceiver : Format_Base { [Required] public string Version { get; set; } } public void LaunchIoTHubReceiver(int companyId, int iotHubId, Format_LaunchIoTHubReceiver parseData) { CDSShareLib.ServiceBus.Model.IoTHubReceiverModel message = new CDSShareLib.ServiceBus.Model.IoTHubReceiverModel(); message.job = TaskName.IoTHubReceiver_Launch; message.task = TaskName.IoTHubReceiver_Launch; message.content = new CDSShareLib.ServiceBus.Model.IoTHubReceiverModel.ContentFormat(); //ServiceBus - Content message.content.companyId = companyId; message.content.iotHubId = iotHubId; message.content.version = parseData.Version; //ServiceBus - Base parameter message.entityId = iotHubId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } public class Format_ShutdownIoTHubReceiver : Format_Base { [Required] public string Version { get; set; } } public void ShuudownIoTHubReceiver(int companyId, int iotHubId, Format_ShutdownIoTHubReceiver parseData) { CDSShareLib.ServiceBus.Model.IoTHubReceiverModel message = new CDSShareLib.ServiceBus.Model.IoTHubReceiverModel(); message.job = TaskName.IoTHubReceiver_Shutdown; message.task = TaskName.IoTHubReceiver_Shutdown; message.content = new CDSShareLib.ServiceBus.Model.IoTHubReceiverModel.ContentFormat(); //ServiceBus - Content message.content.companyId = companyId; message.content.iotHubId = iotHubId; message.content.version = parseData.Version; //ServiceBus - Base parameter message.entityId = iotHubId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } //IoTDevice public void RegisterIoTDevice(int companyId, int iotDeviceId, Format_Base parseData) { CDSShareLib.ServiceBus.Model.IoTDeviceRegisterModel message = new CDSShareLib.ServiceBus.Model.IoTDeviceRegisterModel(); message.content = new CDSShareLib.ServiceBus.Model.IoTDeviceRegisterModel.ContentFormat(); using (CDStudioEntities dbEntity = new CDStudioEntities()) { IoTDevice iotDevice = dbEntity.IoTDevice.Find(iotDeviceId); if (iotDevice == null) throw new CDSException(10902); //ServiceBus - Content message.content.iothubDeviceId = iotDevice.IoTHubDeviceID; message.content.authenticationType = iotDevice.AuthenticationType; message.content.iothubConnectionString = (iotDevice.IoTHub == null ? "" : iotDevice.IoTHub.IoTHubConnectionString); switch (message.content.authenticationType.ToLower()) { case "key": message.content.iothubDeviceKey = iotDevice.IoTHubDeviceKey; message.content.certificateThumbprint = null; break; case "certificate": message.content.iothubDeviceKey = null; message.content.certificateThumbprint = (iotDevice.DeviceCertificate == null ? "" : iotDevice.DeviceCertificate.Thumbprint); break; } } //ServiceBus - Base parameter message.entityId = iotDeviceId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } public class Format_UpdateIoTDevice : Format_Base { [Required] public string OldIothubConnectionString { get; set; } } public void UpdateIoTDevice(int companyId, int iotDeviceId, Format_UpdateIoTDevice parseData) { CDSShareLib.ServiceBus.Model.IoTDeviceUpdateModel message = new CDSShareLib.ServiceBus.Model.IoTDeviceUpdateModel(); message.content = new CDSShareLib.ServiceBus.Model.IoTDeviceUpdateModel.ContentFormat(); using (CDStudioEntities dbEntity = new CDStudioEntities()) { IoTDevice iotDevice = dbEntity.IoTDevice.Find(iotDeviceId); if (iotDevice == null) throw new CDSException(10902); //ServiceBus - Content message.content.oldIothubConnectionString = parseData.OldIothubConnectionString; message.content.iothubDeviceId = iotDevice.IoTHubDeviceID; message.content.authenticationType = iotDevice.AuthenticationType; message.content.iothubConnectionString = (iotDevice.IoTHub == null ? "" : iotDevice.IoTHub.IoTHubConnectionString); switch (message.content.authenticationType.ToLower()) { case "key": message.content.iothubDeviceKey = iotDevice.IoTHubDeviceKey; message.content.certificateThumbprint = null; break; case "certificate": message.content.iothubDeviceKey = null; message.content.certificateThumbprint = (iotDevice.DeviceCertificate == null ? "" : iotDevice.DeviceCertificate.Thumbprint); break; } } //ServiceBus - Base parameter message.entityId = iotDeviceId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } public void DeleteIoTDevice(int companyId, int iotDeviceId, Format_Base parseData) { CDSShareLib.ServiceBus.Model.IoTDeviceDeleteModel message = new CDSShareLib.ServiceBus.Model.IoTDeviceDeleteModel(); message.content = new CDSShareLib.ServiceBus.Model.IoTDeviceDeleteModel.ContentFormat(); using (CDStudioEntities dbEntity = new CDStudioEntities()) { IoTDevice iotDevice = dbEntity.IoTDevice.Find(iotDeviceId); if (iotDevice == null) throw new CDSException(10902); //ServiceBus - Content message.content.iothubDeviceId = iotDevice.IoTHubDeviceID; message.content.iothubConnectionString = (iotDevice.IoTHub == null ? "" : iotDevice.IoTHub.IoTHubConnectionString); } //ServiceBus - Base parameter message.entityId = iotDeviceId; message.requester = parseData.Requester; message.requesterEmail = parseData.requesterEmail; //Operation task OperationTaskModel.Format_Create operationTaskData = new OperationTaskModel.Format_Create(); operationTaskData.Entity = message.entity; operationTaskData.Name = message.task; operationTaskData.EntityId = message.entityId.ToString(); operationTaskData.TaskContent = JsonConvert.SerializeObject(message); OperationTaskModel operationTaskModel = new OperationTaskModel(); message.taskId = operationTaskModel.Create(companyId, operationTaskData); Global.ServiceBus.Helper.SendToQueue(Global.ServiceBus.Queue.Provision, JsonConvert.SerializeObject(message)); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml.Serialization; using Sunny.Lib; namespace MultipleThreads { public class Config { private RunModel _selectedRunModel = null; public RunModel SelectedRunModel { get { if (_selectedRunModel == null) { if (!string.IsNullOrEmpty(SelectedRunModelName) && RunModels != null && RunModels.Count > 0) { _selectedRunModel = RunModels.Where(p => p.Name.Equals(SelectedRunModelName, StringComparison.InvariantCultureIgnoreCase)).First(); } } return _selectedRunModel; } set { _selectedRunModel = value; } } private WorkInfo _selectedWorkInfo = null; public WorkInfo SelectedWorkInfo { get { if (_selectedWorkInfo == null) { if (SelectedWorkInfoId>0 && WorkInfos != null && WorkInfos.Count > 0) { _selectedWorkInfo = WorkInfos.Where(p => p.Id == SelectedWorkInfoId).First(); } } return _selectedWorkInfo; } set { _selectedWorkInfo = value; } } public string SelectedRunModelName { get; set; } public int SelectedWorkInfoId { get; set; } public string StatisticsFileName { get; set; } public List<RunModel> RunModels { get; set; } public List<WorkInfo> WorkInfos { get; set; } public static Config DefaultConfig = XMLSerializerHelper.DeserializeFromFile<Config>(Const.ConfigFileFullPath); } public class RunModel { [XmlAttribute] public string Name { get; set; } public int IntervalTime { get; set; } public bool ThreadAmountReadFromConfig { get; set; } public int MultipleThreadAmount { get; set; } public bool LimitRunTime { get; set; } public double RunTime { get; set; } } public class WorkInfo { [XmlAttribute] public int Id { get; set; } public string ClassName { get; set; } public string Module { get; set; } public string FilePath { get; set; } public string EntryMethod { get; set; } public string MethodParameters { get; set; } public string Description { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ClassLibrary1 { public class TeamModel { /// <summary> /// A list of all the persons on a team /// </summary> public List<PersonModel> TeamMembers { get; set; } = new List<PersonModel>(); /// <summary> /// The name of the team /// </summary> public string TeamName { get; set; } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class BallMovement : MonoBehaviour { [SerializeField] private float BallSpeed = 30; private Rigidbody2D rb; private GameObject BallLauncher; [SerializeField] private Transform ball; [SerializeField] private Sprite SmileTex; [SerializeField] private Sprite NormalTex; void Start () { BallLauncher = GameObject.FindGameObjectWithTag("BallLauncher"); rb = this.GetComponent<Rigidbody2D>(); Physics2D.IgnoreLayerCollision(8, 8); this.gameObject.transform.Rotate(0, 0, BallLauncher.transform.rotation.eulerAngles.z); StartCoroutine(_wait()); } void FixedUpdate() { if (Input.GetKeyDown(KeyCode.I)) { SetRotationAndFireBalls(); } } void OnCollisionEnter2D(Collision2D collision) { if(collision.transform.gameObject.tag == "Under") { Destroy(this.gameObject); } if (collision.transform.gameObject.tag == "Obstacle") { this.GetComponent<SpriteRenderer>().sprite = SmileTex; collision.transform.gameObject.GetComponent<BlockManager>().DecreaseLife(); } } void OnCollisionExit2D(Collision2D collision) { this.GetComponent<SpriteRenderer>().sprite = NormalTex; } public void SetRotationAndFireBalls() { rb.AddRelativeForce(Vector2.up * BallSpeed); } IEnumerator _wait() { yield return new WaitForSeconds(.1f); SetRotationAndFireBalls(); } }
using System; using Server; using Server.Mobiles; using Server.Items; using Server.Gumps; using Server.Engines.Quests; namespace Server.Engines.Quests.TheGraveDigger { public class LindasBoyfriend : BaseQuester { [Constructable] public LindasBoyfriend() : base( "the thug" ) { } public override void InitBody() { InitStats( 100, 100, 25 ); Hue = 0x83F3; Female = false; BodyValue = 400; Name = "Remmy Crockett"; } public override void InitOutfit() { AddItem( new FancyShirt( 1150 ) ); AddItem( new LongPants( 1175 ) ); AddItem( new Boots( 1175 ) ); AddItem( new Cutlass() ); AddItem( new PonyTail( 1175 ) ); AddItem( new Vandyke( 1175 ) ); } public override void OnTalk( PlayerMobile player, bool contextMenu ) { QuestSystem qs = player.Quest; if ( qs is TheGraveDiggerQuest ) { this.Say( "Can't you see i am tring to spend time with my lady?" ); } } public LindasBoyfriend( Serial serial ) : base( serial ) { } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( (int) 0 ); // version } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); } } }
using CommonFrameWork; using Dominio; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace BLL { public class BLLGim { public IEnumerable<Referencia.GIM> RetornarReferenciaPorInscricao(string ie) { using (var dao = new DAL.DbGIM()) { return dao.RetornarReferenciaPorInscricao(ie); } } public IEnumerable<GIMReferencia> RetornaGIMPorInscricaoReferencia(string ie, decimal? referencia) { Validador.Validar(!string.IsNullOrWhiteSpace(ie), "Informe a inscrição estadual."); using (var dao = new DAL.DbGIM()) { return dao.RetornaGIMPorInscricaoReferencia(ie, referencia); } } public GIM RetornaConsultaGuiaMensal(string ie, decimal referencia) { Validador.Validar(!string.IsNullOrWhiteSpace(ie), "Informe a inscrição estadual."); Validador.Validar(referencia > 0, "Informe a referencia."); using (var dao = new DAL.DbGIM()) { return dao.RetornaConsultaGuiaMensal(ie, referencia); } } public IEnumerable<GIMDetalhe> RetornaConsultaGuiaMensalDetalhe(string ie, decimal referencia) { Validador.Validar(!string.IsNullOrWhiteSpace(ie), "Informe a inscrição estadual."); using (var dao = new DAL.DbGIM()) { return dao.RetornaConsultaGuiaMensalDetalhe(ie, referencia); } } } }
using System; using System.Collections.Generic; namespace DFS_and_BFS { class Program { private static Dictionary<int, List<int>> graph; private static HashSet<int> visited; static void Main() { graph = new Dictionary<int, List<int>> { {1, new List<int>{19,21,14} }, {19, new List<int>{7,12,31,21}}, {7, new List<int>{1}}, {12, new List<int>()}, {21, new List<int>{14} }, {31, new List<int>{21} }, {14, new List<int>{6,23} }, {6, new List<int>() }, {23, new List<int>{21} } }; visited = new HashSet<int>(); foreach (var node in graph.Keys) { if (!visited.Contains(node)) { BFS(node); } //DFS(node); } } private static void DFS(int node) { if (visited.Contains(node)) { return; } visited.Add(node); foreach (var child in graph[node]) { DFS(child); } Console.WriteLine(node); } private static void BFS(int startNode) { var queue = new Queue<int>(); queue.Enqueue(startNode); visited.Add(startNode); while (queue.Count > 0) { var node = queue.Dequeue(); Console.WriteLine(node); foreach (var child in graph[node]) { if (!visited.Contains(child)) { queue.Enqueue(child); visited.Add(child); } } } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace BankTwo_v2.Funcionarios { public class Auxiliar : Funcionario // 'Auxiliar' herda propriedades e métodos de 'Funcionario' { public Auxiliar(string cpf) // Construtor 'Auxiliar' recebe cpf e implementa salário e cpf na classe 'Funcionario' : base(2000.0, cpf) { } public override double GetBonificacao() // Calcular a bonificação de um diretor (é um método 'override' pois sobrescreve o método da classe-mãe) { return Salario * 0.20; } public override void AumentarSalario() // Aumentar salário do diretor { Salario *= 1.10; } } }
using System.Collections.Generic; using System.Windows.Input; using WMagic; using WMagic.Brush.Basic; using WMaper.Base; using WMaper.Meta; using WMaper.Meta.Radio; namespace WMaper.Core { public abstract class Geom : Layer { #region 变量 // 是否可见 private bool matte; // 是否修改 private bool amend; // 显示范围 private Arise arise; // 显示光标 private Cursor mouse; // 几何对象 private AShape handle; #endregion #region 构造函数 public Geom() : base() { this.arise = null; this.matte = false; this.amend = false; this.handle = null; } #endregion #region 属性方法 public bool Matte { get { return this.matte; } set { this.matte = value; } } public bool Amend { get { return this.amend; } set { this.amend = value; } } public Arise Arise { get { return this.arise; } set { this.arise = value; } } public Cursor Mouse { get { return this.mouse; } set { this.mouse = value; } } public AShape Handle { get { return this.handle; } set { this.handle = value; } } #endregion #region 函数方法 /// <summary> /// 点集合地理坐标转化为Canvas坐标 /// </summary> /// <param name="way"></param> /// <returns></returns> protected List<GPoint> Fit4r(List<Coord> way) { List<GPoint> fit = new List<GPoint>(); // 坐标转换 { if (!MatchUtils.IsEmpty(way)) { GPoint point = null; { foreach (Coord crd in way) { if (!MatchUtils.IsEmpty(point = this.Fit4p(crd))) { fit.Add(point); } } } } } return fit; } /// <summary> /// 点地理坐标转换为Canvas坐标 /// </summary> /// <param name="crd">地理坐标</param> /// <returns>Canvas坐标</returns> protected GPoint Fit4p(Coord crd) { Pixel pel = null; try { if (!MatchUtils.IsEmpty(crd)) { pel = this.Target.Netmap.Crd2px(crd).Offset(new Pixel( -this.Target.Netmap.Nature.X, -this.Target.Netmap.Nature.Y )); } } catch { pel = null; } return !MatchUtils.IsEmpty(pel) ? new GPoint(pel.X, pel.Y) : null; } /// <summary> /// 辐射地理范围转像素范围 /// </summary> /// <param name="ext"></param> /// <returns></returns> protected GExtra Fit4e(GExtra ext) { if (!MatchUtils.IsEmpty(ext)) { double d2m = this.Target.Netmap.Craft * WMaper.Units.M / this.Target.Netmap.Deg2sc(); { if (d2m > 0) { return new GExtra(ext.X * d2m, ext.Y * d2m); } } } return new GExtra(); } /// <summary> /// 置顶对象 /// </summary> public void Summit() { if (!MatchUtils.IsEmpty(this.Target) && !MatchUtils.IsEmpty(this.handle) && this.Target.Enable && this.Enable) { this.handle.Front(); } } /// <summary> /// 渲染对象 /// </summary> /// <param name="drv"></param> public sealed override void Render(Maper drv) { if (!MatchUtils.IsEmpty(this.Target = drv) && this.Target.Enable) { this.Index = MatchUtils.IsEmpty(this.Index) ? (this.Index = StampUtils.GetTimeStamp()) : this.Index; if (drv.Symbol.Draw.ContainsKey(this.Index)) { Geom geom = drv.Symbol.Draw[this.Index]; if (this.Equals(geom)) { this.Redraw(); } else { { geom.Remove(); } this.Render(drv); } } else { if (!MatchUtils.IsEmpty(this.Facade = drv.Vessel.Draw)) { // 监听广播 this.Observe(drv.Listen.ZoomEvent, this.Redraw); this.Observe(drv.Listen.SwapEvent, this.Redraw); // 绘制图形 try { (drv.Symbol.Draw[this.Index] = this).Redraw(); } catch { drv.Symbol.Draw.Remove(this.Index); } finally { if (!drv.Symbol.Draw.ContainsKey(this.Index)) { // 移除监听 this.Obscure(drv.Listen.ZoomEvent, this.Redraw); this.Obscure(drv.Listen.SwapEvent, this.Redraw); { this.Facade = null; this.Target = null; } } } } } } } /// <summary> /// 绘制对象 /// </summary> /// <param name="msg"></param> public sealed override void Redraw(Msger msg) { if (!MatchUtils.IsEmpty(this.Target) && !MatchUtils.IsEmpty(this.Target.Netmap) && !MatchUtils.IsEmpty(this.Facade) && this.Target.Enable && this.Enable) { if (MatchUtils.IsEmpty(msg)) { this.Redraw(); } else { if (!MatchUtils.IsEmpty(this.handle)) { // Swap Event. if (this.Target.Listen.ZoomEvent.Equals(msg.Chan)) { this.Redraw(); return; } // Swap Event. if (this.Target.Listen.SwapEvent.Equals(msg.Chan)) { if (!(msg.Info as Geog).Cover) { this.Redraw(); } } } } } } /// <summary> /// 移除对象 /// </summary> public sealed override void Remove() { if (!MatchUtils.IsEmpty(this.Target) && this.Target.Enable && this.Enable && !MatchUtils.IsEmpty(this.handle)) { if (this.Obscure(this.Target.Listen.ZoomEvent, this.Redraw)) { if (!this.Obscure(this.Target.Listen.SwapEvent, this.Redraw)) { this.Observe(this.Target.Listen.ZoomEvent, this.Redraw); } else { if (!this.Target.Symbol.Draw.Remove(this.Index)) { this.Observe(this.Target.Listen.ZoomEvent, this.Redraw); this.Observe(this.Target.Listen.SwapEvent, this.Redraw); } else { // 擦除图形 this.handle.Earse(); { this.Facade = null; this.handle = null; this.Target = null; } } } } } } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace SynchWebService.Entity { public class Fk_Department_Entity : AppHdr { /// <summary> /// 构造函数,不生成主键 /// </summary> public Fk_Department_Entity() : this(false) { } /// <summary> /// 构造函数 /// </summary> /// <param name="isCreateKeyField">是否要创建主键</param> public Fk_Department_Entity(bool isCreateKeyField = false) { } public String departmentId { get; set; } public String departmentCode { get; set; } public String departmentName { get; set; } public String passId { get; set; } public String passName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace AnimalDB { public partial class RegistracijosList : System.Web.UI.Page { public List<Registracija> testas = new List<Registracija>(); public string conString = @"Data Source=localhost;port=3306;Initial catalog=animal; User Id= root; password=''"; protected void Page_Load(object sender, EventArgs e) { showRegistracija(); } public void showRegistracija() { Kontekstas test = new Kontekstas(conString); testas = test.GetRegistracija(); Session["ArrayRegistracijos"] = testas; gvMysql.DataSource = testas; gvMysql.DataBind(); } protected void Main_Click(object sender, EventArgs e) { Server.Transfer("HomePage.aspx"); } protected void Klasės_Click1(object sender, EventArgs e) { Server.Transfer("KlaseList.aspx"); } protected void Gyvunai_Click(object sender, EventArgs e) { Server.Transfer("GyvunaiList.aspx"); } protected void Savininkai_Click(object sender, EventArgs e) { Server.Transfer("SavininkaiList.aspx"); } protected void Veisle_Click(object sender, EventArgs e) { Server.Transfer("VeisleList.aspx"); } protected void Registracijos_Click(object sender, EventArgs e) { Server.Transfer("RegistracijosList.aspx"); } protected void Button1_Click(object sender, EventArgs e) { Server.Transfer("RegistracijosAdd.aspx"); } protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) { } protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e) { try { List<Registracija> bandymas = (List<Registracija>)Session["ArrayRegistracijos"]; Kontekstas test = new Kontekstas(conString); test.RemoveRegistracija(bandymas[e.RowIndex].numeris); } catch (Exception exception) { Label2.Text = exception.Message; return; } showRegistracija(); Label2.Text = "Pašalintas elementas indeksu: " + e.RowIndex; } protected void GridView1_RowEditing(object sender, GridViewEditEventArgs e) { Session["editId"] = e.NewEditIndex; Server.Transfer("RegistracijosEdit.aspx", true); } protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e) { } protected void GridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { } protected void Button1_Click1(object sender, EventArgs e) { Server.Transfer("Ataskaitos.aspx"); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /** * Copyright (c) blueback * Released under the MIT License * https://github.com/bluebackblue/fee/blob/master/LICENSE.txt * http://bbbproject.sakura.ne.jp/wordpress/mitlicense * @brief 入力。タッチ。 */ /** NInput */ namespace NInput { /** Touch */ public class Touch { /** [シングルトン]s_instance */ private static Touch s_instance = null; /** [シングルトン]インスタンス。作成。 */ public static void CreateInstance() { if(s_instance == null){ s_instance = new Touch(); } } /** [シングルトン]インスタンス。チェック。 */ public static bool IsCreateInstance() { if(s_instance != null){ return true; } return false; } /** [シングルトン]インスタンス。取得。 */ public static Touch GetInstance() { #if(UNITY_EDITOR) if(s_instance == null){ Tool.Assert(false); } #endif return s_instance; } /** [シングルトン]インスタンス。削除。 */ public static void DeleteInstance() { if(s_instance != null){ s_instance.Delete(); s_instance = null; } } /** タッチデバイスアイテム。 */ public struct Touch_Device_Item { public bool link; public int x; public int y; public Touch_Phase.PhaseType phasetype; /** raw_id */ public int raw_id; /** pressure */ /* public float pressure; */ /** radius */ /* public float radius; */ /** angle_altitude */ /* public float angle_altitude; */ /** angle_azimuth */ /* public float angle_azimuth; */ } /** タッチコールバック。 */ public delegate void CallBack_OnTouch(Touch_Phase a_touch_phase); /** コールバック。 */ public CallBack_OnTouch callback; /** リスト。 */ public List<Touch_Phase> list; /** デバイスアイテムリスト。 */ public Touch_Device_Item[] device_item_list; public int device_item_list_count; /** コールバック。設定。 */ public void SetCallBack(CallBack_OnTouch a_callback) { this.callback = a_callback; } /** [シングルトン]constructor */ private Touch() { //callback this.callback = null; //list this.list = new List<Touch_Phase>(); //device_item_list this.device_item_list = new Touch_Device_Item[1]; this.device_item_list_count = 0; } /** [シングルトン]削除。 */ private void Delete() { } /** 検索。 */ public int SearchListItemFromNoUpdate(int a_x,int a_y,int a_limit) { int t_ret_index = -1; int t_ret_length = 0; for(int ii=0;ii<this.list.Count;ii++){ if(this.list[ii].update == false){ int t_length_x = a_x - this.list[ii].value_x; int t_length_y = a_y - this.list[ii].value_y; int t_length = t_length_x * t_length_x + t_length_y * t_length_y; if((a_limit < 0)||(t_length < a_limit)){ if(t_ret_index < 0){ t_ret_index = ii; t_ret_length = t_length; }else if(t_ret_length > t_length){ t_ret_index = ii; t_ret_length = t_length; } } } } return t_ret_index; } /** 更新。インプットシステムタッチスクリーン。タッチ。 */ public bool Main_InputSystemTouchscreen_Touch(NRender2D.Render2D a_render2d) { UnityEngine.Experimental.Input.Touchscreen t_touchscreen_current = UnityEngine.Experimental.Input.InputSystem.GetDevice<UnityEngine.Experimental.Input.Touchscreen>(); if(t_touchscreen_current != null){ this.device_item_list_count = 0; //リスト作成。 if(this.device_item_list.Length < t_touchscreen_current.activeTouches.Count){ this.device_item_list = new Touch_Device_Item[t_touchscreen_current.activeTouches.Count]; } for(int ii=0;ii<t_touchscreen_current.activeTouches.Count;ii++){ //デバイス。 UnityEngine.Experimental.Input.Controls.TouchControl t_touch = t_touchscreen_current.activeTouches[ii]; UnityEngine.Experimental.Input.PointerPhase t_touch_phase = t_touch.phase.ReadValue(); int t_touch_id = t_touch.touchId.ReadValue(); int t_touch_x = (int)t_touch.position.x.ReadValue(); int t_touch_y = (int)t_touch.position.y.ReadValue(); //(GUIスクリーン座標)=>(仮想スクリーン座標)。 a_render2d.GuiScreenToVirtualScreen(t_touch_x,t_touch_y,out this.device_item_list[this.device_item_list_count].x,out this.device_item_list[this.device_item_list_count].y); //フェーズ。 switch(t_touch_phase){ case UnityEngine.Experimental.Input.PointerPhase.Began: { this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.Began; }break; case UnityEngine.Experimental.Input.PointerPhase.Moved: { this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.Moved; }break; case UnityEngine.Experimental.Input.PointerPhase.Stationary: { this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.Stationary; }break; default: { this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.None; }break; } //フラグ。 this.device_item_list[this.device_item_list_count].link = false; //追加情報。 this.device_item_list[this.device_item_list_count].raw_id = t_touch_id; /* this.device_item_list[this.device_item_list_count].pressure = t_touch.pressure.ReadValue(); this.device_item_list[this.device_item_list_count].radius = 0.0f; this.device_item_list[this.device_item_list_count].angle_altitude = t_touch.radius.ReadValue().x; this.device_item_list[this.device_item_list_count].angle_azimuth = t_touch.radius.ReadValue().y; */ this.device_item_list_count++; } return true; } return false; } /** 更新。インプットマネージャタッチ。タッチ。 */ public bool Main_InputManagerTouch_Touch(NRender2D.Render2D a_render2d) { this.device_item_list_count = 0; //リスト作成。 if(this.device_item_list.Length < UnityEngine.Input.touchCount){ this.device_item_list = new Touch_Device_Item[UnityEngine.Input.touchCount]; } for(int ii=0;ii<UnityEngine.Input.touchCount;ii++){ UnityEngine.Touch t_touch = UnityEngine.Input.GetTouch(ii); switch(t_touch.phase){ case TouchPhase.Began: case TouchPhase.Moved: case TouchPhase.Stationary: { //(GUIスクリーン座標)=>(仮想スクリーン座標)。 a_render2d.GuiScreenToVirtualScreen((int)t_touch.position.x,(int)(Screen.height - t_touch.position.y),out this.device_item_list[this.device_item_list_count].x,out this.device_item_list[this.device_item_list_count].y); //フェーズ。 if(t_touch.phase == TouchPhase.Began){ this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.Began; }else if(t_touch.phase == TouchPhase.Moved){ this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.Moved; }else if(t_touch.phase == TouchPhase.Stationary){ this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.Stationary; }else{ this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.None; } //フラグ。 this.device_item_list[this.device_item_list_count].link = false; //追加情報。 this.device_item_list[this.device_item_list_count].raw_id = -1; /* this.device_item_list[this.device_item_list_count].pressure = t_touch.pressure; this.device_item_list[this.device_item_list_count].radius = t_touch.radius; this.device_item_list[this.device_item_list_count].angle_altitude = t_touch.altitudeAngle; this.device_item_list[this.device_item_list_count].angle_azimuth = t_touch.azimuthAngle; */ this.device_item_list_count++; }break; } } return true; } /** 更新。インプットマネージャマウス。タッチ。 */ #if(true) public bool Main_InputManagerMouse_Touch(NRender2D.Render2D a_render2d) { this.device_item_list_count = 0; //リスト作成。 if(this.device_item_list.Length < 1){ this.device_item_list = new Touch_Device_Item[1]; } if(UnityEngine.Input.GetMouseButton(0) == true){ int t_touch_x = (int)UnityEngine.Input.mousePosition.x; int t_touch_y = (int)UnityEngine.Input.mousePosition.y; //(GUIスクリーン座標)=>(仮想スクリーン座標)。 a_render2d.GuiScreenToVirtualScreen((int)t_touch_x,(int)(Screen.height - t_touch_y),out this.device_item_list[this.device_item_list_count].x,out this.device_item_list[this.device_item_list_count].y); //フェーズ。 this.device_item_list[this.device_item_list_count].phasetype = Touch_Phase.PhaseType.Moved; //フラグ。 this.device_item_list[this.device_item_list_count].link = false; //追加情報。 this.device_item_list[this.device_item_list_count].raw_id = -2; /* this.device_item_list[this.device_item_list_count].pressure = 0.0f; this.device_item_list[this.device_item_list_count].radius = 0.0f; this.device_item_list[this.device_item_list_count].angle_altitude = 0.0f; this.device_item_list[this.device_item_list_count].angle_azimuth = 0.0f; */ this.device_item_list_count++; } return true; } #endif /** 更新。タッチ。 */ public void Main_Touch(NRender2D.Render2D a_render2d) { //インプットシステムタッチ。 if(Config.USE_INPUTSYSTEM_TOUCHSCREEN == true){ if(this.Main_InputSystemTouchscreen_Touch(a_render2d) == true){ return; } } //インプットマネージャタッチ。 if(Config.USE_INPUTMANAGER_TOUCH == true){ if(this.Main_InputManagerTouch_Touch(a_render2d) == true){ return; } } //インプットマネージャマウス。 if(Config.USE_INPUTMANAGER_MOUSE == true){ if(this.Main_InputManagerMouse_Touch(a_render2d) == true){ return; } } } /** 更新。 */ public void Main(NRender2D.Render2D a_render2d) { try{ for(int ii=0;ii<this.list.Count;ii++){ this.list[ii].update = false; } //タッチ。 this.Main_Touch(a_render2d); //近距離追跡。 for(int ii=0;ii<this.device_item_list_count;ii++){ if(this.device_item_list[ii].link == false){ int t_index = this.SearchListItemFromNoUpdate(this.device_item_list[ii].x,this.device_item_list[ii].y,100); if(t_index >= 0){ //追跡。 this.device_item_list[ii].link = true; //設定。 this.list[t_index].Set(this.device_item_list[ii].x,this.device_item_list[ii].y,this.device_item_list[ii].phasetype); this.list[t_index].SetRawID(this.device_item_list[ii].raw_id); /* this.list[t_index].SetAngle(this.device_item_list[ii].angle_altitude,this.device_item_list[ii].angle_azimuth); this.list[t_index].SetPressure(this.device_item_list[ii].pressure); this.list[t_index].SetRadius(this.device_item_list[ii].radius); */ this.list[t_index].update = true; this.list[t_index].fadeoutframe = 0; } } } for(int ii=0;ii<this.device_item_list_count;ii++){ if(this.device_item_list[ii].link == false){ int t_index = this.SearchListItemFromNoUpdate(this.device_item_list[ii].x,this.device_item_list[ii].y,-1); if(t_index >= 0){ //遠距離追跡。 this.device_item_list[ii].link = true; //設定。 this.list[t_index].Set(this.device_item_list[ii].x,this.device_item_list[ii].y,this.device_item_list[ii].phasetype); this.list[t_index].SetRawID(this.device_item_list[ii].raw_id); /* this.list[t_index].SetAngle(this.device_item_list[ii].angle_altitude,this.device_item_list[ii].angle_azimuth); this.list[t_index].SetPressure(this.device_item_list[ii].pressure); ths.list[t_index].SetRadius(this.device_item_list[ii].radius); */ this.list[t_index].update = true; this.list[t_index].fadeoutframe = 0; }else{ Touch_Phase t_touch_phase = new Touch_Phase(); this.list.Add(t_touch_phase); t_index = this.list.Count - 1; { //新規。 this.device_item_list[ii].link = true; //設定。 this.list[t_index].Set(this.device_item_list[ii].x,this.device_item_list[ii].y,this.device_item_list[ii].phasetype); this.list[t_index].SetRawID(this.device_item_list[ii].raw_id); /* this.list[t_index].SetAngle(this.device_item_list[ii].angle_altitude,this.device_item_list[ii].angle_azimuth); this.list[t_index].SetPressure(this.device_item_list[ii].pressure); this.list[t_index].SetRadius(this.device_item_list[ii].radius); */ this.list[t_index].update = true; this.list[t_index].fadeoutframe = 0; } if(this.callback != null){ this.callback(t_touch_phase); } } } } { int ii=0; while(ii<this.list.Count){ if(this.list[ii].update == false){ this.list[ii].fadeoutframe++; if(this.list[ii].fadeoutframe >= 10){ //タイムアウト削除。 this.list.RemoveAt(ii); }else{ this.list[ii].update = true; } }else{ ii++; } } } //更新。 for(int ii=0;ii<this.list.Count;ii++){ this.list[ii].Main(); } }catch(System.Exception t_exception){ Tool.LogError(t_exception); } } /** タッチリスト作成。 */ public static Dictionary<TYPE,NInput.Touch_Phase> CreateTouchList<TYPE>() where TYPE : Touch_Phase_Key_Base { return new Dictionary<TYPE,Touch_Phase>(); } /** タッチリスト更新。 */ public static void UpdateTouchList<TYPE>(Dictionary<TYPE,NInput.Touch_Phase> a_list) where TYPE : Touch_Phase_Key_Base { List<TYPE> t_delete_keylist = null; foreach(KeyValuePair<TYPE,NInput.Touch_Phase> t_pair in a_list){ if(t_pair.Value.update == false){ if(t_delete_keylist == null){ t_delete_keylist = new List<TYPE>(); } t_delete_keylist.Add(t_pair.Key); }else{ //更新。 t_pair.Key.OnUpdate(); } } if(t_delete_keylist != null){ for(int ii=0;ii<t_delete_keylist.Count;ii++){ //リストから削除。 TYPE t_key = t_delete_keylist[ii]; a_list.Remove(t_key); t_key.OnRemove(); } } } } }
using System; using System.Collections.Generic; using System.Text; using Soko.Data.QueryModel; using NHibernate; using NHibernate.Criterion; namespace Soko.Data.NHibernate { internal class QueryTranslator { private ICriteria _criteria; private Query _query; public QueryTranslator(ICriteria criteria, Query query) { _criteria = criteria; _query = query; } public void Execute() { Query myQuery = this._query; foreach (OrderClause clause in myQuery.OrderClauses) { _criteria.AddOrder(new Order(clause.PropertyName, clause.Criterion == OrderClause.OrderClauseCriteria.Ascending ? true : false)); } // TODO: Potrebno je proveriti sledece ogranicenje: Za istu asocijaciju // (tj AssociationPath) nije moguce kombinovati CreateAlias i eager fetch // mode (poziv SetFetchMode sa parametrom FetchMode.Eager) foreach (AssociationAlias a in myQuery.Aliases) { // NOTE: Primetiti da CreateAlias daje inner join _criteria.CreateAlias(a.AssociationPath, a.AliasName); } foreach (Criterion myCriterion in myQuery.Criteria) { ICriterion criterion = null; if (myCriterion.Operator == CriteriaOperator.Equal) criterion = Expression.Eq(myCriterion.PropertyName, myCriterion.Value); else if (myCriterion.Operator == CriteriaOperator.NotEqual) criterion = Expression.Not(Expression.Eq(myCriterion.PropertyName, myCriterion.Value)); else if (myCriterion.Operator == CriteriaOperator.GreaterThan) criterion = Expression.Gt(myCriterion.PropertyName, myCriterion.Value); else if (myCriterion.Operator == CriteriaOperator.GreaterThanOrEqual) criterion = Expression.Ge(myCriterion.PropertyName, myCriterion.Value); else if (myCriterion.Operator == CriteriaOperator.LesserThan) criterion = Expression.Lt(myCriterion.PropertyName, myCriterion.Value); else if (myCriterion.Operator == CriteriaOperator.LesserThanOrEqual) criterion = Expression.Le(myCriterion.PropertyName, myCriterion.Value); else if (myCriterion.Operator == CriteriaOperator.Like) { if (myCriterion.CaseInsensitive) criterion = Expression.InsensitiveLike( myCriterion.PropertyName, myCriterion.Value.ToString(), convertMatchMode(myCriterion.MatchMode)); else criterion = Expression.Like( myCriterion.PropertyName, myCriterion.Value.ToString(), convertMatchMode(myCriterion.MatchMode)); } else if (myCriterion.Operator == CriteriaOperator.NotLike) { if (myCriterion.CaseInsensitive) criterion = Expression.Not(Expression.InsensitiveLike( myCriterion.PropertyName, myCriterion.Value.ToString(), convertMatchMode(myCriterion.MatchMode))); else criterion = Expression.Not(Expression.Like( myCriterion.PropertyName, myCriterion.Value.ToString(), convertMatchMode(myCriterion.MatchMode))); } else if (myCriterion.Operator == CriteriaOperator.IsNull) criterion = Expression.IsNull(myCriterion.PropertyName); else if (myCriterion.Operator == CriteriaOperator.IsNotNull) criterion = Expression.IsNotNull(myCriterion.PropertyName); else throw new ArgumentException("operator", "CriteriaOperator not supported in NHibernate Provider"); if (_query.Operator == QueryOperator.And) _criteria.Add(Expression.Conjunction().Add(criterion)); else if (_query.Operator == QueryOperator.Or) _criteria.Add(Expression.Disjunction().Add(criterion)); } foreach (Query subQuery in myQuery.SubQueries) { QueryTranslator myTranslator = new QueryTranslator(_criteria, _query); myTranslator.Execute(); // Recursive Call } foreach (AssociationFetch f in myQuery.FetchModes) { FetchMode fetchMode = FetchMode.Default; if (f.FetchMode == AssociationFetchMode.Eager) fetchMode = FetchMode.Eager; else if (f.FetchMode == AssociationFetchMode.Lazy) fetchMode = FetchMode.Lazy; _criteria.SetFetchMode(f.AssociationPath, fetchMode); } } private MatchMode convertMatchMode(StringMatchMode stringMatchMode) { switch (stringMatchMode) { case StringMatchMode.Exact: return MatchMode.Exact; case StringMatchMode.Anywhere: return MatchMode.Anywhere; case StringMatchMode.Start: return MatchMode.Start; case StringMatchMode.End: return MatchMode.End; default: throw new ArgumentException("Invalid argument.", "stringMatchMode"); } } } }
using PortioningMachine.SystemComponents; namespace PortioningMachine { public class SocreFunc : IItemScore { public double score(IItem item, IBin bin) { return (bin.target - bin.weight - item.Weight) / bin.target; } } }
using System.Collections.Generic; using BitcoinLib.RPC.RequestResponse; using Newtonsoft.Json; namespace BitcoinLib.Services.Coins.Blocknet.Xrouter { public class GetTransactionsResponse : JsonRpcXrError { public List<RawTransactionResponse> Reply { get; set; } public string Uuid { get; set; } [JsonProperty("allreplies")] public List<ServiceNodeResponse<RawTransactionResponse>> AllReplies { get; set; } } }
using CrazyMinnow.SALSA; using IBM.Watson.NaturalLanguageUnderstanding.V1.Model; using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; //responsible for applying emotions on player public class EmoteManager : NetworkBehaviour { //enum to ensure consistency of data used enum EmotionType { Anger, Disgust, Fear, Joy, Sadness } private static double emotionScoreThreshold = 0.5; private static Dictionary<EmotionType, string> emotionDictionary = new Dictionary<EmotionType, string>() { { EmotionType.Anger, "anger" }, { EmotionType.Disgust, "disgust" }, { EmotionType.Fear, "fear" }, { EmotionType.Joy, "joy" }, { EmotionType.Sadness, "sadness" } }; Emoter emoter; private void Start() { //initate emoter of SALSA emoter = GetComponent<Emoter>(); } //bind events public override void OnStartLocalPlayer() { base.OnStartLocalPlayer(); EmotionList.OnNewEmotion += EmotionList_OnNewEmotion; } //unbind events private void OnDestroy() { if (!isLocalPlayer) { return; } EmotionList.OnNewEmotion -= EmotionList_OnNewEmotion; } //triggered if a new emotion has to be shown private void EmotionList_OnNewEmotion(Emotion emotion) { //do not continue if not local player if (!isLocalPlayer) { return; } //go through all emotions which should be triggered at the same time Dictionary<EmotionType, double> relevantEmotionTypeDictionary = getRelevantEmotionTypeDictionary(emotion.getEmotionScores()); foreach (KeyValuePair<EmotionType, double> emotionTypeEntry in relevantEmotionTypeDictionary) { string expressionComponentName = emotionDictionary[emotionTypeEntry.Key]; double score = emotionTypeEntry.Value; //fire command to server to express emotion CmdExpressEmote(expressionComponentName, score); } } //defines on how to express emotion private void ExpressEmote(string expressionComponentName, double score) { //degree of emotion expression float frac = (float)(1 - (1 - score)); //use salsa interface to apply emotion on face of player emoter.ManualEmote(expressionComponentName, ExpressionComponent.ExpressionHandler.RoundTrip, 5f, true, frac); } //trigger emotion on clients for this player [Command] private void CmdExpressEmote(string expressionComponentName, double score) { RpcExpressEmote(expressionComponentName, score); } //apply emotion on all clients [ClientRpc] private void RpcExpressEmote(string expressionComponentName, double score) { ExpressEmote(expressionComponentName, score); } //identify relevant emotions based on result of IBM Cloud private Dictionary<EmotionType, double> getRelevantEmotionTypeDictionary(EmotionScores emotionScores) { Dictionary<EmotionType, double> emotionTypeDictonary = new Dictionary<EmotionType, double>(); if (emotionScores.Anger != null && emotionScores.Anger.Value > emotionScoreThreshold) { emotionTypeDictonary.Add(EmotionType.Anger, emotionScores.Anger.Value); } if (emotionScores.Disgust != null && emotionScores.Disgust.Value > emotionScoreThreshold) { emotionTypeDictonary.Add(EmotionType.Disgust, emotionScores.Disgust.Value); } if (emotionScores.Fear != null && emotionScores.Fear.Value > emotionScoreThreshold) { emotionTypeDictonary.Add(EmotionType.Fear, emotionScores.Fear.Value); } if (emotionScores.Joy != null && emotionScores.Joy.Value > emotionScoreThreshold) { emotionTypeDictonary.Add(EmotionType.Joy, emotionScores.Joy.Value); } if (emotionScores.Sadness != null && emotionScores.Sadness.Value > emotionScoreThreshold) { emotionTypeDictonary.Add(EmotionType.Sadness, emotionScores.Sadness.Value); } return emotionTypeDictonary; } }
using BaseClass; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Chapter22 { public class Dijkstra { public Dictionary<GraphNode<char>,int> FindShortestPart(GraphAdjacence<char> graph, GraphNode<char> start) { if (start == null || graph == null) return null; HashSet<GraphNode<char>> res = new HashSet<GraphNode<char>>(); Dictionary<GraphNode<char>, int> distance = new Dictionary<GraphNode<char>, int>(); foreach (GraphNode<char> node in graph.Nodes) { if (node == start) { distance.Add(node, 0); } else { distance.Add(node, int.MaxValue); } } res.Add(start); while (res.Count != graph.Nodes.Count) { foreach (GraphNode<char> n in res) { foreach (KeyValuePair<GraphNode<char>, int> neighbor in n.Neiborghs) { if (!res.Contains(neighbor.Key) && distance[neighbor.Key] > distance[n] + neighbor.Value) { distance[neighbor.Key] = distance[n] + neighbor.Value; } } } #region should be able to use heap. call descrease key here. GraphNode<char> tmp = null; int min = int.MaxValue; foreach (GraphNode<char> n in graph.Nodes) { if (!res.Contains(n) && distance[n] < min) { tmp = n; min = distance[n]; } } if (tmp != null) { res.Add(tmp); } #endregion } return distance; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Planning.AdvandcedProjectionActionSelection.PrivacyLeakageCalculation; namespace Planning { abstract class AAdvancedProjectionActionPublisher { protected List<Agent> agents; protected double percentageToSelected; protected Dictionary<Agent, LeakageTrace> traces; protected AAdvancedProjectionActionPublisher(double percentageOfActionsSelected) { this.percentageToSelected = percentageOfActionsSelected; } public void setAgents(List<Agent> newAgents) { this.agents = newAgents; } public void setTraces(Dictionary<Agent, LeakageTrace> traces) { this.traces = traces; } public abstract void publishActions(List<Action> allProjectionAction, Dictionary<Agent, List<Action>> agentsProjections); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CoursIngesup.Projets { class Joueur { public bool Blanc; public int joueur; public Joueur(bool blanc) { Blanc = blanc; if (Blanc) joueur = 1; else joueur = 2; } } }
using System; namespace Task_2._3._ClassFigureWithVirtualVoidDraw { public class Figure { public virtual void Draw() { Console.WriteLine("I am a figure"); Console.WriteLine("Coords of a figure upp left angle is ({0};{1})", X, Y); } public int X, Y; } public class Square : Figure { public override void Draw() { Console.WriteLine("I am a square"); Console.WriteLine("Coords of square upp left angle is ({0};{1})", X, Y); } } public class Rectangle : Figure { public override void Draw() { Console.WriteLine("I am a rectangle"); Console.WriteLine("Coords of rectangle upp left angle is ({0};{1})", X, Y); } } public class Program { public static void Main(string[] args) { Figure figure = new Figure(); Console.Write("Enter the x-coords of the upp left angle of the figure x = "); figure.X = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the y-coords of the upp left angle of the figure y = "); figure.Y = Convert.ToInt32(Console.ReadLine()); figure.Draw(); Square square = new Square(); Console.Write("Enter the x-coords of the upp left angle of the square x = "); square.X = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the y-coords of the upp left angle of the square y = "); square.Y = Convert.ToInt32(Console.ReadLine()); square.Draw(); Rectangle rectangle = new Rectangle(); Console.Write("Enter the x-coords of the upp left angle of the rectangle x = "); rectangle.X = Convert.ToInt32(Console.ReadLine()); Console.Write("Enter the y-coords of the upp left angle of the rectangle y = "); rectangle.Y = Convert.ToInt32(Console.ReadLine()); rectangle.Draw(); Console.ReadLine(); } } }
namespace DDDSouthWest.Domain.Features.Account.Admin.ManageProfile.UpdateExistingProfile { public class ProfileEditModel { public int Id { get; set; } public string GivenName { get; set; } public string FamilyName { get; set; } public string Twitter { get; set; } public string Website { get; set; } public string LinkedIn { get; set; } public string Bio { get; set; } public int UserId { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using ENTITY; using OpenMiracle.DAL; using System.Windows.Forms; using System.Data; namespace OpenMiracle.BLL { public class StockPostingBll { StockPostingSP spStockPosting = new StockPostingSP(); public void DeleteStockPostingForStockJournalEdit(string strVoucherNo, decimal decVoucherTypeId) { try { spStockPosting.DeleteStockPostingForStockJournalEdit(strVoucherNo, decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("BD5:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } public decimal StockPostingAdd(StockPostingInfo stockpostinginfo) { decimal decId = 0; try { decId=spStockPosting.StockPostingAdd(stockpostinginfo); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public decimal StockCheckForProductSale(decimal decProductId, decimal decBatchId) { decimal decId = 0; try { decId = spStockPosting.StockCheckForProductSale(decProductId, decBatchId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public List<DataTable> StockReportGridFill1(String strProductName, decimal decBrandid, decimal decmodelNoId, string strproductCode, decimal decgodownId, decimal decrackId, decimal decsizeId, decimal dectaxId, decimal decgrpId, string strBatchName) { List<DataTable> listobj = new List<DataTable>(); try { listobj = spStockPosting.StockReportGridFill1(strProductName, decBrandid, decmodelNoId, strproductCode, decgodownId, decrackId, decsizeId, dectaxId, decgrpId, strBatchName); } catch (Exception ex) { MessageBox.Show("BD7:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return listobj; } public void DeleteStockPostingByAgnstVouTypeIdAndAgnstVouNo(decimal decAgnstVouTypeId, string strAgnstVouNo) { try { spStockPosting.DeleteStockPostingByAgnstVouTypeIdAndAgnstVouNo(decAgnstVouTypeId, strAgnstVouNo); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } public decimal StockPostingDeleteByagainstVoucherTypeIdAndagainstVoucherNoAndVoucherNoAndVoucherType(decimal decAgainstVoucherTypeId, string strAgainstVoucherNo, string strVoucherNo, decimal decVoucherTypeId) { decimal decId = 0; try { decId = spStockPosting.StockPostingDeleteByagainstVoucherTypeIdAndagainstVoucherNoAndVoucherNoAndVoucherType(decAgainstVoucherTypeId, strAgainstVoucherNo, strVoucherNo, decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public DataSet StockReportPrint(string strProductName, decimal decBrandid, decimal decmodelNoId, string strproductCode, decimal decgodownId, decimal decrackId, decimal decsizeId, decimal dectaxId, decimal decgrpId, string strBatchName) { DataSet ds = new DataSet(); try { ds = spStockPosting.StockReportPrint(strProductName, decBrandid, decmodelNoId, strproductCode, decgodownId, decrackId, decsizeId, decsizeId, decgrpId, strBatchName); } catch (Exception ex) { MessageBox.Show("BD7:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return ds; } public void StpDeleteForProductUpdation(decimal decProductId) { try { spStockPosting.StpDeleteForProductUpdation(decProductId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } public void StockPostingDeleteByVoucherTypeAndVoucherNo(string strVoucherNo, decimal decVoucherTypeId) { try { spStockPosting.StockPostingDeleteByVoucherTypeAndVoucherNo(strVoucherNo, decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } } public decimal BatchViewByProductId(decimal decProductId) { decimal decId = 0; try { decId = spStockPosting.BatchViewByProductId(decProductId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public decimal ProductGetCurrentStock(decimal decProductId, decimal decGodownId, decimal decBatchId, decimal decRackId) { decimal decId = 0; try { decId = spStockPosting.ProductGetCurrentStock(decProductId, decGodownId, decBatchId, decRackId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public decimal StockPostingDeleteForSalesInvoiceAgainstDeliveryNote(decimal decAgainstVoucherTypeId, string strAgainstVoucherNo, string strVoucherNo, decimal decVoucherTypeId) { decimal decId = 0; try { decId = spStockPosting.StockPostingDeleteForSalesInvoiceAgainstDeliveryNote (decAgainstVoucherTypeId, strAgainstVoucherNo, strVoucherNo, decVoucherTypeId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } public int ReturnBatchIdFromStockPosting(decimal decProductId) { int inId = 0; try { inId = spStockPosting.ReturnBatchIdFromStockPosting(decProductId); } catch (Exception ex) { MessageBox.Show("BD1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return inId; } public bool StockPostingEdit(StockPostingInfo stockpostinginfo) { bool isEdit = false; try { isEdit = spStockPosting.StockPostingEdit(stockpostinginfo); } catch (Exception ex) { MessageBox.Show("BD2:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return isEdit; } public bool StpDeleteForRowRemove(decimal decStpId) { bool isEdit = false; try { isEdit = spStockPosting.StpDeleteForRowRemove(decStpId); } catch (Exception ex) { MessageBox.Show("BD8:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return isEdit; } } }
using Leopotam.Ecs; namespace LeoESCTest.UnityComponents.EntityTemplates { public interface IEntityTemplate { public void Create(EcsEntity entity); } }
using GalaSoft.MvvmLight.Command; using Newtonsoft.Json; using nmct.ba.cashlessproject.model.WPF; using nmct.ba.cashlessproject.organisation.ViewModel.General; using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Net.Http; using System.Text; using System.Threading.Tasks; using System.Windows.Input; namespace nmct.ba.cashlessproject.organisation.ViewModel.Administration { public class ProductManagementVM : ObservableObject, IPage { #region Properties public string Name { get { return "Productbeheer"; } } private ObservableCollection<Product> _products; public ObservableCollection<Product> Products { get { return _products; } set { _products = value; OnPropertyChanged("Products"); } } private Product _selectedProduct; public Product SelectedProduct { get { if (_selectedProduct == null) _selectedProduct = new Product(); if(_selectedProduct != null) { if(_selectedProduct.IsValid()) { if (_selectedProduct.ID == 0) CanAdd = true; else CanSaveDelete = true; } else { CanAdd = false; CanSaveDelete = false; } } return _selectedProduct; } set { _selectedProduct = value; OnPropertyChanged("SelectedProduct"); } } private Boolean _showServerMessage; public Boolean ShowServerMessage { get { return _showServerMessage; } set { _showServerMessage = value; OnPropertyChanged("ShowServerMessage"); } } private String _serverMessage; public String ServerMessage { get { return _serverMessage; } set { _serverMessage = value; OnPropertyChanged("ServerMessage"); } } private Boolean _canAdd; public Boolean CanAdd { get { return _canAdd; } set { _canAdd = value; OnPropertyChanged("CanAdd"); } } private Boolean _canSaveDelete; public Boolean CanSaveDelete { get { return _canSaveDelete; } set { _canSaveDelete = value; OnPropertyChanged("CanSaveDelete"); } } #endregion #region Constructor public ProductManagementVM() { GetProducts(); } #endregion #region Methods private async void GetProducts() { using(HttpClient client = new HttpClient()) { client.SetBearerToken(ApplicationVM.token.AccessToken); HttpResponseMessage response = await client.GetAsync("http://localhost:49534/api/product"); if(response.IsSuccessStatusCode) { String json = await response.Content.ReadAsStringAsync(); Products = JsonConvert.DeserializeObject<ObservableCollection<Product>>(json); } } } #endregion #region Commands /* * Command to save product to database. */ public ICommand SaveProductCommand { get { return new RelayCommand(SaveProduct); } } private async void SaveProduct() { using(HttpClient client = new HttpClient()) { client.SetBearerToken(ApplicationVM.token.AccessToken); String product = JsonConvert.SerializeObject(SelectedProduct); HttpResponseMessage response = await client.PutAsync("http://localhost:49534/api/product", new StringContent(product, Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) { GetProducts(); ShowServerMessage = true; ServerMessage = "Het product werd succesvol bewerkt."; } else { ShowServerMessage = true; ServerMessage = "Het product kon niet worden bewerkt."; } } } /* * Command to delete product from database. */ public ICommand DeleteProductCommand { get { return new RelayCommand(DeleteProduct); } } private async void DeleteProduct() { using(HttpClient client = new HttpClient()) { client.SetBearerToken(ApplicationVM.token.AccessToken); String url = String.Format("{0}{1}", "http://localhost:49534/api/product/", SelectedProduct.ID); HttpResponseMessage response = await client.DeleteAsync(url); if (response.IsSuccessStatusCode) { Products.Remove(SelectedProduct); ShowServerMessage = true; ServerMessage = "Het product werd succesvol verwijderd."; } else { ShowServerMessage = true; ServerMessage = "Het product kon niet worden verwijderd."; } } } /* * Command to add product to database. */ public ICommand AddProductCommand { get { return new RelayCommand(AddProduct); } } private async void AddProduct() { using(HttpClient client = new HttpClient()) { client.SetBearerToken(ApplicationVM.token.AccessToken); String product = JsonConvert.SerializeObject(SelectedProduct); HttpResponseMessage response = await client.PostAsync("http://localhost:49534/api/product", new StringContent(product, Encoding.UTF8, "application/json")); if(response.IsSuccessStatusCode) { GetProducts(); ShowServerMessage = true; ServerMessage = "Het product werd succesvol toegevoegd."; } else { ShowServerMessage = true; ServerMessage = "Het product kon niet toegevoegd worden."; } } } /* * Empty all fields. */ public ICommand EmptyFieldsCommand { get { return new RelayCommand(EmptyFields); } } private void EmptyFields() { SelectedProduct = new Product(); } #endregion } }
using System; using Microsoft.EntityFrameworkCore.Migrations; namespace OrderProject.Migrations { public partial class OrderMigration : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.CreateTable( name: "Item", columns: table => new { Iid = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Iname = table.Column<string>(nullable: true), Price = table.Column<int>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Item", x => x.Iid); }); migrationBuilder.CreateTable( name: "Order", columns: table => new { Orderid = table.Column<int>(nullable: false) .Annotation("SqlServer:Identity", "1, 1"), Iid = table.Column<int>(nullable: false), ODate = table.Column<DateTime>(nullable: false), DDate = table.Column<DateTime>(nullable: false) }, constraints: table => { table.PrimaryKey("PK_Order", x => x.Orderid); table.ForeignKey( name: "FK_Order_Item_Iid", column: x => x.Iid, principalTable: "Item", principalColumn: "Iid", onDelete: ReferentialAction.Cascade); }); migrationBuilder.InsertData( table: "Item", columns: new[] { "Iid", "Iname", "Price" }, values: new object[] { 1, "Nippon Blobby", 200 }); migrationBuilder.InsertData( table: "Item", columns: new[] { "Iid", "Iname", "Price" }, values: new object[] { 2, "Smiley", 250 }); migrationBuilder.InsertData( table: "Order", columns: new[] { "Orderid", "DDate", "Iid", "ODate" }, values: new object[] { 1, new DateTime(2019, 11, 19, 17, 20, 49, 490, DateTimeKind.Local).AddTicks(4738), 1, new DateTime(2019, 11, 12, 17, 20, 49, 489, DateTimeKind.Local).AddTicks(3038) }); migrationBuilder.InsertData( table: "Order", columns: new[] { "Orderid", "DDate", "Iid", "ODate" }, values: new object[] { 2, new DateTime(2019, 11, 19, 17, 20, 49, 490, DateTimeKind.Local).AddTicks(6304), 2, new DateTime(2019, 11, 12, 17, 20, 49, 490, DateTimeKind.Local).AddTicks(6277) }); migrationBuilder.CreateIndex( name: "IX_Order_Iid", table: "Order", column: "Iid"); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropTable( name: "Order"); migrationBuilder.DropTable( name: "Item"); } } }
using System; namespace MarsRover { public class GridClass { public GridClass() { } const int gridMinX = 1; const int gridMaxX = 100; const int gridMinY = 1; const int gridMaxY = 100; public string GetGridRef(int x, int y) { return (x + ((y - 1) * gridMaxX)).ToString(); } public int GetGridRefInt(int x, int y) { return x + ((y - 1) * gridMaxX); } public int GetY(string gridRef) { var gf = int.Parse(gridRef); var mod = gf % gridMaxX; if (mod == 0) { return (gf / gridMaxX); } else { return (gf / gridMaxX) + 1; ; } } public int GetX(string gridRef) { var gf = int.Parse(gridRef); var mod = gf % gridMaxX; if (mod == 0) { return gridMaxX; } else { return mod; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace CleanArch.Domain.Commands { public class UpdateCategoryCommand : CategoryCommand { public UpdateCategoryCommand(int id, string name, string description, string imageUrl) { Id = id; Name = name; Content = description; Image = imageUrl; } } }
using UnityEngine; namespace LeoESCTest.UnityComponents.UI { public class ScreenSwitcherComponent : MonoBehaviour { [SerializeField] private GameStateComponent _gameState; [SerializeField] private GameState _state; private void Start() { _gameState.StateChangedEvent += OnStateChangedEvent; gameObject.SetActive(_gameState.CurrentState == _state); } private void OnStateChangedEvent(GameState state) { gameObject.SetActive(state == _state); } } }
using Restoran.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using static Restoran.Models.OrderModel; namespace Restoran.Controllers { public class OrderController : Controller { private OperationDataContext context = null; public OrderController() { context = new OperationDataContext(); } // GET: Order public ActionResult Index() { List<OrderModel> orderList = new List<OrderModel>(); var query = from order in context.tOrders join menu in context.tMenus on order.MenuId equals menu.IdMenu join meja in context.tMejas on order.MejaId equals meja.IdMeja select new OrderModel{ IdOrder = order.IdOrder, MejaId = order.MejaId, MenuId = order.MenuId, Images = menu.Images, JumlahMenu = (int)order.JumlahMenu, Nama = menu.Nama }; orderList = query.ToList(); return View(orderList); } // GET: Order/Details/5 public ActionResult Details(int id) { return View(); } private OrderModel PreparePublisher(OrderModel model) { model.tMejas = context.tMejas.AsQueryable<tMeja>().Select(x => new SelectListItem() { Text = x.IdMeja, Value = x.IdMeja.ToString() }); model.tMenus = context.tMenus.AsQueryable<tMenu>().Select(x => new SelectListItem() { Text = x.Nama, Value = x.IdMenu.ToString() }); return model; } // GET: Order/Create public ActionResult Create() { OrderModel model = new OrderModel(); PreparePublisher(model); //model.DaftarMenu = context.tMenus.AsQueryable<tMenu>().Select(x => //new CheckBoxes //{ // Text = x.Nama, // Value = x.IdMenu //}); model.DaftarMenu = new List<CheckBoxes> { new CheckBoxes { Text = "Nasi", Value="MK001"}, new CheckBoxes { Text = "Kentang", Value="MK002" }, new CheckBoxes { Text = "Kangkung", Value="MK003" }, new CheckBoxes { Text = "Es Teh Manis", Value="MN004" } }; return View(model); } // POST: Order/Create [HttpPost] public ActionResult Create(OrderModel model) { try { // TODO: Add insert logic here tOrder order = new tOrder() { MejaId = model.MejaId, MenuId = model.MenuId, JumlahMenu = model.JumlahMenu }; context.tOrders.InsertOnSubmit(order); context.SubmitChanges(); return RedirectToAction("Create"); } catch { return View(model); } } // GET: Order/Edit/5 public ActionResult Edit(int id) { OrderModel model = context.tOrders.Where(some => some.IdOrder == id).Select( some => new OrderModel() { IdOrder = some.IdOrder, MejaId = some.MejaId, MenuId = some.MenuId, JumlahMenu = (int)some.JumlahMenu }).SingleOrDefault(); PreparePublisher(model); return View(model); } // POST: Order/Edit/5 [HttpPost] public ActionResult Edit(OrderModel model) { try { // TODO: Add update logic here tOrder order = context.tOrders.Where(some => some.IdOrder == model.IdOrder).SingleOrDefault(); order.MejaId = model.MejaId; order.MenuId = model.MenuId; order.JumlahMenu = model.JumlahMenu; context.SubmitChanges(); return RedirectToAction("Index"); } catch { OrderModel modela = new OrderModel(); PreparePublisher(model); return View(model); } } // GET: Order/Delete/5 public ActionResult Delete(int id) { OrderModel model = context.tOrders.Where(some => some.IdOrder == id).Select( some => new OrderModel() { IdOrder = some.IdOrder, MejaId = some.MejaId, MenuId = some.MenuId }).SingleOrDefault(); PreparePublisher(model); return View(model); } // POST: Order/Delete/5 [HttpPost] public ActionResult Delete(OrderModel model) { try { // TODO: Add delete logic here tOrder order = context.tOrders.Where(some => some.IdOrder == model.IdOrder).SingleOrDefault(); context.tOrders.DeleteOnSubmit(order); context.SubmitChanges(); return RedirectToAction("Index"); } catch { return View(); } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Stand : MonoBehaviour { public KeyCode ActivateKey { get; set; } private void Awake() { ActivateKey = KeyCode.F; } public void Activate() { InterfaceController.OpenMenu("EnterMenu"); } public string CreateToolTip() { return $"Открыть [{ActivateKey}]"; } }
using Godot; using Godot.Collections; public struct RawChunk { public Array[] arrays { get; set; } public SpatialMaterial[] materials { get; set; } public Vector3[][] colliderFaces { get; set; } }
 namespace KRF.Core.Entities.Master { public class CrewDetail { public int CrewDetailID { get; set; } public int CrewID { get; set; } public int EmpId { get; set; } public bool IsLead { get; set; } public bool Active { get; set; } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Hearthstone_helper { public partial class Form1 : Form { private Card tempCard; private CardDeck carddeck; private int i; public Form1() { InitializeComponent(); carddeck = new CardDeck(); } private void checkBox1_CheckedChanged(object sender, EventArgs e) { //box1 if (checkBox1.Checked == true) { tempCard = carddeck._CardList[0]; carddeck._CardList.Remove(carddeck._CardList[0]); } if (checkBox1.Checked == false) { tempCard = carddeck._CardList[0]; carddeck._CardList.Add(tempCard); } } private void checkBox2_CheckedChanged(object sender, EventArgs e) { //box2 if (checkBox2.Checked == true) { tempCard = carddeck._CardList[1]; carddeck._CardList.Remove(carddeck._CardList[1]); } if (checkBox2.Checked == false) { tempCard = carddeck._CardList[1]; carddeck._CardList.Add(tempCard); } } private void checkBox3_CheckedChanged(object sender, EventArgs e) { //box3 if (checkBox3.Checked == true) { tempCard = carddeck._CardList[2]; carddeck._CardList.Remove(carddeck._CardList[2]); } if (checkBox3.Checked == false) { tempCard = carddeck._CardList[2]; carddeck._CardList.Add(tempCard); } } private void checkBox4_CheckedChanged(object sender, EventArgs e) { //box4 if (checkBox4.Checked == true) { tempCard = carddeck._CardList[3]; carddeck._CardList.Remove(carddeck._CardList[3]); } if (checkBox4.Checked == false) { tempCard = carddeck._CardList[3]; carddeck._CardList.Add(tempCard); } } private void checkBox5_CheckedChanged(object sender, EventArgs e) { //box5 if (checkBox5.Checked == true) { tempCard = carddeck._CardList[4]; carddeck._CardList.Remove(carddeck._CardList[4]); } if (checkBox5.Checked == false) { tempCard = carddeck._CardList[4]; carddeck._CardList.Add(tempCard); } } private void checkBox6_CheckedChanged(object sender, EventArgs e) { //box6 if (checkBox6.Checked == true) { tempCard = carddeck._CardList[5]; carddeck._CardList.Remove(carddeck._CardList[5]); } if (checkBox6.Checked == false) { tempCard = carddeck._CardList[5]; carddeck._CardList.Add(tempCard); } } private void checkBox7_CheckedChanged(object sender, EventArgs e) { //box7 if (checkBox7.Checked == true) { tempCard = carddeck._CardList[6]; carddeck._CardList.Remove(carddeck._CardList[6]); } if (checkBox7.Checked == false) { tempCard = carddeck._CardList[6]; carddeck._CardList.Add(tempCard); } } private void checkBox8_CheckedChanged(object sender, EventArgs e) { //box8 if (checkBox8.Checked == true) { tempCard = carddeck._CardList[7]; carddeck._CardList.Remove(carddeck._CardList[7]); } if (checkBox8.Checked == false) { tempCard = carddeck._CardList[7]; carddeck._CardList.Add(tempCard); } } private void checkBox9_CheckedChanged(object sender, EventArgs e) { //box9 if (checkBox9.Checked == true) { tempCard = carddeck._CardList[8]; carddeck._CardList.Remove(carddeck._CardList[8]); } if (checkBox9.Checked == false) { tempCard = carddeck._CardList[8]; carddeck._CardList.Add(tempCard); } } private void checkBox10_CheckedChanged(object sender, EventArgs e) { //box10 if (checkBox10.Checked == true) { tempCard = carddeck._CardList[9]; carddeck._CardList.Remove(carddeck._CardList[9]); } if (checkBox10.Checked == false) { tempCard = carddeck._CardList[9]; carddeck._CardList.Add(tempCard); } } private void checkBox11_CheckedChanged(object sender, EventArgs e) { //box11 if (checkBox11.Checked == true) { tempCard = carddeck._CardList[10]; carddeck._CardList.Remove(carddeck._CardList[10]); } if (checkBox11.Checked == false) { tempCard = carddeck._CardList[10]; carddeck._CardList.Add(tempCard); } } private void checkBox12_CheckedChanged(object sender, EventArgs e) { //box12 if (checkBox12.Checked == true) { tempCard = carddeck._CardList[11]; carddeck._CardList.Remove(carddeck._CardList[11]); } if (checkBox12.Checked == false) { tempCard = carddeck._CardList[11]; carddeck._CardList.Add(tempCard); } } private void checkBox13_CheckedChanged(object sender, EventArgs e) { //box13 if (checkBox13.Checked == true) { tempCard = carddeck._CardList[12]; carddeck._CardList.Remove(carddeck._CardList[12]); } if (checkBox13.Checked == false) { tempCard = carddeck._CardList[12]; carddeck._CardList.Add(tempCard); } } private void checkBox14_CheckedChanged(object sender, EventArgs e) { //box14 if (checkBox14.Checked == true) { tempCard = carddeck._CardList[13]; carddeck._CardList.Remove(carddeck._CardList[13]); } if (checkBox14.Checked == false) { tempCard = carddeck._CardList[13]; carddeck._CardList.Add(tempCard); } } private void checkBox15_CheckedChanged(object sender, EventArgs e) { //box15 if (checkBox15.Checked == true) { tempCard = carddeck._CardList[14]; carddeck._CardList.Remove(carddeck._CardList[14]); } if (checkBox15.Checked == false) { tempCard = carddeck._CardList[14]; carddeck._CardList.Add(tempCard); } } private void checkBox16_CheckedChanged(object sender, EventArgs e) { //box16 if (checkBox16.Checked == true) { tempCard = carddeck._CardList[15]; carddeck._CardList.Remove(carddeck._CardList[15]); } if (checkBox16.Checked == false) { tempCard = carddeck._CardList[15]; carddeck._CardList.Add(tempCard); } } private void checkBox17_CheckedChanged(object sender, EventArgs e) { //box17 if (checkBox17.Checked == true) { tempCard = carddeck._CardList[16]; carddeck._CardList.Remove(carddeck._CardList[16]); } if (checkBox17.Checked == false) { tempCard = carddeck._CardList[16]; carddeck._CardList.Add(tempCard); } } private void checkBox18_CheckedChanged(object sender, EventArgs e) { //box18 if (checkBox18.Checked == true) { tempCard = carddeck._CardList[17]; carddeck._CardList.Remove(carddeck._CardList[17]); } if (checkBox18.Checked == false) { tempCard = carddeck._CardList[17]; carddeck._CardList.Add(tempCard); } } private void checkBox19_CheckedChanged(object sender, EventArgs e) { //box19 if (checkBox19.Checked == true) { tempCard = carddeck._CardList[18]; carddeck._CardList.Remove(carddeck._CardList[18]); } if (checkBox19.Checked == false) { tempCard = carddeck._CardList[18]; carddeck._CardList.Add(tempCard); } } private void checkBox20_CheckedChanged(object sender, EventArgs e) { //box20 if (checkBox20.Checked == true) { tempCard = carddeck._CardList[19]; carddeck._CardList.Remove(carddeck._CardList[19]); } if (checkBox20.Checked == false) { tempCard = carddeck._CardList[20]; carddeck._CardList.Add(tempCard); } } private void checkBox21_CheckedChanged(object sender, EventArgs e) { //box21 if (checkBox21.Checked == true) { tempCard = carddeck._CardList[20]; carddeck._CardList.Remove(carddeck._CardList[20]); } if (checkBox21.Checked == false) { tempCard = carddeck._CardList[20]; carddeck._CardList.Add(tempCard); } } private void checkBox22_CheckedChanged(object sender, EventArgs e) { //box22 if (checkBox22.Checked == true) { tempCard = carddeck._CardList[21]; carddeck._CardList.Remove(carddeck._CardList[21]); } if (checkBox22.Checked == false) { tempCard = carddeck._CardList[21]; carddeck._CardList.Add(tempCard); } } private void checkBox23_CheckedChanged(object sender, EventArgs e) { //box23 if (checkBox23.Checked == true) { tempCard = carddeck._CardList[22]; carddeck._CardList.Remove(carddeck._CardList[22]); } if (checkBox23.Checked == false) { tempCard = carddeck._CardList[22]; carddeck._CardList.Add(tempCard); } } private void checkBox24_CheckedChanged(object sender, EventArgs e) { //box24 if (checkBox24.Checked == true) { tempCard = carddeck._CardList[23]; carddeck._CardList.Remove(carddeck._CardList[23]); } if (checkBox24.Checked == false) { tempCard = carddeck._CardList[23]; carddeck._CardList.Add(tempCard); } } private void checkBox25_CheckedChanged(object sender, EventArgs e) { //box25 if (checkBox25.Checked == true) { tempCard = carddeck._CardList[24]; carddeck._CardList.Remove(carddeck._CardList[24]); } if (checkBox25.Checked == false) { tempCard = carddeck._CardList[24]; carddeck._CardList.Add(tempCard); } } private void checkBox26_CheckedChanged(object sender, EventArgs e) { //box26 if (checkBox26.Checked == true) { tempCard = carddeck._CardList[25]; carddeck._CardList.Remove(carddeck._CardList[25]); } if (checkBox26.Checked == false) { tempCard = carddeck._CardList[25]; carddeck._CardList.Add(tempCard); } } private void checkBox27_CheckedChanged(object sender, EventArgs e) { //box27 if (checkBox27.Checked == true) { tempCard = carddeck._CardList[26]; carddeck._CardList.Remove(carddeck._CardList[26]); } if (checkBox27.Checked == false) { tempCard = carddeck._CardList[26]; carddeck._CardList.Add(tempCard); } } private void checkBox28_CheckedChanged(object sender, EventArgs e) { //box28 if (checkBox28.Checked == true) { tempCard = carddeck._CardList[27]; carddeck._CardList.Remove(carddeck._CardList[27]); } if (checkBox28.Checked == false) { tempCard = carddeck._CardList[27]; carddeck._CardList.Add(tempCard); } } private void checkBox29_CheckedChanged(object sender, EventArgs e) { //box29 if (checkBox28.Checked == true) { tempCard = carddeck._CardList[28]; carddeck._CardList.Remove(carddeck._CardList[28]); } if (checkBox28.Checked == false) { tempCard = carddeck._CardList[28]; carddeck._CardList.Add(tempCard); } } private void checkBox30_CheckedChanged(object sender, EventArgs e) { //box26 if (checkBox30.Checked == true) { tempCard = carddeck._CardList[29]; carddeck._CardList.Remove(carddeck._CardList[29]); } if (checkBox30.Checked == false) { tempCard = carddeck._CardList[29]; carddeck._CardList.Add(tempCard); } } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(carddeck._CardList[1].ToString()); foreach (Card card in carddeck._CardList) { MessageBox.Show(card.ToString()); } } } }
using System; namespace Domain.Entities { public class Weather : EntityBase { public DateTime Timestamp { get; set; } public double Temperature { get; set; } public double Pressure { get; set; } public double Humidity { get; set; } public double MinimumTemperature { get; set; } public double MaximumTemperature { get; set; } public int ConditionCode { get; set; } public string Condition { get; set; } public Uri IconURL { get; set; } } }
namespace Tensor.Test.BubbleGame { /// <summary> /// Базовый визуализатор /// </summary> interface IVisualizer { void Render(GameField gameField); } }
/* ************************************************************** * Copyright(c) 2014 Score.web, All Rights Reserved. * File : School.aspx.cs * Description : 学校相关数据处理 * Author : shujianhua * Created : 2014-10-05 * Revision History : ******************************************************************/ namespace App.Web.Score.DataProvider { using App.Score.Data; using App.Score.Db; using App.Score.Entity; using App.Score.Util; using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Web; using System.Web.Services; using System.Web.UI; using System.Web.UI.WebControls; public partial class School : System.Web.UI.Page { //private const string COOKIE_NAME = "ScoreSchool"; [WebMethod] public static SchoolBaseInfo LoadSchool() { //string schoolCookieValue = CookieHelper.GetCookieValue(COOKIE_NAME); //if (!string.IsNullOrEmpty(schoolCookieValue)) //{ // return Newtonsoft.Json.JsonConvert.DeserializeObject<SchoolBaseInfo>(COOKIE_NAME); //} using (AppBLL bll = new AppBLL()) { var sql = "select * FROM tbSchoolBaseInfo"; var schools = bll.FillListByText<SchoolBaseInfo>(sql, null); if (schools.Any()) { SchoolBaseInfo schoolInfo = schools.First(); //CookieHelper.SetCookie(COOKIE_NAME, Newtonsoft.Json.JsonConvert.SerializeObject(schoolInfo), DateTime.Now.AddDays(1)); return schoolInfo; } return null; } } private static IList<GradeCode> BuildGrades(IList<GradeAndClass> ClassList) { IList<GradeCode> gradeList = new List<GradeCode>(); foreach (var gradeAndClass in ClassList) { if (!gradeList.Contains(gradeAndClass.Grade)) { gradeList.Add(gradeAndClass.Grade); } } return gradeList; } private static void BuildGradeClass(GradeCode grade, IList<GradeAndClass> ClassList) { var gradeClasses = from v in ClassList where v.GradeNo == grade.GradeNo && v.ClassNo != null select v; foreach (var gradeClass in gradeClasses) { if (!grade.GradeClasses.Contains(gradeClass.GClass)) { grade.GradeClasses.Add(gradeClass.GClass); } } } [WebMethod] public static IList<GradeCode> LoadGradeClass(int academicYear, bool andStudent) { using (AppBLL bll = new AppBLL()) { var sql = "select a.SystemID GradeSystemID, a.GradeNo,a.GradeName, a.GradeBriefName," + " b.SystemID as ClassSystemID, b.ClassNo, b.AcadEmicYear, b.ClassType, b.IsDelete" + " from tdGradeCode a left join tbGradeClass b on a.GradeNo=b.GradeNo and b.AcademicYear=@Year AND b.ClassType='0'" + " ORDER BY a.GradeNo, b.ClassNo"; IList<GradeAndClass> ClassList = bll.FillListByText<GradeAndClass>(sql, new { Year = academicYear }); IList<GradeCode> gradeList = BuildGrades(ClassList); foreach (var grade in gradeList) { BuildGradeClass(grade, ClassList); } if (andStudent) { sql = "SELECT tbStudentClass.SRID StudentId," + " tbStudentBaseInfo.StdName StdName," + " tbStudentBaseInfo.Sex," + " tbStudentClass.ClassCode ClassCode," + " tbStudentClass.ClassSN ClassSN " + " FROM tbStudentClass LEFT JOIN tbStudentBaseInfo ON " + " tbStudentClass.SRID = tbStudentBaseInfo.SRID " + " LEFT JOIN tbStudentStatus ON " + " tbStudentClass.SRID = tbStudentStatus.SRID AND " + " tbStudentClass.AcademicYear = tbStudentStatus.AcademicYear " + " WHERE tbStudentClass.AcademicYear =@Year" + " AND tbStudentStatus.Status IN ('01','02','03') " + " AND tbStudentBaseInfo.IsDelete = '0' "; IList<Student> allStudents = bll.FillListByText<Student>(sql, new { Year = academicYear }); BuildClassStudent(gradeList, allStudents); } return gradeList; } } public static void BuildClassStudent(IList<GradeCode> gradeList, IList<Student> allStudents) { foreach (var grade in gradeList) { foreach (var gradeClass in grade.GradeClasses) { var classStudents = from v in allStudents where v.ClassCode.Equals(gradeClass.ClassNo) select v; foreach (var student in classStudents) { gradeClass.Students.Add(student); } } } } /// <summary> /// 升留级 /// </summary> /// <param name="academicyear"></param> /// <returns></returns> [WebMethod] public static int UpDown(int acadeMicYear, Student[] downStudents, GradeCode[] grades) { try { using (AppBLL bll = new AppBLL()) { var systemIdBegin = UtilBLL.BuildSystemIdBegin(); var indexForStudentClass = UtilBLL.GetStartIndex("tbStudentClass"); var indexForGradeClass = UtilBLL.GetStartIndex("tbGradeClass"); var indexForStudentStatus = UtilBLL.GetStartIndex("tbStudentStatus"); var sql = ""; object inputParams = null; DataTable table; var nextAcademicYear = acadeMicYear + 1; foreach (var student in downStudents) { //留级 sql = "Select * from tbStudentClass where Academicyear=@Academicyear and SRID = @SRID and isdelete<>'1'"; table = bll.FillDataTableByText(sql, new { Academicyear = acadeMicYear, SRID = student.StudentId }); if (table.Rows.Count == 0) continue; var classCode = int.Parse(student.ClassCode); if ((classCode > 3000 && classCode < 3400) || (classCode >= 2000 && classCode < 2400) || (classCode > 1000 && classCode < 1600)) { var classSN = "00"; var sysID = UtilBLL.CreateSystemID(systemIdBegin, indexForStudentClass++); var SRID = student.StudentId; sql = " if not exists (select * from tbStudentClass where SRID=@SRID"; sql += " and Academicyear=@S_Academicyear) Begin"; sql += " Insert Into tbStudentClass(systemID,SRID,Academicyear,ClassCode,ClassSN) values("; sql += " @s_SYSID,@SRID,@S_Academicyear,@s_ClassCode,@s_ClassSN) end"; inputParams = new { SRID = SRID, s_SYSID = sysID, S_Academicyear = nextAcademicYear, s_ClassCode = classCode, s_ClassSN = classSN }; bll.ExecuteNonQueryByText(sql, inputParams); } } //开留级学生班级 sql = "Select ClassCode from tbStudentClass where Academicyear=@S_Academicyear group by ClassCode"; table = bll.FillDataTableByText(sql, new { S_Academicyear = nextAcademicYear }); for (int i = 0; i < table.Rows.Count; i++) { var sysID = UtilBLL.CreateSystemID(systemIdBegin, indexForGradeClass++); var classCode = table.Rows[i][0].ToString(); sql = " if not exists (select * from tbGradeClass where Academicyear=@S_Academicyear and Classno=@ClassCode)"; sql += " Insert into tbGradeClass(systemid,Academicyear,Gradeno,classno,classType)"; sql += " values(@SYSID,@S_Academicyear,@subClassCode,@ClassCode,0)"; inputParams = new { SYSID = sysID, S_Academicyear = nextAcademicYear, subClassCode = classCode.Substring(0, 2), ClassCode = classCode }; bll.ExecuteNonQueryByText(sql, inputParams); } sql = "Select * from tbStudentClass where Academicyear=@academicyear"; table = bll.FillDataTableByText(sql, new { academicyear = acadeMicYear }); if (table.Rows.Count == 0) return 1; sql = " Select SystemID, SRID, ClassSN, ClassCode, AcademicYear, IsDelete from tbStudentClass where Academicyear=@academicyear"; IList<StudentClass> clsStudents = bll.FillListByText<StudentClass>(sql, new { academicyear = acadeMicYear }); int length = clsStudents.Count(); for (int i = 0; i < length; i++) { var studentClass = clsStudents[i]; string sRID = studentClass.SRID; int downLength = downStudents.Count(); var isKeep = false; for (int j = 0; j < downLength; j++) { if (downStudents[j].StudentId.Equals(sRID)) { isKeep = true; break; } } if (isKeep) continue; var sysID = UtilBLL.CreateSystemID(systemIdBegin, indexForStudentClass++); var classCode = int.Parse(studentClass.ClassCode) + 100; if ((classCode > 3000 && classCode < 3400) || (classCode >= 2000 && classCode < 2400) || (classCode > 1000 && classCode < 1600)) { sql = " if not exists (select * from tbStudentClass where SRID=@SRID and Academicyear=@S_Academicyear)" + " Insert Into tbStudentClass(systemID,SRID,Academicyear,ClassCode,ClassSN)" + " values(@SYSID, @SRID, @S_Academicyear, @s_ClassCode,@s_ClassSN)"; inputParams = new { SRID = sRID, SYSID = sysID, S_Academicyear = nextAcademicYear, s_ClassCode = classCode, s_ClassSN = studentClass.ClassSN }; bll.ExecuteNonQueryByText(sql, inputParams); } } //改变状态 sql = "Select * from tbstudentClass where Isdelete=0 and Academicyear=@CurrentYear"; table = bll.FillDataTableByText(sql, new { CurrentYear = acadeMicYear }); for (int i = 0; i < table.Rows.Count; i++) { var sysID = UtilBLL.CreateSystemID(systemIdBegin, indexForStudentStatus++); sql = "if not exists (select * from tbStudentStatus where Academicyear=@S_Academicyear and SRID=@SRID)"; sql += " Insert Into tbStudentStatus(SystemID,Academicyear,SRID,status)"; sql += " values(@s_SYSID,@S_Academicyear,@SRID,'01')"; inputParams = new { SRID = table.Rows[i]["SRID"].ToString(), s_SYSID = sysID, S_Academicyear = nextAcademicYear }; bll.ExecuteNonQueryByText(sql, inputParams); } //开班级 sql = "Select * from tbstudentclass where Academicyear=@CurrentYear"; table = bll.FillDataTableByText(sql, new { CurrentYear = acadeMicYear }); for (int i = 0; i < table.Rows.Count; i++) { var classCode = int.Parse(table.Rows[i]["ClassCode"].ToString()) + 100; var subClassCode = classCode.ToString().Substring(0, 2); if ((classCode > 3000 && classCode < 3400) || (classCode >= 2000 && classCode < 2400) || (classCode > 1000 && classCode < 1600)) { var sysID = UtilBLL.CreateSystemID(systemIdBegin, indexForGradeClass++); sql = "if not exists (select * from tbGradeClass where Academicyear=@S_Academicyear and classno=@s_ClassCode)"; sql += " Insert into tbGradeClass(systemid,Academicyear,Gradeno,classno,classType)"; sql += " values(@s_SYSID,@S_Academicyear,@subClassCode,@s_ClassCode,'0')"; inputParams = new { s_ClassCode = classCode, subClassCode = subClassCode, s_SYSID = sysID, S_Academicyear = nextAcademicYear }; bll.ExecuteNonQueryByText(sql, inputParams); } } sql = "Update tbSchoolBaseInfo Set AcademicYear=@S_Academicyear, Semester='1'"; inputParams = new { S_Academicyear = nextAcademicYear }; bll.ExecuteNonQueryByText(sql, inputParams); return 1; } } catch (Exception ex) { throw ex; } } /**************************************************转换至学籍************************************/ /// <summary> /// 试算 /// </summary> /// <returns></returns> [WebMethod] public static float TryCalculate(int micYear, string gradeNo, string courseCode, int testType) { using (AppBLL bll = new AppBLL()) { var sumRen = 0; var stdRen = 0; var sql = "select count(*) as SumRen from s_vw_ClassScoreNum" + " where GradeNo=@gradeno" + " and AcademicYear=@micYear" + " and coursecode=@courseCode" + " and testno=@testno" + " and State is null"; DataTable table = bll.FillDataTableByText(sql, new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testType }); sumRen = int.Parse(table.Rows[0][0].ToString()); if (sumRen == 0) return -1; //您选择的考试无人参加! //看标准分 sql = "select count(*) as SumRen from s_vw_ClassScoreNum" + " where GradeNo=@gradeno" + " and AcademicYear=@micYear" + " and normalscore is not null" + " and coursecode=@CourseCode" + " and testno=@testno" + " and State is null"; table = bll.FillDataTableByText(sql, new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testType }); stdRen = int.Parse(table.Rows[0][0].ToString()); if (stdRen == 0) return -2; //您对本次考试还未进行统计! if (sumRen - stdRen > 25) return -3; //在您统计本次考试后有可能有新成绩录入,请再次统计! return Math.Abs(sumRen - stdRen); //有标准分的人数与总人数不一致!相差 abs(sumRen - stdRen) 人,您继续吗? } } [WebMethod] public static float TryCalculateAgain(float c, float k, int micYear, string gradeNo, string courseCode, int testType) { using (AppBLL bll = new AppBLL()) { var sql = "Select Max(normalscore) as MaxScore, min(normalscore) as MinScore from s_vw_ClassScoreNum" + " where GradeNo=@gradeno" + " and AcademicYear=@micYear" + " and normalscore is not null" + " and coursecode=@CourseCode" + " and testno=@testno" + " and State is null"; DataTable table = bll.FillDataTableByText(sql, new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testType }); var maxScore = float.Parse(table.Rows[0]["MaxScore"].ToString()); var minScore = float.Parse(table.Rows[0]["MinScore"].ToString()); float K1, K2; if (maxScore > 0) K1 = (100 - c) / maxScore; else K1 = 9999; if (minScore < 0) K2 = c / Math.Abs(minScore); else K2 = 9999; return K1 > K2 ? (float)Math.Round(K2) : (float)Math.Round(K1); } } /// <summary> /// 执行试算 /// </summary> /// <returns></returns> [WebMethod] public static int TryOk(float c, float K, int micYear, string gradeNo, string courseCode, int testType) { int iK = (int)Math.Truncate(K); if (iK > K) return -1; //您设置K值不能大于试算的K值! using (AppBLL bll = new AppBLL()) { var sql = "Update s_tb_Normalscore set StandardScore=b.NormalScore*(@K)+(@C)" + " FROM s_vw_ClassScoreNum as a INNER JOIN s_tb_normalscore as b" + " ON a.SRID = b.SRID" + " and a.Academicyear=b.Academicyear" + " and a.TestNo=b.testno" + " and a.coursecode=b.coursecode" + " where a.gradeno=@gradeNo" + "` and b.Academicyear=@micYear" + " and b.TestNo=@TestNo" + " and b.CourseCode=@CourseCode" + " and a.Normalscore is not Null" + " and State is null"; return bll.ExecuteNonQueryByText(sql, new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testType, C = c, K = iK }); } } [WebMethod] public static IList<StudentScore> viewOriginData(int micYear, string semester, string gradeNo, string courseCode, int testType, int testNo) { using (AppBLL bll = new AppBLL()) { var sql = ""; if (testType == 0) { sql = " Select SRID, GradeName, ClassCode, ClassSN, StdName, Coursecode, CourseName, avg(NumScore) NumScore, avg(StandardScore) as StandardScore, MarkName" + " from s_vw_ClassScoreNum" + " where GradeNo=@GradeNo" + " and Academicyear=@micYear" + " and Semester=@Semester" + " and CourseCode=@CourseCode" + " and Testtype=@Testtype" + " and STATE is NULL" + " Group by SRID,GradeName,ClassCode,ClassSN,stdName,coursecode,CourseName,MarkName"; return bll.FillListByText<StudentScore>(sql, new { gradeno = gradeNo, Semester = semester, micYear = micYear, courseCode = courseCode, Testtype = testType }); } else { sql = " Select SRID, GradeName, ClassCode, ClassSN, StdName, Coursecode, CourseName, NumScore, StandardScore, MarkName" + " from s_vw_ClassScoreNum" + " where GradeNo=@gradeno" + " and AcademicYear=@micYear" + " and coursecode=@courseCode" + " and testno=@testno" + " and STATE is Null"; } return bll.FillListByText<StudentScore>(sql, new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testNo }); } } [WebMethod] public static SumDecEntry SumDec(int micYear, string semester, string gradeNo, string courseCode, int testType, int testNo) { using (AppBLL bll = new AppBLL()) { SumDecEntry entry = new SumDecEntry(); var sql = ""; var whereSql = ""; var param = new object { }; if (testType == 0) { whereSql = " Where AcademicYear=@micYear and GradeNo=@gradeno and Testtype=@testtype and CourseCode=@courseCode and STATE is NULL"; param = new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, Testtype = testType }; } else { whereSql = " Where AcademicYear=@micYear and GradeNo=@gradeno and Testno=@testtype and CourseCode=@courseCode and STATE is NULL"; param = new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testNo }; } sql = "Select Avg(NumScore) as Avg1,Avg(StandardScore) as Avg2 from s_vw_ClassScoreNum"; DataTable table = bll.FillDataTableByText(sql + whereSql, param); if (table.Rows.Count > 0) { entry.Avg1 = string.IsNullOrEmpty(table.Rows[0]["avg1"].ToString()) ? "无" : table.Rows[0]["avg1"].ToString(); entry.Avg2 = string.IsNullOrEmpty(table.Rows[0]["avg2"].ToString()) ? "无" : table.Rows[0]["avg2"].ToString(); } sql = "Select Count(*) as Cunt1 from s_vw_ClassScoreNum"; table = bll.FillDataTableByText(sql + whereSql + " and Numscore is Null", param); entry.Count1 = int.Parse(table.Rows[0]["cunt1"].ToString()); sql = "Select Count(*) as Cunt1 from s_vw_ClassScoreNum"; table = bll.FillDataTableByText(sql + whereSql + " and StandardScore is Null", param); entry.Count2 = int.Parse(table.Rows[0]["cunt1"].ToString()); sql = "Select Count(*) as Cunt1 from s_vw_ClassScoreNum"; table = bll.FillDataTableByText(sql + whereSql + " and NumScore < 60", param); entry.Count3 = int.Parse(table.Rows[0]["cunt1"].ToString()); sql = "Select Count(*) as Cunt1 from s_vw_ClassScoreNum"; table = bll.FillDataTableByText(sql + whereSql + " and Standardscore < 60", param); entry.Count4 = int.Parse(table.Rows[0]["cunt1"].ToString()); sql = "Select Count(*) as Cunt1 from s_vw_ClassScoreNum"; table = bll.FillDataTableByText(sql + whereSql + " and NumScore >= 200", param); entry.Count5 = int.Parse(table.Rows[0]["cunt1"].ToString()); sql = "Select Count(*) as Cunt1 from s_vw_ClassScoreNum"; table = bll.FillDataTableByText(sql + whereSql + " and Standardscore >= 200", param); entry.Count6 = int.Parse(table.Rows[0]["cunt1"].ToString()); return entry; } } [WebMethod] public static int ConvertToXJ(int micYear, string semester, string gradeNo, string courseCode, int testType, int testNo, int scoreSort, bool ckTeacherOp) { try { using (AppBLL bll = new AppBLL()) { IList<XjEntry> xjEntries = null; var sql = "Select Academicyear,SRID,CourseCode, CourseName,TeacherID,MarkCode"; if (testType == 1) { sql += scoreSort == 1 ? ",avg(Numscore) as Score,operator" : ",avg(standardscore) as Score,operator"; sql += " from s_vw_ClassScoreNum " + " where Gradeno=@gradeNo" + " and Academicyear=@micYear" + " and semester=@semester" + " and CourseCode=@courseCode" + " and TestType=@testType" + " and STATE is NULL" + " group by Academicyear,SRID,CourseCode,Teacherid,MarkCode,operator"; xjEntries = bll.FillListByText<XjEntry>(sql, new { gradeno = gradeNo, micYear = micYear, semester = semester, courseCode = courseCode, testType = testType }); } else { sql += scoreSort == 1 ? ",Numscore as Score,operator" : ",standardscore as Score,operator"; sql += " from s_vw_ClassScoreNum" + " Where GradeNo=@gradeNo" + " and Academicyear=@micYear" + " and CourseCode=@courseCode" + " and TestNo=@testNo" + " and STATE is NULL"; xjEntries = bll.FillListByText<XjEntry>(sql, new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testNo }); } var systemIdBegin = UtilBLL.BuildSystemIdBegin(); var indexForScore = UtilBLL.GetStartIndex("tbScore"); var MinSysID = UtilBLL.CreateSystemID(systemIdBegin, indexForScore); foreach (var xjEntry in xjEntries) { var sysID = UtilBLL.CreateSystemID(systemIdBegin, indexForScore++); var tempTeacher = xjEntry.TeacherID; var tempScore = xjEntry.Score; var strOperator = xjEntry.Operator; sql = "if exists(select * from tbScore where Academicyear=@micYear and CourseCode=@courseCode and SRID=@srid)" + " Update tbScore set "; switch (testType) { case 0: sql += semester.Equals("1") ? "FstAverageScore=" : " SndAverageScore="; break; case 1: sql += semester.Equals("1") ? "FstMidScore=" : " SndMidScore="; break; default: sql += semester.Equals("1") ? "FstEndScore=" : " SndEndScore="; break; } sql += tempScore; sql += " where Academicyear=@micYear" + " and SRID=@srid" + " and CourseCode=@courseCode" + " else" + " Insert Into tbscore(SystemID,AcademicYear,srid,ScoreTypeCode, Coursecode,CourseName,TeacherID,"; switch (testType) { case 0: sql += semester.Equals("1") ? "FstAverageScore, operator)" : " SndAverageScore, operator)"; break; case 1: sql += semester.Equals("1") ? "FstMidScore, operator)" : " SndMidScore, operator)"; break; default: sql += semester.Equals("1") ? "FstEndScore, operator)" : " SndEndScore, operator)"; break; } sql += " values(@sysID,@micYear,@srid,'1100',@courseCode,@courseName,@teacher,@score, @Operator)"; bll.ExecuteNonQueryByText(sql, new { sysID = @sysID, srid = xjEntry.SRID, micYear = micYear, courseCode = courseCode, courseName = xjEntry.CourseName, teacher = xjEntry.TeacherID, score = xjEntry.Score, Operator = string.IsNullOrEmpty(xjEntry.Operator) ? "" : xjEntry.Operator }); } var indexForMoraCol = UtilBLL.GetStartIndex("tbMoralCol"); var minSysId1 = UtilBLL.CreateSystemID(systemIdBegin, indexForMoraCol); if (ckTeacherOp) { sql = " SELECT b.SRID, b.AcademicYear, a.TeacherOP FROM s_tb_TeacherOption a INNER JOIN" + " tbStudentClass b ON a.srid = b.SRID AND " + " a.Academicyear = b.AcademicYear" + " WHERE b.AcademicYear = @micYear" + " AND LEFT(b.ClassCode, 2) = @gradeNo" + " and a.semester=@semester"; IList<TeacherOption> teacherOptions = bll.FillListByText<TeacherOption>(sql, new { micYear = micYear, gradeNo = gradeNo, semester = semester }); foreach (var teacherOption in teacherOptions) { sql = "select count(*) as cnt from tbMoralCol where academicyear =@micYear and semester=@semester and srid =@srid"; DataTable table = bll.FillDataTableByText(sql, new { micYear = micYear, semester = semester, srid = teacherOption.SRID }); if (table.Rows.Count > 0) { sql = " UPDATE tbMoralCol set Remark =@remark where Academicyear=@micYear, srid=@srid and semester=@semester"; bll.ExecuteNonQueryByText(sql, new { remark = teacherOption.TeacherOP, micYear = micYear, semester = semester }); } else { var sysID = UtilBLL.CreateSystemID(systemIdBegin, indexForMoraCol++); sql = " insert into tbMoralCol(SystemID,SRID,AcademicYear,Semester,MoralRank,Remark)" + " values(@sysID, @srid, @micYear, @semester,'良好', @remark)"; bll.ExecuteNonQueryByText(sql, new { sysID = sysID, srid = teacherOption.SRID, remark = teacherOption.TeacherOP, micYear = micYear, semester = semester }); } } } sql = " Insert into tbSchoolOutBox(TableCode,SystemID,RequestDatetime,ThresholdDatetime)" + " Select 'tbscore',SystemID, GETDATE(), DATEADD(day, 1, GETDATE()) from tbscore " + " where systemid>=@minSysID order by SystemID "; bll.ExecuteNonQueryByText(sql, new { minSysID = MinSysID }); if (ckTeacherOp) { sql = " Insert into tbSchoolOutBox(TableCode,SystemID,RequestDatetime,ThresholdDatetime)" + " Select 'tbMoralCol',SystemID, GETDATE(), DATEADD(day, 1, GETDATE()) from tbMoralCol" + " where systemid>=@MinSysID order by SystemID"; bll.ExecuteNonQueryByText(sql, new { minSysID = minSysId1 }); } }//using return 1; } catch (Exception ex) { throw ex; } } [WebMethod] public static int Export(int micYear, string semester, string gradeNo, string courseCode, int testType, int testNo, int scoreSort) { using (AppBLL bll = new AppBLL()) { var sql = ""; DataTable table = null; if (testType == 1) { sql += scoreSort == 1 ? ",avg(Numscore) as Score,operator" : ",avg(standardscore) as Score,operator"; sql += " from s_vw_ClassScoreNum " + " where Gradeno=@gradeNo" + " and Academicyear=@micYear" + " and semester=@semester" + " and CourseCode=@courseCode" + " and TestType=@testType" + " and STATE is NULL" + " group by Academicyear,SRID,CourseCode,Teacherid,MarkCode,operator"; table = bll.FillDataTableByText(sql, new { gradeno = gradeNo, micYear = micYear, semester = semester, courseCode = courseCode, testType = testType }); } else { sql += scoreSort == 1 ? ",Numscore as Score,operator" : ",standardscore as Score,operator"; sql += " from s_vw_ClassScoreNum" + " Where GradeNo=@gradeNo" + " and Academicyear=@micYear" + " and CourseCode=@courseCode" + " and TestNo=@testNo" + " and STATE is NULL"; table = bll.FillDataTableByText(sql, new { gradeno = gradeNo, micYear = micYear, courseCode = courseCode, testno = testNo }); } return 1; } } /****************************************从学籍转换过来*****************************/ [WebMethod] public static string ViewData(int micYear, int chkAll, int cbTestType) { try { using (AppBLL bll = new AppBLL()) { var sql = ""; if (chkAll == 1) { sql = "SELECT a.Academicyear as MicYear, b.StdName, c.BriefName as CourseName, d.Name as Teacher," + " a.FstMidScore, a.FstEndScore, a.SndMidScore, a.SndEndScore" + " FROM TbScore a INNER JOIN" + " tdCourseCode c ON a.Coursecode = c.CourseCode INNER JOIN" + " tbStudentBaseInfo b ON a.SRID = b.SRID LEFT OUTER JOIN" + " tbUserGroupInfo d ON a.TeacherID = d.TeacherID" + " WHERE SUBSTRING(a.Coursecode, 2, 1) = '1'" + " AND (a.Academicyear =@micYear"; } else { var ScoreField = ""; switch (cbTestType) { case 0: ScoreField = "FstMidScore as Score"; break; case 1: ScoreField = "FstEndScore as Score"; break; case 2: ScoreField = "SndMidScore as Score"; break; default: ScoreField = "SndEndScore as Score"; break; } sql = "SELECT a.Academicyear as MicYear, b.StdName, c.BriefName as CourseName," + ScoreField + ",d.Name as Teacher" + " FROM TbScore a INNER JOIN" + " tdCourseCode c ON a.Coursecode = c.CourseCode INNER JOIN" + " tbStudentBaseInfo b ON a.SRID = b.SRID LEFT OUTER JOIN" + " tbUserGroupInfo d ON a.TeacherID = d.TeacherID" + " WHERE SUBSTRING(a.Coursecode, 2, 1) = '1'" + " AND (a.Academicyear =@micYear)"; } DataTable table = bll.FillDataTableByText(sql, new { micYear = micYear }); return Newtonsoft.Json.JsonConvert.SerializeObject(table); } } catch (Exception ex) { throw ex; } } private static int ConvertAll(int micYear, bool canContinue) { var teacherId = "99999999990888"; int testLoginNo, micYear1, testNo1, testNo2, testNo3, testNo4, testNo5; using (AppBLL bll = new AppBLL()) { var sql = ""; DataTable table = null; sql = "Select Count(*) as Pcount from s_tb_testlogin Where AcademicYear=@micYear"; table = bll.FillDataTableByText(sql, new { micYear = micYear }); if (int.Parse(table.Rows[0][0].ToString()) == 0) { testNo1 = 1; } else { if (!canContinue) return -1; sql = "Select Max(convert(integer,testNo)) as testnum from s_tb_Testlogin where AcademicYear=@micYear"; table = bll.FillDataTableByText(sql, new { micYear = micYear }); testNo1 = table.Rows.Count == 0 ? 1 : int.Parse(table.Rows[0][0].ToString()) + 1; } testNo5 = testNo1; testNo2 = testNo1 + 1; testNo3 = testNo1 + 2; testNo4 = testNo1 + 3; sql = "select Max(convert(integer,testloginNo)) as testnum from s_tb_Testlogin"; table = bll.FillDataTableByText(sql, null); testLoginNo = table.Rows.Count == 0 ? 1 : int.Parse(table.Rows[0][0].ToString()) + 1; //判断是否有上学期的期中考试 sql = " Insert Into s_tb_Testlogin(TestloginNo,TestNo,AcademicYear,Semester,TestType,Gradeno,CourseCode,TestTime,MarkTypeCode)" + " Values(@testloginNo,@testNo1,@micYear,'1','1','00','00000',@testTime,'1100')"; var testTime = new DateTime(micYear, 11, 15); bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, testNo1 = testNo1, @micYear = micYear, testTime = testTime }); sql = "insert into s_tb_TestloginUser(TestloginNo,Teacherid) values(@testloginNo,@teacherid)"; bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, teacherid = teacherId }); //第一学期期末考试 testLoginNo++; testNo1++; micYear1 = micYear + 1; testTime = new DateTime(micYear1, 1, 15); sql = "Insert Into s_tb_Testlogin(TestloginNo,TestNo,AcademicYear,Semester,TestType,Gradeno,CourseCode,TestTime,marktypecode)" + " Values(@testloginNo,@testNo1,@micYear,'1','2','00','00000',@testTime,'1100')"; bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, testNo1 = testNo1, @micYear = micYear, testTime = testTime }); sql = "insert into s_tb_TestloginUser(TestloginNo,Teacherid) values(@testloginNo,@teacherid)"; bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, teacherid = teacherId }); testLoginNo++; testNo1++; testTime = new DateTime(micYear1, 4, 15); sql = "Insert Into s_tb_Testlogin(TestloginNo,TestNo,AcademicYear,Semester,TestType,Gradeno,CourseCode,TestTime,MarkTypeCode)" + " Values(@testloginNo,@testNo1,@micYear,'2','2','00','00000',@testTime,'1100')"; bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, testNo1 = testNo1, @micYear = micYear, testTime = testTime }); sql = "insert into s_tb_TestloginUser(TestloginNo,Teacherid) values(@testloginNo,@teacherid)"; bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, teacherid = teacherId }); testLoginNo++; testNo1++; testTime = new DateTime(micYear1, 6, 15); sql = "Insert Into s_tb_Testlogin(TestloginNo,TestNo,AcademicYear,Semester,TestType,Gradeno,CourseCode,TestTime,MarkTypeCode)" + " Values(@testloginNo,@testNo1,@micYear,'2','2','00','00000',@testTime,'1100')"; bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, testNo1 = testNo1, @micYear = micYear, testTime = testTime }); sql = "insert into s_tb_TestloginUser(TestloginNo,Teacherid) values(@testloginNo,@teacherid)"; bll.ExecuteNonQueryByText(sql, new { testloginNo = testLoginNo, teacherid = teacherId }); //开始导入学籍成绩 sql = "Select AcademicYear,srid,Coursecode,Teacherid,FstMidScore,FstEndScore,SndMidScore,SndEndScore,Operator" + " from tbScore" + " where AcademicYear=@micYear and substring(CourseCode,2,1)='1'"; table = bll.FillDataTableByText(sql, new { micYear = micYear }); sql = "Insert Into s_tb_normalscore(AcademicYear,Semester,srid,CourseCode,TeacherID,MarkCode,TestType,TestNo,NumScore,Operator)" + " Values(@YEAR,@SEMESTER,@srid,@COURSECODE,@TEACHERID,@MARKTYPECODE,@TESTTYPE,@TESTNO,@NUMSCORE,@OPERATOR)"; var length = table.Rows.Count; for (int i = 0; i < length; i++) { var YEAR = table.Rows[i]["AcademicYear"].ToString(); var srid = table.Rows[i]["srid"].ToString(); var COURSECODE = table.Rows[i]["CourseCode"].ToString(); var TEACHERID = string.IsNullOrEmpty(table.Rows[i]["Teacherid"].ToString()) ? teacherId : table.Rows[i]["Teacherid"].ToString(); var OPERATOR = string.IsNullOrEmpty(table.Rows[i]["Operator"].ToString()) ? teacherId : table.Rows[i]["Operator"].ToString(); var TESTTYPE = "1"; var TESTNO = testNo5; var MARKTYPECODE = "1100"; var NUMSCORE = 1.0f; var SEMESTER = "1"; string score = table.Rows[i]["FstMidScore"].ToString(); if (!string.IsNullOrEmpty(score)) { NUMSCORE = float.Parse(table.Rows[i]["FstMidScore"].ToString()); bll.ExecuteNonQueryByText(sql, new { YEAR = YEAR, SEMESTER = SEMESTER, srid = srid, COURSECODE = COURSECODE, TEACHERID = TEACHERID, MARKTYPECODE = MARKTYPECODE, TESTTYPE = TESTTYPE, TESTNO = TESTNO, NUMSCORE = NUMSCORE, OPERATOR = OPERATOR }); } score = table.Rows[i]["FstEndScore"].ToString(); if (!string.IsNullOrEmpty(score)) { TESTTYPE = "2"; TESTNO = testNo2; NUMSCORE = float.Parse(table.Rows[i]["FstEndScore"].ToString()); bll.ExecuteNonQueryByText(sql, new { YEAR = YEAR, SEMESTER = SEMESTER, srid = srid, COURSECODE = COURSECODE, TEACHERID = TEACHERID, MARKTYPECODE = MARKTYPECODE, TESTTYPE = TESTTYPE, TESTNO = TESTNO, NUMSCORE = NUMSCORE, OPERATOR = OPERATOR }); } score = table.Rows[i]["SndMidScore"].ToString(); if (!string.IsNullOrEmpty(score)) { TESTTYPE = "1"; TESTNO = testNo3; SEMESTER = "2"; NUMSCORE = float.Parse(table.Rows[i]["SndMidScore"].ToString()); bll.ExecuteNonQueryByText(sql, new { YEAR = YEAR, SEMESTER = SEMESTER, srid = srid, COURSECODE = COURSECODE, TEACHERID = TEACHERID, MARKTYPECODE = MARKTYPECODE, TESTTYPE = TESTTYPE, TESTNO = TESTNO, NUMSCORE = NUMSCORE, OPERATOR = OPERATOR }); } score = table.Rows[i]["SndEndScore"].ToString(); if (!string.IsNullOrEmpty(score)) { TESTTYPE = "2"; TESTNO = testNo4; SEMESTER = "2"; NUMSCORE = float.Parse(table.Rows[i]["SndEndScore"].ToString()); bll.ExecuteNonQueryByText(sql, new { YEAR = YEAR, SEMESTER = SEMESTER, srid = srid, COURSECODE = COURSECODE, TEACHERID = TEACHERID, MARKTYPECODE = MARKTYPECODE, TESTTYPE = TESTTYPE, TESTNO = TESTNO, NUMSCORE = NUMSCORE, OPERATOR = OPERATOR }); } } return 1; } } private static int Convert(int micYear, int cbTestType, bool canContinue) { var teacherId = "99999999990888"; int testLoginNo, testNo1; using (AppBLL bll = new AppBLL()) { var changeScore = ""; var Semester = 1; var testType = 1; var partSql = ""; switch (cbTestType) { case 0: Semester = 1; testType = 1; changeScore = " FstMidScore as scorexj "; partSql = " and FstMidScore is not null and FstMidScore<>''''"; break; case 1: Semester = 1; testType = 1; changeScore = " FstEndScore as scorexj "; partSql = " and FstEndScore is not null and FstMidScore<>''''"; break; case 2: Semester = 1; testType = 2; changeScore = " SndMidScore as scorexj "; partSql = " and SndMidScore is not null and FstMidScore<>''''"; break; default: Semester = 1; testType = 2; changeScore = " SndEndScore as scorexj "; partSql = " and SndEndScore is not null and FstMidScore<>''''"; break; } var sql = "Select Max(cast(testNo as int)) as testnum from s_tb_TestLogin where AcademicYear=@micYear"; DataTable table = bll.FillDataTableByText(sql, new { micYear = micYear }); testNo1 = table.Rows.Count == 0 || string.IsNullOrEmpty(table.Rows[0][0].ToString()) ? 1 : int.Parse(table.Rows[0][0].ToString()) + 1; sql = "select Max(convert(integer,testloginNo)) as testnum from s_tb_Testlogin"; table = bll.FillDataTableByText(sql); testLoginNo = table.Rows.Count == 0 || string.IsNullOrEmpty(table.Rows[0][0].ToString()) ? 1 : int.Parse(table.Rows[0][0].ToString()) + 1; sql = " Insert Into s_tb_Testlogin(TestloginNo,TestNo,AcademicYear,Semester," + " TestType,Gradeno,CourseCode,testtime,MarkTypeCode,startdate,enddate)" + " Values(@testLoginNo,@testNo,@micYear,@semester,@testType,@gradeNo,@courseCode,@testTime,'1100',@startDate,@endDate)"; bll.ExecuteNonQueryByText(sql, new { testLoginNo = testLoginNo, testNo = testNo1, micYear = micYear, semester = Semester, testType = testType, gradeNo = "00", courseCode = "00000", testTime = new DateTime(micYear, 12, 15), startDate = new DateTime(micYear, 12, 16), endDate = new DateTime(micYear, 12, 25) }); sql = "insert into s_tb_testloginUser(TestloginNo,Teacherid) values(@TestloginNo,@Teacherid)"; bll.ExecuteNonQueryByText(sql, new { TestloginNo = testLoginNo, Teacherid = teacherId }); sql = "Select AcademicYEAR,srid,COURSECODE,TEACHERID,Operator," + changeScore + " from tbScore where AcademicYear=@micYear and substring(coursecode,2,1)='1'"; sql += partSql; table = bll.FillDataTableByText(sql, new { micYear = micYear }); sql = "Insert Into s_tb_normalscore(AcademicYear,Semester,srid,CourseCode,TeacherID,MarkCode,TestType,TestNo,NumScore,Operator)" + " Values(@YEAR,@SEMESTER,@srid,@COURSECODE,@TEACHERID,@MARKTYPECODE,@TESTTYPE,@TESTNO,@NUMSCORE,@OPERATOR)"; for (int i = 0; i < table.Rows.Count; i++) { var YEAR = table.Rows[i]["AcademicYear"].ToString(); var srid = table.Rows[i]["srid"].ToString(); var COURSECODE = table.Rows[i]["CourseCode"].ToString(); var TEACHERID = string.IsNullOrEmpty(table.Rows[i]["Teacherid"].ToString()) ? teacherId : table.Rows[i]["Teacherid"].ToString(); var OPERATOR = string.IsNullOrEmpty(table.Rows[i]["Operator"].ToString()) ? teacherId : table.Rows[i]["Operator"].ToString(); var TESTTYPE = testType; var TESTNO = testNo1; var MARKTYPECODE = "1100"; var SEMESTER = Semester; var NUMSCORE = string.IsNullOrEmpty(table.Rows[i]["scorexj"].ToString()) ? 0 : float.Parse(table.Rows[i]["scorexj"].ToString()); bll.ExecuteNonQueryByText(sql, new { YEAR = YEAR, SEMESTER = SEMESTER, srid = srid, COURSECODE = COURSECODE, TEACHERID = TEACHERID, MARKTYPECODE = MARKTYPECODE, TESTTYPE = TESTTYPE, TESTNO = TESTNO, NUMSCORE = NUMSCORE, OPERATOR = OPERATOR }); } return 1; } } /// <summary> /// 转入本系统 /// </summary> /// <param name="micYear"></param> /// <param name="chkAll"></param> /// <param name="testType"></param> /// <param name="canContinue">默认false</param> /// <returns></returns> [WebMethod] public static int ConvertToCJ(int micYear, int chkAll, int cbTestType, bool canContinue) { try { return ConvertAll(micYear, canContinue); //if (chkAll == 1) //{ // return ConvertAll(micYear, canContinue); //} //else //{ // return Convert(micYear, cbTestType, canContinue); //} } catch (Exception ex) { throw ex; } } [WebMethod] public static int CanSelectAll() { using (AppBLL bll = new AppBLL()) { var sql = "Select count(*) as Pcount from s_tb_Normalscore Where AcademicYear=(select academicYear from tbSchoolBaseInfo)"; DataTable table = bll.FillDataTableByText(sql); return int.Parse(table.Rows[0][0].ToString()); } } /****************************************end 从学籍转换过来*****************************/ /****************************************学生编号导入*****************************/ [WebMethod] public static int WriteToDb(int micYear, IList<App.Score.Entity.StudentImportEntry> students) { try { using (AppBLL bll = new AppBLL()) { var systemIdBegin = UtilBLL.BuildSystemIdBegin(); var indexForStudentBase = UtilBLL.GetStartIndex("tbStudentBaseInfo"); var indexForStudentStatus = UtilBLL.GetStartIndex("tbStudentStatus"); var indexForStudentClass = UtilBLL.GetStartIndex("tbStudentClass"); foreach (var student in students) { if (string.IsNullOrEmpty(student.MicYear) || micYear != int.Parse(student.MicYear)) return -1; //系统发现您的Excel学年与系统设置不一样! student.Sex = student.Sex.Equals("男") ? "1" : "2"; //查是否系统中有此学生 var sql = "Select * from s_vw_ClassStudent" + " where Academicyear=@micYear and ClassCode=@classCode" + " and StdName=@name and Sex=@sex"; DataTable table = bll.FillDataTableByText(sql, new { micYear = student.MicYear, classCode = student.GradeClass, name = student.Name, sex = student.Sex }); var mmSRID = ""; if (table.Rows.Count > 0) { mmSRID = table.Rows[0]["srid"].ToString(); sql = " if exists(Select * from s_tb_SchoolID where SRID=@srid)" + " update s_tb_SchoolID set SCHOOLID=@schoolNo where SRID=@srid" + " else Insert into s_tb_SchoolID(SRID,SCHOOLID) values(@srid, @schoolNo)"; bll.ExecuteNonQueryByText(sql, new { srid = mmSRID, schoolNo = student.SchoolNo }); } else { ParamStudentImport1 param1 = new ParamStudentImport1() { ST_SRID = "", YEARCODE = student.MicYear }; bll.ExecuteNonQuery("p_CreateSRID", param1); mmSRID = param1.ST_SRID; var mmSystemId = UtilBLL.CreateSystemID(systemIdBegin, indexForStudentBase++); var stdStatusID = UtilBLL.CreateSystemID(systemIdBegin, indexForStudentStatus++); var mClassID = UtilBLL.CreateSystemID(systemIdBegin, indexForStudentClass++); sql = "Insert Into tbStudentBaseInfo(SystemId,SRID,StdName,sex,ISdelete)" + " values(@mmSystemId, @mmSRID, @mmStdName, @mmSex,'0')"; bll.ExecuteNonQueryByText(sql, new { mmSystemId = mmSystemId, mmSRID = mmSRID, mmStdName = student.Name, mmSex = student.Sex }); //状态 sql = "insert into tbstudentstatus(systemid,AcademicYear,SRID,status,isDelete)" + " values(@mmSystemId,@mmYear,@mmSRID,'01','0')"; bll.ExecuteNonQueryByText(sql, new { mmSystemId = stdStatusID, mmYear = student.MicYear, mmSRID = mmSRID }); //班级 sql = "insert into tbStudentClass(systemid,AcademicYear,SRID,ClassCode,ClassSN,isDelete)" + " values(@mmSystemId, @mmYear, @mmSRID, @mmClassCode, @mmClassSN,'0')"; bll.ExecuteNonQueryByText(sql, new { mmSystemId = mClassID, mmYear = student.MicYear, mmSRID = mmSRID, mmClassCode = student.GradeClass, mmClassSN = student.ClassN }); //学生编号 sql = "if exists(Select * from s_tb_SchoolID where SRID=@mmSRID)" + " update s_tb_SchoolID set SCHOOLID=@mmSchoolNo where SRID=@mmSRID " + " else Insert into s_tb_SchoolID(SRID,SCHOOLID) values(@mmSRID,@mmSchoolNo)"; bll.ExecuteNonQueryByText(sql, new { mmSRID = mmSRID, mmSchoolNo = student.SchoolNo }); } } return 1; } } catch (Exception ex) { throw ex; } } /****************************************end 学生编号导入*****************************/ } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Action : MonoBehaviour { public enum ActionType{UP,DOWN,LEFT,RIGHT}; public ActionType actionType = ActionType.UP; public float speed = 1f; public ClickBox clickBox { get; set; } Rigidbody2D rb; SpriteRenderer spriteRender; void Start() { rb = GetComponent<Rigidbody2D>(); spriteRender = GetComponent<SpriteRenderer>(); } // Update is called once per frame void Update() { var vel = rb.velocity; vel.x = -speed; rb.velocity = vel; } void FixedUpdate() { if(clickBox == null) return; if(clickBox.currentAction == this){ spriteRender.color = Color.green; } else if(spriteRender.color == Color.green){ spriteRender.color = Color.red; } } public void SetActionType(ActionType t){ switch(t){ case ActionType.LEFT: transform.eulerAngles = new Vector3(0, 0, 90); break; case ActionType.DOWN: transform.eulerAngles = new Vector3(0, 0, 180); break; case ActionType.RIGHT: transform.eulerAngles = new Vector3(0, 0, 270); break; default: break; } actionType = t; } }
using System; using System.Collections.Generic; namespace Zhouli.DbEntity.Models { public partial class DictAuthorityType { public string AuthorityTypeId { get; set; } public string AuthorityTypeName { get; set; } } }
using System; using System.Diagnostics; using KelpNet.Common; using KelpNet.Common.Functions.Container; using KelpNet.Common.Tools; using KelpNet.Functions.Activations; using KelpNet.Functions.Connections; using KelpNet.Functions.Noise; using KelpNet.Functions.Poolings; using KelpNet.Loss; using KelpNet.Optimizers; using KelpNetTester.TestData; namespace KelpNetTester.Tests { //Learning MNIST (Handwritten Characters) with 5 Layer CNN //The only difference from Test 4 is network configuration and Optimizer class Test6 { //Number of mini batches const int BATCH_DATA_COUNT = 20; //Number of exercises per generation const int TRAIN_DATA_COUNT = 3000; //= 60000/20 //Number of data at performance evaluation const int TEACH_DATA_COUNT = 200; public static void Run() { Stopwatch sw = new Stopwatch(); //Prepare MNIST data Console.WriteLine("MNIST Data Loading..."); MnistData mnistData = new MnistData(); //Writing the network configuration in FunctionStack FunctionStack nn = new FunctionStack( new Convolution2D(1, 32, 5, pad: 2, name: "l1 Conv2D", gpuEnable: true), new ReLU(name: "l1 ReLU"), //new AveragePooling (2, 2, name: "l1 AVGPooling"), new MaxPooling(2, 2, name: "l1 MaxPooling", gpuEnable: true), new Convolution2D(32, 64, 5, pad: 2, name: "l2 Conv2D", gpuEnable: true), new ReLU(name: "l2 ReLU"), //new AveragePooling (2, 2, name: "l2 AVGPooling"), new MaxPooling(2, 2, name: "l2 MaxPooling", gpuEnable: true), new Linear(13 * 13 * 64, 1024, name: "l3 Linear", gpuEnable: true), new ReLU(name: "l3 ReLU"), new Dropout(name: "l3 DropOut"), new Linear(1024, 10, name: "l4 Linear", gpuEnable: true) ); //Declare optimizer nn.SetOptimizer(new Adam()); Console.WriteLine("Training Start..."); //Three generations learning for (int epoch = 1; epoch < 3; epoch++) { Console.WriteLine("epoch " + epoch); //Total error in the whole Real totalLoss = 0; long totalLossCount = 0; //How many times to run the batch for (int i = 1; i < TRAIN_DATA_COUNT + 1; i++) { sw.Restart(); Console.WriteLine("\nbatch count " + i + "/" + TRAIN_DATA_COUNT); //Get data randomly from training data TestDataSet datasetX = mnistData.GetRandomXSet(BATCH_DATA_COUNT); //Execute batch learning in parallel Real sumLoss = Trainer.Train(nn, datasetX.Data, datasetX.Label, new SoftmaxCrossEntropy()); totalLoss += sumLoss; totalLossCount++; //Result output Console.WriteLine("total loss " + totalLoss / totalLossCount); Console.WriteLine("local loss " + sumLoss); sw.Stop(); Console.WriteLine("time" + sw.Elapsed.TotalMilliseconds); //Test the accuracy if you move the batch 20 times if (i % 20 == 0) { Console.WriteLine("\nTesting..."); //Get data randomly from test data TestDataSet datasetY = mnistData.GetRandomYSet(TEACH_DATA_COUNT); //Run test Real accuracy = Trainer.Accuracy(nn, datasetY.Data, datasetY.Label); Console.WriteLine("accuracy " + accuracy); } } } } } }
using System; using System.Collections.Generic; using System.Text; using System.Collections; using cn.bmob.json; namespace cn.bmob.io { /// <summary> /// ACL基础类 /// /// !!SimpleJson处理Dictionary<string, Object>才正常 /// </summary> public class BmobACL : IBmobValue<Dictionary<string, Object>> { private Dictionary<string, Object> acls = new Dictionary<String, Object>(); //new Dictionary<String, Dictionary<string, bool>>(); /// <summary> /// 获取ACL权限信息 { key : {write : true}, key2 : {read: true} } /// </summary> /// <returns>返回ACL列表, Object的内容为Dictionary<string, bool>可进行强转</returns> public Dictionary<string, Object> Get() { return acls; } public void Set(Object acls) { if (acls is Dictionary<string, Object>) { this.acls = (Dictionary<string, Object>)acls; } else if (acls is IDictionary<string, Object>) { IDictionary<String, Object> kvs = (IDictionary<string, Object>)acls; foreach (var entry in kvs) { this.acls.Add(entry.Key, entry.Value); } } } /// <summary> /// key是objectId(用户表某个用户对应的objectId)或者是 *(表示公共的访问权限),ACL 的值是 "读和写的权限", 这个JSON对象的key总是权限名, 而这些key的值总是 true /// </summary> public BmobACL ReadAccess(String objectId) { BmobOutput.Composite(acls, objectId, "read", true); return this; } public BmobACL WriteAccess(String objectId) { BmobOutput.Composite(acls, objectId, "write", true); return this; } public BmobACL RoleReadAccess(String rolename) { BmobOutput.Composite(acls, "role:" + rolename, "read", true); return this; } public BmobACL RoleWriteAccess(String rolename) { BmobOutput.Composite(acls, "role:" + rolename, "write", true); return this; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace DemoAspNetCore.Exceptions { public class NotSupportedCurrencyException : Exception { } }
using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Mvc; using RestaurantCMS.Business.Abstract; using RestaurantCMS.Models; using RestaurantCMS.ViewModels; using System; using System.Collections.Generic; using System.IO; namespace RestaurantCMS.Controllers { [Authorize] public class DishController : Controller { IDishService dishService; ICategoryService categoryService; IWebHostEnvironment webHost; public DishController(IDishService dishService, ICategoryService categoryService, IWebHostEnvironment webHost) { this.dishService = dishService; this.categoryService = categoryService; this.webHost = webHost; } public IActionResult Index() { List<Dish> dishes = dishService.GetAll(); List<Category> categories = categoryService.GetAll(); DishCategoryModel model = new DishCategoryModel { Dishes = dishes, Categories = categories }; return View(model); } public IActionResult List() { List<Dish> dishes = dishService.GetAll(); return View(dishes); } [HttpGet] public IActionResult ListByCategory(int id) { List<Dish> dishes = dishService.GetByCategoryId(id); List<Category> categories = categoryService.GetAll(); DishCategoryModel model = new DishCategoryModel { Dishes = dishes, Categories = categories }; return View(model); } [HttpGet] public IActionResult Add() { List<Category> categories = categoryService.GetAll(); DishCategoryModel model = new DishCategoryModel { Categories = categories }; return View(model); } [HttpPost] public IActionResult Add(DishCategoryModel model) { if (ModelState.IsValid) { string wwwRootPath = webHost.WebRootPath; string fileName = Path.GetFileNameWithoutExtension(model.Dish.ImageFile.FileName); string extension = Path.GetExtension(model.Dish.ImageFile.FileName); model.Dish.Image = fileName += DateTime.Now.ToString("yymmssfff") + extension; string path = Path.Combine(wwwRootPath + "/images/menu/" + fileName); using (var stream = new FileStream(path, FileMode.Create)) { model.Dish.ImageFile.CopyToAsync(stream); } dishService.Add(model.Dish); return RedirectToAction(nameof(List)); } return View(model); } [HttpGet] public IActionResult Details(int id) { Dish dish = dishService.GetById(id); return View(dish); } [HttpGet] public IActionResult Update(int id) { Dish dish = dishService.GetById(id); return View(dish); } [HttpPost] public IActionResult Update(Dish dish) { if (ModelState.IsValid) { dishService.Update(dish); return RedirectToAction(nameof(List)); } return View(); } [HttpGet] public IActionResult Delete(int id) { dishService.Delete(id); return RedirectToAction(nameof(List)); } } }
using System; using UnityEngine; using UnityStandardAssets.CrossPlatformInput; using UnityEngine.Networking; namespace UnityStandardAssets._2D { [RequireComponent(typeof (PlatformerCharacter2D))] public class Platformer2DUserControl : NetworkBehaviour { private PlatformerCharacter2D m_Character; private status_animator_controller m_status; private bool m_Jump; private Animator m_Anim; private string item = ""; private int itemNum = 0; public GameObject bullet; public Transform bulletSpawn; private float bulletCd = 1 / 16f; private float bulletCdTimer = 0; private Vector2 touchOrigin = -Vector2.one; //Used to store location of screen touch origin for mobile controls public GameObject blackHole; public Transform blackHoleSpawn; public GameObject bomb; public Transform bombSpawn; private float bombCd = 2f; private float bombCdTimer = 0; public GameObject syringe; public Transform syringeSpawn; private float syringeCd = 1 / 4f; private float syringeCdTimer = 0; public GameObject rockets; public Transform rocketsSpawn; public GameObject movingPlatform; private bool isStunned = false; private float stunDuration = 0f; private float slowMultiplier = 1; private float slowDuration = 0f; private bool inStasis = false; private float stasisDuration = 0f; private float statusUpdateTimer; private int statusNum = 0; private void Awake() { m_Character = GetComponent<PlatformerCharacter2D>(); m_Anim = GetComponent<Animator>(); m_status = GetComponentInChildren<status_animator_controller>(); } private void Update() { if (!isLocalPlayer) { return; } if (!m_Jump) { // Read the jump input in Update so button presses aren't missed. m_Jump = CrossPlatformInputManager.GetButtonDown("Jump"); } bool useItem = CrossPlatformInputManager.GetButton("Item"); //bool useItem = Input.GetKey(KeyCode.Alpha5); if (useItem && !item.Equals("")) { if (item.Equals("Item1")) { //CmdBulletFire(); CmdBlackHoleFire(); } if (item.Equals("Item2")) { CmdBombFire(); } if (item.Equals("Item3")) { CmdSyringeFire(); } if (item.Equals("Item4")) { CmdRocketsFire(); } item = ""; itemNum = 0; } //Player has item if (!item.Equals("")) { if (item.Equals("Item2")) { itemNum = 2; } if (item.Equals("Item3")) { itemNum = 3; } } m_Anim.SetInteger("Item", itemNum); syringeCdTimer -= Time.deltaTime; if (isStunned) { stunDuration -= Time.deltaTime; if (stunDuration <= 0) { isStunned = false; print("no more stun"); statusNum = 0; CmdsendStatus(0); m_status.Status(0); } } if (slowMultiplier != 1) { slowDuration -= Time.deltaTime; if (slowDuration <= 0) { slowMultiplier = 1; print("no more slow"); CmdsendStatus(0); m_status.Status(0); } } if (inStasis) { stasisDuration -= Time.deltaTime; if (stasisDuration <= 0) { GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezeRotation; inStasis = false; CmdsendStatus(0); m_status.Status(0); } } } public void IgnoreCollider(Collider c) { Physics.IgnoreCollision(c, GetComponent<Collider>()); } [Command] void CmdBulletFire() { print("item1"); if (Time.time >= bulletCdTimer) { float spray = UnityEngine.Random.Range(-30f, 30f) / 180 * Mathf.PI; //GameObject newBullet = Instantiate(bullet, new Vector2(transform.position.x, transform.position.y), Quaternion.identity); GameObject newBullet = Instantiate(bullet, new Vector2(gameObject.transform.position.x, gameObject.transform.position.y), Quaternion.identity); newBullet.GetComponent<Rigidbody2D>().velocity = new Vector2(100 * Mathf.Sin(spray), 100 * Mathf.Cos(spray)); if (isLocalPlayer) { Physics2D.IgnoreCollision(newBullet.GetComponent<Collider2D>(), GetComponent<Collider2D>()); Physics2D.IgnoreCollision(newBullet.GetComponent<Collider2D>(), GetComponent<BoxCollider2D>()); Physics2D.IgnoreCollision(newBullet.GetComponent<Collider2D>(), GetComponent<CircleCollider2D>()); } bulletCdTimer = Time.time + bulletCd; // Spawn the bullet on the Clients NetworkServer.Spawn(newBullet); } } [Command] void CmdBlackHoleFire() { print("blackHole"); GameObject newHole = Instantiate(blackHole, new Vector2(transform.position.x-5, transform.position.y+5), Quaternion.identity); print("Spawning blackhole on servers"); NetworkServer.Spawn(newHole); } [Command] void CmdBombFire() { print("item2"); if (Time.time >= bombCdTimer) //if (true) { int facingdirection = 1; if (!m_Character.getFacingRight()) { facingdirection = -1; print("facing left"); } GameObject newBomb = Instantiate(bomb, new Vector2(gameObject.transform.position.x , gameObject.transform.position.y + 3), Quaternion.identity); newBomb.GetComponent<Rigidbody2D>().velocity = new Vector2(15f * Mathf.Cos(45f / 180f * Mathf.PI)*facingdirection , 10f * Mathf.Sin(90f / 180f * Mathf.PI)); if (true) { Physics2D.IgnoreCollision(newBomb.GetComponent<Collider2D>(), gameObject.GetComponent<Collider2D>()); Physics2D.IgnoreCollision(newBomb.GetComponent<Collider2D>(), gameObject.GetComponent<BoxCollider2D>()); Physics2D.IgnoreCollision(newBomb.GetComponent<Collider2D>(), gameObject.GetComponent<CircleCollider2D>()); } bombCdTimer = Time.time + bombCd; // Spawn the bomb on the Clients print("Spawning bomb on servers"); NetworkServer.Spawn(newBomb); } } [Command] void CmdSyringeFire() { print("item3"); //if (true) if (Time.time>=syringeCdTimer) { int facingdirection = 1; if (!m_Character.getFacingRight()) { facingdirection = -1; print("facing left"); } GameObject newSyringe = Instantiate(syringe, new Vector2(gameObject.transform.position.x + 2.5f*facingdirection, gameObject.transform.position.y), Quaternion.identity); newSyringe.GetComponent<Rigidbody2D>().velocity = new Vector2(50*facingdirection,0); syringeCdTimer = syringeCd; syringeCdTimer = Time.time + syringeCd; print("Spawning syringes on servers"); NetworkServer.Spawn(newSyringe); //RpcSyringeFire(newSyringe); } } [Command] void CmdRocketsFire() { print("item4"); GameObject newRockets = Instantiate(rockets, new Vector2(transform.position.x, 70), Quaternion.identity); print("Spawning rockets on servers"); NetworkServer.Spawn(newRockets); } [Command] void CmdMove(float move, bool crouch, bool jump) { RpcMove(move, crouch, jump); } [ClientRpc] void RpcMove(float move, bool crouch, bool jump) { if (isLocalPlayer) return; m_Character.Move(move, crouch, jump); } private void FixedUpdate() { if (!isLocalPlayer) { return; } // Read the inputs. // Pass all parameters to the character control script. bool crouch = Input.GetKey(KeyCode.LeftControl); float h = CrossPlatformInputManager.GetAxis("Horizontal"); if (!isStunned || !inStasis) { m_Character.Move(h*slowMultiplier, crouch, m_Jump); CmdMove(h, crouch, m_Jump); } m_Jump = false; if (statusNum == 0 && ((Time.time - statusUpdateTimer) > 1.0f)) { CmdsendStatus(0); statusUpdateTimer = Time.time; } print("Local status is: " + statusNum); } public override void OnStartLocalPlayer() { print("camera attached to robot"); Camera.main.GetComponent<CameraFollow>().setTarget(gameObject.transform); } public void setItem(string item) { this.item = item; } public void applyStun(float duration) { CmdsendStatus(2); m_status.Status(2); statusNum = 2; isStunned = true; stunDuration = duration; print("tio stun liao"); } //update public void applySlow(float multiplier,float duration) { CmdsendStatus(1); m_status.Status(1); statusNum = 1; slowMultiplier = multiplier; slowDuration = duration; print("tio slow liao"); } public void applyStasis(float duration) { CmdsendStatus(3); m_status.Status(3); statusNum = 3; inStasis = true; stasisDuration = duration; GetComponent<Rigidbody2D>().constraints = RigidbodyConstraints2D.FreezePosition | RigidbodyConstraints2D.FreezeRotation; print("oh no!"); } public int getStatus() { return statusNum; } [Command] void CmdsendStatus(int statusUpdate) { RpcsendStatus(statusUpdate); statusNum = statusUpdate; } [ClientRpc] void RpcsendStatus(int statusUpdate) { if (isLocalPlayer) { return; } m_status.Status(statusUpdate); } } }
using System; using System.Text; namespace Bomberman.Api { public static class Extensions { public static int AsInt(this bool b) { return b ? 1 : 0; } public static string ToLogStr<T>(this T[,] m, Func<T, string> itemToString, int itemMaxLen) { var rowsCount = m.GetLength(0); var columnsCount = m.GetLength(1); var sb = new StringBuilder(); sb.Append(" "); for (int c = 0; c < columnsCount; c++) { sb.Append($"{c.ToString().PadLeft(itemMaxLen + 1)}"); } sb.AppendLine(); for (int r = 0; r < rowsCount; r++) { sb.Append($"{r.ToString().PadLeft(2)}:"); for (int c = 0; c < columnsCount; c++) { sb.Append($"{itemToString(m[r, c]).PadLeft(itemMaxLen + 1)}"); } sb.AppendLine(); } return sb.ToString(); } } }
#pragma warning disable SA1600 // Elements should be documented namespace mprCADmanager { using System; using System.Collections.Generic; using ModPlusAPI.Interfaces; public class ModPlusConnector : IModPlusFunctionInterface { public SupportedProduct SupportedProduct => SupportedProduct.Revit; public string Name => "mprCADmanager"; #if R2015 public string AvailProductExternalVersion => "2015"; #elif R2016 public string AvailProductExternalVersion => "2016"; #elif R2017 public string AvailProductExternalVersion => "2017"; #elif R2018 public string AvailProductExternalVersion => "2018"; #elif R2019 public string AvailProductExternalVersion => "2019"; #elif R2020 public string AvailProductExternalVersion => "2020"; #endif public string FullClassName => "mprCADmanager.Commands.DWGImportManagerCommand"; public string AppFullClassName => string.Empty; public Guid AddInId => Guid.Empty; public string LName => "CAD менеджер"; public string Description => "Управление всеми вставками dwg-файлов в текущем документе"; public string Author => "Пекшев Александр aka Modis"; public string Price => "0"; public bool CanAddToRibbon => true; public string FullDescription => "Плагин отображает все виды вставленных dwg-файлов – как принадлежащие видам, так и не принадлежащие видам. Имеется возможность поиска в списке, копирования идентификатора dwg-вставки или вида, открытия вида, содержащего dwg-вставку, а также удаление dwg-вставки"; public string ToolTipHelpImage => string.Empty; public List<string> SubFunctionsNames => new List<string>(); public List<string> SubFunctionsLames => new List<string>(); public List<string> SubDescriptions => new List<string>(); public List<string> SubFullDescriptions => new List<string>(); public List<string> SubHelpImages => new List<string>(); public List<string> SubClassNames => new List<string>(); } } #pragma warning restore SA1600 // Elements should be documented
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace HSE_Graphic_Paint { public partial class Form1 : Form { //Лист для хранения всех нарисованных //линий, удаления проиводиться отсюда же private List<Line> Lines = new List<Line>(); //Выбранная линия private Line selectLine=new Line(); //Новая линия private Line newLine = new Line(); public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } /// <summary> /// Движение /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PBox1_MouseMove(object sender, MouseEventArgs e) { } /// <summary> /// Нажатие /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PBox1_MouseDown(object sender, MouseEventArgs e) { int x1 = Cursor.Position.X; int y1 = Cursor.Position.Y; newLine = new Line(x1,y1,-1,-1); } /// <summary> /// Отпускание /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void PBox1_MouseUp(object sender, MouseEventArgs e) { int x2 = Cursor.Position.X; int y2 = Cursor.Position.Y; newLine.x2 = x2; newLine.y2 = y2; Pen myPen = new Pen( Color.Black,10); Graphics g = null; g.DrawLine(myPen , newLine.x1 , newLine.y1, newLine.x2, newLine.y2) ; } } }
using UnityEngine; using System.Collections; public class RightCardScript : MonoBehaviour { public bool hasRoomCard = false; public int showTime = 0; public bool playedNarration = false; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if(hasRoomCard){ showTime++; } } void OnMouseDown(){ hasRoomCard = true; if(playedNarration == false){ playSound(); } playedNarration = true; } public void playSound(){ audio.Play (); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Startingtext: MonoBehaviour { public GameObject StartRoom; // Use this for initialization void Start() { } // Update is called once per frame void Update() { } public void textDisplay() { StartRoom.SetActive(true); } public void textStop() { StartRoom.SetActive(false); } private void OnTriggerEnter(Collider other) { if (other.tag == "Player") { textDisplay(); } } private void OnTriggerExit(Collider other) { if (other.tag == "Player") { textStop(); } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpOverrides; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.OpenApi.Models; using MongoDB.Driver; using W3ChampionsStatisticService.Admin; using W3ChampionsStatisticService.Clans; using W3ChampionsStatisticService.CommonValueObjects; using W3ChampionsStatisticService.Ladder; using W3ChampionsStatisticService.Matches; using W3ChampionsStatisticService.PadEvents; using W3ChampionsStatisticService.PersonalSettings; using W3ChampionsStatisticService.PlayerProfiles; using W3ChampionsStatisticService.PlayerProfiles.GameModeStats; using W3ChampionsStatisticService.PlayerProfiles.MmrRankingStats; using W3ChampionsStatisticService.PlayerProfiles.RaceStats; using W3ChampionsStatisticService.PlayerStats; using W3ChampionsStatisticService.PlayerStats.HeroStats; using W3ChampionsStatisticService.PlayerStats.RaceOnMapVersusRaceStats; using W3ChampionsStatisticService.Ports; using W3ChampionsStatisticService.ReadModelBase; using W3ChampionsStatisticService.Services; using W3ChampionsStatisticService.Tournaments; using W3ChampionsStatisticService.W3ChampionsStats; using W3ChampionsStatisticService.W3ChampionsStats.DistinctPlayersPerDays; using W3ChampionsStatisticService.W3ChampionsStats.GameLengths; using W3ChampionsStatisticService.W3ChampionsStats.GamesPerDays; using W3ChampionsStatisticService.W3ChampionsStats.HeroPlayedStats; using W3ChampionsStatisticService.W3ChampionsStats.HeroWinrate; using W3ChampionsStatisticService.W3ChampionsStats.HourOfPlay; using W3ChampionsStatisticService.W3ChampionsStats.MapsPerSeasons; using W3ChampionsStatisticService.W3ChampionsStats.MmrDistribution; using W3ChampionsStatisticService.W3ChampionsStats.OverallRaceAndWinStats; using W3ChampionsStatisticService.WebApi.ActionFilters; using W3ChampionsStatisticService.WebApi.ExceptionFilters; namespace W3ChampionsStatisticService { public class Startup { public void ConfigureServices(IServiceCollection services) { var appInsightsKey = Environment.GetEnvironmentVariable("APP_INSIGHTS"); services.AddApplicationInsightsTelemetry(c => c.InstrumentationKey = appInsightsKey?.Replace("'", "")); services.AddControllers(c => { c.Filters.Add<ValidationExceptionFilter>(); }); services.AddSwaggerGen(f => { f.SwaggerDoc("v1", new OpenApiInfo { Title = "w3champions", Version = "v1"}); }); var startHandlers = Environment.GetEnvironmentVariable("START_HANDLERS"); var mongoConnectionString = Environment.GetEnvironmentVariable("MONGO_CONNECTION_STRING") ?? "mongodb://157.90.1.251:3513"; // "mongodb://localhost:27018"; var mongoClient = new MongoClient(mongoConnectionString.Replace("'", "")); services.AddSingleton(mongoClient); services.AddSignalR(); services.AddSpecialBsonRegistrations(); services.AddSingleton<TrackingService>(); services.AddSingleton<PlayerAkaProvider>(); services.AddSingleton<PersonalSettingsProvider>(); services.AddTransient<IMatchEventRepository, MatchEventRepository>(); services.AddTransient<IVersionRepository, VersionRepository>(); services.AddTransient<IMatchRepository, MatchRepository>(); services.AddTransient<TournamentsRepository, TournamentsRepository>(); services.AddSingleton<IPlayerRepository, PlayerRepository>(); services.AddTransient<IRankRepository, RankRepository>(); services.AddTransient<IPlayerStatsRepository, PlayerStatsRepository>(); services.AddTransient<IW3StatsRepo, W3StatsRepo>(); services.AddTransient<IPatchRepository, PatchRepository>(); services.AddTransient<IAdminRepository, AdminRepository>(); services.AddTransient<IPersonalSettingsRepository, PersonalSettingsRepository>(); services.AddTransient<IW3CAuthenticationService, W3CAuthenticationService>(); services.AddSingleton<IOngoingMatchesCache, OngoingMatchesCache>(); services.AddTransient<HeroStatsQueryHandler>(); services.AddTransient<PersonalSettingsCommandHandler>(); services.AddTransient<MmrDistributionHandler>(); services.AddTransient<RankQueryHandler>(); services.AddTransient<GameModeStatQueryHandler>(); services.AddTransient<IClanRepository, ClanRepository>(); services.AddTransient<INewsRepository, NewsRepository>(); services.AddTransient<ILoadingScreenTipsRepository, LoadingScreenTipsRepository>(); services.AddTransient<ClanCommandHandler>(); services.AddTransient<CheckIfBattleTagBelongsToAuthCodeFilter>(); services.AddTransient<InjectActingPlayerFromAuthCodeFilter>(); services.AddTransient<CheckIfBattleTagIsAdminFilter>(); services.AddTransient<MatchmakingServiceRepo>(); services.AddTransient<MatchQueryHandler>(); if (startHandlers == "true") { // PlayerProfile services.AddReadModelService<PlayerOverallStatsHandler>(); services.AddReadModelService<PlayOverviewHandler>(); services.AddReadModelService<PlayerWinrateHandler>(); // PlayerStats services.AddReadModelService<PlayerRaceOnMapVersusRaceRatioHandler>(); services.AddReadModelService<PlayerHeroStatsHandler>(); services.AddReadModelService<PlayerGameModeStatPerGatewayHandler>(); services.AddReadModelService<PlayerRaceStatPerGatewayHandler>(); services.AddReadModelService<PlayerMmrRpTimelineHandler>(); // General Stats services.AddReadModelService<GamesPerDayHandler>(); services.AddReadModelService<GameLengthStatHandler>(); services.AddReadModelService<DistinctPlayersPerDayHandler>(); services.AddReadModelService<HourOfPlayStatHandler>(); services.AddReadModelService<HeroPlayedStatHandler>(); services.AddReadModelService<MapsPerSeasonHandler>(); // Game Balance Stats services.AddReadModelService<OverallRaceAndWinStatHandler>(); services.AddReadModelService<OverallHeroWinRatePerHeroModelHandler>(); // Ladder Syncs services.AddReadModelService<MatchReadModelHandler>(); // On going matches services.AddUnversionedReadModelService<OngoingMatchesHandler>(); services.AddUnversionedReadModelService<RankSyncHandler>(); services.AddUnversionedReadModelService<LeagueSyncHandler>(); } } public void Configure( IApplicationBuilder app, IWebHostEnvironment env) { // without that, nginx forwarding in docker wont work app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto }); app.UseRouting(); app.UseCors(builder => builder .AllowAnyHeader() .AllowAnyMethod() .SetIsOriginAllowed(_ => true) .AllowCredentials()); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); app.UseSwagger(); app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v1/swagger.json", "w3champions"); }); } } public static class ReadModelExtensions { public static IServiceCollection AddReadModelService<T>(this IServiceCollection services) where T : class, IReadModelHandler { services.AddTransient<T>(); services.AddTransient<ReadModelHandler<T>>(); services.AddSingleton<IHostedService, AsyncServiceBase<ReadModelHandler<T>>>(); return services; } public static IServiceCollection AddUnversionedReadModelService<T>(this IServiceCollection services) where T : class, IAsyncUpdatable { services.AddTransient<T>(); services.AddSingleton<IHostedService, AsyncServiceBase<T>>(); return services; } } }
using System; using System.Collections.Generic; using System.Linq; using Grisaia.Geometry; namespace Grisaia.Categories.Sprites { /// <summary> /// Draw information for a sprite selection. /// </summary> public class SpriteDrawInfo { #region Constants /// <summary> /// Gets a sprite draw info structure that represents no sprite. /// </summary> public static SpriteDrawInfo None { get; } = new SpriteDrawInfo(); #endregion #region Fields /// <summary> /// Gets the selection that created this sprite. /// </summary> public ImmutableSpriteSelection Selection { get; } /// <summary> /// Gets the game the character is being drawn from. /// </summary> public GameInfo Game { get; } /// <summary> /// Gets the character being drawn. /// </summary> public CharacterInfo Character { get; } /// <summary> /// Gets the list of sprite draw parts in order of type. /// </summary> public IReadOnlyList<SpritePartDrawInfo> DrawParts { get; } /// <summary> /// Gets the list of actual sprite parts that are used. /// </summary> public IReadOnlyList<ISpritePart> SpriteParts { get; } /// <summary> /// Gets the total size of the sprite. /// </summary> public Point2I TotalSize { get; } /// <summary> /// Gets the draw origin of the sprite. /// </summary> public Point2I Origin { get; } /// <summary> /// Gets if the sprite is expanded. /// </summary> public bool Expand { get; } #endregion #region Properties /// <summary> /// Gets the sprite draw parts that are actually drawn. /// </summary> public IEnumerable<SpritePartDrawInfo> UsedDrawParts => DrawParts.Where(p => !p.IsNone); /// <summary> /// Gets if this sprite selection has no parts to draw. /// </summary> public bool IsNone => !DrawParts.Any(p => !p.IsNone); #endregion #region Constructors /// <summary> /// Constructs an empty unused sprite draw info. /// </summary> private SpriteDrawInfo() { Selection = new ImmutableSpriteSelection(); SpritePartDrawInfo[] drawParts = new SpritePartDrawInfo[SpriteSelection.PartCount]; for (int i = 0; i < SpriteSelection.PartCount; i++) drawParts[i] = SpritePartDrawInfo.None; DrawParts = Array.AsReadOnly(drawParts); SpriteParts = Array.AsReadOnly(new ISpritePart[SpriteSelection.PartCount]); } /// <summary> /// Constructs the sprite draw info with the specified information.<para/> /// The passed arrays must not be used elsewhere. /// </summary> /// <param name="selection">The sprite selection that created this draw info.</param> /// <param name="game">The game the character is being drawn from.</param> /// <param name="character">The character being drawn.</param> /// <param name="drawParts">The sprite parts draw info.</param> /// <param name="spriteParts">The actual sprite parts used.</param> /// <param name="totalSize">The total size of the sprite.</param> /// <param name="origin">The draw origin of the sprite.</param> /// <param name="expand">True if the sprite was created with the expand setting.</param> internal SpriteDrawInfo(IReadOnlySpriteSelection selection, GameInfo game, CharacterInfo character, SpritePartDrawInfo[] drawParts, ISpritePart[] spriteParts, Point2I totalSize, Point2I origin, bool expand) { Selection = selection.ToImmutable(); Game = game; Character = character; DrawParts = Array.AsReadOnly(drawParts); SpriteParts = Array.AsReadOnly(spriteParts); TotalSize = totalSize; Origin = origin; Expand = expand; } #endregion } /// <summary> /// Draw information for a single sprite part used in <see cref="SpriteDrawInfo"/>. /// </summary> public class SpritePartDrawInfo { #region Constants /// <summary> /// Represents no sprite part selection. /// </summary> public static SpritePartDrawInfo None { get; } = new SpritePartDrawInfo(); #endregion #region Fields /// <summary> /// Gets the actual sprite part. /// </summary> public ISpritePart SpritePart { get; } /// <summary> /// Gets the type Id of the sprite part. /// </summary> public int TypeId { get; } /// <summary> /// Gets the frame index of the sprite part. /// </summary> public int Frame { get; } /// <summary> /// Gets the image path for the sprite part. /// </summary> public string ImagePath { get; } /// <summary> /// Gets the margins for the sprite part. /// </summary> public Thickness2I Margin { get; } /// <summary> /// Gets the size of the sprite part. /// </summary> public Point2I Size { get; } #endregion #region Properties /// <summary> /// Gets if the sprite part is no selection. /// </summary> public bool IsNone => ImagePath == null; #endregion #region Constructors private SpritePartDrawInfo() { } internal SpritePartDrawInfo(ISpritePart spritePart, int typeId, int frame, string imagePath, Thickness2I margin, Point2I size) { TypeId = typeId; ImagePath = imagePath; Margin = margin; Size = size; } #endregion } }
using SözTabani.Contexts; using SözTabani.Entities; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; namespace SözTabani.Hesap { public partial class hesabim : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!Request.IsAuthenticated) { Response.Redirect("/error"); } else { MembershipUser user = Membership.GetUser(); LblKullAdi.Text = Membership.GetUser().ToString(); string[] roller = Roles.GetRolesForUser(user.UserName); for(int i = 0; i < roller.Length; i++) { LstRol.Items.Add(roller[i]); } using (SozTabaniContext context = new SozTabaniContext()) { var entity = (from i in context.Kullanıcılar where i.Kullanici_kullaniciadi == LblKullAdi.Text select i).FirstOrDefault(); if (entity != null) { LblAd.Text = entity.Kullanici_Ad; LblSad.Text = entity.Kullanici_Soyad; } } using (SozTabaniContext context = new SozTabaniContext()) { var entity = (from i in context.Sözler where i.soz_kullanici_kullaniciadi == LblKullAdi.Text select i).FirstOrDefault(); if (entity != null) { LblSozSayi.Text = entity.soz_kullanici_kullaniciadi.Count().ToString(); } } LblMail.Text = user.Email; LblKytTarih.Text = user.CreationDate.ToString(); LblEnSnSifre.Text = user.LastPasswordChangedDate.ToString(); if (user.LastPasswordChangedDate == user.CreationDate) { LblEnSnSifre.Text = "Henüz Şifre Değişikliği Yapılmamış !"; } LblBrOnckGrs.Text = user.LastActivityDate.ToString(); /* LblOnline.Text = Membership.UserIsOnlineTimeWindow.ToString(); LblEnSonGiris.Text = user.LastLoginDate.ToString(); LblSimdiOnline.Text = Membership.GetNumberOfUsersOnline().ToString(); */ } } } }
//------------------------------------------------------------------------------ /*sphere is 0, which is not a valid value. Any code that relies on the (normal) fact that enums are restricted to the defined set of enumerated values won’t work. When you create your own values for an enum, make sure that 0 is one of them. If you use bit patterns in your enum, define 0 to be the absence of all the other properties. */ //------------------------------------------------------------------------------ using System; namespace EffectiveC { public enum Planet { // Default starts at 0 otherwise. Mercury = 1, Venus = 2, Earth = 3, Mars = 4, Jupiter = 5, Saturn = 6, Neptune = 7, Uranus = 8 // First edition included Pluto. } Planet sphere = new Planet(); //As it stands now, you force all users to explicitly initialize the value: Planet sphere2 = Planet.Mars; //Another common initialization problem involves value types that contain references. Strings are a common example: public struct LogMessage { private int ErrLevel; private string msg; } LogMessage MyMessage = new LogMessage(); //MyMessage contains a null reference in its msg field. There is no way to force a different initialization //Add logic to that property to return the empty string instead of null: public struct LogMessage2 { private int ErrLevel; private string msg; public string Message { get { return (msg != null) ? msg : string.Empty; } set { msg = value; } } } }
using REQFINFO.Repository.DataEntity; using REQFINFO.Repository.Infrastructure; using REQFINFO.Repository.Infrastructure.Contract; using REQFINFO.Utility; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace REQFINFO.Repository { public class LevelRepository : BaseRepository<Level> { GIGEntities entities; public LevelRepository(IUnitOfWork unit) : base(unit) { entities = (GIGEntities)this.UnitOfWork.Db; } public GetLevelDetailNextOrPrevious_Result GetIDLevel(Int32 IDProject, Int32? CurrentSequence, bool IsNextNotPreviousLevel) { GetLevelDetailNextOrPrevious_Result LevelDetailNextOrPrevious = new GetLevelDetailNextOrPrevious_Result(); LevelDetailNextOrPrevious = entities.GetLevelDetailNextOrPrevious(IDProject, CurrentSequence, IsNextNotPreviousLevel).SingleOrDefault(); return LevelDetailNextOrPrevious; } } }
using System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Runtime.CompilerServices; namespace NetFabric.Hyperlinq { public static partial class DictionaryBindings { public partial struct ValueWrapper<TKey, TValue> { [GeneratedCode("NetFabric.Hyperlinq.SourceGenerator", "1.0.0")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly NetFabric.Hyperlinq.ValueEnumerableExtensions.SelectEnumerable<NetFabric.Hyperlinq.DictionaryBindings.ValueWrapper<TKey, TValue>, System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator, System.Collections.Generic.KeyValuePair<TKey, TValue>, TResult, NetFabric.Hyperlinq.FunctionWrapper<System.Collections.Generic.KeyValuePair<TKey, TValue>, TResult>> Select<TResult>(System.Func<System.Collections.Generic.KeyValuePair<TKey, TValue>, TResult> selector) => NetFabric.Hyperlinq.ValueEnumerableExtensions.Select<NetFabric.Hyperlinq.DictionaryBindings.ValueWrapper<TKey, TValue>, System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator, System.Collections.Generic.KeyValuePair<TKey, TValue>, TResult>(this, selector); [GeneratedCode("NetFabric.Hyperlinq.SourceGenerator", "1.0.0")] [MethodImpl(MethodImplOptions.AggressiveInlining)] public readonly NetFabric.Hyperlinq.ValueEnumerableExtensions.SelectEnumerable<NetFabric.Hyperlinq.DictionaryBindings.ValueWrapper<TKey, TValue>, System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator, System.Collections.Generic.KeyValuePair<TKey, TValue>, TResult, TSelector> Select<TResult, TSelector>(TSelector selector = default) where TSelector : struct, NetFabric.Hyperlinq.IFunction<System.Collections.Generic.KeyValuePair<TKey, TValue>, TResult> => NetFabric.Hyperlinq.ValueEnumerableExtensions.Select<NetFabric.Hyperlinq.DictionaryBindings.ValueWrapper<TKey, TValue>, System.Collections.Generic.Dictionary<TKey, TValue>.Enumerator, System.Collections.Generic.KeyValuePair<TKey, TValue>, TResult, TSelector>(this, selector); } } }
using Microsoft.Xna.Framework; namespace MonoGame.Extended.Entities.Systems { public abstract class EntityUpdateSystem : EntitySystem, IUpdateSystem { protected EntityUpdateSystem(AspectBuilder aspectBuilder) : base(aspectBuilder) { } public abstract void Update(GameTime gameTime); } }
using CarWash.ClassLibrary.Models; using System.Threading.Tasks; namespace CarWash.ClassLibrary.Services { /// <summary> /// Defines a service to create, update and remove Outlook events using a Logic App /// </summary> public interface ICalendarService { /// <summary> /// Create an Outlook event based on a reservation /// </summary> /// <param name="reservation">Reservation to get the details from</param> /// <returns>Outlook event id</returns> Task<string> CreateEventAsync(Reservation reservation); /// <summary> /// Update an Outlook event based on a reservation /// </summary> /// <param name="reservation">Reservation to get the details from</param> /// <returns>Outlook event id</returns> Task<string> UpdateEventAsync(Reservation reservation); /// <summary> /// Delete an Outlook event by id /// </summary> /// <param name="reservation">Reservation to delete event for</param> Task DeleteEventAsync(Reservation reservation); } }
using UnityEngine; using System.Collections; public class GameController : MonoBehaviour { private static int level; private static int[] gomicounter; private static int[] gomibako; public GameObject player; public GameObject enemy; public GameObject Stage; public Camera ca; public GameObject [] gomi1; public GameObject [] gomi2; public GameObject [] gomi3; private GameObject[] g1s; private Transform[] g1tr; private GameObject lightGameObject; public float speed = 10; public int distance = 10; private Vector3 prev; private int t; public float count = 50; //一度に何体のオブジェクトをスポーンさせるか public float interval = 1; //何秒おきに敵を発生させるか private float timer; //経過時間 public int max = 10; private int g1sNum; private int g2sNum; int num1; GameObject[] gomi1Objects; // int g1Num; Vector3 d; public GameObject getPlayer(){ return player; } void Start () { //ライト lightGameObject = new GameObject("The Light"); Light lightComp = lightGameObject.AddComponent<Light>(); lightComp.color = Color.white; lightComp.intensity = 0; lightGameObject.transform.position = new Vector3(0, 10, 0); lightGameObject.transform.rotation = Quaternion.Euler(new Vector3(50, 330, 0)); lightComp.type = LightType.Directional; //ライト //プレイヤー prev = player.transform.position; player.AddComponent<Rigidbody>(); player.AddComponent<SphereCollider>(); SphereCollider sc = player.GetComponent<SphereCollider>(); sc.radius = 0.005f; //プレイヤー //gomiタグ for(int i=0; i<1; i++){ gomi1 [i].tag = "gomi1"; gomi2 [i].tag = "gomi2"; gomi3 [i].tag = "gomi3"; } //gomiタグ // d = new Vector3(0,0,0); //初期ゴミ for (int j = 0; j < 1; ++j) { for (int i = 0; i < 1; ++i) { Instantiate (gomi1 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); Instantiate (gomi2 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); Instantiate (gomi3 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); } } } void Update () { //ライト Light lightComp = lightGameObject.GetComponent<Light> (); if (lightComp.intensity < 1.5) { lightComp.intensity = t * 0.001f; } t++; //ライト //ゴミ発生 num1 = GameObject.FindGameObjectsWithTag ("gomi1").Length; Debug.Log (num1); timer += Time.deltaTime; //経過時間加算 if (timer >= interval) { if (g1sNum < max) { if (num1 < 20) { for (int i = 0; i < 1; ++i) { Instantiate (gomi1 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); } // Spawn1(); //スポーン実行 } if (g2sNum < max) { for (int i = 0; i < 1; ++i) { Instantiate (gomi2 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); } // Spawn2 (); } if (g2sNum < max) { for (int i = 0; i < 1; ++i) { Instantiate (gomi3 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); } // Spawn3 (); } timer = 0; //初期化 } if (num1 < 20) { for (int i = 0; i < 1; ++i) { Instantiate (gomi1 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); Instantiate (gomi2 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); Instantiate (gomi3 [i], enemy.transform.position + new Vector3 (Random.Range (-0.5f, 0.5f) * 10, i * 10 + 10, Random.Range (-0.5f, 0.5f) * 10), Quaternion.identity); } } //ゴミ発生 } } void FixedUpdate (){ //プレイヤー制御 Vector3 forward = player.transform.TransformDirection( Vector3.forward ); Vector3 right = player.transform.TransformDirection( Vector3.right ); float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Rigidbody prb = player.GetComponent<Rigidbody>(); prb.useGravity = true; prb.AddForce(x * right *speed/2 + z * forward *speed ); Vector3 diff = player.transform.position - prev; if (diff.magnitude > 0.005) { prb.rotation = Quaternion.LookRotation (diff); } prev = player.transform.position; //プレイヤー制御 //カメラ制御 Vector3 newPosition = player.transform.position - 3* diff.normalized;; newPosition.y = player.transform.position.y + 1; ca.transform.position = newPosition; ca.transform.LookAt(player.transform); //カメラ制御 } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace FileBrowser { class Program { static void Main(string[] args) { DriveInfo[] drives = DriveInfo.GetDrives(); Console.WriteLine("Drivers:"); Console.WriteLine("-----------------------------"); for (int i = 0; i < drives.Length; i++) { if (drives[i].IsReady) Console.WriteLine($"{i + 1}.{drives[i]}"); } Console.WriteLine("-----------------------------"); Console.WriteLine("Enter Your Choice Number:\n"); int choiceNumber = Int32.Parse(Console.ReadLine()); Console.Clear(); /////////////////////////////////////////////////////////////////// DirectoryInfo di = new DirectoryInfo($@"{drives[choiceNumber - 1]}"); var subDirectories = di.GetDirectories(); var files = di.GetFiles(); Console.WriteLine(di); Console.WriteLine("Directories:"); Console.WriteLine("-----------------------------"); for (int i = 0; i < subDirectories.Length; i++) { Console.WriteLine($"{i + 1}.{subDirectories[i].FullName}"); } Console.WriteLine($"\n"); Console.WriteLine("Files:"); Console.WriteLine("-----------------------------"); for (int i = 0; i < files.Length; i++) { Console.WriteLine($"{i + subDirectories.Length + 1}.{files[i].FullName}\t{files[i].LastWriteTime}\n"); } Console.WriteLine("\n"); //////////////////////////////////////////////////////////////////// while (true) { Console.WriteLine("-----------------------------"); Console.WriteLine("Enter Your Choice Number:\n"); choiceNumber = Int32.Parse(Console.ReadLine()); Console.Clear(); if (choiceNumber - 1 < subDirectories.Length && choiceNumber - 1 >= 0) { di = new DirectoryInfo($@"{subDirectories[choiceNumber - 1].FullName}"); subDirectories = di.GetDirectories(); files = di.GetFiles(); Console.WriteLine("Directories:"); Console.WriteLine("-----------------------------"); for (int i = 0; i < subDirectories.Length; i++) { Console.WriteLine($"{i + 1}.{subDirectories[i].FullName}"); } Console.WriteLine($"\n"); Console.WriteLine("Files:"); Console.WriteLine("-----------------------------"); for (int i = 0; i < files.Length; i++) { Console.WriteLine($"{i + subDirectories.Length + 1}.{files[i].FullName}\t{files[i].LastWriteTime}\n"); } Console.WriteLine("\n"); } else if ((choiceNumber >= (subDirectories.Length + 1)) && (choiceNumber <= (subDirectories.Length + files.Length))) { Process.Start(di.GetFiles()[choiceNumber - subDirectories.Length-1].FullName); } else { Console.WriteLine("Enter True Number:\n"); } } //while (true) //{ // Console.WriteLine("\n"); // Console.WriteLine("Enter Your Choice Number:\n"); // int choiceNumber2 = Int32.Parse(Console.ReadLine()); // DirectoryInfo di2 = new DirectoryInfo($@"{subDirectories[choiceNumber2 - 1]}"); // var subDirectories2 = di2.GetDirectories(); // var files2 = di2.GetFiles(); // Console.Clear(); // /////////////////////////////////////////////////////////////// // Console.WriteLine("Directories:"); // Console.WriteLine("-----------------------------"); // for (int i = 0; i < subDirectories2.Length; i++) // { // Console.WriteLine($"{i + 1}.{subDirectories2[i].FullName}"); // } // Console.WriteLine($"\n"); // Console.WriteLine("Files:"); // Console.WriteLine("-----------------------------"); // for (int i = 0; i < files2.Length; i++) // { // Console.WriteLine($"{i + 1}.{files2[i].FullName}\t{files2[i].LastWriteTime}"); // } // Console.ReadKey(); //} Console.ReadKey(); } } }
using System.Collections.Generic; using System.Threading.Tasks; using Business.Generics; using Core.Utilities.Results; using Entities.Concrete; namespace Business.Abstract { public interface IAddressService:IGenericCrudOperationService<Address> { Task<IDataResult<long>> GetIdAdd(Address address); Task<IDataResult<Address>> GetById(int id); Task<IDataResult<List<Address>>> GetAllByUserId(int userId); Task<IDataResult<List<Address>>> GetAllByCityId(int cityId); } }
// // Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. // using System; namespace Dnn.PersonaBar.Pages.Components.Exceptions { public class TemplateException : Exception { public TemplateException(string message): base(message) { } } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class EnemyHealth : MonoBehaviour { [SerializeField] FloatReference startingHealth = null; float health = 0; [SerializeField] GameObject explosionVFX; [SerializeField] AudioCue deathSFX; [SerializeField] FloatVariable score = null; private bool hasExploded = false; private bool hasDied = false; void Awake() { health = startingHealth.Value; } void Update() { OnDie(); } private void OnTriggerEnter2D(Collider2D other) { DealDamage(other); } private void OnDie() { if (hasDied) { return; } if (health <= 0) { if (!hasExploded) { Instantiate(explosionVFX, transform.position, transform.rotation); deathSFX.PlayClipAtCameraMain(); hasExploded = true; } if (gameObject.CompareTag("EnemyLeader")) { gameObject.GetComponent<Renderer>().enabled = false; } else { Destroy(gameObject); } IncrementScore(); hasDied = true; } } private void DealDamage(Collider2D other) { var damageDealer = other.gameObject.GetComponent<DamageDealer>(); health -= damageDealer.DamagePoints; damageDealer.OnHit(); } private void IncrementScore() { if (score != null) { score.ApplyChange(50); } } }
using AgendaAPI.Dominio.Entidades; using AgendaAPI.Dominio.Repositorios; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace AgendaAPI.Repositorio { public class UsuarioRepositorio : IUsuarioRepositorio { private readonly AgendaContext contexto; public UsuarioRepositorio(AgendaContext contexto) { this.contexto = contexto; } public void Atualizar(Usuario usuario) { contexto.Entry<Usuario>(usuario).State = EntityState.Modified; } public void Criar(Usuario usuario) { contexto.Usuarios.Add(usuario); } public void Excluir(Usuario usuario) { contexto.Usuarios.Remove(usuario); } public List<Usuario> Obter() { return contexto.Usuarios.ToList(); } public Usuario Obter(int id) { return contexto.Usuarios .Where(x => x.Id == id).SingleOrDefault(); } public Usuario Obter(string email) { return contexto.Usuarios .Where(x => x.Email == email).SingleOrDefault(); } } }
/* * By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. * * What is the 10 001st prime number? */ const int MAX_VALUE = 10001; var count = 0; var number = 1; while(count < MAX_VALUE) { number++; if (number.IsPrime()) count++; } Console.WriteLine(number); // Determines if a value is a prime number. private static bool IsPrime(this int n) { if (n == 2 || n == 3) return true; if (n % 2 == 0) return false; int sqrt = (int)Math.Sqrt(n) + 1; for (var i = 3; i < sqrt; i += 2) if (n % i == 0) return false; return true; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Enemy3 : MonoBehaviour { public int health = 5; public Transform myTransform; public GameObject powerUpPrefab; public GameObject[] explosions = new GameObject[2]; public bool turnAround; public float speed = 10f; // Use this for initialization void Start() { turnAround = false; myTransform = transform; } // Update is called once per frame void Update() { // Destroys object when off screen if (transform.position.x > 9 && turnAround == true) { Destroy(gameObject); } Vector3 currentPosition = transform.position; transform.position = currentPosition; // Changing direction if (currentPosition.x < -8) { turnAround = true; } if (turnAround == true) { TurnAround(); } else { Move(); } transform.rotation = Quaternion.Euler(currentPosition.x * 80, 0, 0); } public void Move() { Vector3 currentPosition = transform.position; currentPosition.x += -speed * Time.deltaTime; transform.position = currentPosition; } public void TurnAround() { Vector3 currentPosition = transform.position; transform.position = currentPosition; currentPosition.y += -20f * Time.deltaTime; currentPosition.x += 20f * Time.deltaTime; transform.position = currentPosition; } void OnTriggerEnter(Collider other) { if (other.tag == "Player_Bullet") { health--; Destroy(other.gameObject); if (health == 0) { Death(); } } } void Death() { Destroy(gameObject); Instantiate(explosions[0], transform.position, Quaternion.identity); // Parse the text of the scoreGT into an int int score = int.Parse(Main.scoreGT.text); score += 100; // Convert the score back to a string and display it Main.scoreGT.text = score.ToString(); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Decoding : MonoBehaviour { [HideInInspector] public int decodingProgress = 0; public GameController controller; public Room successRoom; //bool boom = false; /*void completedDecoding() { controller.roomNavigation.currentRoom = successRoom; controller.roomNavigation.previousRoom = controller.roomNavigation.startingRoom; }*/ void Update() { if (decodingProgress == controller.numberOfPatterns && controller.roomNavigation.currentRoom.roomName == "decoding") { controller.roomNavigation.currentRoom = successRoom; controller.roomNavigation.previousRoom = controller.roomNavigation.startingRoom; //boom = true; controller.DisplayRoomText(); controller.DisplayLoggedText(); controller.LogStringWithReturn(controller.fixNewLinesInDescriptions("Exiting decoding...")); controller.DisplayLoggedText(); controller.textMovement.ChangeYLocation(); } } }
namespace Codelet.AspNetCore.Knockout.TagHelpers { using Microsoft.AspNetCore.Mvc.ViewFeatures; using Microsoft.AspNetCore.Razor.TagHelpers; using Microsoft.Extensions.Logging; /// <summary> /// Tag helper to create Knockout attribute binding. /// </summary> [HtmlTargetElement("form")] public class KnockoutFormTagHelper : KnockoutBindingTagHelper { /// <summary> /// Initializes a new instance of the <see cref="KnockoutFormTagHelper" /> class. /// </summary> /// <param name="logger">The logger.</param> public KnockoutFormTagHelper(ILogger<KnockoutFormTagHelper> logger) : base(logger) { } /// <summary> /// Gets or sets the path for the Knockout "submit {callback}" binding. /// </summary> [HtmlAttributeName("ko-submit-callback")] public ModelExpression Callback { get; set; } /// <summary> /// Gets or sets the path for the Knockout "submit {ajaxSettings}" binding. /// </summary> [HtmlAttributeName("ko-submit-ajax-setting")] public ModelExpression AjaxSettings { get; set; } /// <summary> /// Gets or sets the path for the Knockout "submit {ajaxRequest}" binding. /// </summary> [HtmlAttributeName("ko-submit-ajax-request")] public ModelExpression AjaxRequest { get; set; } /// <summary> /// Gets or sets a value indicating whether the submit for is validated (Knockout "submit {validate}" binding). /// </summary> [HtmlAttributeName("ko-submit-validate")] public bool Validate { get; set; } /// <summary> /// Gets or sets the path for the Knockout "submit {validateClass}" binding. /// </summary> [HtmlAttributeName("ko-submit-validated-class")] public string ValidatedClass { get; set; } /// <inheritdoc /> public override void Init(TagHelperContext context) { base.Init(context); if (this.Callback != null && this.AjaxSettings != null) { this.Logger.LogError("Knockout \"submit\" can't be used together with \"submit async\"."); return; } if (this.Callback != null) { this .Bindings .AddComplexBinding("Submit", builder => builder .AddBinding(nameof(this.Callback), this.Callback) .AddBinding(nameof(this.Validate), this.Validate) .AddBinding(nameof(this.ValidatedClass), this.ValidatedClass)); } if (this.AjaxSettings != null) { this .Bindings .AddComplexBinding("SubmitAsync", builder => builder .AddBinding(nameof(this.AjaxSettings), this.AjaxSettings) .AddBinding(nameof(this.AjaxRequest), this.AjaxRequest) .AddBinding(nameof(this.Validate), this.Validate) .AddBinding(nameof(this.ValidatedClass), this.ValidatedClass)); } } } }
using UnityEngine; using System.Collections; public class FuckYeah : MonoBehaviour { public Transform MainCamera; public Transform player; private bool flip = false; public CameraPivotMovement cp; public MouseOrbit ms; private bool fpsActive = false; void Start() { MainCamera.gameObject.SetActive(true); player.gameObject.SetActive(false); } // Update is called once per frame void Update () { if (Input.GetKeyDown(KeyCode.G)) { Flip(); } if (Input.GetKeyDown(KeyCode.F)) { FlipCamera(); } } void FlipCamera() { if (fpsActive) { flip = false; Flip(); cp.SetActive(); ms.SetActive(); fpsActive = !fpsActive; } else { cp.SetActive(); ms.SetActive(); fpsActive = !fpsActive; } } void Flip() { if (flip) { MainCamera.gameObject.SetActive(false); player.gameObject.SetActive(true); flip = !flip; } else { MainCamera.gameObject.SetActive(true); player.gameObject.SetActive(false); flip = !flip; } } }
/* DotNetMQ - A Complete Message Broker For .NET Copyright (C) 2011 Halil ibrahim KALKAN This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ namespace MDS.Settings { /// <summary> /// Represents a Server's design informations in design settings. /// </summary> public class ServerDesignItem { /// <summary> /// Name of this server. /// </summary> public string Name { get; set; } /// <summary> /// Location of server (Left (X) and Top (Y) properties in design area, seperated by comma (,)). /// </summary> public string Location { get; set; } } }
using System.Collections.Generic; using System.Linq; using TombRaiderDatabase; namespace NotificationProviding { class DbDataProvider : IDataProvider { public List<UserGrave> GetGravesForUser(int userId) { var dbConnector = new DbConnector(); var userGravesDtos = dbConnector.GetUserGraves().Where(grave => grave.UserId == userId).ToList(); var userGraves = new List<UserGrave>(); userGravesDtos.ForEach(grave => userGraves.Add(UserGraveDtoToUserGrave(grave))); return userGraves; } public List<UserDetails> GetUserDetails() { var dbConnector = new DbConnector(); var userDtos = dbConnector.GetAllUsers(); var usersDetails = new List<UserDetails>(); userDtos.ForEach(userDto => usersDetails.Add(UserDtoToUserDetails(userDto))); return usersDetails; } private UserGrave UserGraveDtoToUserGrave(UserGraveDto grave) { return new UserGrave { DateDeath = grave.DateDeath, Id = grave.GraveId, UserId = grave.UserId }; } private UserDetails UserDtoToUserDetails(UserDto userDto) { return new UserDetails { Id = userDto.UserId, Mail = userDto.Mail, Name = userDto.Name, Surname = userDto.Surname }; } } }
using EWF.Data; using EWF.Data.Repository; using EWF.Util.Data; using EWF.Util.Options; using Microsoft.Extensions.Options; using System; using System.Collections.Generic; using System.Text; namespace EWF.Repository { public class DefaultRepository { public string Default_Schema = EWFConsts.Default_SchemaName; public string File_Schema = EWFConsts.File_SchemaName; public string RTDB_Schema = EWFConsts.RTDB_SchemaName; protected IDatabase database; public DefaultRepository(IOptionsSnapshot<DbOption> options) { var dbOption = options.Get("Default_Option"); if (dbOption == null) { throw new ArgumentNullException(nameof(DbOption)); } database = DapperFactory.CreateDapper(dbOption.DbType, dbOption.ConnectionString); } } public class DefaultRepository<TEntity> : RepositoryBase<TEntity> where TEntity : class, new() { public string Default_Schema = EWFConsts.Default_SchemaName; public string File_Schema = EWFConsts.File_SchemaName; public string RTDB_Schema = EWFConsts.RTDB_SchemaName; public DefaultRepository(IOptionsSnapshot<DbOption> options) { var dbOption = options.Get("Default_Option"); if (dbOption == null) { throw new ArgumentNullException(nameof(DbOption)); } database = DapperFactory.CreateDapper(dbOption.DbType, dbOption.ConnectionString); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; public class Times : MonoBehaviour { public GameObject horas; public GameObject minutos; int h; // Use this for initialization void Start () { } // Update is called once per frame void Update() { h = Mathf.Abs(System.DateTime.Now.Hour - 12); horas.transform.rotation=Quaternion.Euler(new Vector3( 0f,0f, h*-30 +90 )); minutos.transform.rotation = Quaternion.Euler(new Vector3(0f, 0f, DateTime.Now.Minute*-6+90 )); Debug.Log(DateTime.Now.Minute); } }
using System; using System.Linq; using System.Web.Http; using System.Web.Http.Cors; namespace Microsoft.DataStudio.WebExtensions { public static class HttpConfigurationExtensions { public static void EnableCors(this HttpConfiguration config, string allowedOrigins, bool fAllowHttp) { string[] allowedOriginList = allowedOrigins.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); var corsUrls = string.Join(",", allowedOriginList.Select(u => "https://" + u)); if (fAllowHttp) { corsUrls += ("," + string.Join(",", allowedOriginList.Select(u => "http://" + u))); } var cors = new EnableCorsAttribute(corsUrls, "*", "*"); config.EnableCors(cors); } } }
namespace Triton.Game.Mapping { using ns25; using ns26; using System; using System.Collections.Generic; using Triton.Game.Mono; [Attribute38("OrientedBounds")] public class OrientedBounds : MonoClass { public OrientedBounds(IntPtr address) : this(address, "OrientedBounds") { } public OrientedBounds(IntPtr address, string className) : base(address, className) { } public Vector3 GetTrueCenterPosition() { return base.method_11<Vector3>("GetTrueCenterPosition", Array.Empty<object>()); } public Vector3 CenterOffset { get { return base.method_2<Vector3>("CenterOffset"); } } public List<Vector3> Extents { get { Class246<Vector3> class2 = base.method_3<Class246<Vector3>>("Extents"); if (class2 != null) { return class2.method_25(); } return null; } } public Vector3 Origin { get { return base.method_2<Vector3>("Origin"); } } } }
using Microsoft.AspNetCore.Identity; using System; using System.Collections.Generic; using System.Text; namespace HINVenture.Shared.Models.Entities { public class UserRoles : IdentityUserRole<string> { public ApplicationUser User { get; set; } public ApplicationRole Role { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Simon.Pattern.MethodTemplate { public abstract class SqlBuilderBase { public string BuildSqlString(string tableName, string field, string value) { StringBuilder sb = new StringBuilder(256); sb.Append("Select *"); sb.Append(" From " + tableName); sb.Append(" Where " + field + "=" + GetDateString(value)); return sb.ToString(); } public abstract string GetDateString(string value); } public class SqlBuilderForAccess : SqlBuilderBase { public override string GetDateString(string value) { return string.Format("#{0}#", value); } } public class SqlBuilderForSqlServer : SqlBuilderBase { public override string GetDateString(string value) { return string.Format("'{0}'", value); } } }
using LuaInterface; using SLua; using System; public class Lua_UnityEngine_Rendering_ReflectionProbeMode : LuaObject { public static void reg(IntPtr l) { LuaObject.getEnumTable(l, "UnityEngine.Rendering.ReflectionProbeMode"); LuaObject.addMember(l, 0, "Baked"); LuaObject.addMember(l, 1, "Realtime"); LuaObject.addMember(l, 2, "Custom"); LuaDLL.lua_pop(l, 1); } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace DAGProcessor { /// Execution engine responsible to execute the nodes in the graph. /// </summary> public interface IDagNodeExecutor { /// <summary> /// Executes a node in the graph. /// </summary> /// <param name="unitOfExecution">The node to be executed.</param> /// <returns>0 if success, < 0 otherwise.</returns> public Task<int> ExecuteAsync(IDagNode unitOfExecution); } }
using System; using fraction_calculator_dotnet.Entity; namespace fraction_calculator_dotnet.Render { public class BuilderRenderer : IRenderer { public Fraction Render(Fraction fraction) { if (fraction == null) throw new ArgumentNullException(nameof(fraction)); const ulong smallestPossibleDenominator = 128; var numerator = (long)Math.Round(smallestPossibleDenominator * (fraction.Numerator / (double)fraction.Denominator)); return new Fraction(numerator, smallestPossibleDenominator).Reduce(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net; using HtmlAgilityPack; using System.Text.RegularExpressions; using System.Data.SqlClient; namespace WindowsFormsApplication1 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } String VTbaslik; Int32 VTyil; Int32 VTkm; String VTrenk; Int32 VTfiyat; String VTbirim; DateTime VTtarih; String VTil; String VTilce; String VTmarka; string bagR = "Data Source=BHALTRN;" + "Initial Catalog=bha;" + "Integrated Security=SSPI;"; DataTable table = new DataTable(); public const int limit = 20; public void Tabling() { table.Columns.Add("baslik", typeof(string)); table.Columns.Add("yil", typeof(string)); table.Columns.Add("km", typeof(string)); table.Columns.Add("renk", typeof(string)); table.Columns.Add("fiyat", typeof(string)); table.Columns.Add("tarih", typeof(string)); table.Columns.Add("il", typeof(string)); table.Columns.Add("ilce", typeof(string)); table.Columns.Add("marka", typeof(string)); } private void button1_Click(object sender, EventArgs e) { Uri url = new Uri("https://www.sahibinden.com/otomobil"); WebClient client = new WebClient(); client.Encoding = System.Text.Encoding.UTF8; string html = client.DownloadString(url); html = html.Replace("<br/>", "</td><td class='ilce'>"); html = Regex.Replace(html, @"</td><td class='ilce'>\s", ""); HtmlAgilityPack.HtmlDocument dokuman = new HtmlAgilityPack.HtmlDocument(); dokuman.LoadHtml(html); HtmlNodeCollection fiyatlar = dokuman.DocumentNode.SelectNodes("//td[@class='searchResultsPriceValue']"); HtmlNodeCollection sehirler = dokuman.DocumentNode.SelectNodes("//td[@class='searchResultsLocationValue']"); HtmlNodeCollection ilceler = dokuman.DocumentNode.SelectNodes("//td[@class='ilce']"); HtmlNodeCollection basliklar = dokuman.DocumentNode.SelectNodes("//td[@class='searchResultsTitleValue ']"); HtmlNodeCollection yilKmRenkler = dokuman.DocumentNode.SelectNodes("//td[@class='searchResultsAttributeValue']"); HtmlNodeCollection tarihler = dokuman.DocumentNode.SelectNodes("//td[@class='searchResultsDateValue']"); HtmlNodeCollection marka = dokuman.DocumentNode.SelectNodes("//div[@class='classifiedSubtitle']"); Tabling(); for (int k = 0; k < limit; k++) { string b = basliklar[k].InnerText.ToString(); string[] m = marka[k].InnerText.Split(' '); table.Rows.Add(b.Trim(), yilKmRenkler[3 * k].InnerText.ToString().Trim(), yilKmRenkler[3 * k + 1].InnerText.ToString().Trim(), yilKmRenkler[3 * k + 2].InnerText.ToString().Trim(), fiyatlar[k].InnerText.ToString().Trim(), tarihler[k].InnerText.ToString().Trim(), sehirler[k].InnerText.ToString().Trim(), ilceler[k].InnerText.ToString().Trim(),m[0]); VTbaslik = b.Trim(); VTyil=Int32.Parse(yilKmRenkler[3 * k].InnerText.ToString().Trim()); VTkm = kmBul(yilKmRenkler[3 * k + 1].InnerText.ToString().Trim()); VTrenk= yilKmRenkler[3 * k+ 2 ].InnerText.ToString().Trim(); VTfiyat = fiyatDuzenle(fiyatlar[k].InnerText.ToString().Trim()); VTbirim=birimBul(fiyatlar[k].InnerText.ToString().Trim()); VTtarih=tarihBul(tarihler[k].InnerText.ToString().Trim()); VTil=sehirler[k].InnerText.ToString().Trim(); VTilce=ilceler[k].InnerText.ToString().Trim(); VTmarka=m[0]; // INSERT INTO Varlik(baslik,yil,km,renk,fiyat,tarih,il,ilce,marka,birim) //Sütun isimleri ustteki parantez içinde yazan yazılarla BİRE BİR aynı olacak tatlım //VALUES('"+baslik+"',"+yil+","+km+",'"+renk+"',"+fiyat+" ,'"+tarih+"' ,'"+il+"' ,'"+ilce+"' ,'"+marka+"' ,'"+birim+"'); } dataGridView1.DataSource = table; //EkleVT(VTbaslik, VTyil, VTkm, VTrenk, VTfiyat, VTbirim, VTtarih, VTil, VTilce, VTmarka); } private void EkleVT(String baslik, Int32 yil,Int32 km, String renk, Int32 fiyat, String birim, DateTime tarih,String il, String ilce, String marka) { /* * SqlConnection conn = new SqlConnection(); conn.ConnectionString = "Data Source=BHALTRN;" + "Initial Catalog=bha;" + "Integrated Security=SSPI;"; conn.Open(); */ /* * SqlConnection bagSQLR = new SqlConnection(bagR); bagSQLR.Open(); string Sorgu = "INSERT INTO Varlik(yil,km,renk) VALUES (3,5,'gri')"; SqlCommand Komut = new SqlCommand(Sorgu, bagSQLR); Komut.ExecuteNonQuery(); bagSQLR.Close(); */ using (SqlConnection conn = new SqlConnection(bagR)) { using (SqlCommand comm = new SqlCommand()) { comm.Connection = conn; conn.Open(); String tarihYeni = tarih.ToString("MM-dd"); String sorgu = "INSERT INTO Varlik(baslik,yil,km,renk,fiyat,tarih,il,ilce,marka,birim) VALUES('" + baslik + "'," + yil + "," + km + ",'" + renk + "'," + fiyat + " ,'" + tarih + "' ,'" + il + "' ,'" + ilce + "' ,'" + marka + "' ,'" + birim + "')"; /* { for (int i = 0; i < dataGridView1.Rows.Count - 1; i++) { StrQuery = @"INSERT INTO Varlik(baslik,renk) VALUES ('" + dataGridView1.Rows[i].Cells["baslik"].Value.ToString() + "', '" + dataGridView1.Rows[i].Cells["renk"].Value.ToString() + "');"; // // Tatlım aşağıda yapılması gereken işlemler var // //StrQuery = @"INSERT INTO Varlik(baslik,yil,km,renk,fiyat,tarih,il,ilce,marka) VALUES ('" + dataGridView1.Rows[i].Cells["baslik"].Value.ToString() + "'," + dataGridView1.Rows[i].Cells["yil"].Value.ToString() + "," + dataGridView1.Rows[i].Cells["km"].Value.ToString() + ", '" + dataGridView1.Rows[i].Cells["renk"].Value.ToString() + "','" + dataGridView1.Rows[i].Cells["fiyat"].Value.ToString() + "','" + dataGridView1.Rows[i].Cells["tarih"].Value.ToString() + "','" + dataGridView1.Rows[i].Cells["il"].Value.ToString() + "','" + dataGridView1.Rows[i].Cells["ilce"].Value.ToString() + "','" + dataGridView1.Rows[i].Cells["marka"].Value.ToString() + "');"; } } */ comm.CommandText = sorgu; comm.ExecuteNonQuery(); } } } private void listView1_SelectedIndexChanged(object sender, EventArgs e) { } private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e) { } private void richTextBox1_TextChanged(object sender, EventArgs e) { } private void button2_Click(object sender, EventArgs e) { } public Int32 kmBul(String stKm) { Int32 gercekKm; int sayac; String geciciKm=""; Char[] rakamlar = stKm.ToCharArray(); for (sayac = 0; sayac < rakamlar.Length; sayac++) { if (rakamlar[sayac] == '0') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '1') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '2') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '3') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '4') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '5') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '6') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '7') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '8') { geciciKm = geciciKm + rakamlar[sayac]; } if (rakamlar[sayac] == '9') { geciciKm = geciciKm + rakamlar[sayac]; } } gercekKm = Int32.Parse(geciciKm); return gercekKm; } public Int32 fiyatDuzenle(String fiyat) { Int32 sonFiyat; String gercekFiyat = ""; int sayac; Char[] rakamlar = fiyat.ToCharArray(); for (sayac = 0; sayac < rakamlar.Length; sayac++) { if (rakamlar[sayac] == '0') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '1') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '2') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '3') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '4') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '5') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '6') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '7') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '8') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } if (rakamlar[sayac] == '9') { gercekFiyat = gercekFiyat + rakamlar[sayac]; } } sonFiyat = Int32.Parse(gercekFiyat); return sonFiyat; } public String birimBul(String fiyat) { String birim = ""; if (fiyat.Contains("TL")) birim = "TL"; if (fiyat.Contains("$")) birim = "DOLAR"; if (fiyat.Contains("€")) birim = "EURO"; return birim; } public DateTime tarihBul(String tarih) { int ay=0; int gun=0; int yil = DateTime.Now.Year; if (tarih.Contains("Ocak")) ay = 1; if (tarih.Contains("Şubat")) ay = 2; if (tarih.Contains("Mart")) ay = 3; if (tarih.Contains("Nisan")) ay = 4; if (tarih.Contains("Mayıs")) ay = 5; if (tarih.Contains("Haziran")) ay = 6; if (tarih.Contains("Temmuz")) ay = 7; if (tarih.Contains("Ağustos")) ay = 8; if (tarih.Contains("Eylül")) ay = 9; if (tarih.Contains("Ekim")) ay = 10; if (tarih.Contains("Kasım")) ay = 11; if (tarih.Contains("Aralık")) ay = 12; gun = Int32.Parse(tarih.Substring(0, 2)); DateTime sonTarih= new DateTime(yil,ay,gun); return sonTarih; } } }
using System.Collections.Generic; using System.Linq; public class Box<T> { public Box() { this.elements = new List<T>(); } private IList<T> elements; public int Count => this.elements.Count; public void Add(T element) { this.elements.Add(element); } public T Remove() { var last = elements.LastOrDefault(); elements.RemoveAt(elements.Count - 1); return last; } }
#region Copyright Syncfusion Inc. 2001-2015. // Copyright Syncfusion Inc. 2001-2015. All rights reserved. // Use of this code is subject to the terms of our license. // A copy of the current license can be obtained at any time by e-mailing // licensing@syncfusion.com. Any infringement will be prosecuted under // applicable laws. #endregion using Android.Content; using Com.Syncfusion.Sfrangeslider; using Android.Widget; using Android.Views; using Android.Graphics; using SampleBrowser; using droid = Android.Widget.Orientation; using System.Collections.Generic; using System; namespace SampleBrowser { //[con(Label = "Getting Started")] public class GettingStarted : SamplePage { SfRangeSlider range,range2; View Content; public static TickPlacement tickplacement= TickPlacement.BottomRight; public static ValuePlacement valueplacement=ValuePlacement.BottomRight; public static bool showlabel=true; public static SnapsTo snapsto = SnapsTo.None; string val1,val2,val3,val4; public override View GetSampleContent (Context con) { LinearLayout linearLayout = new LinearLayout(con); linearLayout.SetPadding(20, 20, 20, 30); linearLayout.SetBackgroundColor(Color.Rgb(236, 235, 242)); linearLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent); linearLayout.Orientation = Android.Widget.Orientation.Vertical; TextView textView3 = new TextView(con); textView3.TextSize=20; textView3.Text=" "+"Departure"; textView3.SetTextColor (Color.Black); range = new SfRangeSlider(con); range.Minimum= 0; range.Maximum=12; range.TickFrequency=2; range.ShowValueLabel=showlabel; range.StepFrequency=6; range.DirectionReversed=false; range.ValuePlacement=valueplacement; range.RangeEnd=12; range.RangeStart=0; range.TickPlacement=tickplacement; range.ShowRange=showlabel; range.SnapsTo=snapsto; range.Orientation=Com.Syncfusion.Sfrangeslider.Orientation.Horizontal; range.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 150); LinearLayout depstack =new LinearLayout (con); depstack.Orientation = Android.Widget.Orientation.Horizontal; depstack.AddView (textView3); TextView textView4 = new TextView(con); textView4.TextSize=13; textView4.Text=" "+"(in Hours)"; textView4.LayoutParameters = new ViewGroup.LayoutParams (ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); textView4.SetTextColor (Color.ParseColor("#939394")); textView4.Gravity = GravityFlags.Center; depstack.AddView (textView4); TextView textView7 = new TextView(con); textView7.SetHeight (50); linearLayout.AddView (textView7); linearLayout.AddView (depstack); TextView textView10 = new TextView(con); TextView textView12 = new TextView(con); linearLayout.AddView (textView12); linearLayout.AddView (textView10); linearLayout.AddView(range); textView10.TextSize=13; val3 = "12"; val4 = Math.Round (range.RangeEnd).ToString (); textView10.SetTextColor (Color.ParseColor ("#939394")); textView10.Text = " "+"Time: "+val3 +"AM " +" - "+ val4 +" PM"; textView10.Gravity = GravityFlags.Left; range.RangeChanged += (object sender, SfRangeSlider.RangeChangedEventArgs e) => { String pmstr2="AM",pmstr1 = "AM"; if(Math.Round(e.P1).ToString() =="0" ) { val3 = "12"; pmstr1 = "AM"; } else val3 = Convert.ToString(Math.Round(e.P1)); if (e.P2 <= 12) val4 = Convert.ToString(Math.Round(e.P2)); if(Math.Round(e.P2).ToString()=="12") pmstr2 = "PM"; if(Math.Round(e.P2).ToString()=="12") pmstr2 = "PM"; if(Convert.ToString(Math.Round(e.P1)).Equals(Convert.ToString(Math.Round(e.P2)))){ if(Math.Round(e.P1).ToString() =="0" ) textView10.Text=" "+"Time: "+val3 +" "+ pmstr1; else if(Math.Round(e.P2).ToString()=="12") textView10.Text=" "+"Time: "+val4 +" "+ pmstr2; else textView10.Text=" "+"Time: "+val3 +" "+ pmstr1; } else textView10.Text=" "+"Time: " +val3+" "+ pmstr1 + " - "+ val4+" " + pmstr2; }; TextView textView6 = new TextView(con); textView6.SetHeight (70); linearLayout.AddView (textView6); TextView textView2 = new TextView(con); textView2.TextSize=20; textView2.Text=" "+"Arrival"; textView2.SetTextColor (Color.Black); //linearLayout.AddView(textView2); range2 = new SfRangeSlider(con); range2.Minimum= 0; range2.Maximum=12; range2.TickFrequency=2; range2.ShowValueLabel=showlabel; range2.StepFrequency=6; range2.DirectionReversed=false; range2.ValuePlacement=valueplacement; range2.RangeEnd=12; range2.RangeStart=0; range2.TickPlacement=tickplacement; range2.ShowRange=showlabel; range2.SnapsTo=snapsto; range2.Orientation = Com.Syncfusion.Sfrangeslider.Orientation.Horizontal; range2.LayoutParameters = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 150); TextView textView5 = new TextView(con); textView5.TextSize=13; textView5.Text=" "+"(in Hours)"; textView5.Gravity = GravityFlags.Center; textView5.LayoutParameters = new ViewGroup.LayoutParams (ViewGroup.LayoutParams.WrapContent, ViewGroup.LayoutParams.MatchParent); textView5.SetTextColor (Color.ParseColor("#939394")); TextView textView8 = new TextView(con); textView8.SetHeight (50); LinearLayout arrivestack =new LinearLayout (con); arrivestack.Orientation = Android.Widget.Orientation.Horizontal; arrivestack.AddView (textView2); arrivestack.AddView (textView5); linearLayout.AddView (textView8); linearLayout.AddView (arrivestack); TextView textView13 = new TextView(con); linearLayout.AddView (textView13); TextView textView9 = new TextView(con); linearLayout.AddView (textView9); linearLayout.AddView(range2); textView9.TextSize=13; textView9.SetTextColor (Color.ParseColor ("#939394")); val1 = "12"; val2 = Math.Round (range2.RangeEnd).ToString (); textView9.Text = " "+"Time: "+val1 +"AM " +" - "+ val2 +" PM"; textView9.Gravity = GravityFlags.Left; range2.RangeChanged += (object sender, SfRangeSlider.RangeChangedEventArgs e) => { String pmstr2="AM",pmstr1 = "AM"; if(Math.Round(e.P1).ToString() =="0" ) { val1 = "12"; pmstr1 = "AM"; } else val1 = Convert.ToString(Math.Round(e.P1)); if (e.P2 <= 12) val2 = Convert.ToString(Math.Round(e.P2)); if(Math.Round(e.P2).ToString()=="12") pmstr2 = "PM"; if(Convert.ToString(Math.Round(e.P1)).Equals(Convert.ToString(Math.Round(e.P2)))){ if(Math.Round(e.P1).ToString() =="0" ) textView9.Text=" "+"Time: "+val1 +" "+ pmstr1; else if(Math.Round(e.P2).ToString()=="12") textView9.Text=" "+"Time: "+val2 +" "+ pmstr2; else textView9.Text=" "+"Time: "+val1 +" "+ pmstr1; } else textView9.Text=" "+"Time: " +val1+" "+ pmstr1 + " - "+ val2+" " + pmstr2; }; return linearLayout; } Spinner tickSpinner, labelSpinner; View content; LinearLayout propertylayout, stackView2, stackView3,stackView4; ArrayAdapter<String> labelAdapter, dataAdapter; public override View GetPropertyWindowLayout (Android.Content.Context context) { int width = context.Resources.DisplayMetrics.WidthPixels / 2; propertylayout = new LinearLayout (context); propertylayout.Orientation = droid.Vertical; LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams ( width * 2, 5); layoutParams.SetMargins (0, 5, 0, 0); TextView textView1 = new TextView (context); textView1.Text = " " + "TICK PLACEMENT"; textView1.TextSize = 15; textView1.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); textView1.SetTextColor (Color.White); textView1.Gravity = GravityFlags.Left; TextView textview2 = new TextView (context); textview2.SetHeight (14); propertylayout.AddView (textview2); tickSpinner = new Spinner (context); tickSpinner.SetPadding (0, 0, 0, 0); propertylayout.AddView (textView1); SeparatorView separate = new SeparatorView (context, width * 2); separate.LayoutParameters = new ViewGroup.LayoutParams (width * 2, 5); propertylayout.AddView (separate, layoutParams); TextView textview8 = new TextView (context); textview8.SetHeight (20); propertylayout.AddView (textview8); propertylayout.AddView (tickSpinner); TextView textview3 = new TextView (context); propertylayout.AddView (textview3); List<String> list = new List<String> (); list.Add ("BottomRight"); list.Add ("TopLeft"); list.Add ("Outside"); list.Add ("Inline"); list.Add ("None"); dataAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, list); dataAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); tickSpinner.Adapter = dataAdapter; tickSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem (e.Position); if (selectedItem.Equals ("BottomRight")) { tickplacement = TickPlacement.BottomRight; } else if (selectedItem.Equals ("TopLeft")) { tickplacement = TickPlacement.TopLeft; } else if (selectedItem.Equals ("Inline")) { tickplacement = TickPlacement.Inline; } else if (selectedItem.Equals ("Outside")) { tickplacement = TickPlacement.Outside; } else if (selectedItem.Equals ("None")) { tickplacement = TickPlacement.None; } }; TextView textView3 = new TextView (context); textView3.Text = " " + "LABEL PLACEMENT"; textView3.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); textView3.Gravity = GravityFlags.Left; textView3.TextSize = 15; textView3.SetTextColor (Color.White); List<String> labelList = new List<String> (); labelList.Add ("BottomRight"); labelList.Add ("TopLeft"); labelSpinner = new Spinner (context); labelSpinner.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) => { String selectedItem = dataAdapter.GetItem (e.Position); if (selectedItem.Equals ("TopLeft")) { valueplacement = ValuePlacement.TopLeft; } else if (selectedItem.Equals ("BottomRight")) { valueplacement = ValuePlacement.BottomRight; } }; labelAdapter = new ArrayAdapter<String> (context, Android.Resource.Layout.SimpleSpinnerItem, labelList); labelAdapter.SetDropDownViewResource (Android.Resource.Layout.SimpleSpinnerDropDownItem); labelSpinner.Adapter = labelAdapter; labelSpinner.SetPadding (0, 0, 0, 0); LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams (width * 2, 7); layoutParams2.SetMargins (0, 5, 0, 0); propertylayout.AddView (textView3); SeparatorView separate2 = new SeparatorView (context, width * 2); separate2.LayoutParameters = new ViewGroup.LayoutParams (width * 2, 7); propertylayout.AddView (separate2, layoutParams2); TextView textview9 = new TextView (context); textview9.SetHeight (20); propertylayout.AddView (textview9); propertylayout.AddView (labelSpinner); propertylayout.SetPadding (15, 0, 15, 0); TextView textview7 = new TextView (context); textview7.SetHeight (20); propertylayout.AddView (textview7); TextView textView6 = new TextView (context); textView6.Text = " " + "Show Label"; textView6.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); textView6.Gravity = GravityFlags.Center; textView6.TextSize = 16; Switch checkBox = new Switch (context); checkBox.Checked = true; checkBox.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (e.IsChecked) showlabel = true; else showlabel = false; }; LinearLayout.LayoutParams layoutParams3 = new LinearLayout.LayoutParams ( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams3.SetMargins (0, 10, 0, 0); LinearLayout.LayoutParams layoutParams4 = new LinearLayout.LayoutParams ( ViewGroup.LayoutParams.WrapContent, 55); layoutParams4.SetMargins (0, 10, 0, 0); stackView3 = new LinearLayout (context); stackView3.AddView (textView6, layoutParams4); stackView3.AddView (checkBox, layoutParams3); stackView3.Orientation = droid.Horizontal; propertylayout.AddView (stackView3); SeparatorView separate3 = new SeparatorView (context, width * 2); separate3.LayoutParameters = new ViewGroup.LayoutParams (width * 2, 5); LinearLayout.LayoutParams layoutParams7 = new LinearLayout.LayoutParams ( width * 2, 5); layoutParams7.SetMargins (0, 30, 0, 0); propertylayout.AddView (separate3, layoutParams7); TextView textView7 = new TextView (context); textView7.Text = " "+"SnapsToTicks"; textView7.Typeface = Typeface.Create("Roboto", TypefaceStyle.Normal); textView7.Gravity = GravityFlags.Center; textView7.TextSize = 16; Switch checkBox2 = new Switch (context); checkBox2.Checked = false; checkBox2.CheckedChange += (object sender, CompoundButton.CheckedChangeEventArgs e) => { if (e.IsChecked) snapsto = SnapsTo.Ticks; else snapsto = SnapsTo.None; }; LinearLayout.LayoutParams layoutParams5 = new LinearLayout.LayoutParams ( ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.WrapContent); layoutParams5.SetMargins (0, 20, 0, 0); LinearLayout.LayoutParams layoutParams6 = new LinearLayout.LayoutParams ( ViewGroup.LayoutParams.WrapContent, 55); layoutParams6.SetMargins (0, 20, 0, 0); stackView4 = new LinearLayout (context); stackView4.AddView (textView7, layoutParams6); stackView4.AddView (checkBox2, layoutParams5); stackView4.Orientation = droid.Horizontal; propertylayout.AddView (stackView4); SeparatorView separate4 = new SeparatorView (context, width * 2); separate4.LayoutParameters = new ViewGroup.LayoutParams (width * 2, 5); LinearLayout.LayoutParams layoutParams8 = new LinearLayout.LayoutParams ( width * 2, 5); layoutParams8.SetMargins (0, 30, 0, 0); propertylayout.AddView (separate4, layoutParams8); return propertylayout; } public override void OnApplyChanges () { base.OnApplyChanges (); range2.TickPlacement=tickplacement; range.TickPlacement=tickplacement; range2.ValuePlacement=valueplacement; range.ValuePlacement=valueplacement; range2.ShowValueLabel=showlabel; range.ShowValueLabel=showlabel; range2.SnapsTo=snapsto; range.SnapsTo=snapsto; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Data.SqlClient; using CovidData.Models; using System.Configuration; using System.Data; using System.Web; using System.Web.Mvc; namespace CovidData.Controllers { public class BasicDataController : ApiController { public HttpResponseMessage Get() { DataTable table = new DataTable(); string query = @"select * from daily_cases"; using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["dailycases"].ConnectionString)) using (var cmd = new SqlCommand(query, con)) using (var da = new SqlDataAdapter(cmd)) { cmd.CommandType = CommandType.Text; da.Fill(table); } return Request.CreateResponse(HttpStatusCode.OK, table); } public string Post(BasicData day) { try { DataTable table = new DataTable(); string query = @"insert into daily_cases values('" + day.dailyconfirmed + @"')"; using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["dailycases"].ConnectionString)) using (var cmd = new SqlCommand(query, con)) using (var da = new SqlDataAdapter(cmd)) { cmd.CommandType = CommandType.Text; da.Fill(table); } return "Added Successfully"; } catch (Exception) { return "failwd to add"; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Skizzenbuch : MonoBehaviour { void OnSelect() { Debug.Log("Skizzenbuch ist sichtbar"); GetComponentInParent<MenuController>().SelectSkizzenbuch(); } }
/* .-' '--./ / _.---. '-, (__..-` \ \ . | `,.__. ,__.--/ '._/_.'___.-` FREE WILLY */ using NLog; namespace Automatisation.Model { public class SettingsSpectrumModel : BaseModel { #region Fields private static Logger _log = LogManager.GetCurrentClassLogger(); private SpectrumMeterModel _spectrum; private bool _blnAllowSend = false; //set to false during the first phase -> getting all the settings. Set on true when actually changing settings private bool _blnAllowChannelChange; //When no table is selected (NONE), then no channels can be set. //frequency settings (freq/channel) private string _fq_Center; private string _fq_Start; private string _fq_Stop; //channel settings (freq/channel) private string _ch; private string _chTable; private string[] _chTableArray; private string _chTableSelected; //span settings (span) private string _span; private string _span_Start; private string _span_Stop; //step private string _fq_step; //trig settings (trig) private string _trigger_Repeat; //Amplitude settings (amplitude) private string _ampl_RefLevel; private string _ampl_AutoOrMixerDescription; private bool _ampl_IsAutoAndMixer; private string _ampl_RFAtt; private string _ampl_MixLvl; private string _ampl_VertScale; //RBW (rbw/fft) private string _rbwOrFFT; private bool _rbwMan; private bool _fftMan; private string _rbw_Hz; private string _rbw_FilterShape; //fft (rbw/fft) private string _fft_Points; private string _fft_Windows; private string _extended_Res; //Trace Trace/AVG private string _trc; private string _trc_NumberOfTraces; private string _trc_DisplayDetection; //Measure private string _measure; private string _meas_CHPower_Band; private string _meas_CHPower_FilterShape; private string _meas_CHPower_RollOff; #endregion Fields #region properties /// <summary> /// Allow WriteCommands of any kind to the spectrum analyzer. /// </summary> public bool AllowSend { get { return _blnAllowSend; } set { if (value != _blnAllowSend) { _blnAllowSend = value; } } } /// <summary> /// When no table is selected (NONE), then no channels can be set. /// </summary> public bool AllowChannelChange { get { return _blnAllowChannelChange; } set { if (value != _blnAllowChannelChange) { _blnAllowChannelChange = value; OnPropertyChanged("AllowChannelChange"); } } } //frequency settings (freq/channel) public string FQ_Center { get { return _fq_Center; } set { if (value != _fq_Center) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFreqCenter(_spectrum, value); } _fq_Center = value; OnPropertyChanged("FQ_Center"); } } } public string FQ_Start { get { return _fq_Start; } set { if (value != _fq_Start) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFreqStart(_spectrum, value); } _fq_Start = value; OnPropertyChanged("FQ_Start"); } } } public string FQ_Stop { get { return _fq_Stop; } set { if (value != _fq_Stop) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFreqStop(_spectrum, value); } _fq_Stop = value; OnPropertyChanged("FQ_Stop"); } } } //channel settings (freq/channel) public string Ch { get { return _ch; } set { if (value != _ch) { _ch = value; OnPropertyChanged("Ch"); } } } public string ChTable { get { return _chTable; } set { if (value != _chTable) { _chTable = value; ChTableArray = _chTable.Split(','); OnPropertyChanged("ChTable"); } } } public string[] ChTableArray { get { return _chTableArray; } set { if (value != _chTableArray) { _chTableArray = value; OnPropertyChanged("ChTableArray"); } } } public string ChTableSelected { get { return _chTableSelected; } set { if (value != _chTableSelected) { //if value contains NONE then channel can't be set string s = value.ToUpper(); bool b = s.Contains("\"NONE\""); if (b == true) { AllowChannelChange = false; } else { AllowChannelChange = true; } if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFreqChanCat(_spectrum, value); ChannelTableChanged(); } _chTableSelected = value; OnPropertyChanged("ChTableSelected"); } } } //step public string FQ_Step { get { return _fq_step; } set { if (value != _fq_step) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFreqCenterStepAutoIncr(_spectrum, value); } _fq_step = value; OnPropertyChanged("FQ_Step"); } } } //span settings (span) public string Span { get { return _span; } set { if (value != _span) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFreqSpan(_spectrum, value); } _span = value; OnPropertyChanged("Span"); } } } public string Span_Start { get { return _span_Start; } set { if (value != _span_Start) { _span_Start = value; OnPropertyChanged("Span_Start"); } } } public string Span_Stop { get { return _span_Stop; } set { if (value != _span_Stop) { _span_Stop = value; OnPropertyChanged("Span_Stop"); } } } //trig settings (trig) public string Trigger_Repeat { get { return _trigger_Repeat; } set { if (value != _trigger_Repeat) { _trigger_Repeat = value; OnPropertyChanged("Trigger_Repeat"); } } } //Amplitude settings (amplitude) public string Ampl_RefLevel { get { return _ampl_RefLevel; } set { if (value != _ampl_RefLevel) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetAmplRefLvl(_spectrum, value); } _ampl_RefLevel = value; OnPropertyChanged("Ampl_RefLevel"); } } } public string Ampl_AutoOrMixerDescription { get { return _ampl_AutoOrMixerDescription; } set { if (value != _ampl_AutoOrMixerDescription) { _ampl_AutoOrMixerDescription = value; OnPropertyChanged("Ampl_AutoOrMixerDescription"); } } } public bool Ampl_IsAutoAndMixer { get { return _ampl_IsAutoAndMixer; } set { if (value != _ampl_IsAutoAndMixer) { Ampl_AutoOrMixerDescription = (value == true) ? "Using Auto" : "Using RF"; //description for label for checkbox if (_blnAllowSend) { if (value == true) { Automatisation.Commands.Spectrum.SetAmplAutoAttOn(_spectrum); } else { Automatisation.Commands.Spectrum.SetAmplAutoAttOff(_spectrum); } } _ampl_IsAutoAndMixer = value; OnPropertyChanged("Ampl_IsAutoAndMixer");}}} public string Ampl_RFAtt { get { return _ampl_RFAtt; } set { if (value != _ampl_RFAtt) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetAmplRefAtt(_spectrum, value); } _ampl_RFAtt = value; OnPropertyChanged("Ampl_RFAtt"); } } } public string Ampl_MixLvl { get { return _ampl_MixLvl; } set { if (value != _ampl_MixLvl) { //if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetAmpMixerLvl(_spectrum, value); } _ampl_MixLvl = value; OnPropertyChanged("Ampl_MixLvl"); } } } public string Ampl_VertScale { get { return _ampl_VertScale; } set { if (value != _ampl_VertScale) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetAmpVertScale(_spectrum, value); } _ampl_VertScale = value; OnPropertyChanged("Ampl_VertScale"); } } } //RBW (rbw/fft) public string RBWOrFFT { get { return _rbwOrFFT; } set { if (value != _rbwOrFFT) { UpdateRBWFFT(value); _rbwOrFFT = value; OnPropertyChanged("RBWOrFFT"); } } } public bool RBWEnable { get { return _rbwMan; } set { if (value != _rbwMan) { _rbwMan = value; OnPropertyChanged("RBWEnable"); } } } public bool FFTEnable { get { return _fftMan; } set { if (value != _fftMan) { _fftMan = value; OnPropertyChanged("FFTEnable"); } } } public string RBW_Hz { get { return _rbw_Hz; } set { if (value != _rbw_Hz) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetRBWMan(_spectrum, value); } _rbw_Hz = value; OnPropertyChanged("RBW_Hz"); } } } public string RBW_FilterShape { get { return _rbw_FilterShape; } set { if (value != _rbw_FilterShape) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetRBWFilter(_spectrum, value); } _rbw_FilterShape = value; OnPropertyChanged("RBW_FilterShape"); } } } //fft (rbw/fft) public string FFT_Points { get { return _fft_Points; } set { if (value != _fft_Points) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFFTPoints(_spectrum, value); } _fft_Points = value; OnPropertyChanged("FFT_Points"); } } } public string FFT_Windows { get { return _fft_Windows; } set { if (value != _fft_Windows) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetFFTWindowType(_spectrum, value); } _fft_Windows = value; OnPropertyChanged("FFT_Windows"); } } } public string Extended_Res { get { return _extended_Res; } set { _extended_Res = (int.Parse(value) == 0 || value == "OFF") ? "OFF" : "ON"; { _extended_Res = value; OnPropertyChanged("Extended_Res"); } } } //Trace Trace/AVG public string TRC { get { return _trc; } set { if (value != _trc) { _trc = value; OnPropertyChanged("TRC"); } } } public string TRC_NumberOfTraces { get { return _trc_NumberOfTraces; } set { if (value != _trc_NumberOfTraces) { _trc_NumberOfTraces = value; OnPropertyChanged("TRC_NumberOfTraces"); } } } public string TRC_DisplayDetection { get { return _trc_DisplayDetection; } set { if (value != _trc_DisplayDetection) { _trc_DisplayDetection = value; OnPropertyChanged("TRC_DisplayDetection"); } } } //Measure public string Measure { get { return _measure; } set { if (value != _measure) { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetMeas(_spectrum, value);} UpdateMeasure(value); _measure = value; OnPropertyChanged("Measure"); } } } public string Meas_CHP_Band { get { return _meas_CHPower_Band; } set { if (value != _meas_CHPower_Band) { //CHPower Bandwidth Measurement can only be set when Measure : CHP if (_measure == "CHP"){ if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetChannelBand(_spectrum, value); } _meas_CHPower_Band = value; OnPropertyChanged("Meas_CHP_Band"); } } } } public string Meas_CHP_Filter { get { return _meas_CHPower_FilterShape; } set { if (value != _meas_CHPower_FilterShape) { //CHPower Filter Measurement can only be set when Measure : CHP if (_measure == "CHP") { if (_blnAllowSend) { Automatisation.Commands.Spectrum.SetCHPFilterType(_spectrum, value); } _meas_CHPower_FilterShape = value; OnPropertyChanged("Meas_CHP_Filter"); } } } } public string Meas_CHP_RollOff { get { return _meas_CHPower_RollOff; } set { if (value != _meas_CHPower_RollOff) { //CHPower Rolloff Measurement can only be set when Measure : CHP if (_measure == "CHP") { if (_blnAllowSend) { if (Meas_CHP_Filter == "NYQ" || Meas_CHP_Filter == "RNYQ") { Automatisation.Commands.Spectrum.SetCHPRollOff(_spectrum, value); } } _meas_CHPower_RollOff = value; OnPropertyChanged("Meas_CHP_RollOff"); } } } } #endregion properties #region constructor public SettingsSpectrumModel(SpectrumMeterModel spectrum) { _spectrum = spectrum; AllowSend = false; //don't allow to send commands for writing settings to analyzer when they have just been set } #endregion constructor #region events #endregion events /// <summary> /// When a new table has been selected, update the frequencies /// </summary> private void ChannelTableChanged() { if (_blnAllowSend) { this.FQ_Center = Automatisation.Commands.Spectrum.GetFreqCenter(_spectrum); this.FQ_Start = Automatisation.Commands.Spectrum.GetFreqStart(_spectrum); this.FQ_Stop = Automatisation.Commands.Spectrum.GetFreqStop(_spectrum); } } /// <summary> /// Update RBW, filtershape, extended res, fft points, windows according to fft or rbw being set to auto /// When FFT is set to auto, state and auto can be set or querried /// When FFT is set to manual, state can be set and querries, rbw auto cannot /// </summary> private void UpdateRBWFFT(string value) { switch (value) { case "Auto": Automatisation.Commands.Spectrum.SetRBWStateOn(_spectrum); //turn fft to auto first, if fft is set to manual, crash happens when you try to set / get auto Automatisation.Commands.Spectrum.SetRBWAutoOn(_spectrum); RBW_Hz = Automatisation.Commands.Spectrum.GetRBWMan(_spectrum); RBWEnable = false; FFTEnable = false; break; case "Man": Automatisation.Commands.Spectrum.SetRBWStateOn(_spectrum); //turn fft to auto first, if fft is set to manual, crash happens when you try to set / get auto Automatisation.Commands.Spectrum.SetRBWAutoOff(_spectrum); RBW_Hz = Automatisation.Commands.Spectrum.GetRBWMan(_spectrum); RBW_FilterShape = Automatisation.Commands.Spectrum.GetRBWFilter(_spectrum); Extended_Res = Commands.Spectrum.GetExtended(_spectrum); RBWEnable = true; FFTEnable = false; break; case "FFT": Automatisation.Commands.Spectrum.SetRBWStateOff(_spectrum); Automatisation.Commands.Spectrum.SetRBWAutoOff(_spectrum); Automatisation.Commands.Spectrum.SetRBWStateOff(_spectrum); //Set state off as last, else auto will change state settings again, and can't get window type FFT_Points = Automatisation.Commands.Spectrum.GetFFTPoints(_spectrum); FFT_Windows = Automatisation.Commands.Spectrum.GetFFTWindowType(_spectrum); Extended_Res = Commands.Spectrum.GetExtended(_spectrum); RBWEnable = false; FFTEnable = true; break; default: break; } } /// <summary> /// Call when a new measure has been set, only OFF and CHP supported at this time /// </summary> /// <param name="meas"></param> private void UpdateMeasure(string meas) { switch (meas) { case "OFF": break; case "CHP": this.Meas_CHP_Band = Commands.Spectrum.GetChannelBand(_spectrum); this.Meas_CHP_Filter = Commands.Spectrum.GetCHPFilterType(_spectrum); if(_meas_CHPower_FilterShape == "NYQ" || _meas_CHPower_FilterShape == "RNYQ") this.Meas_CHP_RollOff = Commands.Spectrum.GetCHPRollOff(_spectrum); else this.Meas_CHP_RollOff = "Filter must be (R)NYQ"; break; default: break; } } /// <summary> /// Get every setting on startup /// </summary> public void FillInSettings() { #region FreqChan FQ_Center = Commands.Spectrum.GetFreqCenter(_spectrum); FQ_Start = Commands.Spectrum.GetFreqStart(_spectrum); FQ_Stop = Commands.Spectrum.GetFreqStop(_spectrum); ChTable = Commands.Spectrum.GetFreqChanCatAll(_spectrum); //if there is no channel table list, don't bother looking for a selected table if (ChTable != null) ChTableSelected = Commands.Spectrum.GetFreqChanCatSelected(_spectrum).ToUpper(); //If there is no list selected, don't look for a channel. NONE = no channel list selected if (ChTableSelected.Contains("\"NONE\"") == false && ChTableSelected != null) Ch = Commands.Spectrum.GetFreqChan(_spectrum); FQ_Step = Commands.Spectrum.GetFreqCenterStepAutoIncr(_spectrum); #endregion FreqChan /* Trigger */ /* Span */ Span = Commands.Spectrum.GetFreqSpan(_spectrum); #region Ampl /* Amplitude */ Ampl_RefLevel = Commands.Spectrum.GetAmplRefLvl(_spectrum); Ampl_IsAutoAndMixer = (Commands.Spectrum.GetAmplAutoAtt(_spectrum).Contains("1")) ? true : false; Ampl_RFAtt = Commands.Spectrum.GetAmplRefAtt(_spectrum); //command only works when input:attenuation:auto is on if (Ampl_IsAutoAndMixer == true) { Ampl_MixLvl = Commands.Spectrum.GetAmpMixerLvl(_spectrum); } Ampl_VertScale = Commands.Spectrum.GetAmpVertScale(_spectrum); #endregion Ampl #region RBWFFT //Get RBW Auto and bind to property /* RBWAUTO STATE *AUTO 1 1 *MAN 0 1 *FFT crash 0 */ string state = Commands.Spectrum.GetRBWState(_spectrum); string auto = ""; if (state.Contains("0")) { this.RBWOrFFT = "FFT"; } else if (state.Contains("1")) { auto = Commands.Spectrum.GetRBWAuto(_spectrum); if (auto.Contains("0")) { this.RBWOrFFT = "Man"; } if (auto.Contains("1")) { this.RBWOrFFT = "Auto"; } } #endregion RBWFFT #region Measure + Settings Measure = Commands.Spectrum.GetMeas(_spectrum); Meas_CHP_Band = Commands.Spectrum.GetChannelBand(_spectrum); Meas_CHP_Filter = Commands.Spectrum.GetCHPFilterType(_spectrum); Meas_CHP_RollOff = Commands.Spectrum.GetCHPRollOff(_spectrum); #endregion Measure + Settings } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public interface ILoderImageBoss { Image BossImage(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using YzkSoftWare.Data; namespace YzkSoftWare.DataModel { [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class MinMaxValueAttribute : Attribute { /// <summary> /// 使用如下的表达式表示最大和最小值 /// 格式如:MinValue,MaxValue(用*代替无限制,如*,MaxValue和MinValue,*) /// </summary> /// <param name="valueexpress"></param> public MinMaxValueAttribute(string valueexpress) { ValueExpress = valueexpress; } /// <summary> /// 获取最大和最小值表达式 /// 格式如:MinValue,MaxValue(用*代替无限制,如*,MaxValue和MinValue,*) /// </summary> public string ValueExpress { get; private set; } } public static class MinMaxValueHelper { /// <summary> /// 根据表达式获取最大和最小值 /// </summary> /// <param name="valueexp">表达式</param> /// <param name="valuetype">表达式值类型</param> /// <param name="minvalue">返回最小值</param> /// <param name="maxvalue">返回最大值</param> public static void GetMinMaxValue(string valueexp, Type valuetype, out object minvalue, out object maxvalue) { if (string.IsNullOrEmpty(valueexp)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpress, valueexp)); string[] y = valueexp.Split(new char[] { ',' }); if (y.Length != 2) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpress, valueexp)); minvalue = null; maxvalue = null; if (valuetype == typeof(DateTime)) { if (y[0] != "*") { DateTime d; if (DateTime.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { DateTime d; if (DateTime.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } } else if (valuetype == typeof(TimeSpan)) { if (y[0] != "*") { TimeSpan d; if (TimeSpan.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { TimeSpan d; if (TimeSpan.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } } else { NumberType nv = DataValueParase.IsNumberType(valuetype); if (nv == NumberType.Unkown) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); switch (nv) { case NumberType.Byte: { if (y[0] != "*") { byte d; if (byte.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { byte d; if (byte.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.Decimal: { if (y[0] != "*") { decimal d; if (decimal.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { decimal d; if (decimal.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.Double: { if (y[0] != "*") { double d; if (double.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { double d; if (double.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.Float: { if (y[0] != "*") { float d; if (float.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { float d; if (float.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.Int: { if (y[0] != "*") { int d; if (int.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { int d; if (int.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.Long: { if (y[0] != "*") { long d; if (long.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { long d; if (long.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.Sbyte: { if (y[0] != "*") { sbyte d; if (sbyte.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { sbyte d; if (sbyte.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.Short: { if (y[0] != "*") { short d; if (short.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { short d; if (short.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.UInt: { if (y[0] != "*") { uint d; if (uint.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { uint d; if (uint.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.ULong: { if (y[0] != "*") { ulong d; if (ulong.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { ulong d; if (ulong.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } case NumberType.UShort: { if (y[0] != "*") { ushort d; if (ushort.TryParse(y[0], out d)) minvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } if (y[1] != "*") { ushort d; if (ushort.TryParse(y[1], out d)) maxvalue = d; else throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } break; } } } } /// <summary> /// 判断value值是否在valueexp表达式范围中 /// </summary> /// <param name="valueexp">表达式</param> /// <param name="value">值</param> /// <returns></returns> public static bool ValueIsInRangle(string valueexp, object value) { if (string.IsNullOrEmpty(valueexp)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpress, valueexp)); if (value == null) throw new NullReferenceException(string.Format(LocalResource.ParametIsNull, "value")); string[] y = valueexp.Split(new char[] { ',' }); if (y.Length != 2) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpress, valueexp)); Type valuetype = value.GetType(); if (valuetype == typeof(DateTime)) { if (y[0] != "*") { DateTime d; if (!DateTime.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((DateTime)value < d) return false; } if (y[1] != "*") { DateTime d; if (!DateTime.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((DateTime)value > d) return false; } return true; } else if (valuetype == typeof(TimeSpan)) { if (y[0] != "*") { TimeSpan d; if (!TimeSpan.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((TimeSpan)value < d) return false; } if (y[1] != "*") { TimeSpan d; if (!TimeSpan.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((TimeSpan)value > d) return false; } return true; } else { NumberType nv = DataValueParase.IsNumberType(valuetype); if (nv == NumberType.Unkown) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); switch (nv) { case NumberType.Byte: { if (y[0] != "*") { byte d; if (!byte.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((byte)value < d) return false; } if (y[1] != "*") { byte d; if (!byte.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((byte)value > d) return false; } return true; } case NumberType.Decimal: { if (y[0] != "*") { decimal d; if (!decimal.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((decimal)value < d) return false; } if (y[1] != "*") { decimal d; if (!decimal.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((decimal)value > d) return false; } return true; } case NumberType.Double: { if (y[0] != "*") { double d; if (!double.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((double)value < d) return false; } if (y[1] != "*") { double d; if (!double.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((double)value > d) return false; } return true; } case NumberType.Float: { if (y[0] != "*") { float d; if (!float.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((float)value < d) return false; } if (y[1] != "*") { float d; if (!float.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((float)value > d) return false; } return true; } case NumberType.Int: { if (y[0] != "*") { int d; if (!int.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((int)value < d) return false; } if (y[1] != "*") { int d; if (!int.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((int)value > d) return false; } return true; } case NumberType.Long: { if (y[0] != "*") { long d; if (!long.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((long)value < d) return false; } if (y[1] != "*") { long d; if (!long.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((long)value > d) return false; } return true; } case NumberType.Sbyte: { if (y[0] != "*") { sbyte d; if (!sbyte.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((sbyte)value < d) return false; } if (y[1] != "*") { sbyte d; if (!sbyte.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((sbyte)value > d) return false; } return true; } case NumberType.Short: { if (y[0] != "*") { short d; if (!short.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((short)value < d) return false; } if (y[1] != "*") { short d; if (!short.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((short)value > d) return false; } return true; } case NumberType.UInt: { if (y[0] != "*") { uint d; if (!uint.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((uint)value < d) return false; } if (y[1] != "*") { uint d; if (!uint.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((uint)value > d) return false; } return true; } case NumberType.ULong: { if (y[0] != "*") { ulong d; if (!ulong.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((ulong)value < d) return false; } if (y[1] != "*") { ulong d; if (!ulong.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((ulong)value > d) return false; } return true; } case NumberType.UShort: { if (y[0] != "*") { ushort d; if (!ushort.TryParse(y[0], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((ushort)value < d) return false; } if (y[1] != "*") { ushort d; if (!ushort.TryParse(y[1], out d)) throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); if ((ushort)value > d) return false; } return true; } default: { throw new InvalidOperationException(string.Format(LocalResource.InvalidExpressForType, valuetype, valueexp)); } } } } } }
using ContentBlock.Mvc.StringResources; using Microsoft.VisualStudio.TestTools.UnitTesting; using Navigation.Mvc.StringResources; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Telerik.Microsoft.Practices.Unity; using Telerik.Sitefinity.Abstractions; using Telerik.Sitefinity.Configuration; using Telerik.Sitefinity.Configuration.Data; using Telerik.Sitefinity.Localization; using Telerik.Sitefinity.Localization.Configuration; using Telerik.Sitefinity.Project.Configuration; using UnitTests.DummyClasses; namespace UnitTests.Resources { [TestClass] public class ResourcesTests { [TestMethod] [Owner("Bonchev")] [Description("The test ensures that content block resources are correct.")] public void ContentBlockResources_IterateTheResources_AssureResourcesAreCorrect() { //Act & Assert: Iterate over each resource property and verify its correctness this.TestResourceType<ContentBlockResources>(); } [TestMethod] [Owner("Bonchev")] [Description("The test ensures that navigation widget resources are correct.")] public void NavigationResources_IterateTheResources_AssureResourcesAreCorrect() { //Act & Assert: Iterate over each resource property and verify its correctness this.TestResourceType<NavigationResources>(); } /// <summary> /// Tests a given type of resource. /// </summary> /// <param name="resourceClassType">Type of the resource class.</param> private void TestResourceType<TRes>() where TRes: Telerik.Sitefinity.Localization.Resource, new() { //Arrange: Use the getResourceClassDelegate to register and obtain a resource class instance, get the resource class type, register a dummy Config provider using (new ObjectFactoryContainerRegion()) { ObjectFactory.Container.RegisterType<ConfigManager, ConfigManager>(typeof(XmlConfigProvider).Name.ToUpperInvariant(), new InjectionConstructor(typeof(XmlConfigProvider).Name)); ObjectFactory.Container.RegisterType<XmlConfigProvider, DummyConfigProvider>(); Config.RegisterSection<ResourcesConfig>(); Config.RegisterSection<ProjectConfig>(); var resourceClassType = typeof(TRes); Res.RegisterResource(resourceClassType); var resourceClass = Res.Get<TRes>(); Assert.IsNotNull(resourceClass, "The resource class cannot be instantiated."); //Act & Assert: Iterate over each resource and verify if its resource attribute is correct and if the resource value is correct var properties = resourceClassType.GetProperties().Where(p => p.GetCustomAttributes(typeof(ResourceEntryAttribute), false).Count() == 1); foreach (var prop in properties) { var attribute = prop.GetCustomAttributes(typeof(ResourceEntryAttribute), false).FirstOrDefault() as ResourceEntryAttribute; Assert.IsNotNull(attribute, "The resource property does not have the required resource attribute."); var resource = prop.GetValue(resourceClass) as string; Assert.IsFalse(string.IsNullOrEmpty(resource), String.Format("The resource string for the {0} property cannot be found,", prop.Name)); Assert.AreEqual(prop.Name, attribute.Key, "The resource key does not match the property name,"); Assert.AreEqual(resource, attribute.Value, String.Format("The resource string for the {0} property cannot be found,", prop.Name)); Assert.IsFalse(string.IsNullOrEmpty(attribute.Description), "The description of the resource cannot be empty string."); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class DropFire : MonoBehaviour { public GameObject[] itemPool; private void Start() { if (LevelManager.level != 0) { itemPool = LevelManager.itemPool.ToArray(); } } public void SpawnItem() { int rand = Random.Range(0, itemPool.Length); Instantiate(itemPool[rand], this.transform.position, Quaternion.identity); itemPool[rand] = null; ClearOwnedItems(); } private void ClearOwnedItems() { List<GameObject> items = new List<GameObject>(itemPool); for (var i = items.Count - 1; i > -1; i--) { if (items[i] == null) items.RemoveAt(i); } itemPool = items.ToArray(); LevelManager.itemPool = items; } }
namespace E07_EncodeDecode { using System; using System.Text; public class EncodeDecode { public static void Main(string[] args) { // Write a program that encodes and decodes a // string using given encryption key (cipher). // The key consists of a sequence of characters. // The encoding/decoding is done by performing XOR // (exclusive or) operation over the first letter of // the string with the first of the key, the // second – with the second, etc. When the last key // character is reached, the next is the first. Console.OutputEncoding = Encoding.Unicode; string text = "Write a program that encodes and decodes a string using given encryption key (cipher). The key " + "consists of a sequence of characters. The encoding/decoding is done by performing XOR (exclusive or) " + "operation over the first letter of the string with the first of the key, the second – with the second, " + "etc. When the last key character is reached, the next is the first."; Console.WriteLine(text); string key = "cipherOrPassword"; string resultText = EncodingOrDecoding(text, key); Console.WriteLine(resultText); Console.WriteLine(EncodingOrDecoding(resultText, key)); } private static string EncodingOrDecoding(string text, string key) { StringBuilder newText = new StringBuilder(); for (int index = 0; index < text.Length; index++) { newText.Append((char)(text[index] ^ key[index % key.Length])); } return newText.ToString(); } } }
using System.Collections.Generic; using System.Windows.Forms; using System.Xml.Serialization; namespace YongHongSoft.YueChi { [XmlRoot("dwgStore")] public class DwgStore { static string file = Application.StartupPath + "\\PosOfField.xml"; public DwgStore() { Dwg = new List<Dwg>(); } [XmlElement("dwg")] public List<Dwg> Dwg { get; set; } public DwgStore Load() { return XmlHelper.Load(typeof(DwgStore), file) as DwgStore; } } public class Dwg { public Dwg() { Label = new List<Label>(); } [XmlAttribute("name")] public string Name { get; set; } [XmlAttribute("fontheight")] public string FontHeight { get; set; } [XmlElement("label")] public List<Label> Label { get; set; } } public class Label { [XmlAttribute("x")] public string X { get; set; } [XmlAttribute("y")] public string Y { get; set; } [XmlAttribute] public string Field { get; set; } public string Text { get; set; } } }
using HardwareInventoryManager.Models; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace HardwareInventoryManager.ViewModels { public class DashboardViewModel : AppViewModel { public DashboardViewModel() { DashboardUpdates = new List<DashboardUpdates>(); } public int TotalWishlist { get; set; } public int TotalWishlistPending { get; set; } public int TotalWishlistProcessing { get; set; } public int TotalWishlistSupplied { get; set; } public int TotalWishlistComplete { get; set; } public int TotalPendingUpgrade { get; set; } public IEnumerable<DashboardUpdates> DashboardUpdates { get; set;} public JArray AssetExpiryData { get; set; } public JArray AssetsByCategory { get; set; } public JArray WarrantyExpiryData { get; set; } public bool DisplayButtonsPanel { get; set; } public bool DisplayNotificationsPanel { get; set; } public bool DisplayAssetPieChartPanel { get; set; } public bool DisplayAssetObsoletePanel { get; set; } public bool DisplayAssetWarrantyPanel { get; set; } public bool DisplayWatchlistStatsPanel { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Events; using Photon.Pun; using Photon.Pun.UtilityScripts; public class GrabbableHolon : OVRGrabbable { public UnityEvent onGrab; public UnityEvent onRelease; protected override void Start() { base.Start(); } override public void GrabBegin(OVRGrabber hand, Collider grabPoint) { base.GrabBegin(hand, grabPoint); Invoke("startGrab", 0f); var customHand = hand as HolonGrabber; if (customHand != null) { OVRInput.Controller currentHand = customHand.ReturnHand(); } } override public void GrabEnd(Vector3 linearVelocity, Vector3 angularVelocity) { base.GrabEnd(linearVelocity, angularVelocity); onRelease.Invoke(); } private void startGrab() { Debug.Log("startGrab was called"); onGrab.Invoke(); } }
using Serenity; using Serenity.Data; using Serenity.Services; using System; using System.Data; using MyRequest = Serenity.Services.DeleteRequest; using MyResponse = Serenity.Services.DeleteResponse; using MyRow = ARLink.Default.PackageRow; namespace ARLink.Default { public interface IPackageDeleteHandler : IDeleteHandler<MyRow, MyRequest, MyResponse> {} public class PackageDeleteHandler : DeleteRequestHandler<MyRow, MyRequest, MyResponse>, IPackageDeleteHandler { public PackageDeleteHandler(IRequestContext context) : base(context) { } } }
using System; namespace MusicCopy { internal class File2 { public File2() { MD5 = "0"; Path = "Unknown"; OldestDateUtc = DateTime.MinValue; Size = 0; } public string MD5 { get; set; } public string Path { get; set; } public DateTime OldestDateUtc { get; set; } public long Size { get; set; } } }