text
stringlengths
13
6.01M
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Xamarin.Forms; namespace Liddup.Controls { public class UnderlinedEntry : Entry { public static readonly BindableProperty BorderColorProperty = BindableProperty.Create("BorderColor", typeof(Color), typeof(Entry), Color.White); public static readonly BindableProperty LetterSpacingProperty = BindableProperty.Create("LetterSpacing", typeof(float), typeof(Entry), 0.0f); public Color BorderColor { get { return (Color)GetValue(BorderColorProperty); } set { SetValue(BorderColorProperty, value); } } public float LetterSpacing { get { return (float)GetValue(LetterSpacingProperty); } set { SetValue(BorderColorProperty, value); } } } }
using MediatR; namespace CQSR.Abstraction { public interface IQueryHandler<TQuery, TResponse> : IRequestHandler<TQuery, TResponse> where TResponse: class where TQuery : IQuery<TResponse> { } }
using DEMO_DDD.DOMAIN.Entidades; using DEMO_DDD.DOMAIN.Interfaces.Repositories; using DEMO_DDD.DOMAIN.Interfaces.Services; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DEMO_DDD.DOMAIN.Services { public class ClienteService : ServiceBase<Cliente>, IClienteService { private readonly IClienteRepository _clienteRepository; public ClienteService(IClienteRepository clienteRepository) : base(clienteRepository) { _clienteRepository = clienteRepository; } //Busca clientes especiais, regra de negocio na classe cliente public IEnumerable<Cliente> ObterClientesEspeciais(IEnumerable<Cliente> clientes) { return clientes.Where(c => c.ClienteEspecial(c)); } //Busca os produtos e seus respectivos produtos public async Task<IEnumerable<Cliente>> ObterClientesProdutos() { return await _clienteRepository.ObterClientesProdutos(); } } }
using System; namespace MotorMeans.ViewModels { public class VolumeModel : BaseViewModel { public VolumeModel() { } private decimal liters = 0.0m; public decimal Liters { get { return liters; } set { if (liters != value) { liters = value; OnPropertyChanged(nameof(Liters)); OnPropertyChanged(nameof(CubicInches)); } } } private decimal cubicInches = 0.0m; public decimal CubicInches { get { return cubicInches; } set { if (cubicInches != value) { cubicInches = value; OnPropertyChanged(nameof(Liters)); OnPropertyChanged(nameof(CubicInches)); } } } } }
namespace Palindromes { using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; public class Palindromes { public static void Main(string[] args) { //var for input strings; var inputStrings = Console.ReadLine().Split(new[] { ' ', ',', '?', '!', '.' }, StringSplitOptions.RemoveEmptyEntries); //var for palindromes words; var palindromes = new List<string>(); foreach (var str in inputStrings) { //bool for checkig the symbols in current string; bool flag = true; for (int i = 0; i < str.Length / 2; i++) { if (str[i] != str[(str.Length - 1) - i]) { flag = false; break; } } if (flag) { palindromes.Add(str); } }//end of foreach loop; Console.WriteLine(string.Join(", ", palindromes.Distinct().OrderBy(x => x))); } } }
using System; namespace FileCabinetApp { /// <summary> /// Validator class with default parameters. /// </summary> public class DefaultValidator : IRecordValidator { /// <summary> /// Validate record with default parameters. /// </summary> /// <param name="record">Record to validate.</param> public void ValidateParameters(FileCabinetRecord record) { if (string.IsNullOrWhiteSpace(record.FirstName)) { throw new ArgumentNullException(nameof(record.FirstName)); } if (record.FirstName.Length < 2 || record.FirstName.Length > 60) { throw new ArgumentException("First name length must be greater then 1 and less then 61"); } if (string.IsNullOrWhiteSpace(record.LastName)) { throw new ArgumentNullException(nameof(record.LastName)); } if (record.LastName.Length < 2 || record.LastName.Length > 60) { throw new ArgumentException("Last name length must be greater then 1 and less then 61"); } if (record.DateOfBirth > DateTime.Now || record.DateOfBirth < new DateTime(1950, 1, 1)) { throw new ArgumentException("Date of birth should be greater then 01/01/1950 and less then current date"); } if (record.WorkExperience < 0 || record.WorkExperience > 70) { throw new ArgumentException("Work experience cannot be less then 0 or greater then 70"); } if (record.Weight < 0 || record.Weight > 200) { throw new ArgumentException("Weight cannot be less then 0 or greater then 200"); } if (record.LuckySymbol == ' ') { throw new ArgumentException("Lucky symbol cannot be empty"); } } } }
using MySql.Data.MySqlClient; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Utils; using Model; namespace DataAccess { public class EmployeeDA { public EmployeeDA() { } public string returnPassword(string username) { string cadena = Constants.connectionString; MySqlConnection con = new MySqlConnection(cadena); con.Open(); MySqlCommand comando = new MySqlCommand(); comando.CommandText = "SELECT Password FROM Employee WHERE Dni = " + username + ";"; comando.Connection = con; MySqlDataReader reader = comando.ExecuteReader(); reader.Read(); string pass = reader.GetString("Password"); con.Close(); return pass; } public Employee getEmployee(string username) { MySqlConnection con = new MySqlConnection(Constants.connectionString); con.Open(); MySqlCommand comando = new MySqlCommand(); comando.CommandText = "SELECT * FROM Employee WHERE Dni = " + username + ";"; comando.Connection = con; MySqlDataReader reader = comando.ExecuteReader(); reader.Read(); Employee employee = new Employee(); employee.FullName = reader.GetString("Name") + " " + reader.GetString("Surname"); employee.Id = reader.GetInt32("Person_IdPerson"); con.Close(); return employee; } public void changePassword(string pass) { MySqlConnection con = new MySqlConnection(Constants.connectionString); MySqlCommand cmd = new MySqlCommand(); con.Open(); cmd.Connection = con; cmd.CommandText = "updatePassword"; cmd.CommandType = System.Data.CommandType.StoredProcedure; cmd.Parameters.Add("_username", MySqlDbType.String).Value = Constants.CurrentUserName; cmd.Parameters.Add("_newPassword", MySqlDbType.String).Value = pass; cmd.ExecuteNonQuery(); con.Close(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace Atestat_Gherghev_Andreea { public partial class personalizare : Form { int nr = 1, juc = 1; public personalizare() { InitializeComponent(); button1.Focus(); } private void button1_Click(object sender, EventArgs e) { labirint f = new labirint(nr, juc); f.ShowDialog(); } private void radioButton1_CheckedChanged(object sender, EventArgs e) { nr = 14; } private void radioButton2_CheckedChanged(object sender, EventArgs e) { nr = 13; } private void radioButton3_CheckedChanged(object sender, EventArgs e) { nr = 22; } private void radioButton4_CheckedChanged(object sender, EventArgs e) { nr = 21; } private void radioButton5_CheckedChanged(object sender, EventArgs e) { nr = 26; } private void radioButton6_CheckedChanged(object sender, EventArgs e) { juc = 1; } private void radioButton7_CheckedChanged(object sender, EventArgs e) { juc = 3; } private void radioButton8_CheckedChanged(object sender, EventArgs e) { juc = 2; } private void radioButton9_CheckedChanged(object sender, EventArgs e) { juc = 7; } private void radioButton10_CheckedChanged(object sender, EventArgs e) { juc = 5; } private void personalizare_Load(object sender, EventArgs e) { } private void personalizare_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) button1.PerformClick(); } } }
using System; using System.ComponentModel.DataAnnotations; namespace DemoApp.Model.ViewModels { public class Station { public int StationId { get; set; } public Guid StationUid { get; set; } [Required] [Display(ResourceType = typeof(ModelResources), Name = "Label_MetroStationInternalId")] public int InternalId { get; set; } [Required] [Display(ResourceType = typeof(ModelResources), Name = "Label_MetroStationName")] public string Name { get; set; } [Required] [Display(ResourceType = typeof(ModelResources), Name = "Label_MetroStationIsActive")] public bool Active { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } } }
using System; using System.Windows.Forms; using Airfield_Simulator.Core.Models; namespace Airfield_Simulator.Core.Airplane { public class Aircraft : SimulationObject { public ISimulationProperties SimulationProperties { get; } public GeoPoint Position { get; } public double TargetHeading { get; private set; } private double TrueSpeed => Speed * SimulationProperties.SimulationSpeed; private const int StandardRateTurn = 30; private double Speed => SimulationProperties.AircraftSpeed; private double _actualHeading; private TurnDirection _turnDirection; public Aircraft(GeoPoint position, int heading, ISimulationProperties simprops) { SimulationProperties = simprops; Position = position; ActualHeading = heading; } public double ActualHeading { get { return _actualHeading; } set { if (IsValidHeading(value)) { _actualHeading = value; } else { throw new ArgumentOutOfRangeException(nameof(value), "Value must be between 0 and 360"); } } } public void TurnLeft(double newHeading) { _turnDirection = TurnDirection.Left; if (IsValidHeading(newHeading)) { TargetHeading = newHeading; } else { throw new ArgumentOutOfRangeException(nameof(newHeading), "Value must be between 0 and 360"); } } public void TurnRight(double newHeading) { _turnDirection = TurnDirection.Right; if (IsValidHeading(newHeading)) { TargetHeading = newHeading; } else { throw new ArgumentOutOfRangeException(nameof(newHeading), "Value must be between 0 and 259"); } } public override void BeforeUpdate() { Fly(); Turn(); } private void Fly() { var traveledDistance = TrueSpeed*FrameDispatcher.DeltaTime; var bearing = ActualHeading*Math.PI/180; Position.Y = Math.Round(Position.Y + traveledDistance*Math.Cos(bearing), 5); Position.X = Math.Round(Position.X + traveledDistance*Math.Sin(bearing), 5); } private void Turn() { if (!(ActualHeading - TargetHeading >= 0.2) && !(ActualHeading - TargetHeading <= -0.2)) return; var tempheading = ActualHeading + (int) _turnDirection*(StandardRateTurn*FrameDispatcher.DeltaTime)* SimulationProperties.SimulationSpeed; if (tempheading < 0) { ActualHeading = 360 + tempheading; } else if (tempheading >= 360) { ActualHeading = tempheading - 360; } else { ActualHeading = tempheading; } } private static bool IsValidHeading(double d) { return (d >= 0) && (d < 360); } } }
using System.Collections.Generic; using System.Linq; using TMPro; using UnityEngine; using UnityEngine.UI; public class UIOutputController : MonoBehaviour { #region Fields [SerializeField] private TextMeshProUGUI _inventoryTextMesh; [SerializeField] private TextMeshProUGUI _checkPointTextMesh; [SerializeField] private Image _healthBar; [SerializeField] private GameObject _restartButton; [SerializeField] private GameObject _exitButton; [SerializeField] private GameObject _vicotryImage; private float _maxHealth; #endregion #region UnityMethods private void Start() { HealthController healthController = GetComponent<HealthController>(); DisplayHealth(healthController.HealthValue); healthController.OnChangeHealth += DisplayHealth; _maxHealth = healthController.HealthValue; } #endregion #region Methods private void DisplayHealth(float health) { _healthBar.fillAmount = health / _maxHealth; } public void DisplayInventory(IEnumerable<Item> items) { string itemsString = string.Join("\n", items.Select(x => x.ItemName)); _inventoryTextMesh.text = $"Инвентарь:\n{itemsString}"; } public void DisplayCheckPointMessage(string message, float displayTime) { _checkPointTextMesh.text = message; Invoke(nameof(ClearCheckPointMessage), displayTime); } private void ClearCheckPointMessage() { _checkPointTextMesh.SetText(string.Empty); } public void ShowRestartRound() { _restartButton.SetActive(true); _exitButton.SetActive(true); } public void DisplayVictoryImage() { _vicotryImage.SetActive(true); } #endregion }
using System; using System.Drawing; using System.Linq; using System.Windows.Forms; namespace Course_work_DB { public partial class Port : Form { private readonly int id; readonly bool edit; public Port() { InitializeComponent(); edit = false; } public Port(int id, string location, string name) : this() { edit = true; this.id = id; textBox1.Text = location; textBox2.Text = name; } private void OKBtn_Click(object sender, EventArgs e) { label13.Visible = false; foreach (Control c in Controls) { if (c is TextBox || c is ComboBox) c.BackColor = Color.White; } //проверка на заполненость foreach (Control c in Controls) { if (c is TextBox && c.Text == "") { c.BackColor = Color.LightSalmon; label13.Visible = true; } } //вернуть если ошибки if (label13.Visible == true) { return; } if (edit) { portTableAdapter1.UpdateQueryPort(textBox1.Text, textBox2.Text, id); } else { portTableAdapter1.Insert(portTableAdapter1.GetData().Last().Id + 1, textBox1.Text, textBox2.Text); } portTableAdapter1.Fill(_Yacht_clubDataSet1.Port); Close(); } private void CancelBtn_Click(object sender, EventArgs e) { Close(); } } }
using System.ComponentModel.Composition; using System.Windows.Controls; namespace Torshify.Radio.EchoNest.Views.Similar.Tabs { [Export(typeof(RecentView))] [PartCreationPolicy(CreationPolicy.NonShared)] public partial class RecentView : UserControl { public RecentView() { InitializeComponent(); } [Import] public RecentViewModel Model { get { return DataContext as RecentViewModel; } set { DataContext = value; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.IO.Ports; using System.Diagnostics; namespace FloraGotchiAppV2 { public class SerialRead { Database db; SerialPort SerialPort; bool fanon; bool pumpon; bool ledon; bool heaton; string oudestatus; string serialdata; string value; string sensor; private int Fan; //fan status private int Light; //light status private int Pump; //pomp status private int Heater; //verwarming status public Situation currentSituation { get; private set; } int currentAir = 0; int currentHum = 0; int currentLight = 0; int CurrentSoil = 0; int CurrentTemp = 0; int read = 0; int id = 0; public SerialRead() { currentSituation = new Situation(Situation.SituationType.Current, 0, 0, 0, 0, 0, 0); db = new Database(); Connect(); } public void SetId(int id) { this.id = id; } public void Connect() { SerialPort = new SerialPort("COM8") //welke compoort + extra settings { BaudRate = 9600, Parity = Parity.None, StopBits = StopBits.One, DataBits = 8, Handshake = Handshake.None }; //SerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler); try { SerialPort.Open(); //pur a bowl of serial Debug.WriteLine("connected!!!!!"); ReadSensor(); } catch (Exception ex) { Debug.WriteLine("Failed to connect" + ex); } } public void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e) { ReadSensor(); } public void FanOn() { if (SerialPort.IsOpen == false) { SerialPort.Open(); } SerialPort.WriteLine("61"); SerialPort.Close(); } public Task ReadSensor() { return Task.Run(async () => { while (true) { serialdata = SerialPort.ReadLine(); //serialdata is alles wat binnenkomt, tot er een nieuwe lege lijn is serialdata = serialdata.Replace("\r", ""); // /r afkapping eruit halen sensor = serialdata.Substring(0, 1); //het type sensor is het eerste getal if (serialdata.Contains("?")) //foute invoeren eruit halen { } else if (serialdata.Contains("\0")) //rare \0 waardes eruit halen weet ik veel waarom { } if (serialdata != oudestatus) //als de oude waarde niet hetzelfde is als de vorige waarde { oudestatus = serialdata; //de oude waarde is de serialdata if (serialdata.Length == 3) //als de lengte 3 is, dan is de value de laatste 2 getallen { value = serialdata.Substring(1, 2); } else if (serialdata.Length == 4)//als de lengte 4 is, dan is de value de laatste 3 getallen { value = serialdata.Substring(1, 3); } int intsensor = Int32.Parse(sensor); //maak een int van de sensor Debug.WriteLine(intsensor); //schrijf de waardes op Debug.WriteLine(value); //schrijf de waardes op switch (intsensor) //afhankelijk van welk type sensor de data verstuurd, spring dan naar die case { case 1: //lichtsterkte Debug.WriteLine(value); currentLight = Convert.ToInt32(value); read++; break; case 2: //temperatoehr Debug.WriteLine(value); currentLight = Convert.ToInt32(value); read++; break; case 3: //luchtvochtigheid Debug.WriteLine(value); currentLight = Convert.ToInt32(value); read++; break; case 4: //grondvochtigheid Debug.WriteLine(value); currentLight = Convert.ToInt32(value); read++; break; case 5: //luchtkwaliteit Debug.WriteLine(value); currentLight = Convert.ToInt32(value); read++; if (read == 5) { if (id != 0) { currentSituation = new Situation(Situation.SituationType.Current, id, currentAir, currentHum, currentLight, CurrentSoil, CurrentTemp); } else { currentSituation = new Situation(Situation.SituationType.Current, 0, 0, 0, 0, 0, 0); } } read = 0; break; } } else { } // Hier word bepaald of er een actie moet gebeuren op nresultaten die net gelezen zijn Situation set = db.GetSituation(0, Situation.SituationType.Desired); Situation cur = db.GetSituation(0, Situation.SituationType.Current); if (set.Temperature > cur.Temperature) { Fan = 0; Heater = 1; } else if (set.Temperature < cur.Temperature) { Fan = 1; Heater = 0; } else if (set.Temperature == cur.Temperature) { Fan = 0; Heater = 0; } /* if (set.SoilMoisture > cur.SoilMoisture) { Pump = 1; } else if (set.SoilMoisture < cur.SoilMoisture) { Pump = 0; } else if (set.SoilMoisture == cur.SoilMoisture) { Pump = 0; } */ Light = set.LightLevel; if (set.Humidity > cur.Humidity) { Fan = 0; Pump = 1; } else if (set.Humidity < cur.Humidity) { Fan = 1; Pump = 0; } else if (set.Humidity == cur.Humidity) { Fan = 0; Pump = 0; } if (set.AirQuality > cur.AirQuality) { Fan = 1; } else if (set.AirQuality < cur.AirQuality) { Fan = 0; } else if (set.AirQuality == cur.AirQuality) { Fan = 0; } writeValues(); SerialPort.Close(); await Delay(20000); } }); } public async void writeValues() { string FanMessage = "1" + Fan.ToString() + ";"; string LightMessage = "2" + Light.ToString() + ";"; string PumpMessage = "3" + Pump.ToString() + ";"; string HeaterMessage = "4" + Heater.ToString() + ";"; SerialPort.WriteLine(FanMessage); await Delay(200); SerialPort.WriteLine(LightMessage); await Delay(200); SerialPort.WriteLine(PumpMessage); await Delay(200); SerialPort.WriteLine(HeaterMessage); await Delay(200); Debug.WriteLine("Writing values Fan " + Fan.ToString() + "Lights " + Light.ToString() + "Pump " + Pump.ToString() + "Heater " + Heater.ToString()); } public async Task Delay(int DelayTime) { await Task.Delay(DelayTime); } public void close() { SerialPort.Close(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Xml.Serialization; using System.Drawing; namespace CraneMonitor { public class Param { public Param() { SetInitValue(); } public int UpdateInterval { get; set; } public string MotorComPort1 { get; set; } public string MotorComPort2 { get; set; } public string SensorComPort { get; set; } public string ControllerComPort { get; set; } public int[] UsbCameraId { get; set; } public bool[] MotorFbMode { get; set; } public bool[] MotorDirection { get; set; } public bool[] EncoderDirection { get; set; } public string[] Source { get; set; } public string[] MeterLabel { get; set; } public double LightAmplitude { get; set; } public double LightFrequency { get; set; } public int PotentioLower { get; set; } public int PotentioUpper { get; set; } public void SetInitValue() // default parameters { UpdateInterval = 50 * 1; // serial port of motor driver (2018) MotorComPort1 = "COM5"; MotorComPort2 = "COM6"; SensorComPort = "COM7"; // serial port of controller box ControllerComPort = "COM3"; UsbCameraId = new int[] { 0, 1 }; MotorFbMode = new bool[] { true, true, true, true, true, true }; MotorDirection = new bool[] { true, true, true, true, true, true }; EncoderDirection = new bool[] { true, true, true, true, true, true }; Source = new string[] { "0", "1", "2", "L", "", "" }; MeterLabel = new string[] { "1", "2", "3"}; LightAmplitude = 255; LightFrequency = 1.0; PotentioLower = 0; PotentioUpper = 1024; } private static string GetSettingPath() { string[] PathCandidates = new string[] { "settings.xml", "..\\settings.xml", "" }; //ユーザ毎のアプリケーションデータディレクトリに保存する PathCandidates[2] = String.Format( "{0}\\{1}", Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "CraneMonitor\\settings.xml"); for (int i = 0; i < 2/* 3 */; i++) if (File.Exists(PathCandidates[i])) return PathCandidates[i]; return PathCandidates[0]; // default is current path } //設定をファイルから読み込む public static Param Load() { Param param = null; String path = GetSettingPath(); if (File.Exists(path)) { XmlSerializer serializer = new XmlSerializer(typeof(Param)); using (FileStream stream = new FileStream(path, FileMode.Open)) { param = serializer.Deserialize(stream) as Param; } } else { param = new Param(); } return param; } //設定をファイルに保存する public static void Save(Param param) { String path = GetSettingPath(); XmlSerializer serializer = new XmlSerializer(typeof(Param)); using (FileStream stream = new FileStream(path, FileMode.Create)) { serializer.Serialize(stream, param); } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace ShortId_Dnx { public class Program { public void Main(string[] args) { var id = JasonSoft.ShortId.New(); Console.WriteLine(id); Console.WriteLine("done"); Console.Read(); } } }
using System; using System.Collections.Generic; using System.Text; namespace Reserva.Domain.Command.Result { public class SalaCommandRegisterResult { public SalaCommandRegisterResult(int salaId, string nome) { SalaId = salaId; Nome = nome; } public int SalaId { get; set; } public string Nome { get; set; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEditor; namespace Dawnfall.FullSerializer { public class UnityObjectConverter : fsConverter { public override bool CanProcess(Type type) { return typeof(UnityEngine.Object).IsAssignableFrom(type); } public override object CreateInstance(fsData data, Type storageType) { return null; } public override bool RequestCycleSupport(Type storageType) { return false; } public override bool RequestInheritanceSupport(Type storageType) { return base.RequestInheritanceSupport(storageType); } public override fsResult TryDeserialize(fsData data, ref object instance, Type storageType, object other) { IUnityObjectRegister unityObjectRegister = other as IUnityObjectRegister; //TODO: maybe? do interface for this if (unityObjectRegister != null) instance = unityObjectRegister.GetRegisteredUO((int)data.AsInt64); else instance = null; return fsResult.Success; } public override fsResult TrySerialize(object instance, out fsData serialized, Type storageType, object other) { IUnityObjectRegister unityObjectRegister = other as IUnityObjectRegister; //TODO: maybe? do interface for this if (unityObjectRegister != null) serialized = new fsData(unityObjectRegister.RegisterUnityObject(instance as UnityEngine.Object)); else serialized = new fsData(-1); return fsResult.Success; } } public interface IUnityObjectRegister { int RegisterUnityObject(UnityEngine.Object uo); UnityEngine.Object GetRegisteredUO(int index); } }
using MongoDB.Bson; using System; namespace EnglishHubRepository { public class PackageResult { public PackageEntity package { get; set; } public int wordCount { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace YiXiangLibrary { public partial class SiteMaster : System.Web.UI.MasterPage { public string did = ""; public string uid = ""; public string str00 = ""; public string str01 = ""; public string str02 = ""; public string str03 = ""; protected void Page_Load(object sender, EventArgs e) { uid = Request["uid"]; str00 = "~/Default.aspx?uid=" + uid; str01 = "~/search_bingli_user.aspx?uid=" + uid; str02 = "~/p_bingli_select.aspx?uid=" + uid; str03 = "~/question.aspx?uid=" + uid; //str = "~/question.aspx?did=" + did + "&uid=" + uid; Menu1.Items[0].NavigateUrl = str00; Menu1.Items[1].NavigateUrl = str01; Menu1.Items[2].NavigateUrl = str02; Menu1.Items[3].NavigateUrl = str03; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpriteLooker : MonoBehaviour { private Sprite[] sprites; // Use this for initialization void Start () { var thing = this.gameObject.GetComponent<SpriteRenderer>(); //thing.sprite = Resources.Load<Sprite>(Game.current.player.Sprite); } // Update is called once per frame void Update () { //transform.position = GameObject.Find("Capsule").transform.position; var thing = GameObject.Find("Hitbox").transform.position; thing.y = thing.y -0.6466f; transform.position = thing; transform.rotation = Quaternion.LookRotation(Camera.main.transform.position); transform.LookAt(Camera.main.transform.position, Vector3.up); } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; public class CubeInteraction : MonoBehaviour { private float timer; public float gazeTime = 2f; private bool gazedAt; private CharacterController cc; public float speed = 3.0f; public Transform vrCamera; public GameObject other; void Start () { //timer = 0; } public void OnGazeEnter(){ } public void OnGazeExit(){ } // Update is called once per frame void Update () { if (gazedAt == true) { timer += Time.deltaTime; if (timer >= gazeTime) { ExecuteEvents.Execute (gameObject, new PointerEventData (EventSystem.current), ExecuteEvents.pointerClickHandler); other.transform.position = new Vector3 (15, 20, 10); // Transform child = transform.GetChild (0); // Vector3 newScale = new Vector3(2,2,2); // child.localScale = newScale; timer = 0f; GetComponent<Collider> ().enabled = false; } } } public void PointerEnter() { //Debug.Log ("Pointer Enter"); gazedAt = true; } public void PointerExit() { //Debug.Log ("Pointer Exit"); gazedAt = false; } public void PointerClick() { //Debug.Log ("Pointer Click"); //Vector3 forward = vrCamera.TransformDirection(Vector3) } }
using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace HT.Framework { /// <summary> /// 字符串工具箱 /// </summary> public static class StringToolkit { #region 不重复命名 private static HashSet<string> NoRepeatNames = new HashSet<string>(); /// <summary> /// 开始不重复命名 /// </summary> public static void BeginNoRepeatNaming() { NoRepeatNames.Clear(); } /// <summary> /// 获取不重复命名(自动加工原名,以防止重复) /// </summary> /// <param name="rawName">原名</param> /// <returns>不重复命名</returns> public static string GetNoRepeatName(string rawName) { if (NoRepeatNames.Contains(rawName)) { int index = 0; string noRepeatName = rawName + " " + index.ToString(); while (NoRepeatNames.Contains(noRepeatName)) { index += 1; noRepeatName = rawName + " " + index.ToString(); } NoRepeatNames.Add(noRepeatName); return noRepeatName; } else { NoRepeatNames.Add(rawName); return rawName; } } #endregion #region 字符串拼接 private static StringBuilder StringInstance = new StringBuilder(); /// <summary> /// 字符串拼接 /// </summary> /// <param name="str">待拼接的字符串</param> /// <returns>拼接成功的字符串</returns> public static string Concat(params string[] str) { StringInstance.Clear(); for (int i = 0; i < str.Length; i++) { StringInstance.Append(str[i]); } return StringInstance.ToString(); } /// <summary> /// 字符串拼接 /// </summary> /// <param name="str">待拼接的字符串</param> /// <returns>拼接成功的字符串</returns> public static string Concat(List<string> str) { StringInstance.Clear(); for (int i = 0; i < str.Count; i++) { StringInstance.Append(str[i]); } return StringInstance.ToString(); } #endregion #region 字符串转换 /// <summary> /// 转换成枚举 /// </summary> /// <typeparam name="EnumType">枚举类型</typeparam> /// <param name="value">字符串</param> /// <param name="defaultValue">默认值</param> /// <returns>枚举值</returns> public static EnumType ToEnum<EnumType>(this string value, EnumType defaultValue) { if (!string.IsNullOrEmpty(value)) { try { return (EnumType)Enum.Parse(typeof(EnumType), value); } catch { return defaultValue; } } return defaultValue; } /// <summary> /// 转换成Vector3,格式:x,y,z /// </summary> /// <param name="value">字符串</param> /// <returns>Vector3值</returns> public static Vector3 ToVector3(this string value) { value = value.Replace("f", ""); string[] values = value.Split(','); if (values.Length == 3) { try { return new Vector3(float.Parse(values[0]), float.Parse(values[1]), float.Parse(values[2])); } catch { return Vector3.zero; } } return Vector3.zero; } /// <summary> /// 将指定位置的子字串转换为富文本 /// </summary> /// <param name="value">字符串</param> /// <param name="subStr">子字串</param> /// <param name="color">颜色</param> /// <returns>转换后的字符串</returns> public static string ToRichBoldColor(this string value, string subStr, Color color) { if (subStr.Length <= 0 || !value.Contains(subStr)) { return value; } string valueRich = value; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<b><color=" + color.ToHexSystemString() + ">"); else return value; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</color></b>"); else return value; return valueRich; } /// <summary> /// 将指定位置的子字串转换为富文本 /// </summary> /// <param name="value">字符串</param> /// <param name="subStr">子字串</param> /// <param name="color">颜色</param> /// <returns>转换后的字符串</returns> public static string ToRichColor(this string value, string subStr, Color color) { if (subStr.Length <= 0 || !value.Contains(subStr)) { return value; } string valueRich = value; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<color=" + color.ToHexSystemString() + ">"); else return value; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</color>"); else return value; return valueRich; } /// <summary> /// 将指定位置的子字串转换为富文本 /// </summary> /// <param name="value">字符串</param> /// <param name="subStr">子字串</param> /// <param name="size">字体大小</param> /// <returns>转换后的字符串</returns> public static string ToRichSize(this string value, string subStr, int size) { if (subStr.Length <= 0 || !value.Contains(subStr)) { return value; } string valueRich = value; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<size=" + size + ">"); else return value; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</size>"); else return value; return valueRich; } /// <summary> /// 将指定位置的子字串转换为富文本 /// </summary> /// <param name="value">字符串</param> /// <param name="subStr">子字串</param> /// <returns>转换后的字符串</returns> public static string ToRichBold(this string value, string subStr) { if (subStr.Length <= 0 || !value.Contains(subStr)) { return value; } string valueRich = value; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<b>"); else return value; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</b>"); else return value; return valueRich; } /// <summary> /// 将指定位置的子字串转换为富文本 /// </summary> /// <param name="value">字符串</param> /// <param name="subStr">子字串</param> /// <returns>转换后的字符串</returns> public static string ToRichItalic(this string value, string subStr) { if (subStr.Length <= 0 || !value.Contains(subStr)) { return value; } string valueRich = value; int index = valueRich.IndexOf(subStr); if (index >= 0) valueRich = valueRich.Insert(index, "<i>"); else return value; index = valueRich.IndexOf(subStr) + subStr.Length; if (index >= 0) valueRich = valueRich.Insert(index, "</i>"); else return value; return valueRich; } #endregion } }
using PurificationPioneer.Scriptable; using UnityEngine; using UnityEngine.UI; namespace PurificationPioneer.Script { public class HeroNameFieldUi : MonoBehaviour { public Text heroNameText; public void Init(HeroConfigAsset config) { heroNameText.text = config.heroName; } } }
using System; using System.Collections.Generic; using System.Linq; namespace CodeGen.Models { public class EntityItem { public string Name { get; set; } public bool IsNullable { get; set; } public string NativeDataType { get; set; } public int? Length { get; set; } public int? NumericScale { get; set; } public int? NumericPrecision { get; set; } public int? DateTimePrecision { get; set; } } }
using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Viselica { class GetWord { public void GettingWord() { string text = (File.ReadAllText("C:/Dictionary.txt")); AlllData.Words.AddRange((text).Split("\n")); Random rnd = new Random(); AlllData.word = rnd.Next(0, AlllData.Words.Count); AlllData.Words.Remove(AlllData.Words[AlllData.word]); /*Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(" "); Console.WriteLine(AlllData.Words[AlllData.word]);*/ } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using UnityEngine; namespace Assets.Scripts.RobinsonCrusoe_Game.Cards.EventCards { public interface IEventCard { bool IsCardTypeBook(); QuestionMark GetQuestionMark(); void ExecuteSuccessEvent(); bool CanCompleteQuest(); int GetActionCosts(); RessourceCosts GetRessourceCosts(); } } public enum QuestionMark { None, Gathering, Building, Exploring }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class proceduralManager : MonoBehaviour { public float throwForce; //public GameObject ball; public GameObject ground; public GameObject cricketBall; public Collider coll; public Collider Pcoll; public Rigidbody rb; public Material secondMat; public float actualForce; int ballCounter = 0; float bowlerX = 1f; float actualBX; void Start () { throwForce = 2f; } public void throwBall(){ //ballTexture = (Texture2D)Resources.Load("cricket-ball-texture-flat-background-regular-red-leather-pattern-52560591.jpg"); ground = GameObject.Find("Plane"); //cricketBall.transform.localScale = new Vector3(0.5F, 0.5F, 0.5F); GameObject this_cricket_ball = Instantiate(cricketBall); ballCounter += 1; actualBX = bowlerX +Random.Range (-0.2f, 0.2f); this_cricket_ball.transform.position = new Vector3(actualBX, 4f, -4f); //ball = GameObject.CreatePrimitive(PrimitiveType.Sphere); //cricketBall.AddComponent<Rigidbody>(); //bowler = GameObject.CreatePrimitive(PrimitiveType.Cube); //bowler.transform.position = new Vector3(0f, 3f, 7f); // PhysicMaterial material = new PhysicMaterial(); PhysicMaterial material1 = new PhysicMaterial(); material1.dynamicFriction = 1; // material.bounciness = 1; material1.bounciness = 0.5F; Pcoll = ground.GetComponent<MeshCollider>(); Pcoll.material = material1; coll = this_cricket_ball.GetComponent<SphereCollider>(); // coll.material = material; rb = this_cricket_ball.GetComponent<Rigidbody>(); rb.angularDrag = 1F; //ball.GetComponent<Renderer>().material.mainTexture = ballTexture; actualForce = throwForce + Random.Range(-0.2f, 0.2f); if (ballCounter % 3 == 0) { throwForce += 0.2f; } if (actualForce > 2f) { actualForce = 2f; // Debug.Log ("Clamping actual force to " + actualForce); } this_cricket_ball.GetComponent<Rigidbody>().AddForce(transform.forward * actualForce, ForceMode.Impulse); } public void destroyBalls(){ GameObject[] all_balls = GameObject.FindGameObjectsWithTag("ball"); foreach (GameObject x in all_balls ){ Destroy(x); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Particles.Helpers { public sealed class RandomNumberGenerator { private static RandomNumberGenerator m_oInstance = null; private static readonly object m_oPadLock = new object(); private Random mRandom; // store the random object public static RandomNumberGenerator Instance { get { lock (m_oPadLock) { if (m_oInstance == null) { m_oInstance = new RandomNumberGenerator(); } return m_oInstance; } } } private RandomNumberGenerator() { mRandom = new Random(DateTime.Now.Millisecond); } /// <summary> /// Returns the next double no greater than max /// </summary> /// <param name="max"></param> /// <returns></returns> public double NextDouble(double max) { return mRandom.NextDouble() * max; } /// <summary> /// Returns the next double between min and max /// </summary> /// <param name="min"></param> /// <param name="max"></param> /// <returns></returns> public double NextDouble(double min, double max) { if (min > max) return mRandom.NextDouble() * (min - max) + max; else return mRandom.NextDouble() * (max - min) + min; } } }
using System.Windows; using System.Windows.Controls; using System.Windows.Input; using System.Windows.Markup; using HandyControl.Data; namespace HandyControl.Controls { [ContentProperty("Content")] public class SelectableItem : Control, ISelectable { private bool _isMouseLeftButtonDown; protected override void OnMouseLeave(MouseEventArgs e) { base.OnMouseLeave(e); _isMouseLeftButtonDown = false; } protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e) { base.OnMouseLeftButtonDown(e); _isMouseLeftButtonDown = true; } protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e) { base.OnMouseLeftButtonUp(e); if (_isMouseLeftButtonDown) { RaiseEvent(new RoutedEventArgs(SelectedEvent, this)); _isMouseLeftButtonDown = false; } } public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register( "IsSelected", typeof(bool), typeof(SelectableItem), new PropertyMetadata(ValueBoxes.FalseBox)); public bool IsSelected { get => (bool)GetValue(IsSelectedProperty); set => SetValue(IsSelectedProperty, value); } public static readonly RoutedEvent SelectedEvent = EventManager.RegisterRoutedEvent("Selected", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(SelectableItem)); public event RoutedEventHandler Selected { add => AddHandler(SelectedEvent, value); remove => RemoveHandler(SelectedEvent, value); } public static readonly DependencyProperty ContentProperty = DependencyProperty.Register( "Content", typeof(object), typeof(SelectableItem), new PropertyMetadata(default(object))); public object Content { get => GetValue(ContentProperty); set => SetValue(ContentProperty, value); } } }
using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Cache.Configuration; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace IgniteDemo { public class Seat : IBinarizable { [QuerySqlField(IsIndexed = true)] public int SeatId { set; get; } public int ActId { set; get; } public int SectionId { set; get; } public int BlockId { set; get; } public int RowId { set; get; } public int SeatNo { set; get; } public Seat(int seatId, int actId, int sectionId, int blockId, int rowId, int seatNo) { SeatId = seatId; ActId = actId; SectionId = sectionId; BlockId = blockId; RowId = rowId; SeatNo = seatNo; } public Seat() { } public void WriteBinary(IBinaryWriter writer) { writer.WriteInt("SeatId", SeatId); writer.WriteInt("ActId", ActId); writer.WriteInt("SectionId", SectionId); writer.WriteInt("BlockId", BlockId); writer.WriteInt("RowId", RowId); writer.WriteInt("SeatNo", SeatNo); } public void ReadBinary(IBinaryReader reader) { SeatId = reader.ReadInt("SeatId"); ActId = reader.ReadInt("ActId"); SectionId = reader.ReadInt("SectionId"); BlockId = reader.ReadInt("BlockId"); RowId = reader.ReadInt("RowId"); SeatNo = reader.ReadInt("SeatNo"); } } }
using System; namespace AsyncMethodDemo { internal class Program { static async Task Main(string[] args) { //async、await背后的原理揭秘 /* using HttpClient httpClient = new HttpClient(); string html = await httpClient.GetStringAsync("https://www.ptpress.com.cn"); Console.WriteLine(html); string destFilePath = "sub.txt"; string content = "hello async and await"; await File.WriteAllTextAsync(destFilePath, content); string content2 = await File.ReadAllTextAsync(destFilePath); Console.WriteLine(content2); */ //async背后的线程切换 /* Console.WriteLine("1-ThreadID="+Thread.CurrentThread.ManagedThreadId); string str1 = new string('a', 10000000); string str2 = new string('b', 10000000); string str3 = new string('c', 10000000); await File.WriteAllTextAsync("1.txt", str1); Console.WriteLine("2-ThreadID="+Thread.CurrentThread.ManagedThreadId); await File.WriteAllTextAsync("2.txt", str2); Console.WriteLine("3-ThreadID="+Thread.CurrentThread.ManagedThreadId); File.WriteAllText("3.txt", str3); Console.WriteLine("4-ThreadID="+Thread.CurrentThread.ManagedThreadId); */ //异步方法不等于多线程 /* Console.WriteLine("1-Main-ThreadID="+Thread.CurrentThread.ManagedThreadId); Console.WriteLine(await CalcAsync(10000)); Console.WriteLine("2-Main-ThreadID="+Thread.CurrentThread.ManagedThreadId); */ //没有async的异步方法 /* string str = await ReadFileAsync(2); Console.WriteLine(str); */ //手动创建Task对象 /* await WriteFileAsync(3, "hello"); string str = await ReadFileAsync(5); Console.WriteLine(str); */ //不建议的操作 /* string str1 = File.ReadAllTextAsync("1.txt").Result; string str2 = File.ReadAllTextAsync("1.txt").GetAwaiter().GetResult(); File.WriteAllTextAsync("1.txt", "www.ankium.com").Wait(); Console.WriteLine(str1); Console.WriteLine(str2); */ //异步暂停的方法 /* using HttpClient httpClient= new HttpClient(); string str1 = await httpClient.GetStringAsync("https://www.baidu.com"); await Task.Delay(3000); string str2 = await httpClient.GetStringAsync("https://www.bing.com"); */ //同时等待多个Task的执行结束 Task<string> t1 = File.ReadAllTextAsync("1.txt"); Task<string> t2 = File.ReadAllTextAsync("2.txt"); Task<string> t3 = File.ReadAllTextAsync("3.txt"); string[] results = await Task.WhenAll(t1, t2, t3); Console.WriteLine(results[0]); Console.WriteLine(results[1]); Console.WriteLine(results[2]); } static Task WriteFileAsync(int num,string content) { switch (num) { case 1: return File.WriteAllTextAsync("1.txt", content); case 2: return File.WriteAllTextAsync("2.txt", content); default: Console.WriteLine("文件暂时不可用"); return Task.CompletedTask; } } static Task<string> ReadFileAsync(int num) { switch (num) { case 1: return File.ReadAllTextAsync("1.txt"); case 2: return File.ReadAllTextAsync("2.txt"); default: return Task.FromResult("Love"); } } async Task<decimal> CalcAsync(int n) { Console.WriteLine("CalcAsync-ThreadID=" + Thread.CurrentThread.ManagedThreadId); return await Task.Run<decimal>(() => { Console.WriteLine("Task.Run-ThreadID=" + Thread.CurrentThread.ManagedThreadId); decimal result = 1; Random rand = new Random(); for (int i = 0; i < n * n; i++) { result += (decimal)rand.NextDouble(); } return result; }); } static async Task<int> DownloadAsync(string url,string destFilePath) { using HttpClient client = new HttpClient(); string body = await client.GetStringAsync(url); await File.WriteAllTextAsync(destFilePath, body); return body.Length; } } }
using Mirror; using System.Collections; using System.Collections.Generic; using UnityEngine; public class ThirdPersonCameraController : NetworkBehaviour { [SerializeField] private const float y_angle_min = 0f; [SerializeField] private const float y_angle_max = 70f; [SerializeField] private Transform lookAt; [SerializeField] private Transform camTransform; [SerializeField] private float currentX = 0f; [SerializeField] private float currentY = 0f; [SerializeField] private float sensitivityX = 4f; [SerializeField] private float sensitivityY = 1f; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { currentX += Input.GetAxis("Mouse X") * sensitivityX; currentY += -Input.GetAxis("Mouse Y") * sensitivityY; currentY = Mathf.Clamp(currentY, y_angle_min, y_angle_max); } private void LateUpdate() { MoveCamera(); } public void MoveCamera() { camTransform.LookAt(lookAt); lookAt.rotation = Quaternion.Euler(currentY, currentX, 0); } }
// Copyright 2019 Intel Corporation. // // The source code, information and material ("Material") contained herein is owned by // Intel Corporation or its suppliers or licensors, and title to such Material remains // with Intel Corporation or its suppliers or licensors. The Material contains // proprietary information of Intel or its suppliers and licensors. The Material is // protected by worldwide copyright laws and treaty provisions. No part of the // Material may be used, copied, reproduced, modified, published, uploaded, posted, // transmitted, distributed or disclosed in any way without Intel's prior express // written permission. No license under any patent, copyright or other intellectual // property rights in the Material is granted to or conferred upon you, either // expressly, by implication, inducement, estoppel or otherwise. Any license under // such intellectual property rights must be express and approved by Intel in writing. // // Unless otherwise agreed by Intel in writing, you may not remove or alter this // notice or any other notice embedded in Materials by Intel or Intel's suppliers or // licensors in any way. using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using System.Windows.Forms; namespace PCSkillExample { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new IRCExample()); } } }
using LuaInterface; using SLua; using System; using UnityEngine.Experimental.Director; public class Lua_UnityEngine_Experimental_Director_FrameData : LuaObject { [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int constructor(IntPtr l) { int result; try { FrameData frameData = default(FrameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_updateId(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_updateId()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_time(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_time()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_lastTime(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_lastTime()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_deltaTime(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_deltaTime()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_timeScale(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_timeScale()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_dTime(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_dTime()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_dLastTime(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_dLastTime()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_dDeltaTime(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_dDeltaTime()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } [MonoPInvokeCallback(typeof(LuaCSFunction))] public static int get_dtimeScale(IntPtr l) { int result; try { FrameData frameData; LuaObject.checkValueType<FrameData>(l, 1, out frameData); LuaObject.pushValue(l, true); LuaObject.pushValue(l, frameData.get_dtimeScale()); result = 2; } catch (Exception e) { result = LuaObject.error(l, e); } return result; } public static void reg(IntPtr l) { LuaObject.getTypeTable(l, "UnityEngine.Experimental.Director.FrameData"); LuaObject.addMember(l, "updateId", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_updateId), null, true); LuaObject.addMember(l, "time", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_time), null, true); LuaObject.addMember(l, "lastTime", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_lastTime), null, true); LuaObject.addMember(l, "deltaTime", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_deltaTime), null, true); LuaObject.addMember(l, "timeScale", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_timeScale), null, true); LuaObject.addMember(l, "dTime", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_dTime), null, true); LuaObject.addMember(l, "dLastTime", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_dLastTime), null, true); LuaObject.addMember(l, "dDeltaTime", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_dDeltaTime), null, true); LuaObject.addMember(l, "dtimeScale", new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.get_dtimeScale), null, true); LuaObject.createTypeMetatable(l, new LuaCSFunction(Lua_UnityEngine_Experimental_Director_FrameData.constructor), typeof(FrameData), typeof(ValueType)); } }
namespace RobbersLang { using System; using System.Collections.Generic; using System.Linq; public class Translator { public string Encode(string input) { var encodedChars = input.SelectMany(ToRobberish).ToArray(); return new string(encodedChars); } public string Decode(string encoded) { return new string(SkipEncodedChars(encoded).ToArray()); } private IEnumerable<char> SkipEncodedChars(string encoded) { for (var i = 0; i < encoded.Length; i++) { yield return encoded[i]; if (CharHelper.IsConsonant(encoded[i]) && i < encoded.Length - 1 && encoded[i + 1] == 'o') i += 2; } } private IEnumerable<char> ToRobberish(char c) { yield return c; if (CharHelper.IsConsonant(c)) { yield return 'o'; yield return c.ToString().ToLower().First(); } } internal static class CharHelper { static char[] vowels = "AEIOUYÅÄÖ".ToCharArray(); internal static bool IsConsonant(char c) { return char.IsLetter(c) && !vowels.Contains(c.ToString().ToUpper().First()); } } } }
using async_inn.Data; using async_inn.Models.DTOs; using async_inn.Models.Interfaces; using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace async_inn.Models.Services { public class AmenityRepository : IAmenity { private AsyncInnDbContext _context; // bringin in db public AmenityRepository(AsyncInnDbContext context) { _context = context; } /// <summary> /// Creates an amenity /// </summary> /// <param name="amenity">amenity object </param> /// <returns>task completion</returns> public async Task<AmenityDTO> Create(AmenityDTO amenitydto) { // convert amenityDTO to an entity Amenity entity = new Amenity() { Name = amenitydto.Name }; _context.Entry(entity).State = Microsoft.EntityFrameworkCore.EntityState.Added; // Saves Changes await _context.SaveChangesAsync(); return amenitydto; } /// <summary> /// deletes selected amenity /// </summary> /// <param name="id">amenity identifier</param> /// <returns>task completion </returns> public async Task Delete(int id) { var amenity = await _context.Amenities.FindAsync(id); _context.Entry(amenity).State = EntityState.Deleted; await _context.SaveChangesAsync(); } /// <summary> /// Gets all the amenities /// </summary> /// <returns> list of amenities </returns> public async Task<List<AmenityDTO>> GetAmenities() { var list = await _context.Amenities.ToListAsync(); var amenitiesdto = new List<AmenityDTO>(); foreach (var item in list) { amenitiesdto.Add(await GetAmenity(item.Id)); } return amenitiesdto; } /// <summary> /// Gets a single amenity by id /// </summary> /// <param name="id">amenity identifier</param> /// <returns>task completion</returns> public async Task<AmenityDTO> GetAmenity(int id) { Amenity amenity = await _context.Amenities.FindAsync(id); /* var roomAmenities = await _context.RoomAmenities.Where(x => x.AmenityId == id) .Include(x => x.room) .ToListAsync();*/ AmenityDTO amenitydto = new AmenityDTO() { Id = amenity.Id, Name = amenity.Name, }; return amenitydto; } /// <summary> /// updates amenity /// </summary> /// <param name="amenity"> amenity object</param> /// <returns>task completion </returns> public async Task<AmenityDTO> Update(AmenityDTO amenitydto) { // change amenityDTO to entity Amenity entity = new Amenity() { Id = amenitydto.Id, Name = amenitydto.Name }; _context.Entry(entity).State = EntityState.Modified; // Save changes await _context.SaveChangesAsync(); return amenitydto; } } }
using System; namespace Algorithms { public class GameOfLife { int[,] newboard; public GameOfLife() { int[,] board = new int[,] {{ 0, 1, 0, 0, 0 }, { 1, 1, 1, 0, 0 }, { 0, 0, 0, 0, 0 }, { 0, 0, 0, 1, 0 }, { 0, 0, 0, 1, 0 } }; newboard = new int[5, 5]; Array.Copy(board, newboard, 25); } public int[,] GetNextGeneration() { int[] nextGen; return newboard; } } }
using UnityEngine; using System.Collections; using System; [RequireComponent(typeof(AudioSource))] public class AudioEffect : MonoBehaviour, ISpecialEffect { //public AudioClip Sound; //public enum TypeAudioEffect { None, Default, Register, FreeRegister } //public TypeAudioEffect TypeAudio; [SerializeField] bool UnscaleTime; AudioSource AS; int id; bool isInit; TypeSpecialEffect type = TypeSpecialEffect.Audio; [SerializeField] AudioClip[] Clips; public TypeSpecialEffect Type { get { return type; } } void OnDestroy() { AudioController.UnRegisterSource(ref id); } void Awake() { if(!isInit) Init(); } public bool CheckEnd() { return !AS.isPlaying; } public void Stop() { AS.Stop(); } public void Init() { AS = GetComponent<AudioSource>(); if (AS == null) AS = gameObject.AddComponent<AudioSource>(); id = AudioController.RegisterSource(AS, UnscaleTime); //AS.clip = Sound; #if UNITY_EDITOR CheckEditor(); #endif isInit = true; } #if UNITY_EDITOR void CheckEditor() { if (AS == null) Debug.Log(GetType() + " error: AudioSource is NULL(maybe manual add) on " + gameObject); //else if (AS.clip == null) Debug.Log(GetType() + " error: Audioclip is NULL on " + gameObject); if (id == AudioController.NULL_ID) Debug.Log(GetType() + " error: AudioSource is NULL on " + gameObject); } #endif public void VisualStop() { throw new NotImplementedException(); } // void Start() // { // //Debug.Log("EXP POS"+transform.position); // if (Sound != null) { AS.clip = Sound; AS.Play(); } //#if UNITY_EDITOR // else Debug.LogError(GetType() + " error: Sound clip is null on " + gameObject); //#endif // } public void Begin() { AS.Stop(); if(Clips.Length>0) AS.clip = Clips[UnityEngine.Random.Range(0, Clips.Length)]; AS.Play(0); } public void FullReset() { Begin(); } }
using System; using System.Diagnostics; using System.IO; using System.Net; using System.Text; using System.Threading; using log4net; using SpiderCore.Util; namespace SpiderCore { public class HttpDownloader : IDownloader { private readonly ILog _logger = LogManager.GetLogger(typeof(HttpDownloader)); public Response Download(Request request) { //启动计时器 var stopwatch = new Stopwatch(); Response response = null; try { if (request.Sleep > 0) { Thread.Sleep(request.Sleep); } stopwatch.Start(); //Build Request var req = (HttpWebRequest)WebRequest.Create(request.Url); req.Timeout = request.Timeout; req.Headers.Clear(); foreach (var header in request.Header) { req.Headers.Add(header.Name, header.Value); } if (string.IsNullOrEmpty(request.ContentType) == false) { req.ContentType = request.ContentType; } if (string.IsNullOrEmpty(request.Host) == false) { req.Host = request.Host; } if (string.IsNullOrEmpty(request.Method) == false) { req.Method = request.Method; } if (string.IsNullOrEmpty(request.Referer) == false) { req.Referer = request.Referer; } if (string.IsNullOrEmpty(request.UserAgent) == false) { req.UserAgent = request.UserAgent; } req.CookieContainer = new CookieContainer(); foreach (var cookie in request.Cookie) { req.CookieContainer.Add(new Cookie(cookie.Name, cookie.Value)); } //GetResponse var rep = (HttpWebResponse)req.GetResponse(); response = GetResponseContext(rep, request.Encoding); if (response == null) return null; //Header Handle for (var i = 0; i < rep.Headers.Count; i++) { var key = rep.Headers[i]; var value = rep.Headers.Get(key); response.Header.Add(new NameValue(key, value)); } //Cookie Handle for (var i = 0; i < rep.Cookies.Count; i++) { var key = rep.Cookies[i].Name; var value = rep.Cookies[i].Value; response.Cookie.Add(new NameValue(key, value)); } //停止计时器 stopwatch.Stop(); request.DownloadTime = stopwatch.Elapsed.TotalMilliseconds; request.CrawlTime = DateTime.Now; response.Request = request; return response; } catch (TimeoutException timeoutException) { _logger.Error(timeoutException); } catch (Exception ex) { //抓取错误,切换网站 SchedulerManage.Instance.Switch(); _logger.Error(ex); } finally { if (stopwatch.IsRunning) { stopwatch.Stop(); } if (response != null && response.GetType() == typeof(HtmlResponse)) { var htmlResponse = response as HtmlResponse; if (htmlResponse != null) { Console.WriteLine("{0}-{1}-{2}", stopwatch.Elapsed, htmlResponse.Html.Length, request.Url); } } else { Console.WriteLine("{0}-{1}", stopwatch.Elapsed, request.Url); } } return null; } private Response GetResponseContext(HttpWebResponse httpWebResponse, string encoding) { //ContentType:text/html if (string.IsNullOrEmpty(httpWebResponse.ContentType) || httpWebResponse.ContentType.Contains("text/html")) { return GetTextHtmlResponse(httpWebResponse, encoding); } return null; } /// <summary> /// ContentType:text/html /// </summary> /// <param name="httpWebResponse"></param> /// <param name="encoding"></param> /// <returns></returns> private HtmlResponse GetTextHtmlResponse(HttpWebResponse httpWebResponse, string encoding) { var response = new HtmlResponse(); using (var stream = httpWebResponse.GetResponseStream()) { if (stream == null) return response; using (var reader = new StreamReader(stream, Encoding.GetEncoding(encoding))) { response.Html = reader.ReadToEnd(); reader.Close(); reader.Dispose(); } stream.Close(); stream.Dispose(); } return response; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace WebApiDesafio.Models { public class Palestra{ public int Codigo { get; set; } public int CodigoTipoCategoria { get; set; } public String Imagem { get; set; } public String Titulo { get; set; } public String Palestrante { get; set; } public String Descricao { get; set; } public String Data { get; set; } public String Hora { get; set; } public int QtdVagasDisponiveis { get; set; } //when listed by a user, must have this atributes on it public String EmailCadastrado { get; set; } public String DataInscricao { get; set; } public String HoraInscricao { get; set; } } }
using System; using System.Collections.Generic; using Microsoft.DirectX; using Microsoft.DirectX.Direct3D; using SonicRetro.SAModel; using SonicRetro.SAModel.Direct3D; using SonicRetro.SAModel.SAEditorCommon.DataTypes; using SonicRetro.SAModel.SAEditorCommon.SETEditing; namespace SADXObjectDefinitions.EmeraldCoast { public abstract class O_AOSummon : ObjectDefinition { protected NJS_OBJECT whale; protected Mesh[] whalemsh; protected NJS_OBJECT sphere; protected Mesh[] spheremsh; public override HitResult CheckHit(SETItem item, Vector3 Near, Vector3 Far, Viewport Viewport, Matrix Projection, Matrix View, MatrixStack transform) { HitResult result = HitResult.NoHit; transform.Push(); transform.NJTranslate(item.Position); transform.NJRotateY(item.Rotation.Y); transform.NJScale(4.5f, 4.5f, 4.5f); transform.Push(); result = HitResult.Min(result, sphere.CheckHit(Near, Far, Viewport, Projection, View, transform, spheremsh)); transform.Pop(); transform.Push(); transform.NJTranslate(item.Position + item.Scale); transform.NJRotateY(item.Rotation.Y); transform.NJScale(0.40000001f, 0.40000001f, 0.40000001f); transform.Push(); result = HitResult.Min(result, whale.CheckHit(Near, Far, Viewport, Projection, View, transform, whalemsh)); transform.Pop(); return result; } public override List<RenderInfo> Render(SETItem item, Device dev, EditorCamera camera, MatrixStack transform) { List<RenderInfo> result = new List<RenderInfo>(); transform.Push(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); result.AddRange(sphere.DrawModelTree(dev, transform, null, spheremsh)); if (item.Selected) result.AddRange(sphere.DrawModelTreeInvert(transform, spheremsh)); transform.Pop(); transform.Push(); transform.NJTranslate(item.Position + item.Scale); transform.NJRotateY(item.Rotation.Y); transform.NJScale(0.40000001f, 0.40000001f, 0.40000001f); result.AddRange(whale.DrawModelTree(dev, transform, ObjectHelper.GetTextures("OBJ_BEACH"), whalemsh)); if (item.Selected) result.AddRange(whale.DrawModelTreeInvert(transform, whalemsh)); transform.Pop(); return result; } public override BoundingSphere GetBounds(SETItem item) { MatrixStack transform = new MatrixStack(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); return ObjectHelper.GetModelBounds(sphere, transform); } } public class AOSummon : O_AOSummon { public override void Init(ObjectData data, string name, Device dev) { whale = ObjectHelper.LoadModel("Objects/Levels/Emerald Coast/Whale.sa1mdl"); whalemsh = ObjectHelper.GetMeshes(whale, dev); sphere = ObjectHelper.LoadModel("Objects/Collision/C SPHERE.sa1mdl"); spheremsh = ObjectHelper.GetMeshes(sphere, dev); } public override string Name { get { return "Whale Spawner"; } } } public abstract class O_AOKill : ObjectDefinition { protected NJS_OBJECT whale; protected Mesh[] whalemsh; protected NJS_OBJECT sphere; protected Mesh[] spheremsh; public override HitResult CheckHit(SETItem item, Vector3 Near, Vector3 Far, Viewport Viewport, Matrix Projection, Matrix View, MatrixStack transform) { HitResult result = HitResult.NoHit; transform.Push(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); transform.Push(); result = HitResult.Min(result, sphere.CheckHit(Near, Far, Viewport, Projection, View, transform, spheremsh)); transform.Pop(); transform.Push(); transform.NJTranslate(item.Position); transform.NJRotateZ(0x8000); transform.NJScale(0.40000001f, 0.40000001f, 0.40000001f); transform.Push(); result = HitResult.Min(result, whale.CheckHit(Near, Far, Viewport, Projection, View, transform, whalemsh)); transform.Pop(); return result; } public override List<RenderInfo> Render(SETItem item, Device dev, EditorCamera camera, MatrixStack transform) { List<RenderInfo> result = new List<RenderInfo>(); transform.Push(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); result.AddRange(sphere.DrawModelTree(dev, transform, null, spheremsh)); if (item.Selected) result.AddRange(sphere.DrawModelTreeInvert(transform, spheremsh)); transform.Pop(); transform.Push(); transform.NJTranslate(item.Position); transform.NJRotateZ(0x8000); transform.NJScale(0.40000001f, 0.40000001f, 0.40000001f); result.AddRange(whale.DrawModelTree(dev, transform, ObjectHelper.GetTextures("OBJ_BEACH"), whalemsh)); if (item.Selected) result.AddRange(whale.DrawModelTreeInvert(transform, whalemsh)); transform.Pop(); return result; } public override BoundingSphere GetBounds(SETItem item) { MatrixStack transform = new MatrixStack(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); return ObjectHelper.GetModelBounds(sphere, transform); } } public class AOKill : O_AOKill { public override void Init(ObjectData data, string name, Device dev) { whale = ObjectHelper.LoadModel("Objects/Levels/Emerald Coast/Whale.sa1mdl"); whalemsh = ObjectHelper.GetMeshes(whale, dev); sphere = ObjectHelper.LoadModel("Objects/Collision/C SPHERE.sa1mdl"); spheremsh = ObjectHelper.GetMeshes(sphere, dev); } public override string Name { get { return "Whale Despawner"; } } } public abstract class O_POSummon : ObjectDefinition { protected NJS_OBJECT whale; protected Mesh[] whalemsh; protected NJS_OBJECT sphere; protected Mesh[] spheremsh; public override HitResult CheckHit(SETItem item, Vector3 Near, Vector3 Far, Viewport Viewport, Matrix Projection, Matrix View, MatrixStack transform) { HitResult result = HitResult.NoHit; transform.Push(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); transform.Push(); result = HitResult.Min(result, sphere.CheckHit(Near, Far, Viewport, Projection, View, transform, spheremsh)); transform.Pop(); transform.Push(); transform.NJTranslate(item.Position); transform.NJRotateX(0x2000); transform.NJScale(0.40000001f, 0.40000001f, 0.40000001f); transform.Push(); result = HitResult.Min(result, whale.CheckHit(Near, Far, Viewport, Projection, View, transform, whalemsh)); transform.Pop(); return result; } public override List<RenderInfo> Render(SETItem item, Device dev, EditorCamera camera, MatrixStack transform) { List<RenderInfo> result = new List<RenderInfo>(); transform.Push(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); result.AddRange(sphere.DrawModelTree(dev, transform, null, spheremsh)); if (item.Selected) result.AddRange(sphere.DrawModelTreeInvert(transform, spheremsh)); transform.Pop(); transform.Push(); transform.NJTranslate(item.Position); transform.NJRotateX(0x2000); transform.NJScale(0.40000001f, 0.40000001f, 0.40000001f); result.AddRange(whale.DrawModelTree(dev, transform, ObjectHelper.GetTextures("OBJ_BEACH"), whalemsh)); if (item.Selected) result.AddRange(whale.DrawModelTreeInvert(transform, whalemsh)); transform.Pop(); return result; } public override BoundingSphere GetBounds(SETItem item) { MatrixStack transform = new MatrixStack(); transform.NJTranslate(item.Position); transform.NJScale(4.5f, 4.5f, 4.5f); return ObjectHelper.GetModelBounds(sphere, transform); } } public class POSummon : O_POSummon { public override void Init(ObjectData data, string name, Device dev) { whale = ObjectHelper.LoadModel("Objects/Levels/Emerald Coast/Whale.sa1mdl"); whalemsh = ObjectHelper.GetMeshes(whale, dev); sphere = ObjectHelper.LoadModel("Objects/Collision/C SPHERE.sa1mdl"); spheremsh = ObjectHelper.GetMeshes(sphere, dev); } public override string Name { get { return "PO Whale Spawner"; } } } }
using UnityEngine; public abstract class Attack : MonoBehaviour { public abstract void Launch (EnemyController enemy, PlayerController player); }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class ScripMenu : MonoBehaviour { // Use this for initialization public void Jugar() { Global.index = Global.index + 1; SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex + 1); } }
using System.Collections.Generic; using System; namespace Contoso.Common.Configuration.ExpressionDescriptors { public class SelectorLambdaOperatorDescriptor : OperatorDescriptorBase { public OperatorDescriptorBase Selector { get; set; } public string SourceElementType { get; set; } public string BodyType { get; set; } public string ParameterName { get; set; } } }
using System; using System.Collections.Generic; using System.Text; namespace 设计模式.观察者模式 { public class Cat { public void Miao() { Console.WriteLine("喵一下"); new Dog().Wang(); new Baby().Cry(); } public void MiaoDelegate(Action action) { Console.WriteLine("喵一下"); action.Invoke(); } public event Action miaoAction; public void MiaoEvent() { Console.WriteLine("喵一下"); miaoAction?.Invoke(); } } }
// // 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; using System.Configuration; using System.Net; using System.Net.Http; using System.Web; using DNN.Integration.Test.Framework; using NUnit.Framework; namespace DotNetNuke.Tests.Integration.Tests.DotNetNukeWeb { [TestFixture] public class DotNetNukeWebTests : IntegrationTestBase { #region private data private readonly HttpClient _httpClient; private readonly TimeSpan _timeout = TimeSpan.FromSeconds(30); private const string GetMonikerQuery = "/API/web/mobilehelper/monikers?moduleList="; private const string GetModuleDetailsQuery = "/API/web/mobilehelper/moduledetails?moduleList="; public DotNetNukeWebTests() { var url = ConfigurationManager.AppSettings["siteUrl"]; var siteUri = new Uri(url); _httpClient = new HttpClient { BaseAddress = siteUri, Timeout = _timeout }; } #endregion #region tests [Test] [TestCase(GetMonikerQuery)] [TestCase(GetModuleDetailsQuery)] public void CallingHelperForAnonymousUserShouldReturnSuccess(string query) { var result = _httpClient.GetAsync(query + HttpUtility.UrlEncode("ViewProfile")).Result; var content = result.Content.ReadAsStringAsync().Result; LogText(@"content => " + content); Assert.AreEqual(HttpStatusCode.OK, result.StatusCode); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace TimeTableManagementSystem.Physical_Module { public partial class ViewRescheduleForm : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Request req = RequestService.getRequest(); category.Text = req.Category; batch.Text = req.Batch; year.Text = req.Year; subject.Text = req.Subject; rescheduleDate.Text = req.RescheduleDate; from.Text = req.From; to.Text = req.To; comments.Text = req.Comments; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using Navigation.DAL; using Navigation.Models; namespace Navigation.Controllers { public class BlogController : Controller { private readonly NaviContext db = new NaviContext(); // GET: Blog public ActionResult Index() { List<Blog> blogs = db.Blogs.OrderByDescending(x=>x.Orderby).ToList(); return View(blogs); } //blog detailsi public ActionResult Details(int? id) { if (id==null) { return HttpNotFound(); } Blog blog = db.Blogs.Find(id); return View(blog); } } }
namespace Millo.Migrations { using System; using System.Data.Entity.Migrations; public partial class custom : DbMigration { public override void Up() { DropForeignKey("dbo.Users", "Role_Id", "dbo.Roles"); DropIndex("dbo.Users", new[] { "Role_Id" }); CreateTable( "dbo.UserLogins", c => new { Id = c.Int(nullable: false, identity: true), LoginProvider = c.String(), ProviderKey = c.String(), UserId = c.String(), User_UserId = c.Int(), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.Users", t => t.User_UserId) .Index(t => t.User_UserId); CreateTable( "dbo.UserRoles", c => new { User_UserId = c.Int(nullable: false), Role_Id = c.String(nullable: false, maxLength: 128), }) .PrimaryKey(t => new { t.User_UserId, t.Role_Id }) .ForeignKey("dbo.Users", t => t.User_UserId, cascadeDelete: true) .ForeignKey("dbo.Roles", t => t.Role_Id, cascadeDelete: true) .Index(t => t.User_UserId) .Index(t => t.Role_Id); DropColumn("dbo.Users", "Role_Id"); } public override void Down() { AddColumn("dbo.Users", "Role_Id", c => c.String(maxLength: 128)); DropForeignKey("dbo.UserLogins", "User_UserId", "dbo.Users"); DropForeignKey("dbo.UserRoles", "Role_Id", "dbo.Roles"); DropForeignKey("dbo.UserRoles", "User_UserId", "dbo.Users"); DropIndex("dbo.UserRoles", new[] { "Role_Id" }); DropIndex("dbo.UserRoles", new[] { "User_UserId" }); DropIndex("dbo.UserLogins", new[] { "User_UserId" }); DropTable("dbo.UserRoles"); DropTable("dbo.UserLogins"); CreateIndex("dbo.Users", "Role_Id"); AddForeignKey("dbo.Users", "Role_Id", "dbo.Roles", "Id"); } } }
using System; using System.Collections.Generic; using System.IO; using Microsoft.AspNetCore.Mvc.Abstractions; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Routing; using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.Options; namespace Microsoft.AspNetCore.Mvc.RazorPages.Infrastructure { public class PageActionDescriptorProvider : IActionDescriptorProvider { private readonly IFileProvider _fileProvider; private readonly MvcOptions _options; public PageActionDescriptorProvider( IPageFileProviderAccessor fileProvider, IOptions<MvcOptions> options) { _fileProvider = fileProvider.FileProvider; _options = options.Value; } public int Order { get; set; } public void OnProvidersExecuting(ActionDescriptorProviderContext context) { foreach (var file in EnumerateFiles()) { if (string.Equals(Path.GetExtension(file.ViewEnginePath), ".razor", StringComparison.Ordinal)) { AddActionDescriptors(context.Results, file); } } } public void OnProvidersExecuted(ActionDescriptorProviderContext context) { } private void AddActionDescriptors(IList<ActionDescriptor> actions, RazorPageFileInfo file) { var template = file.ViewEnginePath.Substring(1, file.ViewEnginePath.Length - (Path.GetExtension(file.ViewEnginePath).Length + 1)); if (string.Equals("Index", template, StringComparison.OrdinalIgnoreCase)) { template = string.Empty; } var filters = new List<FilterDescriptor>(_options.Filters.Count); for (var i = 0; i < _options.Filters.Count; i++) { filters.Add(new FilterDescriptor(_options.Filters[i], FilterScope.Global)); } actions.Add(new PageActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Template = template, }, DisplayName = $"Page: {file.ViewEnginePath}", FilterDescriptors = filters, RelativePath = "Pages" + file.ViewEnginePath, RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) { { "page", file.ViewEnginePath.Substring(0, file.ViewEnginePath.Length - ".razor".Length) }, }, ViewEnginePath = file.ViewEnginePath, }); } private IEnumerable<RazorPageFileInfo> EnumerateFiles() { var directory = _fileProvider.GetDirectoryContents("Pages"); return EnumerateFiles(directory, "/"); } private IEnumerable<RazorPageFileInfo> EnumerateFiles(IDirectoryContents directory, string prefix) { if (directory.Exists) { foreach (var file in directory) { if (file.IsDirectory) { var children = EnumerateFiles(_fileProvider.GetDirectoryContents(file.PhysicalPath), prefix + file.Name + "/"); foreach (var child in children) { yield return child; } } else { yield return new RazorPageFileInfo(file, prefix + file.Name); } } } } private class RazorPageFileInfo { public RazorPageFileInfo(IFileInfo fileInfo, string viewEnginePath) { FileInfo = fileInfo; ViewEnginePath = viewEnginePath; } public IFileInfo FileInfo { get; } public string ViewEnginePath { get; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; namespace MyCore { public class PanelMainControlUI : UIBase { protected override void Start() { base.Start(); GameEvent.instance.EventPlayDialog += OnEventStartDialog; GameEvent.instance.EventEndDialog += OnEventEndDialog; } private void OnDestroy() { GameEvent.instance.EventPlayDialog -= OnEventStartDialog; GameEvent.instance.EventEndDialog -= OnEventEndDialog; } void OnEventStartDialog(NPC npc) { gameObject.SetActive(false); } void OnEventEndDialog() { gameObject.SetActive(true); } } }
using Abp.Domain.Entities; using Abp.Domain.Entities.Auditing; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Hiraya.Domain.MongoDBCollections.Common { public class AuditedEntity : Entity<string>, IAudited { //Audit Creation public long? CreatorUserId { get; set; } public DateTime CreationTime { get; set; } //Audit Modification public DateTime? LastModificationTime { get; set; } public long? LastModifierUserId { get; set; } } }
using Data.Core; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace VocabularyApi.Models { public class UserVocabularyWord { public int Id { get; set; } public string Word { get; set; } public string Translation { get; set; } public int UserVocabularyId { get; set; } public UserVocabulary UserVocabulary { get; set; } public ICollection<TrainingStatistic> TrainingStatistics { get; set; } private TrainingStatistic GetTrainingStatistic(TrainingTypeEnum trainingType, bool isReverseTraining) => TrainingStatistics.SingleOrDefault(ts => ts.TrainingType == trainingType && ts.IsReverseTraining == isReverseTraining); public decimal GetKnowledgeRatio(TrainingTypeEnum trainingType, bool isReverseTraining) { var trainingStatistic = GetTrainingStatistic(trainingType, isReverseTraining); if (trainingStatistic == null) { return 0; } return trainingStatistic.RightAnswerCount - trainingStatistic.WrongAnswerCount; } public int GetKnowledgeRatio() { var sucessfullTrainings = TrainingStatistics.Count(ts => !ts.NeedToRepeat()); var totalTrainings = Enum.GetValues(typeof(TrainingTypeEnum)).Length * 2; return sucessfullTrainings *100 / totalTrainings ; } public bool NeedToRepeat(TrainingTypeEnum trainingType, bool isReverseTraining) { var trainingStatistic = GetTrainingStatistic(trainingType, isReverseTraining); if (trainingStatistic != null && !trainingStatistic.NeedToRepeat()) { return false; } return true; } public void SetTrainingResult(TrainingTypeEnum trainingType, bool isReverseTraining, bool isRight, string userOption) { var trainingStatistic = GetTrainingStatistic(trainingType, isReverseTraining); if (trainingStatistic == null) { trainingStatistic = new TrainingStatistic { TrainingType = trainingType, IsReverseTraining = isReverseTraining, UserVocabularyWordId = Id }; TrainingStatistics.Add(trainingStatistic); } if (isRight) { trainingStatistic.RightAnswerCount++; trainingStatistic.LastRightAnswerDate = DateTime.Now; } else { trainingStatistic.WrongAnswerCount++; trainingStatistic.LastWrongAnswerDate = DateTime.Now; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System; using System.Collections.Generic; using System.Linq; using Repository; using SamuraiBattle.Data; using SamuraiBattle.Domain; namespace Samurai.Console { class Program { static void Main(string[] args) { SamuraBattleRepos er = new SamuraBattleRepos(); er.SeedSamuraiBattle(); } } }
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using DartsTracker.Interfaces; using DartsTracker.Models; namespace DartsTracker.Presenters { class MainPresenter : IMainPresenter { private IMainView view; public MainPresenter(IMainView view) { this.view = view; } public bool FabOkClicked(string groupName, string playersNumber) { if (!CheckValidGroupName(groupName) || !CheckPlayersNumber(playersNumber, out int players)) return false; view.NavigateToGroupActivity(groupName, players, true); return true; } public async Task<List<string>> GetGroupsNames() { var lst = await MainActivity.Database.GetGroupAsync(); return lst .Select(a => a.Name) .ToList(); } private bool CheckValidGroupName(string groupName) { if (string.IsNullOrEmpty(groupName)) { view.MakeToast(Resource.String.toast_group_name_error); return false; } //Checks if database already contains a group with this given name. if (MainActivity.Database.GetGroupAsync().Result .Select(a => a.Name) .ToList() .Contains(groupName)) { view.MakeToast(Resource.String.toast_group_unique); return false; } return true; } private bool CheckPlayersNumber(string text, out int playersNumber) { if (string.IsNullOrEmpty(text)) { view.MakeToast(Resource.String.toast_players_error); playersNumber = 0; return false; } if (int.TryParse(text, out playersNumber)) { if (playersNumber < 0 && playersNumber > 7) return false; } return true; } public async Task DeleteFromDatabase(string groupName) { var players = await MainActivity.Database.GetPlayersAsync(groupName); var games = await MainActivity.Database.GetGamesAsync(groupName); await DeletePlayersFromDatabase(players); await DeleteGamesFromDatabase(games); await MainActivity.Database.DeleteGroupAsync(await MainActivity.Database.GetGroupAsync(groupName)); view.OnGroupsLoaded(MainActivity.Database.GetGroupAsync().Result.Select(a => a.Name).ToList()); } /* * Method deletes player and all his throws from database. */ private async Task DeletePlayersFromDatabase(IEnumerable<Player> players) { foreach (var player in players) { var playerThrow = MainActivity.Database.GetThrowsAsync().Result.Where(a => a.PlayerId == player.Id).ToList(); foreach (var t in playerThrow) { await MainActivity.Database.DeleteThrowAsync(t); } await MainActivity.Database.DeletePlayerAsync(player); } } private async Task DeleteGamesFromDatabase(IEnumerable<Game> games) { foreach (var game in games) { await MainActivity.Database.DeleteGameAsync(game); } } } }
using System; using System.ComponentModel; using System.Collections.Generic; using System.Text; using System.Data; using System.Data.Common; using RealEstate.BusinessObjects; using RealEstate.DataAccess; namespace RealEstate.BusinessLogic { public class ProductTypeBL { #region ***** Init Methods ***** ProductTypeDA objProductTypeDA; public ProductTypeBL() { objProductTypeDA = new ProductTypeDA(); } #endregion #region ***** Get Methods ***** /// <summary> /// Get ProductType by producttypeid /// </summary> /// <param name="producttypeid">ProductTypeId</param> /// <returns>ProductType</returns> public ProductType GetByProductTypeId(int producttypeid) { return objProductTypeDA.GetByProductTypeId(producttypeid); } /// <summary> /// Get all of ProductType /// </summary> /// <returns>List<<ProductType>></returns> public List<ProductType> GetList() { string cacheName = "lstProductType"; if( ServerCache.Get(cacheName) == null ) { ServerCache.Insert(cacheName, objProductTypeDA.GetList(), "ProductType"); } return (List<ProductType>) ServerCache.Get(cacheName); } /// <summary> /// Get DataSet of ProductType /// </summary> /// <returns>DataSet</returns> public DataSet GetDataSet() { string cacheName = "dsProductType"; if( ServerCache.Get(cacheName) == null ) { ServerCache.Insert(cacheName, objProductTypeDA.GetDataSet(), "ProductType"); } return (DataSet) ServerCache.Get(cacheName); } /// <summary> /// Get all of ProductType paged /// </summary> /// <param name="recperpage">recperpage</param> /// <param name="pageindex">pageindex</param> /// <returns>List<<ProductType>></returns> public List<ProductType> GetListPaged(int recperpage, int pageindex) { return objProductTypeDA.GetListPaged(recperpage, pageindex); } /// <summary> /// Get DataSet of ProductType paged /// </summary> /// <param name="recperpage">recperpage</param> /// <param name="pageindex">pageindex</param> /// <returns>DataSet</returns> public DataSet GetDataSetPaged(int recperpage, int pageindex) { return objProductTypeDA.GetDataSetPaged(recperpage, pageindex); } #endregion #region ***** Add Update Delete Methods ***** /// <summary> /// Add a new ProductType within ProductType database table /// </summary> /// <param name="obj_producttype">ProductType</param> /// <returns>key of table</returns> public int Add(ProductType obj_producttype) { ServerCache.Remove("ProductType", true); return objProductTypeDA.Add(obj_producttype); } /// <summary> /// updates the specified ProductType /// </summary> /// <param name="obj_producttype">ProductType</param> /// <returns></returns> public void Update(ProductType obj_producttype) { ServerCache.Remove("ProductType", true); objProductTypeDA.Update(obj_producttype); } /// <summary> /// Delete the specified ProductType /// </summary> /// <param name="producttypeid">ProductTypeId</param> /// <returns></returns> public void Delete(int producttypeid) { ServerCache.Remove("ProductType", true); objProductTypeDA.Delete(producttypeid); } #endregion } }
using System; using System.Collections.Generic; using System.Reflection; using System.Text; using CYQ.Data; using System.Configuration; using CYQ.Data.Tool; using System.Text.RegularExpressions; using CYQ.Data.Cache; using System.IO; using Aries.Core.Sql; using System.Threading; using Aries.Core.DB; using CYQ.Data.Table; namespace Aries.Core.Extend { /// <summary> /// 跨库处理 /// </summary> public static partial class CrossDb { #region 预处理所有表结构缓存 private static bool isFirstLoad = false; private static readonly object obj = new object(); private static FileSystemWatcher fyw = new FileSystemWatcher(SqlCode.path, "*.sql"); internal static void PreLoadAllDBSchemeToCache() { if (!isFirstLoad) { isFirstLoad = true; lock (obj) { if (isFirstLoad) { //DealUpdateSql(); //处理单表 foreach (ConnectionStringSettings item in ConfigurationManager.ConnectionStrings) { string name = item.Name.ToLower(); if (!string.IsNullOrEmpty(name) && name.EndsWith("conn")) { try { CacheManage.PreLoadDBSchemaToCache(name, true); } catch { } } } ThreadBreak.AddGlobalThread(new ParameterizedThreadStart(LoadViewSchema)); //处理视图文件 fyw.EnableRaisingEvents = true; fyw.Changed += fyw_Changed; } } } } static void fyw_Changed(object sender, FileSystemEventArgs e) { SqlCode.FileList = null; } static void LoadViewSchema(object para) { try { Dictionary<string, string> fileList = SqlCode.FileList; if (fileList != null && fileList.Count > 0) { foreach (KeyValuePair<string, string> item in fileList) { if (item.Key.StartsWith("V_"))//视图文件 { string sql = ""; if (item.Value.Contains(":\\"))//存档的是文件路径 { sql = SqlCode.GetCode(item.Key); } else { sql = item.Value; } if (sql.IndexOf('@') == -1)//仅处理无参数的。 { DBTool.GetColumns(sql, GetConn(sql)); } } } } } catch { } } #endregion public static object GetEnum(string objName) { if (objName == null || DbTables.Count < 2) { return objName; } int index = objName.LastIndexOf(')'); if (index == -1)//单表。 { if (objName.IndexOf('.') > -1) { return objName; } string dbName = GetDBName(objName); if (dbName != "") { return dbName + "." + objName; } } else // 自定义视图语句 { string tName = GetTableNameFromObjName(objName); if (tName != "") { string dbName = GetDBName(tName); if (dbName != "") { return objName.Substring(0, index + 1) + " " + dbName + "." + objName.Substring(index + 1).Trim(); } } } return objName; } private static Dictionary<string, string> _ConnDic = new Dictionary<string, string>(); private static Dictionary<string, DalType> _DbTypeDic = new Dictionary<string, DalType>(); private static Dictionary<string, Dictionary<string, string>> _DbTablesDic = new Dictionary<string, Dictionary<string, string>>(); private static object lockObj = new object(); private static string badConn = string.Empty; /// <summary> /// 所有数据库的表 /// </summary> public static Dictionary<string, Dictionary<string, string>> DbTables { get { if (_DbTablesDic.Count == 0) { lock (lockObj) { if (_DbTablesDic.Count == 0) { foreach (ConnectionStringSettings item in ConfigurationManager.ConnectionStrings) { string name = item.Name.ToLower(); if (!string.IsNullOrEmpty(name) && name.EndsWith("conn") && !badConn.Contains("," + name)) { if (DBTool.TestConn(name)) { string dbName = string.Empty; Dictionary<string, string> dic = DBTool.GetTables(name, out dbName); if (dic != null && dic.Count > 0 && !_DbTablesDic.ContainsKey(dbName)) { _DbTablesDic.Add(dbName, dic); _DbTypeDic.Add(dbName, DBTool.GetDalType(name)); _ConnDic.Add(dbName, name); } } else { badConn = "," + name; } } } } } } return _DbTablesDic; } } /// <summary> /// 获得数据库名称 /// </summary> /// <param name="tableName">表名</param> /// <returns></returns> public static string GetDBName(string tableName) { foreach (KeyValuePair<string, Dictionary<string, string>> item in DbTables) { if (item.Value.ContainsKey(tableName)) { return item.Key; } } //找不到时,可能是视图,根据数据库类型匹配第一个可能的数据库 foreach (KeyValuePair<string,DalType> item in _DbTypeDic) { switch (item.Value) { case DalType.Txt: case DalType.Xml: continue; default: return item.Key; } } return ""; } /// <summary> /// 获得数据库链接 /// </summary> /// <param name="sqlOrTableName">表名或sql</param> /// <returns></returns> public static string GetConn(string sqlOrTableName) { string tableName = GetTableNameFromObjName(sqlOrTableName); string dbName = GetDBName(tableName); if (!string.IsNullOrEmpty(dbName) && _ConnDic.ContainsKey(dbName)) { return _ConnDic[dbName]; } return AppConfig.DB.DefaultConn; } /// <summary> /// 获得数据库类型 /// </summary> /// <param name="tableName">表名</param> /// <returns></returns> public static DalType GetDalType(string tableName) { string dbName = GetDBName(tableName); if (!string.IsNullOrEmpty(dbName) && _DbTypeDic.ContainsKey(dbName)) { return _DbTypeDic[dbName]; } return DBTool.GetDalType(AppConfig.DB.DefaultConn); } internal static string GetDescription(string tableName) { foreach (KeyValuePair<string, Dictionary<string, string>> item in DbTables) { if (item.Value.ContainsKey(tableName)) { return item.Value[tableName]; } } return ""; } private static string GetTableNameFromObjName(string objName) { int index = objName.LastIndexOf(')'); if (index > -1) { string vName = objName.Substring(index + 1).Trim(' ');// v_xxx if (vName.IndexOf('.') == -1) // xxx.v_xxx 的不处理 { return GetTableNameFromSql(objName); } return objName; } return GetTableNameFromSql(objName); } private static string GetTableNameFromSql(string sql) { //获取原始表名 string[] items = sql.Replace("\r\n"," ").Split(' '); if (items.Length == 1) { return sql; }//单表名 if (items.Length > 3) // 总是包含空格的select * from xxx { bool startFrom = false; foreach (string item in items) { if (!string.IsNullOrEmpty(item)) { if (item.ToLower() == "from") { startFrom = true; } else if (startFrom) { if (item[0] == '(' || item.IndexOf('.') > -1) { startFrom = false; } else { return item; } } } } return ""; } return sql; } } public static partial class CrossDb { } }
 #region Aliases using System.Globalization; using RipplerES.CommandHandler; using Result = RipplerES.CommandHandler.IAggregateCommandResult<RipplerAccountTest.AccountAggregate.Account>; #endregion namespace RipplerAccountTest.AccountAggregate { [FriendlyName(name: "Account")] public class Account: AggregateBase<Account>, ISnapshotable { public double _balance = 0; public Result Execute(Deposit command) { return Success(new Deposited(amount: command.Amount)); } public void Apply(Deposited @event) { _balance += @event.Amount; } public Result Execute(Withdraw command) { if(_balance - command.Amount > 0) return Success(new Withdrawn(amount: command.Amount )); return Error(new InsufficientFunds()); } public Result Execute(SetAccountFriendlyName command) { return Success(new AccountFriendlyNameSet(name: command.Name)); } public void Apply(Withdrawn @event) { _balance -= @event.Amount; } #region Snapshotable public string TakeSnapshot() { return _balance.ToString(CultureInfo.InvariantCulture); } public void RestoreFromSnapshot(string snapshot) { if (!string.IsNullOrWhiteSpace(snapshot)) _balance = double.Parse(snapshot); } #endregion } }
using System; namespace cn.bmob.io { /// <summary> /// BmobRole角色管理类 /// </summary> public class BmobRole : BmobTable { /// <summary> /// 获取表名 /// </summary> public override string table { get { return "_Role"; } } /// <summary> /// /// </summary> public String name { get; set; } public BmobRole AddUsers(BmobRelation<BmobUser> value) { AddRelation("users", value); return this; } public BmobRole RemoveUsers(BmobRelation<BmobUser> value) { RemoveRelation("users", value); return this; } /// <summary> /// 一个角色可以包含另一个,可以为 2 个角色建立一个父-子关系。 这个关系的结果就是任何被授予父角色的权限隐含地被授予子角色。 /// /// 这样的关系类型通常在用户管理的内容类的应用上比较常见, 比如在论坛中,有一些少数的用户是 "管理员(Administartors)", 有最高的权限,可以调整系统设置、 创建新的论坛等等。 另一类用户是 "版主(Moderators)",他们可以对用户发帖的内容进行管理。可见,任何有管理员权限的人都应该有版主的权限。为建立起这种关系, 您应该把 "Administartors" 的角色设置为 "Moderators" 的子角色, 具体来说就是把 "Administrators" 这个角色加入 "Moderators" 对象的 roles 关系之中 /// </summary> public BmobRole AddRoles(BmobRelation<BmobRole> value) { AddRelation("roles", value); return this; } public BmobRole RemoveRoles(BmobRelation<BmobRole> value) { RemoveRelation("roles", value); return this; } public override void write(BmobOutput output, bool all) { base.write(output, all); output.Put("name", this.name); } public override void readFields(BmobInput input) { base.readFields(input); this.name = input.getString("name"); } } }
namespace E01_DayOfWeekService { using System; using System.Globalization; public class GetDayService : IGetDayService { public string GetDateBul(DateTime date) { var culture = new CultureInfo("bg-BG"); return culture.DateTimeFormat.GetDayName(DateTime.Today.DayOfWeek); } } }
/* * Copyright (c) 2020 Samsung Electronics Co., Ltd. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; namespace Pedometer.Services { /// <summary> /// Service for managing app state /// </summary> public sealed class AppTerminatedService { private static AppTerminatedService _this; /// <summary> /// Initializes AppTerminatedService class /// </summary> private AppTerminatedService() { } /// <summary> /// Provides singleton instance of AppTerminatedService class /// </summary> public static AppTerminatedService Instance { get { if (_this == null) { _this = new AppTerminatedService(); } return _this; } } /// <summary> /// Event invoked when app is terminated /// </summary> public event EventHandler Terminated; /// <summary> /// Invokes Terminated event /// </summary> public void Terminate() { Terminated?.Invoke(this, EventArgs.Empty); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class scrGetCompInParentTest : MonoBehaviour { // Use this for initialization void Start () { Debug.Log("en utilisant la méthode propre, ça donne : " + GetComponentInParent<BoxCollider>().isTrigger); Debug.Log("en utilisant la méthode sale, ça donne : " + transform.parent.GetComponent<BoxCollider>().isTrigger); } // Update is called once per frame void Update () { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(fileName = "Investment", menuName = "ScriptableObjects/Investment", order = 1)] public class Investment_Obj : ScriptableObject { public Tag tag; public Tag[] subTags; public float estimateValue; public float max; public float min; }
using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Forms; using DevComponents.DotNetBar; using HPMS.Config; using HPMS.DB; using HPMS.Log; using HPMS.Util; using NationalInstruments.Restricted; using Newtonsoft.Json; using Tool; using _32p_analyze; namespace HPMS { public partial class frmProfile : Office2007Muti { private bool _loaded = false; private List<Project> _projects; public frmProfile() { EnableGlass = false; InitializeComponent(); } private void FastProfileLoad() { _projects = ProjectDao.Findfast(); foreach (Project project in _projects) { ButtonX button = new ButtonX(); button.Text = Tool.Encode.Decrypt(project.Pn); button.Style = eDotNetBarStyle.StyleManagerControlled; button.ColorTable = eButtonColor.OrangeWithBackground; button.Font = new Font("微软雅黑", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); button.AutoSize = true; button.Click+=buttonFastProfile_Click; flowLayoutPanel_FastprofileBtn.Controls.Add(button); } } private void buttonFastProfile_Click(object sender, EventArgs e) { ButtonX btn = (ButtonX) sender; Project findedProject = _projects.First(t => t.Pn == Encode.Encrypt(btn.Text)); SetCheckListUnchecked(); SetProject(findedProject); txt_Pn.Text = ""; } private void frmProfile_Load(object sender, EventArgs e) { if (_loaded ) { return; } _loaded = true; TestItemIni(); FastProfileLoad(); tabControl1.Appearance = TabAppearance.FlatButtons; tabControl1.ItemSize = new Size(0, 1); tabControl1.SizeMode = TabSizeMode.Fixed; foreach (TabPage tab in tabControl1.TabPages) { tab.Text = ""; } tableLayoutPanel1.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel1, true, null); tableLayoutPanel2.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel2, true, null); tableLayoutPanel4.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel4, true, null); cmb_ILDSpec.SelectedIndex = 0; } private void itemPanel_category_ItemClick(object sender, EventArgs e) { ButtonItem button = sender as ButtonItem; if (button == null) return; tabControl1.SelectTab("tabPage_" + button.Text); } private bool TestItemIni() { TestItem testItem = (TestItem)LocalConfig.GetObjFromXmlFile("config\\testitem.xml", typeof(TestItem)); chkList_Diff.Items.Clear(); chkList_Single.Items.Clear(); chkList_TDR.Items.Clear(); chkList_SPair.Items.Clear(); chkList_NextPair.Items.Clear(); chkList_FextPair.Items.Clear(); foreach (string temp in testItem.Diff) { chkList_Diff.Items.Add(temp, false); } foreach (string temp in testItem.Single) { chkList_Single.Items.Add(temp, false); } foreach (string temp in testItem.Tdr) { chkList_TDR.Items.Add(temp, false); } foreach (string temp in testItem.DiffPair) { chkList_SPair.Items.Add(temp, false); } foreach (string temp in testItem.NextPair) { chkList_NextPair.Items.Add(temp, false); } foreach (string temp in testItem.FextPair) { chkList_FextPair.Items.Add(temp, false); } foreach (string temp in testItem.Speed) { cmbSpeed.Items.Add(temp); } foreach (string temp in testItem.ProductType) { cmbTypeL.Items.Add(temp); cmbTypeR.Items.Add(temp); } foreach (string temp in testItem.Power) { cmbPower.Items.Add(temp); } return true; } private void btn_SpecFreFileBrowse_Click(object sender, EventArgs e) { string filter = "表格|*.xls;*.xlsx";//打开文件对话框筛选器 FileBrowseCallback(filter, delegate(string fileName) { string strPath = fileName; txt_FreSpecFilePath.Text = strPath; dgv_SpecFre.Columns.Clear(); DataTable temp = EasyExcel.GetSpecifiedTable(strPath); dgv_SpecFre.DataSource = temp; dgv_SpecFre.Columns[0].Name = ""; }); } private void frmProfile_FormClosing(object sender, FormClosingEventArgs e) { Hide(); e.Cancel = true; } private void btnSave_Click(object sender, EventArgs e) { SaveProfile(); } private static bool CheckValueInRange(NumericUpDown numBox,int min,int max) { return (numBox.Value < max)&&(numBox.Value>min); } readonly Func<NumericUpDown,int,int,bool> _dFunc=CheckValueInRange; private string GetDescription() { string speed = cmbSpeed.GetValue(); string productTypeL = cmbTypeL.GetValue(); string productTypeR = cmbTypeR.GetValue(); string power = cmbPower.GetValue(); int awg = (int)num_AWG.Value; int length = (int)num_Length.Value; return String.Format("{0} {1} to {2} {3} Cable Assembly {4}AWG {5}mm", speed, productTypeL, productTypeR,power,awg,length); } private void SaveProfile() { try { //MessageBox.Show(cmbPower.GetValue()); Project pnProject = new Project(); pnProject.Awg = num_AWG.GetNumVali<int>(1,40,_dFunc); pnProject.Length = num_Length.GetNumVali<int>(1, 10000, _dFunc); pnProject.PnCustomer = txt_PnCustomer.GetTextVali(); pnProject.Customer = txt_Customer.GetTextVali(); pnProject.Pn = txt_Pn.GetTextVali(); pnProject.Diff = GetlistboxValue(chkList_Diff); pnProject.Single = GetlistboxValue(chkList_Single); pnProject.Tdr = GetlistboxValue(chkList_TDR); pnProject.DiffPair = GetlistboxValue(chkList_SPair); pnProject.NextPair = GetlistboxValue(chkList_NextPair); pnProject.FextPair = GetlistboxValue(chkList_FextPair); pnProject.ReportTempletePath = txt_ReportTempletePath.GetTextVali(); pnProject.RomFileMode = GetRomFileMode(); pnProject.RomWrite = chk_RomWrite.Checked; pnProject.RomFilePath = txt_RomFilePath.GetTextVali(); pnProject.SwitchFilePath = txt_SwitchFilePath.GetTextVali(); pnProject.FreSpec = Serializer.Datatable2Json((DataTable)dgv_SpecFre.DataSource); pnProject.FrePoints = num_FrePoints.GetNumVali<int>(1, 20000, _dFunc); pnProject.FreSpecFilePath = txt_FreSpecFilePath.GetTextVali(); TdrParam[] tdrParamTemp = GetTdrParam(); pnProject.Tdd11 = tdrParamTemp[0]; pnProject.Tdd22 = tdrParamTemp[1]; pnProject.Ild = (IldSpec)Enum.Parse(typeof(IldSpec), cmb_ILDSpec.SelectedItem.ToString(), true); pnProject.Skew = (double)num_Skew.Value; pnProject.Speed = cmbSpeed.GetValue(); pnProject.ProductTypeL = cmbTypeL.GetValue(); pnProject.ProductTypeR = cmbTypeR.GetValue(); pnProject.Power = cmbPower.GetValue(); pnProject.Description = GetDescription(); pnProject.CalFilePath = txt_CalFilePath.Text; pnProject.KeyPoint = GetKeypoint(); string msg = ""; if (ProjectHelper.Find(pnProject.Pn) != null) { var key = Ui.MessageBoxYesNoMuti("确定覆盖当前料号吗?"); if (key == DialogResult.Yes) { SaveProfile(pnProject, true, ref msg); } else { return; } } else { SaveProfile(pnProject,false, ref msg); } Ui.MessageBoxMuti(msg); } catch (Exception e) { LogHelper.WriteLog("保存料号时参数异常",e); } } private bool SaveProfile(Project pnProject, bool replace,ref string msg) { bool ret = false; msg = "保存料号档案到数据库成功"; if (replace) { ret = ProjectDao.Update(pnProject, ref msg); } else { ret = ProjectDao.Add(pnProject, ref msg); } return ret; } private void LoadProfile() { string pn = txt_Pn.GetTextVali(); Project pnProject = ProjectHelper.Find(pn); if (pnProject == null) { Ui.MessageBoxMuti("未能找到对应的料号档案"); return; } Ui.MessageBoxMuti("成功找到对应的料号档案"); SetProject(pnProject); } private void SetProject(Project pnProject) { num_AWG.Value = pnProject.Awg; num_Length.Value = pnProject.Length; txt_PnCustomer.Text = pnProject.PnCustomer; txt_Customer.Text = pnProject.Customer; txt_Pn.Text = pnProject.Pn; SetlistboxValue(chkList_Diff, pnProject.Diff); SetlistboxValue(chkList_Single, pnProject.Single); SetlistboxValue(chkList_TDR, pnProject.Tdr); SetlistboxValue(chkList_SPair, pnProject.DiffPair); SetlistboxValue(chkList_NextPair, pnProject.NextPair); SetlistboxValue(chkList_FextPair, pnProject.FextPair); txt_ReportTempletePath.Text = pnProject.ReportTempletePath; SetRomFileMode(pnProject.RomFileMode); chk_RomWrite.Checked = pnProject.RomWrite; txt_RomFilePath.Text = pnProject.RomFilePath; txt_SwitchFilePath.Text = pnProject.SwitchFilePath; txt_CalFilePath.Text = pnProject.CalFilePath; dgv_SpecFre.Columns.Clear(); dgv_SpecFre.DataSource = Serializer.Json2DataTable(pnProject.FreSpec); dgv_SpecFre.Columns[0].Name = ""; num_FrePoints.Value = pnProject.FrePoints; txt_FreSpecFilePath.Text = pnProject.FreSpecFilePath; SetTdrParam(new[] { pnProject.Tdd11, pnProject.Tdd22 }); cmb_ILDSpec.SelectedIndex = cmb_ILDSpec.FindString(pnProject.Ild.ToString()); num_Skew.Value = (decimal)pnProject.Skew; cmbSpeed.SelectedIndex = cmbSpeed.FindString(pnProject.Speed); cmbTypeL.SelectedIndex = cmbTypeL.FindString(pnProject.ProductTypeL); cmbTypeR.SelectedIndex = cmbTypeR.FindString(pnProject.ProductTypeR); cmbPower.SelectedIndex = cmbPower.FindString(pnProject.Power); SetKeypoint(pnProject.KeyPoint); } private TdrParam[] GetTdrParam() { TdrParam[]ret=new TdrParam[2]; TdrParam tdd11=new TdrParam(); tdd11.StartTime = (double)num_StartTime1.Value; tdd11.EndTime = (double)num_StopTime1.Value; tdd11.Points = (int)num_TdrPoint1.Value; tdd11.RiseTime = (double)num_RiseTime1.Value; tdd11.Offset = (double)num_TdrOffset1.Value; tdd11.UperTimePoints = new[] { (double)num_UpperMatingStartTime1.Value, (double)num_UpperCableStartTime1.Value }; tdd11.UperResi = new[] { (double)num_UpperMatingSpec1.Value, (double)num_UpperCableSpec1.Value }; tdd11.LowerTimePoints = new[] { (double)num_LowerMatingStartTime1.Value, (double)num_LowerCableStartTime1.Value }; tdd11.LowerResi = new[] { (double)num_LowerMatingSpec1.Value, (double)num_LowerCableSpec1.Value }; TdrParam tdd22 = new TdrParam(); tdd22.StartTime = (double)num_StartTime2.Value; tdd22.EndTime = (double)num_StopTime2.Value; tdd22.Points = (int)num_TdrPoint2.Value; tdd22.RiseTime = (double)num_RiseTime2.Value; tdd22.Offset = (double)num_TdrOffset2.Value; tdd22.UperTimePoints = new[] { (double)num_UpperMatingStartTime2.Value, (double)num_UpperCableStartTime2.Value }; tdd22.UperResi = new[] { (double)num_UpperMatingSpec2.Value, (double)num_UpperCableSpec2.Value }; tdd22.LowerTimePoints = new[] { (double)num_LowerMatingStartTime2.Value, (double)num_LowerCableStartTime2.Value }; tdd22.LowerResi = new[] { (double)num_LowerMatingSpec2.Value, (double)num_LowerCableSpec2.Value }; ret[0] = tdd11; ret[1] = tdd22; return ret; } private void SetTdrParam(TdrParam[] tdrParams) { num_StartTime1.Value = (decimal)tdrParams[0].StartTime; num_StopTime1.Value = (decimal)tdrParams[0].EndTime; num_TdrPoint1.Value = tdrParams[0].Points; num_RiseTime1.Value = (decimal)tdrParams[0].RiseTime; num_TdrOffset1.Value = (decimal)tdrParams[0].Offset; num_UpperMatingStartTime1.Value = (decimal)tdrParams[0].UperTimePoints[0]; num_UpperCableStartTime1.Value = (decimal)tdrParams[0].UperTimePoints[1]; num_UpperMatingSpec1.Value = (decimal)tdrParams[0].UperResi[0]; num_UpperCableSpec1.Value = (decimal)tdrParams[0].UperResi[1]; num_LowerMatingStartTime1.Value = (decimal)tdrParams[0].LowerTimePoints[0]; num_LowerCableStartTime1.Value = (decimal)tdrParams[0].LowerTimePoints[1]; num_LowerMatingSpec1.Value = (decimal)tdrParams[0].LowerResi[0]; num_LowerCableSpec1.Value = (decimal)tdrParams[0].LowerResi[1]; num_StartTime2.Value = (decimal)tdrParams[1].StartTime; num_StopTime2.Value = (decimal)tdrParams[1].EndTime; num_TdrPoint2.Value = tdrParams[1].Points; num_RiseTime2.Value = (decimal)tdrParams[1].RiseTime; num_TdrOffset2.Value = (decimal)tdrParams[1].Offset; num_UpperMatingStartTime2.Value = (decimal)tdrParams[1].UperTimePoints[0]; num_UpperCableStartTime2.Value = (decimal)tdrParams[1].UperTimePoints[1]; num_UpperMatingSpec2.Value = (decimal)tdrParams[1].UperResi[0]; num_UpperCableSpec2.Value = (decimal)tdrParams[1].UperResi[1]; num_LowerMatingStartTime2.Value = (decimal)tdrParams[1].LowerTimePoints[0]; num_LowerCableStartTime2.Value = (decimal)tdrParams[1].LowerTimePoints[1]; num_LowerMatingSpec2.Value = (decimal)tdrParams[1].LowerResi[0]; num_LowerCableSpec2.Value = (decimal)tdrParams[1].LowerResi[1]; } private RomFileMode GetRomFileMode() { if (rb_DB.Checked) { return RomFileMode.DB; } return RomFileMode.Local; } private void SetRomFileMode(RomFileMode romFileMode) { if (romFileMode == RomFileMode.DB) { rb_DB.Checked = true; } else { rb_Local.Checked = true; } } private List<string> GetlistboxValue(CheckedListBox clbBox) { List<string>ret=new List<string>(); foreach (var clbBoxSelectedItem in clbBox.CheckedItems) { ret.Add(clbBoxSelectedItem.ToString()); } return ret; } private void SetlistboxValue(CheckedListBox clbBox,List<string>selectedValues) { foreach (var VARIABLE in selectedValues) { int indexFind = clbBox.FindString(VARIABLE); if (indexFind != -1) { clbBox.SetItemChecked(indexFind,true); } } } private void chkTdr2Same_CheckValueChanged(object sender, EventArgs e) { if (chkTdr2Same.Checked) { num_StartTime2.Value = num_StartTime1.Value; num_StopTime2.Value = num_StopTime1.Value; num_TdrPoint2.Value = num_TdrPoint1.Value; num_RiseTime2.Value = num_RiseTime1.Value; num_TdrOffset2.Value = num_TdrOffset1.Value; num_UpperMatingStartTime2.Value = num_UpperMatingStartTime1.Value; num_UpperCableStartTime2.Value = num_UpperCableStartTime1.Value; num_UpperMatingSpec2.Value = num_UpperMatingSpec1.Value; num_UpperCableSpec2.Value = num_UpperCableSpec1.Value; num_LowerMatingStartTime2.Value = num_LowerMatingStartTime1.Value; num_LowerCableStartTime2.Value = num_LowerCableStartTime1.Value; num_LowerMatingSpec2.Value = num_LowerMatingSpec1.Value; num_LowerCableSpec2.Value = num_LowerCableSpec1.Value; } } private void btnQuery_Click(object sender, EventArgs e) { SetCheckListUnchecked(); lsvSummary.Items.Clear(); LoadProfile(); } private void SetCheckListUnchecked() { for (int i = 0; i < chkList_Diff.Items.Count; i++) { chkList_Diff.SetItemChecked(i,false); } for (int i = 0; i < chkList_Single.Items.Count; i++) { chkList_Single.SetItemChecked(i, false); } for (int i = 0; i < chkList_TDR.Items.Count; i++) { chkList_TDR.SetItemChecked(i, false); } for (int i = 0; i < chkList_SPair.Items.Count; i++) { chkList_SPair.SetItemChecked(i, false); } for (int i = 0; i < chkList_NextPair.Items.Count; i++) { chkList_NextPair.SetItemChecked(i, false); } for (int i = 0; i < chkList_FextPair.Items.Count; i++) { chkList_FextPair.SetItemChecked(i, false); } } private void btnDel_Click(object sender, EventArgs e) { try { string pn = txt_Pn.GetTextVali(); var key = Ui.MessageBoxYesNoMuti("确定删除当前料号吗?"); if (key == DialogResult.Yes) { if (ProjectHelper.Find(pn) != null) { Ui.MessageBoxMuti(DeleteProfile(pn) ? "删除料号成功" : "删除料号失败"); } else { Ui.MessageBoxMuti("未能找到对应的料号档案"); } } } catch (Exception exception) { Console.WriteLine(exception); } } private bool DeleteProfile(string pn) { return ProjectDao.Delete(pn); } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void btnBrowseReport_Click(object sender, EventArgs e) { string filter = "表格|*.xls;*.xlsx";//打开文件对话框筛选器 FileBrowseCallback(filter, delegate(string fileName) { txt_ReportTempletePath.Text = fileName; }); } private void btnBrowseRomTemplete_Click(object sender, EventArgs e) { string filter = @"txt|*.txt|bin|*.bin"; FileBrowseCallback(filter, delegate(string fileName) { txt_RomFilePath.Text = fileName; }); } private void btnBrowseSwitch_Click(object sender, EventArgs e) { string filter = @"txt|*.txt"; FileBrowseCallback(filter, delegate(string fileName) { txt_SwitchFilePath.Text = fileName; }); } private void FileBrowseCallback(string filter,Action<string> action) { OpenFileDialog ofd = new OpenFileDialog {Filter = filter}; if (ofd.ShowDialog() == DialogResult.OK) { action.Invoke(ofd.FileName); } } private void chkDBMode_CheckedChanged(object sender, EventArgs e) { ProjectDao.DbMode = chkDBMode.Checked; } private void btnBrowseCalFile_Click(object sender, EventArgs e) { string filter = @"CSA|*.csa"; FileBrowseCallback(filter, delegate(string fileName) { txt_CalFilePath.Text = fileName; }); } private void txt_Pn_KeyDown(object sender, KeyEventArgs e) { if (e.KeyCode == Keys.Enter) { btnQuery.PerformClick(); } } private void btnSummaryAdd_Click(object sender, EventArgs e) { if (lsvSummary.Items.Count > 20) { Ui.MessageBoxMuti("最多只能添加20个频点"); return; } ListViewItem lvi = new ListViewItem(); lvi.Text = numSummaryKeypoint.Value.ToString(); lsvSummary.Items.Add(lvi); } private void btnSummaryClear_Click(object sender, EventArgs e) { lsvSummary.Items.Clear(); } private void btnSummaryDel_Click(object sender, EventArgs e) { foreach (ListViewItem lvi in lsvSummary.SelectedItems) //选中项遍历 { lsvSummary.Items.RemoveAt(lvi.Index); // 按索引移除 //listView1.Items.Remove(lvi); //按项移除 } } private string GetKeypoint() { List<string>keyList=new List<string>(); foreach (ListViewItem lvi in lsvSummary.Items) { keyList.Add(lvi.Text); } return JsonConvert.SerializeObject(keyList); } private void SetKeypoint(string keyList) { List<string> key = JsonConvert.DeserializeObject<List<string>>(keyList); lsvSummary.Items.Clear(); if(key==null) return; foreach (var variable in key) { ListViewItem lvi = new ListViewItem(); lvi.Text = variable; lsvSummary.Items.Add(lvi); } } } }
using ConsoleApp.Core; using ConsoleApp.Core.Interfaces; using System; using System.Collections.Generic; using System.Text; namespace ConsoleApp { public class Process { IFenwicktree FTree; int[] freq = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9}; private readonly int n = 0; public Process(IFenwicktree ftree) { n = freq.Length; FTree = ftree; } public void Start() { FTree.constructBITree(freq, n); Console.WriteLine("La suma de elementos en arr[0..5]" + " es " + FTree.getSum(5)); // Actualizar BIT para el cambio anterior en arr[] freq[3] += 6; FTree.updateBIT(n, 3, 6); // Se obtiene la suma despues de que el valor se actualiza Console.WriteLine("La suma de los elementos en arr[0..5]" + " despues de actualizar es: " + FTree.getSum(5)); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class LeftHandController : MonoBehaviour { private SteamVR_TrackedObject trackedObj; public float m_Speed = 2.0F; public float m_TurnSpeed = 2.0F; public float gravity = 20.0F; private float m_MovementInputValue; private float m_TurnInputValue; public GameObject tollary; private Vector3 position = Vector3.zero; private Valve.VR.EVRButtonId touchpad = Valve.VR.EVRButtonId.k_EButton_SteamVR_Touchpad; public CharacterController person;//人称控制器改名为person private Vector3 moveDirection = Vector3.zero; //不要撞墙 public int Limit = 50; private List<Vector3> HistoryPos; private List<Quaternion> HistoryRot; private bool timebreak = false; public int time = 1; private void Start() { //controller = GetComponent<CharacterController>();//为什么这个注释掉 HistoryPos = new List<Vector3>(); HistoryRot = new List<Quaternion>(); } private SteamVR_Controller.Device Controller { get { return SteamVR_Controller.Input((int)trackedObj.index); } } void Awake() { trackedObj = GetComponent<SteamVR_TrackedObject>(); } // Update is called once per frame void Update () { if (timebreak == true)//1 { TimeBack(); } else { if (Controller.GetTouch(touchpad))//2-----------1和2可能会调下顺序 { m_TurnInputValue = Controller.GetAxis().y; m_MovementInputValue = Controller.GetAxis().x; if (tollary.GetComponent<Tmove>().touch == 0) { person.transform.Rotate(0, m_MovementInputValue * m_TurnSpeed, 0); Vector3 forward = person.transform.TransformDirection(Vector3.forward); float curSpeed = m_Speed * m_TurnInputValue; person.SimpleMove(forward * curSpeed); position = person.GetComponent<Transform>().position; Quaternion rot = transform.rotation; HistoryPos.Add(position); HistoryRot.Add(rot); if (HistoryPos.Count > Limit) { HistoryPos.RemoveAt(0); HistoryRot.RemoveAt(0); } } else { timebreak = true; } } } } void TimeBack() { // Debug.Log("我想知道运行几次 " + time); if (HistoryPos.Count > 0) { int index = HistoryPos.Count - time; person.GetComponent<Transform>().position = HistoryPos[index]; HistoryPos.RemoveAt(index); } if (HistoryRot.Count > 0) { int index = HistoryRot.Count - time; //person.GetComponent<Transform>().rotation = HistoryRot[index]; this.transform.rotation = HistoryRot[index]; //键盘控制里的情况是这样 HistoryRot.RemoveAt(index); } timebreak = false; } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Console2.From_076_To_100 { public class _087_ValidParentheses { /* * Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not. */ public bool IsValidParentheses(string str) { Stack<char> s = new Stack<char>(); for (int i = 0; i < str.Length; i++) { if (str[i] == '(' || str[i] == '[' || str[i] == '{') { s.Push(str[i]); } else { switch (str[i]) { case '}': if (s.Pop() != '{') return false; break; case ')': if (s.Pop() != '(') return false; break; case ']': if (s.Pop() != '[') return false; break; default: return false; } } } return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data; using System.Collections; using HSoft.SQL; using OboutInc.Calendar2; public partial class Pages_Contact_overview : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { HSoft.SQL.SqlServer _sql = new SqlServer(System.Configuration.ConfigurationManager.ConnectionStrings["ClientManager"].ConnectionString); String ssql = String.Format("SELECT TOP {0} " + " c.Id,c.Number, c.FirstName, c.LastName, c.OrigEntryDate, AssignedToId, " + " e.Email, p.Number PhoneNumber, " + " l.CallLaterDate, emp.FirstName empFirstName, emp.LastName empLastName, " + " nc.Note cNote,ne.Note eNote " + " FROM Customer c " + " INNER JOIN Email e ON c.Id = e.CustomerId AND e.[Primary] = 1 AND e.isdeleted = 0 " + " INNER JOIN Lead l ON c.Id = l.CustomerId AND e.isdeleted = 0 " + " INNER JOIN Employee emp ON emp.Id = l.AssignedToId AND emp.isdeleted = 0 " + " INNER JOIN PhoneNumber p ON c.Id = p.CustomerId AND p.isdeleted = 0 AND IsLead = 1 " + " INNER JOIN Note nc ON c.Id = nc.CustomerId AND nc.NoteTypeId = (SELECT Id FROM _NoteType WHERE isCustomer=1 AND isEmployee = 0) " + " INNER JOIN Note ne ON c.Id = ne.CustomerId AND ne.NoteTypeId = (SELECT Id FROM _NoteType WHERE isCustomer=1 AND isEmployee = 1 AND isPrivate=0) " + " WHERE e.isdeleted = 0 " + // " AND Priority = 'f00563e9-b454-42c6-8257-476a702efabf' " + // " AND AssignedToId = '7D5AA961-5478-4FA1-B5DB-D6A2071ED834' " + " ORDER BY OrigEntryDate DESC, Id " + "", 2); DataTable table = _sql.GetTable(ssql); ssql = "SELECT * FROM _LeadEmail WHERE isdeleted = 0 ORDER BY shortCode"; DataTable tablelead = _sql.GetTable(ssql); ssql = "SELECT l.Id,MasterId,SlaveId,FirstName,LastName FROM _LeadSalesmanPath l,Employee e WHERE l.isdeleted = 0 AND e.isdeleted = 0 AND l.SlaveId = e.Id ORDER BY MasterId"; DataTable tableleadsale = _sql.GetTable(ssql); ssql = String.Format("SELECT * FROM LeadEmail WHERE isdeleted = 0 ",""); DataTable tableleademail = _sql.GetTable(ssql); ssql = String.Format("SELECT * FROM Employee", ""); DataTable tableemployee = _sql.GetTable(ssql); foreach (DataRow dr in table.Rows) { TableRow r = new TableRow(); TableCell c = new TableCell(); c.Controls.Add(new LiteralControl(dr["Number"].ToString())); r.Cells.Add(c); c = new TableCell(); c.Controls.Add(new LiteralControl(dr["Email"].ToString())); r.Cells.Add(c); c = new TableCell(); c.Controls.Add(new LiteralControl(dr["PhoneNumber"].ToString())); r.Cells.Add(c); c = new TableCell(); c.Controls.Add(new LiteralControl(String.Format("{0} {1}", dr["FirstName"].ToString().Trim(), dr["LastName"].ToString().Trim()).Replace(" ", "&nbsp;"))); r.Cells.Add(c); c = new TableCell(); c.Controls.Add(new LiteralControl(String.Format("{0:yyyy-MM-dd HH:mm:ss}", dr["OrigEntryDate"]).Replace(" ", "&nbsp;").Replace("-", "&#8209;"))); r.Cells.Add(c); c = new TableCell(); TextBox t = new TextBox(); t.Columns = 10; t.ID = String.Format("{0}_{1}", dr["Id"], "dp"); OboutInc.Calendar2.Calendar ca = new OboutInc.Calendar2.Calendar(); ca.DatePickerMode = true; ca.TextBoxId = t.ID; ca.Enabled = true; ca.DateMin = DateTime.Now; ca.MultiSelectedDates = false; ca.DatePickerSynchronize = true; ca.DatePickerImagePath = @"..\Images\Calendar\styles\date_picker1.gif"; ca.AllowDeselect = true; ca.ValidateRequestMode = System.Web.UI.ValidateRequestMode.Disabled; ca.ShowTimeSelector = false; ca.DateFormat = "MM/dd/yyyy"; if (dr["CallLaterDate"].ToString().Length != 0) { t.Text = String.Format("{0:MM/dd/yyyy}",dr["CallLaterDate"]); } if (dr["CallLaterDate"].ToString().Length != 0) { ca.SelectedDate = DateTime.Parse(dr["CallLaterDate"].ToString()); } c.Controls.Add(t); c.Controls.Add(ca); r.Cells.Add(c); //c = new TableCell(); //DropDownList d = new DropDownList(); //SortedList sl = new SortedList(10); //DataRow dl2 = tableemployee.Select(String.Format("Id = '{0}'", dr["AssignedToId"]))[0]; //d.Items.Add(new ListItem(String.Format("{0} {1}", dl2["FirstName"], dl2["LastName"]), dr["AssignedToId"].ToString())); //foreach (DataRow dl in tableleadsale.Select(String.Format("MasterId = '{0}'", Session["guser"]))) //{ // if (dl["SlaveId"].ToString() != dr["AssignedToId"].ToString()) // { // d.Items.Add(new ListItem(String.Format("{0} {1}", dl["FirstName"], dl["LastName"]), dl["SlaveId"].ToString())); // } //} //c.Controls.Add(d); //r.Cells.Add(c); c = new TableCell(); foreach (DataRow dr2 in tablelead.Rows) { Button b = new Button(); b.Text = dr2["shortCode"].ToString(); b.Visible = true; b.Width = 3; b.Enabled = (tableleademail.Select(String.Format("CustomerId='{0}' AND LeadEmailId='{1}'",dr["Id"],dr2["Id"])).GetLength(0)==0); c.Controls.Add(b); } r.Cells.Add(c); c = new TableCell(); c.Controls.Add(new LiteralControl(dr["cNote"].ToString())); r.Cells.Add(c); c = new TableCell(); c.Controls.Add(new LiteralControl(dr["eNote"].ToString())); r.Cells.Add(c); tblCustomer.Rows.Add(r); } } }
using ComplexNumbers; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace ComplexTest { [TestClass] public class TestAriphmetics { [TestMethod] public void TestSum() { var x = new ComplexNumber(3, 2); var y = new ComplexNumber(4, -5); var result = ComplexOperations.Add(x, y); Assert.AreEqual(7, result.a); Assert.AreEqual(-3, result.b); } [TestMethod] public void TestSubstaction() { var x = new ComplexNumber(3, 2); var y = new ComplexNumber(4, -5); var result = ComplexOperations.Substract(x, y); Assert.AreEqual(-1, result.a); Assert.AreEqual(7, result.b); } [TestMethod] public void TestMultiplication() { var x = new ComplexNumber(3, 2); var y = new ComplexNumber(4, -5); var result = ComplexOperations.Multiply(x, y); Assert.AreEqual(22, result.a); Assert.AreEqual(-7, result.b); } [TestMethod] public void TestDivision() { var x = new ComplexNumber(3, 2); var y = new ComplexNumber(4, -5); var result = ComplexOperations.Divide(x, y); Assert.AreEqual(2/41.0, result.a); Assert.AreEqual(23/41.0, result.b); } [TestMethod] public void TestDivisionBy0() { var x = new ComplexNumber(3, 2); var y = new ComplexNumber(0, 0); var result = ComplexOperations.Divide(x, y); Assert.AreEqual(float.NaN, result.a); Assert.AreEqual(float.NaN, result.b); } [TestMethod] public void TestSquare() { var x = new ComplexNumber(9, 4); var result = ComplexOperations.Sqr(x); Assert.AreEqual(65, result.a); Assert.AreEqual(72, result.b); } [TestMethod] public void TestSquareI() { var x = new ComplexNumber(0, 1); var result = ComplexOperations.Sqr(x); Assert.AreEqual(-1, result.a); Assert.AreEqual(0, result.b); } [TestMethod] public void TestSquareRootI() { var x = new ComplexNumber(-1, 0); var result = ComplexOperations.Sqrt(x); Assert.AreEqual(0, result.a); Assert.AreEqual(1, result.b); } } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.Dynamic; using System.Threading.Tasks; using doob.Reflectensions; using doob.Scripter; using doob.Scripter.Engine.Powershell; using doob.Scripter.Engine.Powershell.JsonConverter; using doob.Scripter.Module.ConsoleWriter; using doob.Scripter.Module.Http; using doob.Scripter.Shared; using Microsoft.Extensions.DependencyInjection; using NamedServices.Microsoft.Extensions.DependencyInjection; using Xunit; using Xunit.Abstractions; namespace PowershellCoreTests { public class UnitTest1 { private IServiceProvider ServiceProvider { get; } private readonly ITestOutputHelper _output; public UnitTest1(ITestOutputHelper output) { _output = output; Json.Converter.RegisterJsonConverter<PSObjectJsonConverter>(); Json.Converter.JsonSerializer.Error += (sender, args) => { args.ErrorContext.Handled = true; }; var sc = new ServiceCollection(); sc.AddScripter(options => options .AddPowerShellCoreEngine() .AddScripterModule<ConsoleWriterModule>() .AddScripterModule<HttpModule>() ); ServiceProvider = sc.BuildServiceProvider(); } [Fact] public async Task Test1() { var psEngine = ServiceProvider.GetRequiredNamedService<IScriptEngine>("PowerShellCore"); var psScript = "$dt = get-date"; await psEngine.ExecuteAsync(psScript); var dt = psEngine.GetValue<DateTime>("dt"); Assert.Equal(dt.Minute, DateTime.Now.Minute); } [Fact] public async Task PsObjectConverterTest() { var psEngine = ServiceProvider.GetRequiredNamedService<IScriptEngine>("PowerShellCore"); var psScript = @" $res = $PsVersionTable.PSVersion "; await psEngine.ExecuteAsync(psScript); var res = psEngine.GetValue<Version>("res"); Assert.Equal(7, res.Major); var json = Json.Converter.ToJson(res, true); _output.WriteLine(json); } [Fact] public async Task GetProcessTest() { var proc = Process.GetCurrentProcess(); var psEngine = ServiceProvider.GetRequiredNamedService<IScriptEngine>("PowerShellCore"); var psScript = @" $res = [System.Diagnostics.Process]::GetCurrentProcess() "; await psEngine.ExecuteAsync(psScript); //var j = psEngine.GetValueAsJson("res"); var res = psEngine.GetValue<Process>("res"); Assert.Equal(proc.Id, res.Id); } [Fact] public async Task TryToGetFunctionAndInvokeIt() { var psEngine = ServiceProvider.GetRequiredNamedService<IScriptEngine>("PowerShellCore"); var psScript = @" function ExecuteResponse([string]$name, [int]$age) { return ""$($name):$($age)"" } "; await psEngine.ExecuteAsync(psScript); var func = psEngine.GetFunction("ExecuteResponse"); if (func != null) { var returnValue = func.Invoke("Bernhard", 41); //var returnValue = tsEngine.InvokeFunction("ExecuteResponse", "Bernhard", 41); } } } }
using UnityEngine.UI; namespace UnityUIPlayables { public class GraphicAnimationMixerBehaviour : AnimationMixerBehaviour<Graphic, GraphicAnimationMixer, GraphicAnimationBehaviour> { } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class TargetCounter : MonoBehaviour { [SerializeField] GameObject TargetGate; // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { int childCount = transform.childCount; if (childCount == 1) { TargetGate.GetComponent<Animator>().SetTrigger("openGate"); Destroy(this.gameObject); //Prevents it from running trigger multiple times } } }
namespace CleanArchitecture.Core.DTOs { public class GetAllProductsDTO { } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Exercise4 { /* 4. Write a method that counts how many times given number appears in given array. * Write a test program to check if the method is working correctly. */ class Program { static void Main(string[] args) { int[] array = new int[20]; Console.WriteLine("Please enter number in array : "); for (int i = 0; i < array.Length; i++) { array[i] = int.Parse(Console.ReadLine()); } Console.WriteLine("Please enter number fo search in array : "); int num = int.Parse(Console.ReadLine()); Console.WriteLine("Number {0} is found in array", Count(num, array)); } static int Count(int num, int[] array) { int count = 0; for (int i = 0; i < array.Length; i++) { if (num == array[i]) { count++; } } return count; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Xml; using System.Xml.Serialization; using System.IO; using System.Collections.ObjectModel; using WpfAppAbit2.Models; namespace WpfAppAbit2.XML { class xml { private XmlDocument doc; //private xmlContent xmlContent; private ObservableCollection<EntrantApplication> applications; private ListOfEntrantApplication appsXml; public xml(ObservableCollection<EntrantApplication> applications) { doc = new XmlDocument(); this.applications = applications; appsXml = new ListOfEntrantApplication(applications); } public void SetAuthData(string login = "", string pass = "") { } public void SetContent() { XmlSerializer xml = new XmlSerializer(typeof(ListOfEntrantApplication)); using (FileStream fs = new FileStream("apps.xml", FileMode.OpenOrCreate)) { xml.Serialize(fs, appsXml); } } //public void SetContent() //{ // XmlElement aaps = doc.CreateElement("Applications"); // int i = 0; // foreach (EntrantApplication item in applications) // { // XmlElement app = doc.CreateElement("Application"); // XmlElement uid = doc.CreateElement("UID"); // XmlText uidContent = doc.CreateTextNode(i++.ToString()); // uid.AppendChild(uidContent); // XmlElement applNum = doc.CreateElement("ApplicationNumber"); // XmlText applNumContent = doc.CreateTextNode(i++.ToString()); // uid.AppendChild(applNumContent); // XmlElement entrant = item.Entrant.GetAsXmlElement(doc); // XmlElement uid = doc.CreateElement("UID"); // XmlText uidContent = doc.CreateTextNode(i++.ToString()); // uid.AppendChild(uidContent); // XmlElement uid = doc.CreateElement("UID"); // XmlText uidContent = doc.CreateTextNode(i++.ToString()); // uid.AppendChild(uidContent); // XmlElement uid = doc.CreateElement("UID"); // XmlText uidContent = doc.CreateTextNode(i++.ToString()); // uid.AppendChild(uidContent); // } //} } }
using Raven.Abstractions; using Raven.Database.Linq; using System.Linq; using System.Collections.Generic; using System.Collections; using System; using Raven.Database.Linq.PrivateExtensions; using Lucene.Net.Documents; using System.Globalization; using System.Text.RegularExpressions; using Raven.Database.Indexing; public class Index_TimeoutsIndex : Raven.Database.Linq.AbstractViewGenerator { public Index_TimeoutsIndex() { this.ViewText = @"docs.TimeoutDatas.Select(doc => new { Time = doc.Time, SagaId = doc.SagaId, OwningTimeoutManager = doc.OwningTimeoutManager })"; this.ForEntityNames.Add("TimeoutDatas"); this.AddMapDefinition(docs => docs.Where(__document => string.Equals(__document["@metadata"]["Raven-Entity-Name"], "TimeoutDatas", System.StringComparison.InvariantCultureIgnoreCase)).Select((Func<dynamic, dynamic>)(doc => new { Time = doc.Time, SagaId = doc.SagaId, OwningTimeoutManager = doc.OwningTimeoutManager, __document_id = doc.__document_id }))); this.AddField("Time"); this.AddField("SagaId"); this.AddField("OwningTimeoutManager"); this.AddField("__document_id"); } }
namespace _3.Mankind { using System; using System.Text; public class Worker : Human { public Worker(string firstName, string lastName, double weekSalary, double hoursPerDay) : base(firstName, lastName) { this.Salary = weekSalary; this.HoursPerDay = hoursPerDay; } private double housrPerDay; private double salary; public double HoursPerDay { get { return this.housrPerDay; } set { if (value < 1 || value > 12) { throw new ArgumentException("Expected value mismatch! Argument: workHoursPerDay"); } this.housrPerDay = value; } } public double Salary { get { return this.salary; } set { if (value <= 10) { throw new ArgumentException("Expected value mismatch! Argument: weekSalary"); } this.salary = value; } } public double GetSalaryPerHour() { return this.Salary / (this.HoursPerDay * 5); } public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"First Name: {base.FirstName}"); stringBuilder.AppendLine($"Last Name: {base.LastName}"); stringBuilder.AppendLine($"Week Salary: {this.Salary:f2}"); stringBuilder.AppendLine($"Hours per day: {this.HoursPerDay:f2}"); stringBuilder.Append($"Salary per hour: {this.GetSalaryPerHour():f2}"); return stringBuilder.ToString(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using GameSystem; public class PlayerCore2 : Comp { private void Update() { if (Input.GetKeyDown(Setter.setting.shoot2)) { tank.Shoot(); } if (Input.GetKey(Setter.setting.up2)) { tank.Drive(Vector3.up); } else if (Input.GetKey(Setter.setting.down2)) { tank.Drive(Vector3.down); } else if (Input.GetKey(Setter.setting.left2)) { tank.Drive(Vector3.left); } else if (Input.GetKey(Setter.setting.right2)) { tank.Drive(Vector3.right); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MainGhostFacialAnimationController : AnimatorParameterSetter { [SerializeField] float _tauntFrequence; float _lastCheckTime; private void FixedUpdate() { if (Time.time - _lastCheckTime > 1) { _lastCheckTime = Time.time; if (Random.Range(0f, 1f) < _tauntFrequence) { if (Random.Range(0f, 1f) < 0.65) ShowTongue(); else ShowTeeth(); } } } public void ShowTeeth() { SetTrigger("ShowTeeth"); } public void ShowTongue() { SetTrigger("ShowTongue"); } public void GetHit() { SetTrigger("GetHit"); SetTrigger("ShowTeeth"); } }
using Millo.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Millo.BLL { public class TokenToUserDbConverter { public TokenToUserDbConverter() { } public User TokenToUser(string token) { ClaimsUserManager cum = new ClaimsUserManager(); string Userid = cum.getClaimValue("Id", token); return null; } } }
using System.Text; namespace MyWeb.Module { public class Pager { public static string GetString2(string url, int recordnum, int pagesize, int currentpage) { string url2 = ""; int l = url.IndexOf("#"); if (l > -1) { if (l == 0) { url2 = url; url = ""; } else { url2 = url.Substring(l); url = url.Substring(0, l); } } StringBuilder sb = new StringBuilder(); sb.Append("<div class=\"AntPager\">"); url = url.IndexOf('?') > -1 ? url : (url + "?show=1"); int pager = recordnum % pagesize == 0 ? recordnum / pagesize : ((recordnum / pagesize) + 1); sb.Append("<span>").Append(currentpage).Append("/").Append(pager).Append("</span>"); if (currentpage > 1) { sb.Append("<a class=\"btn_prev btn\" href=\"").Append(url + "&page=" + (currentpage - 1).ToString() + url2).Append("\">上一页</a>"); } else { sb.Append("<a class=\"btn_prev_disable btn\" href=\"javascript:void(0);\">上一页</a>"); } if (currentpage < pager) { sb.Append("<a class=\"btn_next btn\" href=\"").Append(url + "&page=" + (currentpage + 1).ToString() + url2).Append("\">下一页</a>"); } else { sb.Append("<a class=\"btn_next_disable btn\" href=\"javascript:void(0);\">下一页</a>"); } sb.Append("</div>"); return sb.ToString(); } public static string GetString3(string url, int recordnum, int pagesize, int currentpage) { string url2 = ""; int l = url.IndexOf("#"); if (l > -1) { if (l == 0) { url2 = url; url = ""; } else { url2 = url.Substring(l); url = url.Substring(0, l); } } StringBuilder sb = new StringBuilder(); url = url.IndexOf('?') > -1 ? url : (url + "?show=1"); sb.Append("<div class=\"pagination\"><ul>"); if (currentpage < 2) sb.Append("<li><a href=\"javascript:void(0)\"> 上一页</a> </li>"); else sb.Append("<li><a href=\"" + url + "&page=" + (currentpage - 1).ToString() + url2 + "\"> 上一页 </a></li>"); int pager = recordnum % pagesize == 0 ? recordnum / pagesize : ((recordnum / pagesize) + 1); int p_start = 0; int p_end = 0; p_start = (currentpage / 10) * 10; p_end = p_start + 10; p_start = p_start < 1 ? 1 : p_start; p_end = p_end > pager ? pager : p_end; if (p_start > 1) { sb.Append("<li><a href=\"" + url + "&page=1" + url2 + "\">1</a></li>"); } for (int i = p_start; i <= p_end; i++) { if (i != currentpage) sb.Append("<li><a href=\"" + url + "&page=" + i.ToString() + url2 + "\">" + i.ToString() + "</a></li>"); else sb.Append("<li><a href=\"javascript:void(0)\"> " + i.ToString() + "</a></li>"); } if (p_end < pager) { sb.Append("<li><a href=\"" + url + "&page=" + pager.ToString() + url2 + "\">" + pager.ToString() + "</a></li>"); } if (currentpage < pager) { sb.Append("<li><a href=\"" + url + "&page=" + (currentpage + 1).ToString() + url2 + "\"> 下一页 </a></li>"); } else { sb.Append("<li><a href=\"javascript:void(0)\"> 下一页 </a></li>"); } sb.Append("</ul></div>"); return sb.ToString(); } public static string GetString4(string url, int recordnum, int pagesize, int currentpage) { string url2 = ""; int l = url.IndexOf("#"); if (l > -1) { if (l == 0) { url2 = url; url = ""; } else { url2 = url.Substring(l); url = url.Substring(0, l); } } StringBuilder sb = new StringBuilder(); url = url.IndexOf('?') > -1 ? url : (url + "?show=1"); sb.Append("<ul class=\"pagination\">"); if (currentpage < 2) sb.Append("<li><a href=\"javascript:void(0)\"> 上一页</a> </li>"); else sb.Append("<li><a href=\"" + url + "&page=" + (currentpage - 1).ToString() + url2 + "\"> 上一页 </a></li>"); int pager = recordnum % pagesize == 0 ? recordnum / pagesize : ((recordnum / pagesize) + 1); int p_start = 0; int p_end = 0; p_start = (currentpage / 10) * 10; p_end = p_start + 10; p_start = p_start < 1 ? 1 : p_start; p_end = p_end > pager ? pager : p_end; if (p_start > 1) { sb.Append("<li><a href=\"" + url + "&page=1" + url2 + "\">1</a></li>"); } for (int i = p_start; i <= p_end; i++) { if (i != currentpage) sb.Append("<li><a href=\"" + url + "&page=" + i.ToString() + url2 + "\">" + i.ToString() + "</a></li>"); else sb.Append("<li><a href=\"javascript:void(0)\"> " + i.ToString() + "</a></li>"); } if (p_end < pager) { sb.Append("<li><a href=\"" + url + "&page=" + pager.ToString() + url2 + "\">" + pager.ToString() + "</a></li>"); } if (currentpage < pager) { sb.Append("<li><a href=\"" + url + "&page=" + (currentpage + 1).ToString() + url2 + "\"> 下一页 </a></li>"); } else { sb.Append("<li><a href=\"javascript:void(0)\"> 下一页 </a></li>"); } sb.Append("</ul>"); return sb.ToString(); } public static string GetString(string url, int recordnum, int pagesize, int currentpage) { string url2 = ""; int l = url.IndexOf("#"); if (l > -1) { if (l == 0) { url2 = url; url = ""; } else { url2 = url.Substring(l); url = url.Substring(0, l); } } //<span class="disabled"> < </span><span class="current">1</span><a href="#">2</a><a href="#">3</a><a href="#">4</a><a href="#">5</a><a href="#">6</a><a href="#">7</a>...<a href="#">199</a><a href="#">200</a><a href="#"> > </a></div> StringBuilder sb = new StringBuilder(); url = url.IndexOf('?') > -1 ? url : (url + "?show=1"); sb.Append("<div class=\"sabrosus\">"); if (currentpage < 2) sb.Append("<span class=\"disabled\"> 上一页 </span>"); else sb.Append("<a href=\"" + url + "&page=" + (currentpage - 1).ToString() + url2 + "\"> 上一页 </a>"); int pager = recordnum % pagesize == 0 ? recordnum / pagesize : ((recordnum / pagesize) + 1); int p_start = 0; int p_end = 0; p_start = (currentpage / 10) * 10; p_end = p_start + 10; p_start = p_start < 1 ? 1 : p_start; p_end = p_end > pager ? pager : p_end; if (p_start > 1) { sb.Append("<a href=\"" + url + "&page=1" + url2 + "\">1</a>..."); } for (int i = p_start; i <= p_end; i++) { if (i != currentpage) sb.Append("<a href=\"" + url + "&page=" + i.ToString() + url2 + "\">" + i.ToString() + "</a>"); else sb.Append("<span class=\"current\">" + i.ToString() + "</span>"); } if (p_end < pager) { sb.Append("...<a href=\"" + url + "&page=" + pager.ToString() + url2 + "\">" + pager.ToString() + "</a>"); } if (currentpage < pager) { sb.Append("<a href=\"" + url + "&page=" + (currentpage + 1).ToString() + url2 + "\">▶︎</a>"); } else { sb.Append("<span class=\"disabled\">▶︎</a>"); } sb.Append("</div>"); return sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Text; namespace dynamic_configuration_parser { public class UnknownKeyException : Exception { } }
/** * Created 21/10/2020 * By: Sharek Khan * Last modified 03/12/2020 * By: Sharek Khan * * Contributors: Aswad Mirza, Sharek Khan */ using UnityEngine; /* * Myoviridae handles all the logic, AI and behaviour patterns of the Myoviridae GameObject */ public class Myoviridae : Enemy { private GameObject m_player; private Vector3 m_initialPos; private Quaternion m_initialRot; public int m_speed = 6; public int m_rushSpeed = 9; private int m_rotSpeed = 45; private string m_enemyState; private AudioSource m_source; public GameObject myoviridaeKilled; public float chargingDelta = 5f; public float chargingDistance = 5f; public float grabDistance = 3f; public float grabSpeed = 120f; private Vector3 m_lastPlayerLocation = Vector3.zero; //health public int initialHealth = 10; Rigidbody rigidbody; bool originalKinematicSetting =false; // Start is called before the first frame update void Start() { // Initializes the original position of Myoviridae m_initialPos = transform.position; // Initializes the original rotation of Myoviridae m_initialRot = transform.rotation; // Initializes the inital behaviour state of Myoviridae //m_enemyState = "IDLE"; m_enemyState = "IDLE"; m_source = GetComponent<AudioSource>(); // Retrieves the Player script through the active Player GameObject m_player = GameObject.FindGameObjectWithTag("Player"); this.Health = initialHealth; rigidbody = GetComponent<Rigidbody>(); if (rigidbody != null) { originalKinematicSetting = rigidbody.isKinematic; } } // Update is called once per frame void Update() { // Check Enemy behaviour state if(m_enemyState == "IDLE") { OnIdle(); } else if(m_enemyState == "ATTACK") { OnAttack(); } Grabbed(); } // OnTriggerEnter detects all trigger collisions on entry void OnTriggerEnter(Collider collider) { // Checks if Enemy has entered the Players vicinity bubble if (collider.gameObject.tag == "AIDetection") { Debug.Log("Myoviridae is inside Player vicinty."); // Switch enemy state to attack m_enemyState = "ATTACK"; } // Because we are using ontrigger enter in this class, it needs to be updated if (collider.GetComponent<Bullet>() != null) { // Calls an instance of the PlasmaAmmo script component Bullet bullet = collider.GetComponent<Bullet>(); // Checks if PlasmaAmmo was shot by Player if (bullet.ShotByPlayer == true) { // Queue audio for enemy taking damage if (!m_source.isPlaying && this.Health > 0) { m_source.Play(); } // Enemy takes damage TakeDamage(bullet.damage); // PlasmaAmmo will be deactivated once contact is made bullet.gameObject.SetActive(false); } } } // OnTriggerExit detects all trigger collisions on exit void OnTriggerExit(Collider collider) { // Checks if Enemy has exited the Players vicinity bubble if (collider.gameObject.tag == "AIDetection") { Debug.Log("Myoviridae is outside Player vicinty."); // Reset enemy position // transform.position = m_initialPos; transform.rotation = m_initialRot; // Switch enemy state to idle m_enemyState = "IDLE"; } } // Enemies Behaviour Patterns when not near Player void OnIdle() { // Translate enemy back and forth, while rotating around transform.Translate(Vector3.forward * m_speed * Time.deltaTime); if(transform.position.z >= (m_initialPos.z + 10)) { // Rotate Enemy transform.Rotate(Vector3.up, m_rotSpeed * Time.deltaTime); } else if (transform.position.z <= (m_initialPos.z - 10)) { // Rotate Enemy transform.Rotate(Vector3.up, m_rotSpeed * Time.deltaTime); } } // Enemies Behaviour Patterns when enter Player vicinity void OnAttack() { // Rotate in Player direction Vector3 playerDir = m_player.transform.position - transform.position; transform.rotation = Quaternion.LookRotation(playerDir); // Attack Player by rushing them with melee damage transform.position = CalculateDirection(transform.position, m_player.transform.position, m_rushSpeed); } // OnKill handles the logic for when the Myoviridae dies, in this case it calls the base class function and instantiates // the killed version of this prefab and destroys this game object protected override void OnKill() { base.OnKill(); // Kill State Debug.Log("Myoviridae is killed."); Instantiate(myoviridaeKilled, transform.position, transform.rotation); Destroy(this.gameObject); } // Grabbed handles the behaviour of the CancerCell reacts when grabbed by the Player through MeleeWeapon [Added By: Aswad Mirza] protected override void Grabbed() { if (IsGrabbed) { Debug.Log("Grabbed"); // Get the initial Kinematic value if (rigidbody != null) { rigidbody.isKinematic = true; } if (m_lastPlayerLocation.Equals(Vector3.zero)) { Debug.Log("Going to the last Player location"); m_lastPlayerLocation = m_player.transform.position; } if (Vector3.Distance(transform.position, m_lastPlayerLocation) > grabDistance) { transform.position = CalculateDirection(transform.position, m_lastPlayerLocation, grabSpeed); } else { IsGrabbed = false; m_lastPlayerLocation = Vector3.zero; if (rigidbody != null) { rigidbody.isKinematic = originalKinematicSetting; } Debug.Log("Not Grabbed Anymore"); } } } }
using System; using System.Linq.Expressions; namespace Utilities.NET.Extensions { public static class TypeExtensions { /// <summary> /// Get the default value for <see cref="Type"/>. /// </summary> /// <remarks> /// Closest thing to `default(T)` without generics. /// </remarks> /// <param name="type"> The type to get the default value of. </param> /// <returns> The default value of <see cref="Type"/>. </returns> public static object GetDefaultValue(this Type type) { // Validate parameters. if (type == null) throw new ArgumentNullException(nameof(type)); // We want an Func<object> which returns the default. // Create that expression here. var e = Expression.Lambda<Func<object>>( // Have to convert to object. Expression.Convert( // The default value, always get what the *code* tells us. Expression.Default(type), typeof(object) ) ); // Compile and return the value. return e.Compile()(); } } }
using System; using System.Runtime.InteropServices; using System.Windows.Forms; namespace Xoru.Controls { public class XoruListBox : ListBox { public event EventHandler<ScrollLimitEventArgs> ScrollLimitReached; public event EventHandler<ScrollValueEventArgs> ScrollValueChanged; private const int SB_HORZ = 0; private const int SB_VERT = 1; private const int SB_LINELEFT = 0; private const int SB_LINERIGHT = 1; private const int SB_PAGELEFT = 2; private const int SB_PAGERIGHT = 3; private const int SB_THUMBPOSITION = 4; private const int SB_THUMBTRACK = 5; private const int SB_RIGHT = 7; private const int SB_TOP = 6; private const int SB_LEFT = 6; private const int SB_BOTTOM = 7; private const int SB_ENDSCROLL = 8; protected virtual void OnScrollLimit(ScrollLimit limit) { if (ScrollLimitReached!=null) { var arg = new ScrollLimitEventArgs(limit); ScrollLimitReached(this, arg); } } protected override void WndProc(ref Message m) { base.WndProc(ref m); if (IsScrolling(m)) { InspectScrollBarAndTriggerEventIfNeeded(); } } private bool IsScrolling(Message m) { const int WM_VSCROLL = 0x0115; const int WM_MOUSEWHEEL = 0x020A; return m.Msg == WM_VSCROLL || m.Msg == WM_MOUSEWHEEL; } private void SetScrollBar() { int sizeOfFile = 10000000; int positionInFile = sizeOfFile / 2; NativeMethods.Scrollinfo scrollinfo = new NativeMethods.Scrollinfo(); scrollinfo.Size = (uint) Marshal.SizeOf(typeof(NativeMethods.Scrollinfo)); scrollinfo.Mask = (uint) Convert.ToInt32(ScrollInfoMask.SIF_ALL); scrollinfo.Min = 0; scrollinfo.Max = sizeOfFile; // for example the number of items in the control scrollinfo.Position = positionInFile; scrollinfo.Page = 1; bool redraw = true; int scrollBoxPosition = NativeMethods.SetScrollInfo(Handle, SB_VERT, ref scrollinfo, redraw);//The return value is the current position of the scroll box. } private NativeMethods.Scrollinfo? lastScrollinfo; private bool InspectScrollBarAndTriggerEventIfNeeded() { bool ret = false; NativeMethods.Scrollinfo scrollinfo = new NativeMethods.Scrollinfo { Size = (uint) Marshal.SizeOf(typeof(NativeMethods.Scrollinfo)), Mask = (uint) Convert.ToInt32(ScrollInfoMask.SIF_ALL) }; bool success = NativeMethods.GetScrollInfo(Handle, SB_VERT, ref scrollinfo); if (!success) return false; if (ScrollInfoChanged(scrollinfo)) { OnScrollValueChanged(scrollinfo); } if (scrollinfo.Position == 0) { OnScrollLimit(ScrollLimit.FirstLine); ret = true; } if (scrollinfo.Position + scrollinfo.Page - 1 == scrollinfo.Max) { OnScrollLimit(ScrollLimit.LastLine); ret = true; } lastScrollinfo = scrollinfo; return ret; } private bool ScrollInfoChanged(NativeMethods.Scrollinfo scrollinfo) { if (lastScrollinfo.HasValue == false) { return true; } if (scrollinfo.Position != lastScrollinfo.Value.Position) { return true; } return false; } private void OnScrollValueChanged(NativeMethods.Scrollinfo scrollinfo) { if (ScrollValueChanged == null) return; var value = new ScrollValueEventArgs(scrollinfo.Min, scrollinfo.Max, scrollinfo.Position); ScrollValueChanged(this, value); } } }
using Enrollment.Contexts; using LogicBuilder.EntityFrameworkCore.SqlServer.Crud.DataStores; namespace Enrollment.Stores { public class EnrollmentStore : StoreBase, IEnrollmentStore { public EnrollmentStore(EnrollmentContext context) : base(context) { } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class MidairFloat : MonoBehaviour { /// <summary> /// The float amount in the y axis. /// </summary> public float floatAmount; /// <summary> /// The duration. /// </summary> [Range(0f, 10.0f)] public float duration; /// <summary> /// represents time /// </summary> private float t; /// <summary> /// The float up. /// </summary> private bool floatUp = true; /// <summary> /// Fixeds duration between update. /// </summary> void FixedUpdate () { float yAmt = floatAmount / duration; yAmt *= Time.fixedDeltaTime; Vector3 pos = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y, gameObject.transform.position.z); if (floatUp) { pos.y += yAmt; } else { pos.y -= yAmt; } gameObject.transform.position = pos; t += Time.fixedDeltaTime; if (t > duration) { floatUp = !floatUp; t = 0; } } }
using System.Collections; using System.Collections.Generic; using System.Threading; using UnityEngine; public class crosshair : MonoBehaviour{ public float sensitivity = 180f; public Transform player1; float xRotation = 0f; //Esta variable lee constantemente la ubicación de el eje y, deberia llamarse yRotations but who cares // Start is called before the first frame update void Start() { Cursor.lockState = CursorLockMode.Locked; //Fija el cursor al centro de la ventana del juego, obvio necesario para un shooter } // Update is called once per frame void Update() { float mouseX = Input.GetAxis("Mouse X") * sensitivity * Time.deltaTime; float mouseY = Input.GetAxis("Mouse Y") * sensitivity * Time.deltaTime; //en cada cuadro actualizamos la ubicacion en X, esto moviendolo por //sensibilidad y tiempo desde el ultimo cuadro if(Mathf.Abs(mouseX) > 20 || Mathf.Abs(mouseY) > 20) //al parecer verifica si los movimientos fueron mayores a "20"-> sacado proyecto Minecraft Sam Hogan return; xRotation -= mouseY; //Actualizamos donde estamos en "y" actualmente xRotation = Mathf.Clamp(xRotation, -90f, 75f); //Clamp limita los valores de una variable dada "xRotation" transform.localRotation = Quaternion.Euler(xRotation, 0f, 0f); //RITACION EN Y player1.Rotate(Vector3.up * mouseX); //ROTACIÓN EN X } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Web; using System.Text; namespace DataLayer { public static class GeneralOperations { public static RMPEntities dbContext = new RMPEntities(); public static DataTable LINQToDataTable<T>(IEnumerable<T> varlist, int page = 0, int rowCount = 10) { DataTable dtReturn = new DataTable(); //varlist = varlist.Skip(page).Take(rowCount); // column names PropertyInfo[] oProps = null; if (varlist == null) return dtReturn; foreach (T rec in varlist) { // Use reflection to get property names, to create table, Only first time, others will follow if (oProps == null) { oProps = ((Type)rec.GetType()).GetProperties(); foreach (PropertyInfo pi in oProps) { Type colType = pi.PropertyType; if ((colType.IsGenericType) && (colType.GetGenericTypeDefinition() == typeof(Nullable<>))) { colType = colType.GetGenericArguments()[0]; } dtReturn.Columns.Add(new DataColumn(pi.Name, colType)); } } DataRow dr = dtReturn.NewRow(); foreach (PropertyInfo pi in oProps) { dr[pi.Name] = pi.GetValue(rec, null) == null ? DBNull.Value : pi.GetValue(rec, null); } dtReturn.Rows.Add(dr); } return dtReturn; } public static string GeneratePassword(string username, string website, int numberofchars, string algorithmhardness, long userId) { SaveQuery(username, website, numberofchars, algorithmhardness, userId); int hardness = 0; string generatedpassword = string.Empty; string[] usingChars = new string[4]; int[,] asciiofChars; switch (algorithmhardness) { case "Easy": hardness = 2; asciiofChars = new int[2, 2]; break; case "Medium": hardness = 3; asciiofChars = new int[3, 2]; break; case "Hard": hardness = 4; asciiofChars = new int[4, 2]; break; default: hardness = 4; asciiofChars = new int[4, 2]; break; } usingChars[0] = Constants.easychars; usingChars[1] = Constants.easynumberchars; usingChars[2] = Constants.mediumchars; usingChars[3] = Constants.hardchars; for (int i = 0; i < hardness; i++) { for (int j = 0; j < 2; j++) { asciiofChars[i, j] = 1; } } for (int i = 0; i < username.Length; i++) { asciiofChars[i % hardness, 0] *= (int)username[i]; } for (int i = 0; i < website.Length; i++) { asciiofChars[i % hardness, 1] *= (int)website[i]; } for (int i = 0; i < numberofchars; i++) { int multiple = (asciiofChars[i % hardness, 0] * asciiofChars[i % hardness, 1]); if (multiple < 0) { multiple *= -1; } char c = usingChars[i % hardness][multiple % usingChars[i % hardness].Length]; int index = generatedpassword.IndexOf(c); if (index != -1) { asciiofChars[i % hardness, 0] -= numberofchars; asciiofChars[i % hardness, 1] -= numberofchars; i--; continue; } generatedpassword += c; asciiofChars[i % hardness, 0] /= numberofchars; asciiofChars[i % hardness, 1] /= numberofchars; } return generatedpassword; } public static DataTable GetUserQueries(long userId) { var table = (from list in dbContext.GetUserSavedWebSites where list.UserId == userId select list); // && (list.Description.Contains(searchtext) || list.Name.Contains(searchtext) || list.UserName.Contains(searchtext) return LINQToDataTable(table); } public static DataTable GetUserQueries2(long userId, string searchtext) { var table = (from list in dbContext.GetUserSavedWebSites where list.UserId == userId && (list.Description.Contains(searchtext) || list.Name.Contains(searchtext) || list.UserName.Contains(searchtext)) select list); return LINQToDataTable(table); } public static string GetUserQueryById(long Id, long userId) { var table = (from list in dbContext.GetUserSavedWebSites where list.Id == Id && list.UserId == userId select list); DataTable dt = LINQToDataTable(table); return GetJSONString(dt); } public static bool SavePassQuery(string websitename, long userId, string description, string username, string name, int charcount, string algorithmlevel) { try { long websiteId = GetWebsiteId(websitename); SavedUserQuery suq = new SavedUserQuery(); suq.WebSiteId = websiteId; suq.UserId = userId; suq.UserName = username; suq.Description = description; suq.CharCount = charcount; suq.AlgorithmLevel = algorithmlevel; suq.CreatedAt = DateTime.Now; suq.Name = name; suq.ApplicationSource = "Web"; dbContext.SavedUserQueries.AddObject(suq); dbContext.SaveChanges(); return true; } catch { return false; } } private static void SaveQuery(string username, string websitename, int numberofchars, string algorithmhardness, long userId) { long websiteId = GetWebsiteId(websitename); PasswordQuery pq = new PasswordQuery(); if (userId != 0) { pq.UserId = userId; } pq.WebSiteId = websiteId; pq.UserName = username; pq.AlgorithmType = algorithmhardness; pq.CharCount = numberofchars; pq.GeneratedAt = DateTime.Now; dbContext.PasswordQueries.AddObject(pq); dbContext.SaveChanges(); } private static long GetWebsiteId(string websitename) { WebSite website = dbContext.WebSites.Where(ws => ws.Name == websitename).FirstOrDefault(); if (website == null) { website = new WebSite(); website.Name = websitename; dbContext.WebSites.AddObject(website); dbContext.SaveChanges(); } return website.Id; } public static string GetJSONString(DataTable Dt) { string[] StrDc = new string[Dt.Columns.Count]; string HeadStr = string.Empty; for (int i = 0; i < Dt.Columns.Count; i++) { StrDc[i] = Dt.Columns[i].Caption; HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\","; } HeadStr = HeadStr.Substring(0, HeadStr.Length - 1); StringBuilder Sb = new StringBuilder(); Sb.Append("{\"" + "query" + "\" : ["); for (int i = 0; i < Dt.Rows.Count; i++) { string TempStr = HeadStr; Sb.Append("{"); for (int j = 0; j < Dt.Columns.Count; j++) { TempStr = TempStr.Replace(Dt.Columns[j] + j.ToString() + "¾", Dt.Rows[i][j].ToString()); } Sb.Append(TempStr + "},"); } Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1)); Sb.Append("]}"); return Sb.ToString(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Data; using System.Windows.Forms; using ENTITY; using OpenMiracle.DAL; namespace OpenMiracle.BLL { public class SizeBll { SizeSP spSize = new SizeSP(); /// <summary> /// Function to get all values from Size Table /// </summary> /// <returns></returns> public List<DataTable> SizeViewAlling() { List<DataTable> ListObj = new List<DataTable>(); try { ListObj = spSize.SizeViewAlling(); } catch (Exception ex) { MessageBox.Show("SZ1:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return ListObj; } /// <summary> /// Function to check existence of size based on parameter /// </summary> /// <param name="strSizeName"></param> /// <param name="decSizeId"></param> /// <returns></returns> public bool SizeNameCheckExistence(String strSizeName, decimal decSizeId) { try { spSize.SizeNameCheckExistence(strSizeName, decSizeId); } catch (Exception ex) { MessageBox.Show("SZ2:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return false; } /// <summary> /// Function to insert values to Size Table and return the Curresponding row's Id /// </summary> /// <param name="infoSize"></param> /// <returns></returns> public decimal SizeAdding(SizeInfo infoSize) { decimal decSizeId = 0; try { decSizeId = spSize.SizeAdding(infoSize); } catch (Exception ex) { MessageBox.Show("SZ3:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decSizeId; } /// <summary> /// Function to Update values in Size Table and return the status /// </summary> /// <param name="infoSize"></param> /// <returns></returns> public bool SizeEditing(SizeInfo infoSize) { bool isEdit = false; try { isEdit= spSize.SizeEditing(infoSize); } catch (Exception ex) { MessageBox.Show("SZ4:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return isEdit; } /// <summary> /// Function to delete size based on parameter and return corresponding id /// </summary> /// <param name="SizeId"></param> /// <returns></returns> public decimal SizeDeleting(decimal SizeId) { decimal decId = 0; try { decId = spSize.SizeDeleting(SizeId); } catch (Exception ex) { MessageBox.Show("SZ5:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return decId; } /// <summary> /// Function to get values from Size Table based on the parameter /// </summary> /// <param name="decSizeId"></param> /// <returns></returns> public SizeInfo SizeViewing(decimal decSizeId) { SizeInfo infoSize = new SizeInfo(); try { infoSize = spSize.SizeViewing(decSizeId); } catch (Exception ex) { MessageBox.Show("SZ6:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return infoSize; } /// <summary> /// Function to get all the values from Size Table /// </summary> /// <returns></returns> public List<DataTable> SizeViewAll() { List<DataTable> ListObj = new List<DataTable>(); try { ListObj = spSize.SizeViewAll(); } catch (Exception ex) { MessageBox.Show("SZ7:" + ex.Message, "OpenMiracle", MessageBoxButtons.OK, MessageBoxIcon.Information); } return ListObj; } } }
using System; using System.Collections.Generic; using Framework.Utils; namespace Framework.Metadata { public class CxWinSectionOrder { //------------------------------------------------------------------------- private UniqueList<string> m_XmlExplicitOrderIds; private List<string> m_CustomOrderIds; private IList<string> m_XmlImplicitOrderIdsCache; private CxWinSectionsMetadata m_XmlExplicitSource; private readonly CxWinSectionsMetadata m_Metadata; //------------------------------------------------------------------------- //------------------------------------------------------------------------- /// <summary> /// Returns the custom ordered ids list. /// </summary> protected List<string> CustomOrderIds { get { return m_CustomOrderIds; } set { if (value != null) m_CustomOrderIds = new List<string>(value); else m_CustomOrderIds = null; } } //------------------------------------------------------------------------- /// <summary> /// True if custom order is used. /// </summary> public bool IsCustom { get { return CustomOrderIds != null; } } //------------------------------------------------------------------------- /// <summary> /// The source of the explicit XML order. /// </summary> protected CxWinSectionsMetadata XmlExplicitSource { get { return m_XmlExplicitSource; } set { m_XmlExplicitSource = value; } } //------------------------------------------------------------------------- /// <summary> /// Returns the sections in the actual order to be used. /// </summary> public IList<CxWinSectionMetadata> OrderSections { get { return m_Metadata.GetSectionsFromIds(OrderIds); } } //------------------------------------------------------------------------- /// <summary> /// Returns the sectins in the actual order to be used + /// all the "new" sections as well. /// </summary> public IList<CxWinSectionMetadata> OrderPlusNewSections { get { UniqueList<CxWinSectionMetadata> result = new UniqueList<CxWinSectionMetadata>(); result.AddRange(OrderSections); if (IsCustom) { foreach (string name in m_Metadata.NewSectionNames) { CxWinSectionMetadata section = m_Metadata[name]; result.Add(section); } } return result; } } //------------------------------------------------------------------------- /// <summary> /// Returns the section ids in the actual order to be used. /// </summary> public IList<string> OrderIds { get { IList<string> orderIds = GetOrderIds(); if (orderIds == null) throw new ExNullReferenceException("orderIds"); return orderIds; } } //------------------------------------------------------------------------- /// <summary> /// Xml defined order. /// </summary> public IList<string> XmlOrderIds { get { IList<string> order = XmlExplicitOrderIds; if (!CxList.IsEmpty2(order)) { return order; } return XmlImplicitOrderIds; } } //------------------------------------------------------------------------- #region Xml Implicit orders //------------------------------------------------------------------------- /// <summary> /// Returns the section order implicitly defined in the XML. /// </summary> protected IList<string> XmlImplicitOrderIds { get { if (m_XmlImplicitOrderIdsCache == null) { m_XmlImplicitOrderIdsCache = new List<string>(); IList<string> sectionIds = GetAllIdsInNaturalOrder(); foreach (string id in sectionIds) { CxWinSectionMetadata item = m_Metadata.AllItems[id]; if (CxBool.Parse(item["visible"], true)) { m_XmlImplicitOrderIdsCache.Add(id); } } } return m_XmlImplicitOrderIdsCache; } } //------------------------------------------------------------------------- #endregion #region Xml Explicit orders //------------------------------------------------------------------------- /// <summary> /// Returns ids of the sections in order of their explicit declaration. /// </summary> protected IList<string> XmlExplicitOrderIds { get { if (XmlExplicitSource != null) { return XmlExplicitSource.WinSectionOrder.XmlExplicitOrderIds; } return m_XmlExplicitOrderIds; } } //------------------------------------------------------------------------- #endregion #region Ctors //------------------------------------------------------------------------- /// <summary> /// Constructor. /// </summary> /// <param name="metadata">section metadata</param> public CxWinSectionOrder(CxWinSectionsMetadata metadata) { m_Metadata = metadata; } //------------------------------------------------------------------------- #endregion #region Methods //------------------------------------------------------------------------- /// <summary> /// Returns the ordered ids list. /// </summary> protected IList<string> GetOrderIds() { if (CustomOrderIds != null) { return CustomOrderIds; } return XmlOrderIds; } //------------------------------------------------------------------------- /// <summary> /// Returns ids of all the section in their natural order. /// </summary> /// <returns></returns> protected IList<string> GetAllIdsInNaturalOrder() { return m_Metadata.GetIdsFromSection(m_Metadata.AllItemsListWithoutHiddenForUser); } //------------------------------------------------------------------------- /// <summary> /// Sets custom order from the given comma-separated text. /// </summary> /// <param name="orderText">comma-separated text</param> public void SetCustomOrder(string orderText) { if (CxUtils.IsEmpty(CxText.TrimSpace(orderText))) { CustomOrderIds = null; } else { IList<string> resultList = CxText.RemoveEmptyStrings(CxText.DecomposeWithWhiteSpaceAndComma(orderText.ToUpper())); CustomOrderIds = new List<string>(); CustomOrderIds.AddRange(resultList); } } //------------------------------------------------------------------------- /// <summary> /// Sets XML defined order from the given comma-separated text. /// </summary> /// <param name="orderText">comma-separated text</param> public void SetXmlDefOrder(string orderText) { if (CxUtils.IsEmpty(CxText.TrimSpace(orderText))) return; IList<string> resultList = CxText.RemoveEmptyStrings(CxText.DecomposeWithWhiteSpaceAndComma(orderText.ToUpper())); m_XmlExplicitOrderIds = new UniqueList<string>(StringComparer.OrdinalIgnoreCase); m_XmlExplicitOrderIds.AddRange(resultList); SetXmlDefSource(m_Metadata); } //------------------------------------------------------------------------- /// <summary> /// Sets source for the XML defined section order. /// </summary> /// <param name="source">source for the section order</param> protected void SetXmlDefSource(CxWinSectionsMetadata source) { if (source != m_Metadata) { if (m_XmlExplicitOrderIds != null) { m_XmlExplicitSource = null; return; } m_XmlExplicitSource = source; } else { m_XmlExplicitSource = null; } } //------------------------------------------------------------------------- /// <summary> /// Resets order to XML defined order. /// </summary> public void ResetToDefault() { CustomOrderIds = null; } //------------------------------------------------------------------------- #endregion } }
using System; using System.Text; using System.Collections.Generic; using Newtonsoft.Json; using NHibernate; using NHibernate.Cfg; using NHibernate.Criterion; using NHibernate.Exceptions; using LePapeoGenNHibernate.Exceptions; using LePapeoGenNHibernate.EN.LePapeo; using LePapeoGenNHibernate.CAD.LePapeo; namespace LePapeoGenNHibernate.CEN.LePapeo { /* * Definition of the class TipoCocinaCEN * */ public partial class TipoCocinaCEN { private ITipoCocinaCAD _ITipoCocinaCAD; public TipoCocinaCEN() { this._ITipoCocinaCAD = new TipoCocinaCAD (); } public TipoCocinaCEN(ITipoCocinaCAD _ITipoCocinaCAD) { this._ITipoCocinaCAD = _ITipoCocinaCAD; } public ITipoCocinaCAD get_ITipoCocinaCAD () { return this._ITipoCocinaCAD; } public string New_ (string p_tipo) { TipoCocinaEN tipoCocinaEN = null; string oid; //Initialized TipoCocinaEN tipoCocinaEN = new TipoCocinaEN (); tipoCocinaEN.Tipo = p_tipo; //Call to TipoCocinaCAD oid = _ITipoCocinaCAD.New_ (tipoCocinaEN); return oid; } public void Modify (string p_TipoCocina_OID) { TipoCocinaEN tipoCocinaEN = null; //Initialized TipoCocinaEN tipoCocinaEN = new TipoCocinaEN (); tipoCocinaEN.Tipo = p_TipoCocina_OID; //Call to TipoCocinaCAD _ITipoCocinaCAD.Modify (tipoCocinaEN); } public void Destroy (string tipo ) { _ITipoCocinaCAD.Destroy (tipo); } public System.Collections.Generic.IList<TipoCocinaEN> ReadAll (int first, int size) { System.Collections.Generic.IList<TipoCocinaEN> list = null; list = _ITipoCocinaCAD.ReadAll (first, size); return list; } public TipoCocinaEN ReadOID (string tipo ) { TipoCocinaEN tipoCocinaEN = null; tipoCocinaEN = _ITipoCocinaCAD.ReadOID (tipo); return tipoCocinaEN; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using MySql.Data; using MySql.Data.MySqlClient; using System.Windows.Forms; using System.Data; namespace Yelemani.Database { class comptabilite { MySqlConnection con; MySqlCommand cmd; public comptabilite() { con = new MySqlConnection("datasource=localhost;port=3306;username=root;password=;database=yelemani"); con.Close(); } public DataTable refresh() { con.Open(); MySqlDataAdapter da = new MySqlDataAdapter("select Nom_Produit, Prix, Quantite, Date from historique", con); DataTable ds = new DataTable(); da.Fill(ds); con.Close(); return ds; } } }
using DevExpress.Office.Utils; using DevExpress.XtraEditors; using DevExpress.XtraReports.UI; using PDV.CONTROLER.Funcoes; using PDV.CONTROLER.FuncoesFaturamento; using PDV.DAO.Custom; using PDV.DAO.Entidades; using PDV.DAO.Entidades.PDV; using PDV.DAO.Enum; using PDV.REPORTS.Reports.PedidoVendaTermica; using PDV.VIEW.App_Context; using PDV.VIEW.Forms.Relatorios; using PDV.VIEW.Forms.Util; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Text; using System.Windows.Forms; using Contexto = PDV.VIEW.FRENTECAIXA.App_Context.Contexto; namespace PDV.VIEW.FRENTECAIXA.Forms { public partial class FormVendas : XtraForm { public string NomeTela { get; set; } = "Vendas"; public decimal IdFluxoCaixa { get; set; } private string ConverterStatus(int numStatus) { if (numStatus == StatusPedido.Faturado) return "FATURADO"; if (numStatus == StatusPedido.Cancelado) return "CANCELADO"; return "ABERTO"; } public List<decimal> IdsSelecionados { get { var ids = new List<decimal>(); foreach (var linha in gridView1.GetSelectedRows()) ids.Add(Grids.GetValorDec(gridView1, "idvenda", linha)); return ids; } } public FormVendas(decimal idFluxoCaixa) { InitializeComponent(); IdFluxoCaixa = idFluxoCaixa; Atualizar(); } private void Atualizar() { gridControl1.DataSource = FuncoesVenda.GetListaVendasPorFluxoDeCaixa(IdFluxoCaixa); Grids.FormatGrid(ref gridView1); Grids.FormatColumnType(ref gridView1, new List<string> { "quantidadeitens", "idcomanda", "idcliente", "idusuario", "vendedor", "tipodevenda" }, GridFormats.VisibleFalse); gridView1.Columns["status"].VisibleIndex = gridView1.Columns.Count - 1; } private void buttonCancelar_Click(object sender, System.EventArgs e) { if (Confirm("Deseja efetuar o cancelamento?") == DialogResult.Yes) foreach (var id in IdsSelecionados) { try { PDVControlador.BeginTransaction(); var venda = FuncoesVenda.GetVenda(id); if (venda.Status != StatusPedido.Faturado) { PDVControlador.Commit(); continue; } var vendaFaturamento = new VendaFaturamento(venda, Contexto.USUARIOLOGADO); var motivoCancelamento = XtraInputBox.Show($"Insira um motivo para o cancelamento da venda {id}", NomeTela, ""); vendaFaturamento.CancelarVenda(motivoCancelamento); PDVControlador.Commit(); Atualizar(); } catch (Exception ex) { PDVControlador.Rollback(); Alert(ex.Message); } } } private DialogResult Confirm(string msg) { return MessageBox.Show(msg, NomeTela, MessageBoxButtons.YesNo, MessageBoxIcon.Question); } private void Alert(string msg) { MessageBox.Show(msg, NomeTela, MessageBoxButtons.OK, MessageBoxIcon.Error); } private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e) { if (e.Column.FieldName == "status") { string valor; try { var cellValue = gridView1.GetRowCellValue(e.RowHandle, "status"); if (cellValue != null) valor = cellValue.ToString(); else throw new Exception(); } catch (Exception) { valor = ""; } switch (valor) { case "FATURADO": e.Appearance.ForeColor = System.Drawing.Color.Green; break; case "CANCELADO": e.Appearance.ForeColor = System.Drawing.Color.Red; break; case "ABERTO": e.Appearance.ForeColor = System.Drawing.Color.Blue; break; case "DESFEITO": e.Appearance.ForeColor = System.Drawing.Color.Purple; break; case "APP": e.Appearance.ForeColor = System.Drawing.Color.Blue; e.Appearance.BackColor = System.Drawing.Color.Yellow; break; } } } private void EmitirCupomGerencial(decimal idVenda) { try { Configuracao Config_NomeImpressora = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGURACAOPEDIDOVENDA_NOMEIMPRESSORA); Configuracao Config_ExibirCaixaDialogo = FuncoesConfiguracao.GetConfiguracao(ChavesConfiguracao.CHAVE_CONFIGURACAOPEDIDOVENDA_EXIBIRCAIXADIALOGO); ReciboPedidoVenda _ReciboPedidoVenda = new ReciboPedidoVenda(idVenda); if (Config_ExibirCaixaDialogo != null && "1".Equals(Encoding.UTF8.GetString(Config_ExibirCaixaDialogo.Valor))) { using (ReportPrintTool printTool = new ReportPrintTool(_ReciboPedidoVenda)) { _ReciboPedidoVenda.PrintingSystem.ShowMarginsWarning = false; printTool.Print(); } } else { Stream STRel = new MemoryStream(); _ReciboPedidoVenda.ExportToPdf(STRel); new FREL_Preview(STRel).ShowDialog(this); } } catch (Exception Ex) { MessageBox.Show(this, "Não foi possivel imprimir o cupom Detalhes:" + Ex.Message, "Pedido de Venda"); } } private void simpleButton1_Click(object sender, EventArgs e) { EmitirCupomGerencial(Grids.GetValorDec(gridView1, "idvenda")); } } }
using System; using HW2; namespace Task_4._1 { class Program { static void Main(string[] args) { for (int i = 0; i < 4; i++) { Exception exeption; switch (i) { case 0: exeption = new InsufficientFundsExeption(); break; case 1: exeption = new LimitExceedExeption(); break; case 2: exeption = new PaymentServiceExeption(); break; default: exeption = new Exception(); break; } try { throw exeption; } catch (InsufficientFundsExeption) { Console.WriteLine("Insufficient Funds Exeption!"); } catch (LimitExceedExeption) { Console.WriteLine("Limit Exceed Exeption!"); } catch (PaymentServiceExeption) { Console.WriteLine("Payment Service Exeption!"); } catch (Exception) { Console.WriteLine("Exeption!"); } } } } }
using log4net; namespace CloneDeploy_DataModel { public class RawSqlRepository { private readonly CloneDeployDbContext _context; private readonly ILog log = LogManager.GetLogger(typeof(RawSqlRepository)); public RawSqlRepository() { _context = new CloneDeployDbContext(); } public int Execute(string sql) { return _context.Database.ExecuteSqlCommand(sql); } } }
namespace AspNetCoreSample.Services { /// <summary> /// /// </summary> public interface ILogService { /// <summary> /// /// </summary> /// <param name="content"></param> void Info(string content); } }
using System; namespace ConsoleProcessRedirection { using System.Runtime.Remoting; /// <summary> /// Allows redirection of I/O for console processes. /// </summary> }
using GUIEX2PROJECT.Models; using Microsoft.AspNetCore.Identity.EntityFrameworkCore; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Internal; namespace GUIEX2PROJECT.Data { public class ApplicationDbContext : IdentityDbContext<Employee> { public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options) { } public DbSet<Employee> Employees { get; set; } public DbSet<Room> Rooms { get; set; } public DbSet<RoomBooking> RoomBookings { get; set; } protected override void OnModelCreating(ModelBuilder modelbuilder) { base.OnModelCreating(modelbuilder); modelbuilder.Entity<Room>() .HasKey(r => r.RoomId); modelbuilder.Entity<Room>() .HasIndex(r => r.RoomNumber) .IsUnique(); modelbuilder.Entity<RoomBooking>() .HasKey(r => r.BookingId); modelbuilder.Entity<RoomBooking>() .HasOne<Room>(r => r.Room) .WithMany(r => r.RoomBookings) .HasForeignKey(r => r.RoomNumber); modelbuilder.Entity<Room>() .Property(r => r.RoomNumber); } } }