text
stringlengths
13
6.01M
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Enemy : MonoBehaviour { public float startHealth = 100; private float health; public float amount; public GameObject deathEffect; public Image healthBar; // Start is called before the first frame update void Start() { { health = startHealth; } } public void TakeDamage(float amount) { health -= amount; healthBar.fillAmount = health / startHealth; if (health <= 0) { // Die(); } } // Update is called once per frame void Update() { } }
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace ChatBot.Models { public class Courses { public int id { get; set; } [Display(Name = "Course Id")] public string number { get; set; } [Display(Name = "Course Name")] public string name { get; set; } [Display(Name = "Time")] public string time { get; set; } [Display(Name = "Room No.")] public string location { get; set; } [Display(Name = "No. of Units")] public int noOfUnits { get; set; } public Professors professors { get; set; } [Display(Name = "Professor")] public int professorsId { get; set; } } }
 public static class PvpHandle { public static bool ParseUserList(byte[] msg_, int msgLen_) { return true; } public static bool ParseCreateUserRet(byte[] msg_, int msgLen_) { return true; } public static bool ParseUserBaseData(byte[] msg_, int msgLen_) { return true; } public static bool ParseUserItemList(byte[] msg_, int msgLen_) { return true; } }
using System.Collections.Generic; using Merchello.UkFest.Web.Ditto.ValueResolvers; using Our.Umbraco.Ditto; namespace Merchello.UkFest.Web.Models.Category { public class CategoryTree { /// <summary> /// Gets or sets the items. /// </summary> [DittoValueResolver(typeof(CategoryTreeItemValueResolver))] public IEnumerable<CategoryTreeItem> Items { get; set; } } }
using System; /* 编写一个抽象排序类,定义排序方法,接收一个数组,返回排序后的数组并输出: 定义两个对抽象类的继承类,实现两种不同的排序方法; 在主函数中分别调用两个类的方法对数组进行排序; */ namespace Ex3 { class Program { static void Main(string[] args) { int[] arrNum = Init(); // 调用第一个排序类 ArraySort1 arrSort1 = new ArraySort1(); int[] result1 = arrSort1.Sort(arrNum); Output("ArraySort1", result1); // 调用第二个排序类 ArraySort2 arrSort2 = new ArraySort2(); int[] result2 = arrSort2.Sort(arrNum); Output("ArraySort2", result2); Console.ReadKey(); } // 初始化数组 static int[] Init() { Console.WriteLine("请在下方输入需要排序的数组,格式为:1,2,6,3,5,4 \n请使用英文符号!"); string temp = Console.ReadLine(); Array arr = temp.Split(','); int[] arrNum = new int[arr.Length]; for (int i = 0; i < arr.Length; i++) { arrNum[i] = Convert.ToInt32(arr.GetValue(i)); } return arrNum; } // 格式化输出数组 static void Output(string name, int[] arrNum) { Console.Write(name + " output: "); for (int j = 0; j < arrNum.Length; j++) { Console.Write(arrNum[j]); if (j != arrNum.Length - 1) { Console.Write(","); } else { Console.WriteLine(); } } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class BonusAreaInfo : MonoBehaviour { const bool IsBonus = true; public int AreaNumber; public List<StageInfo> StageInfos = new List<StageInfo>(); }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DSSCriterias.Logic { public class ReportExcel : Report { public ReportExcel(IStatGame matrix) : base(matrix) { } public override void Create() { throw new NotImplementedException(); } public override void Open() { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [System.Serializable] public class InteractionScript { public InputActionScript inputAction; [TextArea] public string textResponse; public ActionResponseScript actionResponse; }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Player : MonoBehaviour { private float _speed = 15; private Vector3 _direction = Vector3.zero; private void Update() { _direction.x = -Input.GetAxis("Horizontal"); _direction.z = -Input.GetAxis("Vertical"); transform.position += _direction * Time.deltaTime; } }
using Foundation; using System; using System.CodeDom.Compiler; using System.Diagnostics; using CoreGraphics; using UIKit; namespace ResidentAppCross.iOS { public partial class VerticalCollectionSection : SectionViewBase { public VerticalCollectionSection (IntPtr handle) : base (handle) { } public VerticalCollectionSection() { } public UICollectionView Collection => _collection; public void SetVerticalTableMode(float itemHeight) { var layout = new CollectionViewTableLayout() { ScrollDirection = UICollectionViewScrollDirection.Vertical, }; //layout.EstimatedItemSize = new CGSize(100,100); Collection.SetCollectionViewLayout(layout,true); } } public partial class CollectionViewTableLayout : UICollectionViewFlowLayout { public float ItemHeight { get; set; } public override CGSize ItemSize { get { return new CGSize(CollectionView.Frame.Size.Width - SectionInset.Left - SectionInset.Right - CollectionView.ContentInset.Left - CollectionView.ContentInset.Right, 0) ; } set { } } public override CGSize EstimatedItemSize { get { return new CGSize (CollectionView.Frame.Size.Width - SectionInset.Left - SectionInset.Right - CollectionView.ContentInset.Left - CollectionView.ContentInset.Right, 120); } set{ } } } }
 /* ****************************************************************************** * @file : Program.cs * @Copyright: ViewTool * @Revision : ver 1.0 * @Date : 2015/02/13 10:57 * @brief : Program demo ****************************************************************************** * @attention * * Copyright 2009-2015, ViewTool * http://www.viewtool.com/ * All Rights Reserved * ****************************************************************************** */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; using Ginkgo; namespace ControlSPI_Test { class Program { static void Main(string[] args) { int ret; ControlSPI.VSI_INIT_CONFIG pSPI_Config = new ControlSPI.VSI_INIT_CONFIG(); //Scan connected device ret = ControlSPI.VSI_ScanDevice(1); if (ret <= 0) { Console.WriteLine("No device connect!"); return; } // Open device ret = ControlSPI.VSI_OpenDevice(ControlSPI.VSI_USBSPI, 0, 0); if (ret != ControlSPI.ERROR.SUCCESS) { Console.WriteLine("Open device error!"); return; } // Initialize device(Master Mode, Hardware SPI, Half-Duplex) // function VSI_WriteBytes,VSI_ReadBytes,VSI_WriteReadBytes can be support in software SPI mode pSPI_Config.ControlMode = 1; pSPI_Config.MasterMode = 1; pSPI_Config.ClockSpeed = 36000000; pSPI_Config.CPHA = 0; pSPI_Config.CPOL = 0; pSPI_Config.LSBFirst = 0; pSPI_Config.TranBits = 8; pSPI_Config.SelPolarity = 0; ret = ControlSPI.VSI_InitSPI(ControlSPI.VSI_USBSPI, 0, ref pSPI_Config); if (ret != ControlSPI.ERROR.SUCCESS) { Console.WriteLine("Initialize device error!"); return; } Byte[] write_buffer = new Byte[10240]; Byte[] read_buffer = new Byte[10240]; Byte BlockNum = 5; Byte BlockSize = 2; UInt32 IntervalTime = 100; // Block mode write data, data will be send out BlockNum time(s), send out BlockSize bytes of data every time // Set CS to low before send data and set CS to high after send data complete when every time send data // Each time send data, interval is IntervalTime us, that is CS set to high and hold IntervalTime us for (Byte i = 0; i < BlockNum; i++ ) { for (Byte j = 0; j < BlockSize; j++ ) { write_buffer[i * BlockSize + j] = (Byte)(i * j); } } ret = ControlSPI.VSI_BlockWriteBytes(ControlSPI.VSI_USBSPI, 0, 0, write_buffer, BlockSize, BlockNum, IntervalTime); if (ret != ControlSPI.ERROR.SUCCESS) { Console.WriteLine("Block write data error!\n"); return; } // Block mode read data: same as write data ret = ControlSPI.VSI_BlockReadBytes(ControlSPI.VSI_USBSPI, 0, 0, read_buffer, BlockSize, BlockNum, IntervalTime); if (ret != ControlSPI.ERROR.SUCCESS) { Console.WriteLine("Block read data error!\n"); return; } else { Console.WriteLine("Read data(Hex):\n"); for (int i = 0; i < BlockNum; i++) { for (int j = 0; j < BlockSize; j++) { Console.Write("{0,-4:x}", read_buffer[i * BlockSize + j]); } //Console.Write(" \n"); } } Console.WriteLine(); // Block mode: write and read data UInt16 write_BlockSize = 1; UInt16 read_BlockSize = 2; for (int i = 0; i < BlockNum; i++) { for (int j = 0; j < write_BlockSize; j++) { write_buffer[i * write_BlockSize + j] = (Byte)(i * j); } } ret = ControlSPI.VSI_BlockWriteReadBytes(ControlSPI.VSI_USBSPI, 0, 0, write_buffer, write_BlockSize, read_buffer, read_BlockSize, BlockNum, IntervalTime); if (ret != ControlSPI.ERROR.SUCCESS) { Console.WriteLine("Block write read data error!\n"); return; } else { Console.WriteLine("Read data(Hex):\n"); for (int i = 0; i < BlockNum; i++) { for (int j = 0; j < read_BlockSize; j++) { Console.Write("{0,-4:x}", read_buffer[i * read_BlockSize + j]); } //Console.WriteLine("\n"); } } Console.ReadLine(); return; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Terraria.ModLoader; namespace StarlightRiver.Codex.Entries { class StaminaEntry : CodexEntry { public StaminaEntry() { Category = (int)Categories.Misc; Title = "Stamina"; Body = "All of your abilities utilize stamina, represtented\n" + "by the orange crystals to the left of your mana bar.\n" + "Stamina is consumed when an ability is used, and\n" + "can be passively regenerated over time."; Image = ModContent.GetTexture("StarlightRiver/GUI/Stamina"); Icon = ModContent.GetTexture("StarlightRiver/GUI/Stamina"); } } class InfusionEntry : CodexEntry { public InfusionEntry() { Category = (int)Categories.Misc; Title = "Infusions"; Body = "Infusions are special upgrades which, when slotted\n" + "into their appropriate slots, will upgrade your\n" + "abilities. Each ability has 2 major infusions, which\n" + "grant special abilities to them."; Image = ModContent.GetTexture("StarlightRiver/Items/Infusions/DashAstralItem"); Icon = ModContent.GetTexture("StarlightRiver/Items/Infusions/DashAstralItem"); } } }
using System.Collections.Generic; using System.Linq; using Uintra.Features.Permissions.Interfaces; using Uintra.Features.Permissions.Models; using Uintra.Infrastructure.Caching; using Uintra.Infrastructure.Extensions; using Umbraco.Core.Logging; using Umbraco.Core.Models; using Umbraco.Core.Services; namespace Uintra.Features.Permissions.Implementation { public class IntranetMemberGroupService : IIntranetMemberGroupService { protected virtual string IntranetMemberGroupCacheKey => "IntranetMemberGroupCache"; private readonly ILogger _logger; private readonly IMemberService _memberService; private readonly IMemberGroupService _memberGroupService; private readonly ICacheService _cacheService; public IntranetMemberGroupService(IMemberGroupService memberGroupService, IMemberService memberService, ICacheService cacheService, ILogger logger) { _memberGroupService = memberGroupService; _memberService = memberService; _cacheService = cacheService; _logger = logger; } protected virtual IEnumerable<IntranetMemberGroup> CurrentCache() { return _cacheService.GetOrSet(IntranetMemberGroupCacheKey, () => _memberGroupService.GetAll().Map<IEnumerable<IntranetMemberGroup>>()); } public virtual IEnumerable<IntranetMemberGroup> GetAll() => CurrentCache(); public virtual IEnumerable<IntranetMemberGroup> GetForMember(int id) { var allGroups = GetAll(); var groupNamesAssignedToMember = _memberService.GetAllRoles(id); var memberGroups = allGroups .Join(groupNamesAssignedToMember, group => group.Name, x => x, (group, _) => group).ToList(); return memberGroups; } public virtual int Create(string name) { if (string.IsNullOrWhiteSpace(name)) return int.MinValue; var group = _memberGroupService.GetByName(name); if (group != null) return group.Id; _memberGroupService.Save(new MemberGroup {Name = name}); group = _memberGroupService.GetByName(name); ClearCache(); return group.Id; } public virtual bool Save(int id, string name) { if (string.IsNullOrWhiteSpace(name)) return false; var groupByName = _memberGroupService.GetByName(name); if (groupByName != null && groupByName.Id != id) return false; var memberGroup = _memberGroupService.GetById(id); memberGroup.Name = name; _memberGroupService.Save(memberGroup); ClearCache(); return true; } public virtual void Delete(int id) { var group = _memberGroupService.GetById(id); _memberGroupService.Delete(group); ClearCache(); } public void RemoveFromAll(int memberId) { var memberRolesNames = GetForMember(memberId).Select(r => r.Name); _memberService.DissociateRoles(new[] {memberId}, memberRolesNames.ToArray()); } public void AssignDefaultMemberGroup(int memberId) { var uiUserGroup = GetAll().FirstOrDefault(i => i.Name.Equals("UiUser")); if (uiUserGroup != null) { _memberService.AssignRole(memberId, uiUserGroup.Name); } } public void ClearCache() { _cacheService.Remove(IntranetMemberGroupCacheKey); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace WritingPlatformCore.Entities { public class CatalogLanguage { public string Language { get; private set; } public CatalogLanguage(string language) { Language = language; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Data.SqlClient; namespace AracKiralama { public partial class Yonetici : System.Web.UI.Page { database bgl = new database(); string id = ""; string islem = ""; protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { id = Request.QueryString["arabaID"]; islem = Request.QueryString["islem"]; } SqlCommand komut = new SqlCommand("select * from aracTablo", bgl.dbBaglanti()); SqlDataReader oku = komut.ExecuteReader(); DataList2.DataSource = oku; DataList2.DataBind(); if (islem == "sil") { SqlCommand komutSil = new SqlCommand("delete from aracTablo where arabaID=@p1", bgl.dbBaglanti()); komutSil.Parameters.AddWithValue("@p1", id); komutSil.ExecuteReader(); bgl.dbBaglanti().Close(); Response.Redirect("Yonetici.aspx"); } } protected void btnAracEkle_Click(object sender, EventArgs e) { FileUpload1.SaveAs(Server.MapPath("/images/" + FileUpload1.FileName)); SqlCommand komut = new SqlCommand("insert into aracTablo (model,aciklama,ucret,yil,durum,aracFoto) values (@m1,@m2,@m3,@m4,@m5,@m6)", bgl.dbBaglanti()); komut.Parameters.AddWithValue("@m1", txtModel.Text); komut.Parameters.AddWithValue("@m2", txtAciklama.Text); komut.Parameters.AddWithValue("@m3", txtUcret.Text); komut.Parameters.AddWithValue("@m4", txtYili.Text); komut.Parameters.AddWithValue("@m5", "False"); komut.Parameters.AddWithValue("@m6", "~/images/" + FileUpload1.FileName); komut.ExecuteReader(); bgl.dbBaglanti().Close(); ClientScript.RegisterStartupScript(Page.GetType(), "Message", "alert('Araç Ekleme Başarılı.');window.location='Yonetici.aspx';", true); txtModel.Text = ""; txtAciklama.Text = ""; txtUcret.Text = ""; txtYili.Text = ""; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; using UnityEngine.UI; public class MainMenu : MonoBehaviour { GameObject previousPage; GameObject currentPage; public void StartGame() { GameObject levelPicker = GameObject.Find ("Canvas").transform.GetChild(1).gameObject; GameObject mainMenu = GameObject.Find ("MainMenu_Page"); previousPage = mainMenu; currentPage = levelPicker; levelPicker.SetActive (true); mainMenu.SetActive (false); } public void JoinGame() { GameObject joinPage = GameObject.Find ("Canvas").transform.GetChild(2).gameObject; GameObject mainMenu = GameObject.Find ("MainMenu_Page"); previousPage = mainMenu; currentPage = joinPage; joinPage.SetActive (true); mainMenu.SetActive (false); SceneManager.LoadScene("Connect"); } public void GameOptions() { GameObject gameOptions = GameObject.Find ("Canvas").transform.GetChild(3).gameObject; GameObject levelPicker = GameObject.Find ("LevelPicker_Page"); previousPage = levelPicker; currentPage = gameOptions; levelPicker.SetActive (false); gameOptions.SetActive (true); } public void Previous() { currentPage.SetActive (false); previousPage.SetActive (true); currentPage = previousPage; previousPage = GameObject.Find ("Canvas").transform.GetChild(0).gameObject; } public void Exit() { Application.Quit (); } public void OnMaximumPlayerChanged() { Dropdown mpdd = GameObject.Find ("MaxPlayers_Dropdown").GetComponent<Dropdown> (); Dropdown dd = GameObject.Find ("NbPlayers_Dropdown").GetComponent<Dropdown> (); List<Dropdown.OptionData> options = mpdd.options; int maxSelected = mpdd.value + 2; int current = dd.value + 1; dd.options.Clear (); for (int i = 1; i <= maxSelected; i++) { dd.options.Add (new Dropdown.OptionData(i.ToString())); } dd.value = (current <= maxSelected) ? current - 1 : maxSelected - 1; GameLoader gl = GameObject.Find ("GameLoader").GetComponent<GameLoader> (); gl.setMaxPlayers (maxSelected); gl.setNbPlayers (current); } public void OnNbPlayersChanged() { Dropdown dd = GameObject.Find ("NbPlayers_Dropdown").GetComponent<Dropdown> (); GameLoader gl = GameObject.Find ("GameLoader").GetComponent<GameLoader> (); gl.setNbPlayers (dd.value + 1); } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RoutingControllerBeta { class AddressBook { List<Address> addresses; public AddressBook() { addresses = new List<Address>(); } public AddressBook(string addressesFilePath) { addresses = new List<Address>(); try { string[] addressesDefinitions = File.ReadAllLines(addressesFilePath); foreach(string addressDefinition in addressesDefinitions) { string[] definition = addressDefinition.Split('_'); addresses.Add(new Address(definition[0], definition[1], Int32.Parse(definition[2]))); } } catch (FileNotFoundException ex) { } } public void add(Address address) { this.addresses.Add(address); } public int getAddressOf(Router router) { foreach(Address address in addresses) { if (router.getSubNetworkCallSign().Equals(address.getSubNetworkCallSign()) && router.getAutonomicNetworkCallSign().Equals(address.getAutonomicNetworkCallSign())) return address.getPortNumber(); } return 0; } } }
using System; using System.Collections.Generic; using System.Text; namespace _03.Mankind { public class Worker : Person { private double weekSalary; private double workHoursPerDay; public Worker(string firstName, string secondName, double weekSalary, double workHoursPerDay) : base(firstName, secondName) { this.WeekSalary = weekSalary; this.WorkHoursPerDay = workHoursPerDay; } public double WeekSalary { get { return this.weekSalary; } set { if (value <= 10) { throw new ArgumentException("Expected value mismatch! Argument: weekSalary"); } this.weekSalary = value; } } public double WorkHoursPerDay { get { return this.workHoursPerDay; } set { if (value > 12 || value < 1) { throw new ArgumentException("Expected value mismatch! Argument: workHoursPerDay"); } this.workHoursPerDay = value; } } public double CalcSalary() { double salary = this.weekSalary / 5 / this.WorkHoursPerDay; return salary; } public override string ToString() { StringBuilder result = new StringBuilder(); result.Append(base.ToString()); result.AppendLine(string.Format( "Week Salary: {0:F2}", this.WeekSalary)); result.AppendLine(string.Format( "Hours per day: {0:F2}", this.WorkHoursPerDay)); result.AppendLine(string.Format( "Salary per hour: {0:F2}", this.CalcSalary())); return result.ToString().Trim(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace TestProject.Controllers { public class HomeController : Controller { public ActionResult Index() { ViewBag.Message = "Modify this template to jump-start your A S P.NET MVC application."; for (int i = 0; i < 11; i++) { var test = Number(); var test1 = test.Aggregate((x, y) => x + y); } return View(); } private IEnumerable<int> Number() { for (int i = 0; i < 10; i++) { yield return i; } var test= "Aroan"; } public ActionResult About() { ViewBag.Message = "Your app description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
using BaseLib.IO; using BaseLib.Threading; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; namespace BaseLib.Media.Audio { public class Mixer : IMixer { class streaminf { public int channels; internal float[] audiolevel; public bool muted = false; public float volume = 1.0f; internal bool running = true; internal long starttime = -1; public Action Done; public streaminf(int channels) { this.channels = channels; this.audiolevel = new float[this.channels]; } internal void Set(bool muted, float volume) { this.muted = muted; this.volume = volume; } } private readonly List<FifoStream> streams = new List<FifoStream>(); private readonly List<streaminf> streaminfo = new List<streaminf>(); public ReaderWriterLock StreamsLock { get; } = new ReaderWriterLock(); private byte[] buffer; public int TotalStreams { get { return this.streams.Count; } } public int Channels { get; } public ChannelsLayout ChannelLayout { get; } public AudioFormat Format { get; } public int SampleRate { get; } public int SampleSize { get; } protected bool inaction = false; public Mixer(int samplerate, AudioFormat format, ChannelsLayout channels) { try { this.SampleRate = samplerate; this.Channels = channels == ChannelsLayout.Dolby ? 6 : 2; this.ChannelLayout = channels; this.Format = format; switch (format) { case AudioFormat.Short16: this.SampleSize = 2; break; case AudioFormat.Float32: this.SampleSize = 4; break; } this.buffer = new byte[this.SampleRate * this.SampleSize * this.Channels]; } catch { GC.SuppressFinalize(this); throw; } } ~Mixer() { Dispose(false); } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } void Dispose(bool disposing) { foreach (FifoStream audiostream in this.streams) { audiostream.Dispose(); } this.streams.Clear(); } public void Register(FifoStream audiostream, int channels, bool paused) { GetLock(out LockCookie cookie, out WriteLock wl); this.streams.Add(audiostream); this.streaminfo.Add(new streaminf(channels) { running = !paused }); ReleaseLock(cookie, wl); } public void Unregister(FifoStream audiostream) { if (audiostream != null) { audiostream.Close(); GetLock(out LockCookie cookie, out WriteLock wl); int ind = this.streams.IndexOf(audiostream); if (ind >= 0) { this.streaminfo.RemoveAt(ind); this.streams.RemoveAt(ind); } else { Debug.Assert(false); } ReleaseLock(cookie, wl); audiostream.Clear(); } } public void SetSetAudio(FifoStream audiostream, bool muted, float volume) { using (var rl = new ReadLock(this.StreamsLock)) { int ind = streams.IndexOf(audiostream); if (ind != -1) { this.streaminfo[ind].Set(muted, volume); } } } public void Peek(int totsamples) // shoud be locked by caller { for (int nit = 0; nit < this.streams.Count; nit++) { int len = totsamples * this.SampleSize * this.Channels; int total = this.streams[nit].Peek(buffer, 0, len); if (len == total) { RootMeanSquare(this.streaminfo[nit].audiolevel, buffer, this.streaminfo[nit].channels); } } } private void RootMeanSquare(float[] audiolevel, byte[] buffer, int channels) { switch (this.Format) { case AudioFormat.Short16: AudioOut.RootMeanSquareShort(audiolevel, buffer, channels); break; case AudioFormat.Float32: AudioOut.RootMeanSquareFloat(audiolevel, buffer, channels); break; default: throw new NotImplementedException(); } } private void Add2Buffer(byte[] buffer, byte[] result, int totsamples, int channels1, int channels2, bool v, float volume) { switch (this.Format) { case AudioFormat.Short16: AudioOut.Add2BufferShort(buffer, result, totsamples, channels1, channels2, v, volume); break; case AudioFormat.Float32: AudioOut.Add2BufferFloat(buffer, result, totsamples, channels1, channels2, v, volume); break; default: throw new NotImplementedException(); } } public byte[] Read(Int64 time, int totsamples) // shoud be locked by caller { byte[] result = new byte[totsamples * this.SampleSize * this.Channels]; for (int nit = 0; nit < this.streams.Count; nit++) { int len = totsamples * this.SampleSize * this.Channels; lock (this.streaminfo[nit]) { if (!this.streaminfo[nit].running) { if (this.streams[nit].EOS.WaitOne(0, false)) { /* var cookie = this.StreamsLock.UpgradeToWriterLock(-1); this.streams[nit].Close(); this.streaminfo.RemoveAt(nit); this.streams.RemoveAt(nit); this.StreamsLock.DowngradeFromWriterLock(ref cookie); nit--;*/ } else if (this.streaminfo[nit].starttime != -1 && this.streaminfo[nit].starttime <= time) { this.streaminfo[nit].starttime = -1; this.streaminfo[nit].running = true; // Debug.WriteLine("starting audio stream"); } else { int total = this.streams[nit].Peek(buffer, 0, len); if (len == total) { RootMeanSquare(this.streaminfo[nit].audiolevel, buffer, this.streaminfo[nit].channels); } } } } if (this.streaminfo[nit].running) { lock (this.streaminfo[nit]) { int total = this.streams[nit].Read(buffer, 0, len); if (len == total) { RootMeanSquare(this.streaminfo[nit].audiolevel, buffer, this.streaminfo[nit].channels); //AudioConverter.Average(this.streaminfo[nit].audiolevel, this.buffer, totsamples, streaminfo[nit].channels); if (!streaminfo[nit].muted) { if (this.streaminfo[nit].channels == 1) { Add2Buffer(this.buffer, result, totsamples, streaminfo[nit].channels, this.Channels, true, this.streaminfo[nit].volume); } else { Add2Buffer(this.buffer, result, totsamples, streaminfo[nit].channels, this.Channels, false, this.streaminfo[nit].volume); } } } else if (this.streams[nit].EOS.WaitOne(0, false)) { if (total > 0) { if (!streaminfo[nit].muted) { if (this.streaminfo[nit].channels == 1) { Add2Buffer(this.buffer, result, total / (this.SampleSize * this.Channels), streaminfo[nit].channels, this.Channels, true, this.streaminfo[nit].volume); } else { Add2Buffer(this.buffer, result, total / (this.SampleSize * this.Channels), streaminfo[nit].channels, this.Channels, false, this.streaminfo[nit].volume); } } } // Debug.Assert(total == 0); this.streaminfo[nit].running = false; this.streaminfo[nit].Done?.Invoke(); // Debug.WriteLine("stopping audio stream"); /* var cookie = this.StreamsLock.UpgradeToWriterLock(-1); this.streams[nit].Close(); this.streaminfo.RemoveAt(nit); this.streams.RemoveAt(nit); this.StreamsLock.DowngradeFromWriterLock(ref cookie); nit--;*/ //this.streams[nit].EOS.Reset(); } else { // Debug.Assert(false); } } } } return result; } public float[] GetAudioLevels(FifoStream audiostream) { using (var wl = new ReadLock(this.StreamsLock)) { int ind = streams.IndexOf(audiostream); if (ind == -1) { return new float[0]; } return this.streaminfo[ind].audiolevel; } } public void Flush(FifoStream audiostream) { audiostream.WaitAllReadDone(); } public void Close() { using (var wl = new ReadLock(this.StreamsLock)) { foreach (FifoStream audiostream in this.streams) { audiostream.Close(); } } } public void Open() { using (var wl = new ReadLock(this.StreamsLock)) { foreach (FifoStream audiostream in this.streams) { audiostream.Open(); } } } public void CloseRead() { using (var wl = new ReadLock(this.StreamsLock)) { for (int nit = 0; nit < this.streams.Count; nit++) { if (this.streaminfo[nit].running) { this.streams[nit].CloseRead(); } } } } public void OpenRead() { using (var wl = new ReadLock(this.StreamsLock)) { foreach (FifoStream audiostream in this.streams) { audiostream.OpenRead(); } } } public void CloseWrite() { using (var wl = new ReadLock(this.StreamsLock)) { for (int nit = 0; nit < this.streams.Count; nit++) { if (this.streaminfo[nit].running) { this.streams[nit].CloseWrite(); } } } } public void OpenWrite() { using (var wl = new ReadLock(this.StreamsLock)) { foreach (FifoStream audiostream in this.streams) { audiostream.OpenWrite(); } } } public void Reset() { using (var wl = new ReadLock(this.StreamsLock)) { foreach (FifoStream audiostream in this.streams) { audiostream.Clear(); } } } public void Start(FifoStream audiostream) { GetLock(out LockCookie cookie, out WriteLock wl); int ind = streams.IndexOf(audiostream); if (ind != -1) { this.streaminfo[ind].running = true; } ReleaseLock(cookie, wl); } public void StartAt(FifoStream audiostream, long time) { GetLock(out LockCookie cookie, out WriteLock wl); int ind = streams.IndexOf(audiostream); if (ind != -1) { this.streaminfo[ind].starttime = time; } ReleaseLock(cookie, wl); } public void Pause(FifoStream audiostream) { GetLock(out LockCookie cookie, out WriteLock wl); int ind = streams.IndexOf(audiostream); if (ind != -1) { this.streaminfo[ind].running = false; } ReleaseLock(cookie, wl); } private void ReleaseLock(LockCookie cookie, WriteLock wl) { if (wl != null) { wl.Dispose(); } else { this.StreamsLock.DowngradeFromWriterLock(ref cookie); } } private void GetLock(out LockCookie cookie, out WriteLock wl) { cookie = default(LockCookie); wl = null; if (this.inaction) { cookie = this.StreamsLock.UpgradeToWriterLock(-1); } else { wl = new WriteLock(this.StreamsLock); } } public void ListenEnd(FifoStream audiostream, Action function) { using (var rl = new ReadLock(this.StreamsLock)) { //GetLock(out LockCookie cookie, out WriteLock wl); int ind = streams.IndexOf(audiostream); if (ind != -1) { lock (this.streaminfo[ind]) { if (!this.streaminfo[ind].running) { function(); } else { this.streaminfo[ind].Done = function; } } } // ReleaseLock(cookie, wl); } } public void Clear() { throw new NotImplementedException(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Lazer : MonoBehaviour { static public Lazer instance; public GameObject LinePrefab; float maxStepDistance = 20; List<WhiteBall> lasers = new List<WhiteBall>(); List<GameObject> lines = new List<GameObject>(); public void AddLazer(WhiteBall ball) { lasers.Add(ball); } void RemoveOldLine() { if(lines.Count>0) { Destroy(lines[lines.Count - 1]); lines.RemoveAt(lines.Count - 1); RemoveOldLine(); } } // Start is called before the first frame update void Start() { instance = this; } // Update is called once per frame void Update() { RemoveOldLine(); int lineCount = 0; foreach (WhiteBall laser in lasers) { if (lineCount == 0) { RaycastHit hit; Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); if (Physics.Raycast(ray, out hit)) { var ballPos = new Vector3(laser.transform.position.x, laser.transform.localScale.y/2, laser.transform.position.z); var mousePos = new Vector3(hit.point.x, laser.transform.localScale.y / 2, hit.point.z); CalcLaserLine(ballPos, (mousePos - ballPos).normalized, lineCount); } } else CalcLaserLine(laser.transform.position + laser.transform.forward * 0.6f, laser.transform.forward, lineCount); } } int CalcLaserLine(Vector3 startPos, Vector3 direction,int index) { int result=1; RaycastHit hit; Ray ray = new Ray(startPos, direction); bool intersect=Physics.Raycast(ray, out hit, maxStepDistance); Vector3 hitPosition = hit.point; if(!intersect) { hitPosition = startPos + direction * maxStepDistance; } DrawLine(startPos, hitPosition,index); if (intersect) { result+=CalcLaserLine(hitPosition, Vector3.Reflect(direction, hit.normal),index+result); } return result; } void DrawLine(Vector3 startPos, Vector3 finshPos,int index) { if (index > 2) return ; LineRenderer line = null; if(index <lines.Count) { line = lines[index].GetComponent<LineRenderer>(); } else { GameObject go = Instantiate(LinePrefab, Vector3.zero, Quaternion.identity); line = go.GetComponent<LineRenderer>(); lines.Add(go); } line.SetPosition(0, startPos); line.SetPosition(1, finshPos); } }
using UnityEngine; public abstract class UnitySingleton<T> : MonoBehaviour where T : UnitySingleton<T> { static T m_instance; public static T Instance { get { return m_instance; } } void Awake() { m_instance = (T)this; } }
using System; using System.Collections.Generic; namespace DemoApp.Entities { public partial class SchoolStaffSubjects { public Guid Id { get; set; } public Guid? StaffId { get; set; } public Guid? SubjectId { get; set; } public Guid? ClassId { get; set; } public DateTime DateCreated { get; set; } public virtual SchoolClasses Class { get; set; } public virtual SchoolStaffProfiles Staff { get; set; } public virtual Subjects Subject { get; set; } } }
using Alabo.Data.People.BranchCompanies.Domain.Entities; using Alabo.Data.People.BranchCompanies.Domain.Services; using Alabo.Framework.Core.WebApis.Controller; using Alabo.Framework.Core.WebApis.Filter; using Microsoft.AspNetCore.Mvc; using MongoDB.Bson; namespace Alabo.Data.People.BranchCompanies.Controllers { [ApiExceptionFilter] [Route("Api/BranchCompany/[action]")] public class ApiBranchCompanyController : ApiBaseController<BranchCompany, ObjectId> { public ApiBranchCompanyController() : base() { BaseService = Resolve<IBranchCompanyService>(); } } }
using System; using Microsoft.Xna.Framework; using Terraria; using Terraria.ID; using Terraria.ModLoader; namespace StarlightRiver.Projectiles.WeaponProjectiles { public class PHImplosion : ModProjectile { public override void SetDefaults() { projectile.width = 2; projectile.height = 2; projectile.friendly = true; projectile.penetrate = 4; projectile.timeLeft = 180; projectile.magic = true; projectile.ignoreWater = false; } public override void SetStaticDefaults() { DisplayName.SetDefault("PH Implosion"); } public override void AI() { Player player = Main.player[projectile.owner]; if (!player.channel) { projectile.timeLeft -= 12; } if (projectile.height <= 26) { projectile.width += 1; projectile.height += 1; } for (int counter = 0; counter <= 4; counter++) { int dustType = Utils.SelectRandom<int>(Main.rand, new int[] { 269, 203, 6 }); Dust dust = Main.dust[Dust.NewDust(projectile.position, projectile.width, projectile.height, dustType, projectile.velocity.X, projectile.velocity.Y, 100, default(Color), 1f)]; dust.velocity += new Vector2(Main.rand.NextFloat(-1.6f, 1.6f), Main.rand.NextFloat(-1.6f, 1.6f)); dust.noGravity = true; dust.scale = 1.2f; if (dustType == 269) { dust.position = projectile.Center; } dust.noLight = true; } projectile.ai[0] += 1f; if (projectile.ai[0] >= 25f) { projectile.velocity.Y += 0.15f; projectile.velocity.X *= 0.98f; } Vector2 vectorToCursor = projectile.Center - player.Center; bool projDirection = projectile.Center.X < player.Center.X; if (projectile.Center.X < player.Center.X) { vectorToCursor = -vectorToCursor; } player.direction = ((projDirection) ? -1 : 1); player.itemRotation = vectorToCursor.ToRotation(); player.itemTime = 20; player.itemAnimation = 20; } public override void OnHitNPC(NPC target, int damage, float knockback, bool crit) { target.AddBuff(BuffID.OnFire, 120, false); } public override void Kill(int timeLeft) { Player player = Main.player[projectile.owner]; Main.PlaySound(2, (int)player.position.X, (int)player.position.Y, 14); //boom Main.PlaySound(2, (int)player.position.X, (int)player.position.Y, 74); //fork boom int explosion = Projectile.NewProjectile(projectile.Center, new Vector2(0f, 0f), mod.ProjectileType("AOEExplosion"), projectile.damage, projectile.knockBack, player.whoAmI); Main.projectile[explosion].ai[0] = 60; for (int counter = 0; counter <= 21; counter++) { int dustType = Utils.SelectRandom<int>(Main.rand, new int[] { 269, 6, 36 }); int dust = Dust.NewDust(new Vector2(projectile.position.X, projectile.position.Y), projectile.width, projectile.height, dustType, 1f, 1f, 100, default(Color), 1.2f); if (dustType != 36) { Main.dust[dust].velocity *= 6f; Main.dust[dust].scale *= 2.2f; } else { Main.dust[dust].velocity *= 1.4f; Main.dust[dust].scale *= 1.2f; } Main.dust[dust].scale += Main.rand.NextFloat(0.8f, 0.16f); Main.dust[dust].noGravity = true; } } } public class HMImplosion : ModProjectile { public override void SetDefaults() { projectile.width = 2; projectile.height = 2; projectile.friendly = true; projectile.penetrate = 6; projectile.timeLeft = 280; projectile.magic = true; } public override void SetStaticDefaults() { DisplayName.SetDefault("VortexPenisStaff moment 2"); } public override void AI() { Player player = Main.player[projectile.owner]; if (projectile.ai[0] == 1) { projectile.velocity = new Vector2(0f, 0f); projectile.ai[1] -= 1; if (projectile.ai[1] == 0) { int explosion = Projectile.NewProjectile(projectile.Center, new Vector2(0f, 0f), mod.ProjectileType("AOEExplosion"), projectile.damage, projectile.knockBack, player.whoAmI); Main.projectile[explosion].ai[0] = 150; projectile.Kill(); } for (int num1 = 0; num1 <= 20; num1++) { int dustType = Utils.SelectRandom<int>(Main.rand, new int[] { 269, 203, 6 }); Vector2 dustPos = projectile.Center + ((float)Main.rand.NextDouble() * 6.28318548f).ToRotationVector2() * ((8f * projectile.ai[1]) - (num1 * 2)); int dust = Dust.NewDust(dustPos - Vector2.One * 8f, 16, 16, dustType, 0f, 0f, 0, default, 0.6f); Main.dust[dust].velocity = Vector2.Normalize(projectile.Center - dustPos) * 1.5f * (10f - num1 * 2f) / 10f; Main.dust[dust].noGravity = true; Main.dust[dust].scale = 1.1f; } for (int k = 0; k <= 200; k += 1) { float maxDistance = 9f * projectile.ai[1]; NPC npc = Main.npc[k]; Vector2 vectorToNPC = npc.Center - projectile.Center; float distanceToNPC = vectorToNPC.Length(); if (distanceToNPC <= maxDistance) { Vector2 Direction = new Vector2(projectile.Center.X - npc.Center.X, projectile.Center.Y - npc.Center.Y); Direction.Normalize(); npc.velocity = Direction * 4f; } } } if (projectile.ai[0] == 0) { if (!player.channel) { projectile.ai[0] = 1; projectile.ai[1] = 20; } if (projectile.height <= 34) { projectile.width += 2; projectile.height += 2; } for (int counter = 0; counter <= 5; counter++) { int dustType = Utils.SelectRandom<int>(Main.rand, new int[] { 269, 203, 6 }); Dust dust = Main.dust[Dust.NewDust(projectile.position, projectile.width, projectile.height, dustType, projectile.velocity.X, projectile.velocity.Y, 100, default(Color), 1f)]; dust.velocity += new Vector2(Main.rand.NextFloat(-1.6f, 1.6f), Main.rand.NextFloat(-1.6f, 1.6f)); dust.noGravity = true; dust.scale = 1.4f; if (dustType == 269) { dust.position = projectile.Center; } dust.noLight = true; } projectile.ai[1] += 1f; if (projectile.ai[1] >= 25f) { projectile.velocity.Y += 0.15f; projectile.velocity.X *= 0.99f; } Vector2 vectorToCursor = projectile.Center - player.Center; bool projDirection = projectile.Center.X < player.Center.X; if (projectile.Center.X < player.Center.X) { vectorToCursor = -vectorToCursor; } player.direction = ((projDirection) ? -1 : 1); player.itemRotation = vectorToCursor.ToRotation(); player.itemTime = 20; player.itemAnimation = 20; } } public override void Kill(int timeLeft) { Player player = Main.player[projectile.owner]; Main.PlaySound(2, (int)player.position.X, (int)player.position.Y, 14); //boom Main.PlaySound(2, (int)player.position.X, (int)player.position.Y, 74); //fork boom for (int counter = 0; counter <= 21; counter++) { Vector2 velocity = new Vector2(Main.rand.NextFloat(-2f, 2f), Main.rand.NextFloat(-2f, 2f)); int dustType = Utils.SelectRandom<int>(Main.rand, new int[] { 269, 6 }); int dust = Dust.NewDust(new Vector2(projectile.position.X, projectile.position.Y), projectile.width, projectile.height, dustType, 0f, 0f, 100, default(Color), 1.2f); Main.dust[dust].velocity = velocity * 8f; Main.dust[dust].scale *= 1.4f; Main.dust[dust].scale += Main.rand.NextFloat(0.8f, 1.6f); Main.dust[dust].noGravity = true; } for (int counter2 = 0; counter2 <= 10; counter2++) //sparks { Vector2 velocity = new Vector2(Main.rand.NextFloat(-4f, 4f), Main.rand.NextFloat(-4f, 4f)); velocity *= 2f * (counter2 / 3); int dustType = 133; int dust = Dust.NewDust(new Vector2(projectile.Center.X, projectile.Center.Y), projectile.width, projectile.height, dustType, 0f, 0f, 100, default(Color), 1.2f); Main.dust[dust].velocity = velocity; } } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using Otiport.API.Contract.Request.Medicines; using Otiport.API.Helpers; using Otiport.API.Services; namespace Otiport.API.Controllers { [Route("medicines")] [ApiController] public class MedicinesController : ApiControllerBase { private readonly IMedicineService _medicineService; public MedicinesController(IMedicineService medicineService) { _medicineService = medicineService; } [HttpPost] public async Task<IActionResult> AddMedicine([FromBody] AddMedicineRequest request) { var response = await _medicineService.AddMedicineAsync(request); return GenerateResponse(response); } [HttpGet] public async Task<IActionResult> GetMedicines() { GetMedicinesRequest request = new GetMedicinesRequest(); var response = await _medicineService.GetMedicinesAsync(request); return GenerateResponse(response); } [HttpDelete] public async Task<IActionResult> DeleteMedicine([FromBody] DeleteMedicineRequest request) { var response = await _medicineService.DeleteMedicineAsync(request); return GenerateResponse(response); } [HttpPut("{id}")] public async Task<IActionResult> UpdateMedicine([FromRoute] int id, [FromBody] UpdateMedicineRequest request) { request = request ?? new UpdateMedicineRequest(); request.Id = id; var response = await _medicineService.UpdateMedicinesAsync(request); return GenerateResponse(response); } } }
// Copyright © 2020 Void-Intelligence All Rights Reserved. using Nomad.Core; namespace Vortex.Normalization.Utility { public abstract class BaseNormalization : INormalization { public abstract Matrix Normalize(Matrix input); public abstract ENormalizationType Type(); } }
using UnityEngine; public class vButton : MonoBehaviour { public int btnIndex; }
namespace Sentry; public readonly partial struct MeasurementUnit { /// <summary> /// A fraction unit /// </summary> /// <seealso href="https://getsentry.github.io/relay/relay_metrics/enum.FractionUnit.html"/> public enum Fraction { /// <summary> /// Floating point fraction of 1. /// A ratio of 1.0 equals 100%. /// </summary> Ratio, /// <summary> /// Ratio expressed as a fraction of 100. /// 100% equals a ratio of 1.0. /// </summary> Percent } /// <summary> /// Implicitly casts a <see cref="MeasurementUnit.Fraction"/> to a <see cref="MeasurementUnit"/>. /// </summary> public static implicit operator MeasurementUnit(Fraction unit) => new(unit); }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RTreeCodeApproach { public class Search { private int distanceCalculated = 0; //Calculates the minimum distance from a point to a minimum bounding rectangle double MinDistance(double objLng, double objLat, double mbrMinY, double mbrMaxY, double mbrMinX, double mbrMaxX) { var objBounds = new double[4]; objBounds[0] = objLng; objBounds[1] = objLat; objBounds[2] = objLng; objBounds[3] = objLat; var MBR = new double[4]; MBR[0] = mbrMinY; MBR[1] = mbrMaxY; MBR[2] = mbrMinX; MBR[3] = mbrMaxX; double sum = 0.0; double r; int i; for (i = 0; i < 2; i++) { if (objBounds[i] < MBR[2 * i]) r = MBR[2 * i]; else { if (objBounds[i] > MBR[2 * i + 1]) r = MBR[2 * i + 1]; else r = objBounds[i]; } sum += Math.Pow(objBounds[i] - r, 2); } return (Math.Sqrt(sum)); } /// <summary> /// Incremental nearest neighbor /// </summary> /// <param name="lat">Users latitude</param> /// <param name="lng">Users longitude</param> /// <param name="tree">R tree</param> /// <param name="k">Desired number of results</param> /// <param name="keywords">User defined keywords</param> /// <param name="result">List to store results</param> private void IncNearest(double lat, double lng, RBush<Restaurant> tree, int k, List<string> keywords, out List<ISpatialData> result) { PriorityQueue<ISpatialData> queue = new PriorityQueue<ISpatialData>(); queue.Add(0, tree.root); result = new List<ISpatialData>(); bool kFound = false; while (queue.Count != 0) { if (kFound) break; var element = queue.RemoveMin(); if (element.Height >= 2) //non leaf node { foreach (var child in element.Children) { double priority = MinDistance(lng, lat, child.Envelope.MinY, child.Envelope.MaxY, child.Envelope.MinX, child.Envelope.MaxX); queue.Add(priority, child); child.Distance = priority; } } else if (element.IsLeaf) //leaf node { foreach (var obj in element.Children) { double priority = MinDistance(lng, lat, obj.Envelope.MinY, obj.Envelope.MaxY, obj.Envelope.MinX, obj.Envelope.MaxX); queue.Add(priority, obj); obj.Distance = priority; distanceCalculated++; } } else //object { /*** search for all keywords ***/ //if (keywords.All(kw => element.Keywords.Contains(kw))) // result.Add(element); /*** search for any keywords ***/ if (keywords.Any(kw => element.Keywords.Contains(kw))) result.Add(element); if (result.Count == k) { kFound = true; } } } } private List<Restaurant> LoadData() { var allRest = new List<Restaurant>(); using (var reader = new StreamReader(@"C:\Users\Tolnes\Documents\Sync\Infomations teknologi\6. Semester\Bachelor\500k.csv")) { int i = 0; while (!reader.EndOfStream) { i++; var line = reader.ReadLine(); var values = line.Split('|'); if (values.Length == 6) { var kw = values[5].Split(';'); allRest.Add(new Restaurant(values[4], kw.ToList(), Convert.ToDouble(values[2]), Convert.ToDouble(values[3]), Convert.ToDouble(values[2]), Convert.ToDouble(values[3]))); } else { Console.WriteLine(i.ToString()); Console.WriteLine(values[1]); } } return allRest; } } //Use this to initalize the R tree and invoke the INN algorithm public void SearchWithINN() { var tree = new RBush<Restaurant>(); tree.BulkLoad(LoadData()); Console.WriteLine("Dataloaded"); var result = new List<ISpatialData>(); //Initializes a list of keywords to search for var keywords = new List<string>(); //keywords.Add("Italian"); keywords.Add("Pizza"); //keywords.Add("Pasta"); //keywords.Add("Burger"); //keywords.Add("American"); //keywords.Add("Pie"); //keywords.Add("Milkshake"); //keywords.Add("Fried chicken"); //keywords.Add("Corndogs"); var sw = new Stopwatch(); var timeList = new List<string>(); Console.WriteLine("R tree Approach"); for (int i = 1; i <= 100; i++) { sw.Start(); IncNearest(57.04, 9.92, tree, 10, keywords, out result); sw.Stop(); var time = sw.Elapsed.TotalMilliseconds; timeList.Add(Convert.ToString(time)); Console.WriteLine(time); sw.Reset(); } foreach (var rest in result) { Console.WriteLine(rest); } Console.WriteLine(distanceCalculated); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace ConsoleApp7 { class Program { static void Main(string[] args) { double salario, aumento, resultado; Console.Write("salario: "); salario = double.Parse(Console.ReadLine()); aumento = salario * 0.25; resultado = aumento+ salario; Console.WriteLine("Aumento será de: " +resultado ); Console.ReadKey(); } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// Clase se encarga de la camara en la escena de juego. /// Fue creada a partir de una clase tomada como referencia. /// Brackeys,"MULTIPLE TARGET CAMERA in Unity", Youtube, 17-Dec-2017.[Online].Available: https://www.youtube.com/watch?v=aLpixrPvlB8. /// [Accesed: 13-Dec-2020] /// </summary> public class MultipleTargetCamera : MonoBehaviour { private List<Transform> targets; private GameObject[] playerlist; public Vector3 offset; private Vector3 velocity; public Camera cam; public float smoothTime = 0.5f; public float maxZoom = 6f; public float minZoom = 4f; public float zoomLimit = 26f; private int indice; private bool updated; private void Start() { offset.z = -10f; playerlist = PlayerManager.getPlayerlist(); targets = new List<Transform>(); updated = false; } private void OnEnable() { PlayerManager.OnPlayerListChange += UpdateTargets; } private void OnDisable() { PlayerManager.OnPlayerListChange -= UpdateTargets; } /// <summary> /// Obtiene lso objetos jugdor del PlayerManager y los conecta a la camara /// </summary> private void UpdateTargets() { playerlist = PlayerManager.getPlayerlist(); indice = 0; foreach (GameObject newPlayer in playerlist) { if (newPlayer.activeSelf) { Debug.Log(newPlayer.transform); PlayerHub playerhub = newPlayer.GetComponent(typeof(PlayerHub)) as PlayerHub; Transform child = newPlayer.transform.Find(playerhub.getActiveModel()); targets.Add(child); indice++; } } updated = true; } /// <summary> /// Mueve la camara /// </summary> private void LateUpdate() { if (updated) { if (indice == 0) { return; Debug.Log("Es cero"); } moveCamara(); zoomCamara(); } } /// <summary> /// Calcula la distancia a la cual la camara esta de los objetos segun cuan separados estan /// </summary> void zoomCamara() { float newZoom = Mathf.Lerp(minZoom, maxZoom, GetGreatestDistance()/zoomLimit); cam.fieldOfView = newZoom; } /// <summary> /// Calcula la mayor distancia entre los objetos. /// </summary> /// <returns>La mayor distancia entres lso objetos como float</returns> float GetGreatestDistance() { if(indice == 0) { return 0f; } var bounds = new Bounds(targets[0].position,Vector2.zero); for(int i = 0; i < targets.Count; i++) { bounds.Encapsulate(targets[i].position); } return bounds.size.x; } /// <summary> /// Mueve la camara segun la posicion de los objetos /// </summary> void moveCamara() { Vector3 centerPoint = GetCenterPoint(); Vector3 withOffset = centerPoint + offset; transform.position = Vector3.SmoothDamp(transform.position, withOffset, ref velocity, smoothTime); } /// <summary> /// Calcula el centro de un rectangulo que encierra a todos los objetos /// </summary> /// <returns>El punto central entre los objetos como un Vector3</returns> Vector3 GetCenterPoint() { if (indice == 0) { return new Vector3(0,0,0); } else if (indice == 1){ return targets[0].position; } else { Bounds bounds = new Bounds(targets[0].position, Vector2.zero); for (int i = 0; i < indice; i++) { bounds.Encapsulate(targets[i].position); } return bounds.center; } } }
using Newtonsoft.Json; using System.Collections.Generic; namespace Intelecom.SmsGateway.Client.Models { /// <summary> /// Settings. /// </summary> public class Settings { /// <summary> /// Uses service value unless specified. /// Used to prioritize between messages sent from the same service. /// 1: low (slower), 2: medium, 3: high(faster) /// </summary> public int? Priority { get; set; } /// <summary> /// Uses service value unless specified. /// Specifies the TTL(time to live) for the message, /// i.e.how long before the message times out in cases /// where it cannot be delivered to a handset. /// </summary> public int? Validity { get; set; } /// <summary> /// Arbitrary string set by the client to enable grouping messages in certain statistic reports. /// </summary> public string Differentiator { get; set; } /// <summary> /// Only relevant for CPA/GAS messages. /// Defines an age limit for message content. /// The mobile network operators enforces this. /// IMPORTANT: If the service is a subscription service all CPA/GAS messages must have age set to 18. /// Valid values: 0, 16 or 18. /// </summary> public int? Age { get; set; } /// <summary> /// Used to start a new session. /// </summary> public bool NewSession { get; set; } /// <summary> /// Used to continue an existing session. /// </summary> public string SessionId { get; set; } /// <summary> /// Arbitrary string set by the client to enable grouping messages on the service invoice. /// </summary> public string InvoiceNode { get; set; } /// <summary> /// Currently not in use. /// </summary> public bool AutoDetectEncoding { get; set; } /// <summary> /// If set to true the gateway will remove or safely substitute invalid characters in the message content instead of rejecting the message. /// </summary> public bool SafeRemoveNonGsmCharacters { get; set; } /// <summary> /// Uses service value unless specified. Used to specify the originator. /// </summary> public OriginatorSettings OriginatorSettings { get; set; } /// <summary> /// Uses service value unless specified. Used if the message is a CPA Goods and Services transaction. /// </summary> public GasSettings GasSettings { get; set; } /// <summary> /// Used if the message should be queued and sent in the future instead of immediately. /// </summary> public SendWindow SendWindow { get; set; } /// <summary> /// Used to specify special settings including settings for binary message. /// </summary> [JsonProperty("parameter")] public IEnumerable<Parameter> Parameters { get; set; } /// <summary> /// Returns a string that represents the current object. /// </summary> /// <returns> /// A string that represents the current object. /// </returns> public override string ToString() => $"Priority: {Priority}, Validity: {Validity}, Differentiator: {Differentiator}, Age: {Age}, " + $"NewSession: {NewSession}, SessionId: {SessionId}, InvoiceNode: {InvoiceNode}, " + $"AutoDetectEncoding: {AutoDetectEncoding}, SafeRemoveNonGsmCharacters: {SafeRemoveNonGsmCharacters}, " + $"OriginatorSettings: {OriginatorSettings}, GasSettings: {GasSettings}, SendWindow: {SendWindow}, Parameter: {Parameters}"; } }
using System.Collections.Generic; namespace Restaurants.Domain { public interface IMenuService : IServiceBase<Menu> { List<Menu> GetMenuByRestaurant(int idRestaurant); } }
using System; using System.Collections.Generic; using Hl7.Fhir.Support; using System.Xml.Linq; /* Copyright (c) 2011-2012, HL7, Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of HL7 nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ // // Generated on Mon, Apr 15, 2013 13:14+1000 for FHIR v0.08 // using Hl7.Fhir.Model; using System.Xml; namespace Hl7.Fhir.Parsers { /// <summary> /// Parser for Observation instances /// </summary> internal static partial class ObservationParser { /// <summary> /// Parse Observation /// </summary> public static Observation ParseObservation(IFhirReader reader, ErrorList errors, Observation existingInstance = null ) { Observation result = existingInstance != null ? existingInstance : new Observation(); try { string currentElementName = reader.CurrentElementName; reader.EnterElement(); while (reader.HasMoreElements()) { // Parse element extension if( ParserUtils.IsAtFhirElement(reader, "extension") ) { result.Extension = new List<Extension>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "extension") ) result.Extension.Add(ExtensionParser.ParseExtension(reader, errors)); reader.LeaveArray(); } // Parse element language else if( ParserUtils.IsAtFhirElement(reader, "language") ) result.Language = CodeParser.ParseCode(reader, errors); // Parse element text else if( ParserUtils.IsAtFhirElement(reader, "text") ) result.Text = NarrativeParser.ParseNarrative(reader, errors); // Parse element contained else if( ParserUtils.IsAtFhirElement(reader, "contained") ) { result.Contained = new List<Resource>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "contained") ) result.Contained.Add(ParserUtils.ParseContainedResource(reader,errors)); reader.LeaveArray(); } // Parse element internalId else if( reader.IsAtRefIdElement() ) result.InternalId = Id.Parse(reader.ReadRefIdContents()); // Parse element name else if( ParserUtils.IsAtFhirElement(reader, "name") ) result.Name = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element value else if( ParserUtils.IsAtFhirElement(reader, "value", true) ) result.Value = FhirParser.ParseElement(reader, errors); // Parse element interpretation else if( ParserUtils.IsAtFhirElement(reader, "interpretation") ) result.Interpretation = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element comments else if( ParserUtils.IsAtFhirElement(reader, "comments") ) result.Comments = FhirStringParser.ParseFhirString(reader, errors); // Parse element applies else if( ParserUtils.IsAtFhirElement(reader, "applies", true) ) result.Applies = FhirParser.ParseElement(reader, errors); // Parse element issued else if( ParserUtils.IsAtFhirElement(reader, "issued") ) result.Issued = InstantParser.ParseInstant(reader, errors); // Parse element status else if( ParserUtils.IsAtFhirElement(reader, "status") ) result.Status = CodeParser.ParseCode<ObservationStatus>(reader, errors); // Parse element reliability else if( ParserUtils.IsAtFhirElement(reader, "reliability") ) result.Reliability = CodeParser.ParseCode<Observation.ObservationReliability>(reader, errors); // Parse element bodySite else if( ParserUtils.IsAtFhirElement(reader, "bodySite") ) result.BodySite = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element method else if( ParserUtils.IsAtFhirElement(reader, "method") ) result.Method = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element identifier else if( ParserUtils.IsAtFhirElement(reader, "identifier") ) result.Identifier = IdentifierParser.ParseIdentifier(reader, errors); // Parse element subject else if( ParserUtils.IsAtFhirElement(reader, "subject") ) result.Subject = ResourceReferenceParser.ParseResourceReference(reader, errors); // Parse element performer else if( ParserUtils.IsAtFhirElement(reader, "performer") ) result.Performer = ResourceReferenceParser.ParseResourceReference(reader, errors); // Parse element referenceRange else if( ParserUtils.IsAtFhirElement(reader, "referenceRange") ) { result.ReferenceRange = new List<Observation.ObservationReferenceRangeComponent>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "referenceRange") ) result.ReferenceRange.Add(ObservationParser.ParseObservationReferenceRangeComponent(reader, errors)); reader.LeaveArray(); } // Parse element component else if( ParserUtils.IsAtFhirElement(reader, "component") ) { result.Component = new List<Observation.ObservationComponentComponent>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "component") ) result.Component.Add(ObservationParser.ParseObservationComponentComponent(reader, errors)); reader.LeaveArray(); } else { errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader); reader.SkipSubElementsFor(currentElementName); result = null; } } reader.LeaveElement(); } catch (Exception ex) { errors.Add(ex.Message, reader); } return result; } /// <summary> /// Parse ObservationComponentComponent /// </summary> public static Observation.ObservationComponentComponent ParseObservationComponentComponent(IFhirReader reader, ErrorList errors, Observation.ObservationComponentComponent existingInstance = null ) { Observation.ObservationComponentComponent result = existingInstance != null ? existingInstance : new Observation.ObservationComponentComponent(); try { string currentElementName = reader.CurrentElementName; reader.EnterElement(); while (reader.HasMoreElements()) { // Parse element extension if( ParserUtils.IsAtFhirElement(reader, "extension") ) { result.Extension = new List<Extension>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "extension") ) result.Extension.Add(ExtensionParser.ParseExtension(reader, errors)); reader.LeaveArray(); } // Parse element internalId else if( reader.IsAtRefIdElement() ) result.InternalId = Id.Parse(reader.ReadRefIdContents()); // Parse element name else if( ParserUtils.IsAtFhirElement(reader, "name") ) result.Name = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element value else if( ParserUtils.IsAtFhirElement(reader, "value", true) ) result.Value = FhirParser.ParseElement(reader, errors); else { errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader); reader.SkipSubElementsFor(currentElementName); result = null; } } reader.LeaveElement(); } catch (Exception ex) { errors.Add(ex.Message, reader); } return result; } /// <summary> /// Parse ObservationReferenceRangeComponent /// </summary> public static Observation.ObservationReferenceRangeComponent ParseObservationReferenceRangeComponent(IFhirReader reader, ErrorList errors, Observation.ObservationReferenceRangeComponent existingInstance = null ) { Observation.ObservationReferenceRangeComponent result = existingInstance != null ? existingInstance : new Observation.ObservationReferenceRangeComponent(); try { string currentElementName = reader.CurrentElementName; reader.EnterElement(); while (reader.HasMoreElements()) { // Parse element extension if( ParserUtils.IsAtFhirElement(reader, "extension") ) { result.Extension = new List<Extension>(); reader.EnterArray(); while( ParserUtils.IsAtArrayElement(reader, "extension") ) result.Extension.Add(ExtensionParser.ParseExtension(reader, errors)); reader.LeaveArray(); } // Parse element internalId else if( reader.IsAtRefIdElement() ) result.InternalId = Id.Parse(reader.ReadRefIdContents()); // Parse element meaning else if( ParserUtils.IsAtFhirElement(reader, "meaning") ) result.Meaning = CodeableConceptParser.ParseCodeableConcept(reader, errors); // Parse element range else if( ParserUtils.IsAtFhirElement(reader, "range", true) ) result.Range = FhirParser.ParseElement(reader, errors); else { errors.Add(String.Format("Encountered unknown element {0} while parsing {1}", reader.CurrentElementName, currentElementName), reader); reader.SkipSubElementsFor(currentElementName); result = null; } } reader.LeaveElement(); } catch (Exception ex) { errors.Add(ex.Message, reader); } return result; } } }
using System; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace NumbersToWords.Tests { [TestClass] public class UnitsConverter_Tests { [TestMethod] public void Given_I_Have_A_Value_Of_1_The_Value_Returned_Should_Be_One() { // Given I have a value of 1 var value = 1; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "one" Assert.AreEqual("one", result); } [TestMethod] public void Given_I_Have_A_Value_Of_2_The_Value_Returned_Should_Be_Two() { // Given I have a value of 2 var value = 2; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "two" Assert.AreEqual("two", result); } [TestMethod] public void Given_I_Have_A_Value_Of_3_The_Value_Returned_Should_Be_Three() { // Given I have a value of 3 var value = 3; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "three" Assert.AreEqual("three", result); } [TestMethod] public void Given_I_Have_A_Value_Of_4_The_Value_Returned_Should_Be_Four() { // Given I have a value of 4 var value = 4; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "four" Assert.AreEqual("four", result); } [TestMethod] public void Given_I_Have_A_Value_Of_5_The_Value_Returned_Should_Be_Five() { // Given I have a value of 5 var value = 5; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "five" Assert.AreEqual("five", result); } [TestMethod] public void Given_I_Have_A_Value_Of_6_The_Value_Returned_Should_Be_Six() { // Given I have a value of 6 var value = 6; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "six" Assert.AreEqual("six", result); } [TestMethod] public void Given_I_Have_A_Value_Of_7_The_Value_Returned_Should_Be_Seven() { // Given I have a value of 7 var value = 7; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "seven" Assert.AreEqual("seven", result); } [TestMethod] public void Given_I_Have_A_Value_Of_8_The_Value_Returned_Should_Be_Eight() { // Given I have a value of 8 var value = 8; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "eight" Assert.AreEqual("eight", result); } [TestMethod] public void Given_I_Have_A_Value_Of_9_The_Value_Returned_Should_Be_Nine() { // Given I have a value of 9 var value = 9; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "nine" Assert.AreEqual("nine", result); } [TestMethod] public void Given_I_Have_A_Value_Of_10_The_Value_Returned_Should_Be_Ten() { // Given I have a value of 10 var value = 10; // When I pass the value into the word converter IUnitsConverter converter = new UnitsConverter(); string result = converter.ConvertSingleNumberToWord(value); // Then I expect the value returned is "ten" Assert.AreEqual("ten", result); } } }
using Framework.Core.Common; using Tests.Data.Van.Input; using OpenQA.Selenium; using Tests.Pages.Van.Main.Common; using Tests.Pages.Van.Main.LiveCallsCampaign; namespace Tests.Pages.Van.Main.LiveCallsCampaign { public class LiveCallsWizard :VanBasePage { #region Element Declarations #region Setup Tab Elements //public new IWebElement TabLabel { get { return TabLabel("Setup"); } } public IWebElement CampaignNameField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsName_VANInputItemDetailsItemLiveCallsName_LiveCallsName")); } } public IWebElement CallingScriptDropDown { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsScripts_VANInputItemDetailsItemLiveCallsScripts_LiveCallsScripts")); } } public IWebElement CampaignBudgetField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsBudget_VANInputItemDetailsItemLiveCallsBudget_LiveCallsBudget")); } } public IWebElement DescriptionTextarea { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsDescription_VANInputItemDetailsItemLiveCallsDescription_LiveCallsDescription")); } } public IWebElement NextChooseDatesButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_Next1")); } } #endregion #region Schedule Tab // public new IWebElement TabLabel { get { return TabLabel("Schedule"); } } public IWebElement CallingDatesFromField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemDateFrom_VANInputItemDetailsItemDateFrom_DateFrom")); } } public IWebElement CallingDatesToField { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemDateFrom_VANInputItemDetailsItemDateFrom_VanInputItemDateTo_VanInputItemDateTo")); } } public IWebElement SpecialInstructionsForCallersTextArea { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemInstructions_VANInputItemDetailsItemInstructions_Instructions")); } } public IWebElement PreviousButton { get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_Prev2")); } } public IWebElement NextConfirmationButton {get { return _driver.FindElement(By.CssSelector("ctl00_ContentPlaceHolderVANPage_Next2"));}} #endregion #region Confirmation Tab public IWebElement ContactNameField {get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsContactName_VANInputItemDetailsItemLiveCallsContactName_LiveCallsContactName")); }} public IWebElement PhoneNumberField {get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsPhoneNum_VANInputItemDetailsItemLiveCallsPhoneNum_LiveCallsPhoneNum")); }} public IWebElement EmailAddressField {get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsEmail_VANInputItemDetailsItemLiveCallsEmail_LiveCallsEmail")); }} public IWebElement OrganizationNameField {get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsOrganizationName_VANInputItemDetailsItemLiveCallsOrganizationName_LiveCallsOrganizationName")); }} public IWebElement TermsAndConditionsRadioButton {get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_VanDetailsItemLiveCallsTermsAndConditions_VANInputItemDetailsItemLiveCallsTermsAndConditions_LiveCallsTermsAndConditions_0")); }} public IWebElement PreviousButton2 {get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_Prev3")); }} public IWebElement FinishSendCampaignToCallCenterButton {get { return _driver.FindElement(By.Id("ctl00_ContentPlaceHolderVANPage_Finish3"));}} #endregion // public string TabLabelText { get { return TabLabel.Text; } } #endregion public LiveCallsWizard(Driver driver) : base(driver) { } public void SetCampaignName(string campaignName) { _driver.ClearAndSendKeys(CampaignNameField, campaignName); } } }
using AddressBook.Infrastructure.Domain; using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading.Tasks; namespace AddressBook.Repository.Extensions { public static class QueryableExtensions { public static async Task<PaginationResult<T>> GetPagedResultAsync<T>( this IQueryable<T> query, int? page, int? pageSize) { var result = new PaginationResult<T>(); result.CurrentPage = !page.HasValue || page.Value == 0 ? 1 : page.Value; result.PageSize = pageSize ?? int.MaxValue; result.RowCount = query.Count(); var pageCount = (double)result.RowCount / result.PageSize; result.PageCount = (int)Math.Ceiling(pageCount); var skip = (result.CurrentPage - 1) * result.PageSize; result.Results = await query.Skip(skip).Take(result.PageSize).ToListAsync(); return result; } } }
using System; using System.Collections.Generic; using System.Text; using DBDiff.Schema.Model; namespace DBDiff.Schema.SQLServer2000.Model { /// <summary> /// Clase de constraints de Columnas (Default Constraint y Check Constraint) /// </summary> public class ColumnConstraint:SchemaBase { private Constraint.ConstraintType type; private string value; private Boolean notForReplication; public ColumnConstraint(Column parent) : base("[", "]", StatusEnum.ObjectTypeEnum.Constraint) { this.Parent = parent; this.Status = StatusEnum.ObjectStatusType.OriginalStatus; } /// <summary> /// Clona el objeto ColumnConstraint en una nueva instancia. /// </summary> public ColumnConstraint Clone(Column parent) { ColumnConstraint ccons = new ColumnConstraint(parent); ccons.Name = this.Name; ccons.Type = this.Type; ccons.Value = this.Value; ccons.Status = this.Status; return ccons; } /// <summary> /// Indica si la constraint va a ser usada en replicacion. /// </summary> public Boolean NotForReplication { get { return notForReplication; } set { notForReplication = value; } } /// <summary> /// Valor de la constraint. /// </summary> public string Value { get { return this.value; } set { this.value = value; } } /// <summary> /// Indica el tipo de constraint (Default o Check constraint). /// </summary> public Constraint.ConstraintType Type { get { return type; } set { type = value; } } /// <summary> /// Convierte el schema de la constraint en XML. /// </summary> public string ToXML() { string xml = ""; if (this.Type == Constraint.ConstraintType.Default) { xml += "<COLUMNCONSTRAINT name=\"" + Name + "\" type=\"DF\" value=\"" + value + "\"/>\n"; } if (this.Type == Constraint.ConstraintType.Check) { xml += "<COLUMNCONSTRAINT name=\"" + Name + "\" type=\"C\" value=\"" + value + "\" notForReplication=\"" + (NotForReplication?"1":"0") + "\"/>\n"; } return xml; } /// <summary> /// Compara dos campos y devuelve true si son iguales, caso contrario, devuelve false. /// </summary> public static Boolean Compare(ColumnConstraint origen, ColumnConstraint destino) { if (origen.NotForReplication != destino.NotForReplication) return false; if (!origen.Value.Equals(destino.Value)) return false; return true; } /// <summary> /// Devuelve el schema de la constraint en formato SQL. /// </summary> public string ToSQL() { string sql = ""; if (this.Type == Constraint.ConstraintType.Default) sql = " CONSTRAINT [" + Name + "] DEFAULT " + value; if (this.Type == Constraint.ConstraintType.Check) sql = " CONSTRAINT [" + Name + "] CHECK " + (NotForReplication?"NOT FOR REPLICATION":"") + " (" + value + ")"; return sql; } public override string ToSQLAdd() { if (this.Type == Constraint.ConstraintType.Default) return "ALTER TABLE " + ((Table)Parent.Parent).FullName + " ADD" + ToSQL() + " FOR " + Parent.Name + "\r\nGO\r\n"; if (this.Type == Constraint.ConstraintType.Check) return "ALTER TABLE " + ((Table)Parent.Parent).FullName + " ADD" + ToSQL() + "\r\nGO\r\n"; return ""; } public override string ToSQLDrop() { return "ALTER TABLE " + ((Table)Parent.Parent).FullName + " DROP CONSTRAINT [" + Name + "]\r\nGO\r\n"; } } }
using System.ComponentModel; using Android.Graphics; using Android.Text; using Android.Views; using Android.App; using Android.Content; using Xamarin.Forms; using Xamarin.Forms.Platform.Android; using CustomXamarinControls; using CustomXamarinControls.Droid; [assembly: ExportRenderer(typeof(LabelStriked), typeof(LabelStrikedRenderer))] namespace CustomXamarinControls.Droid { public class LabelStrikedRenderer : LabelRenderer { public LabelStrikedRenderer(Context context) : base (context) { } protected override void OnElementChanged(ElementChangedEventArgs<Label> e) { base.OnElementChanged(e); if (Control != null) { //Control.Gravity = GravityFlags.CenterVertical | GravityFlags.Left; //Control.SetBackgroundColor(Android.Graphics.Color.Transparent); //Control.InputType |= InputTypes.TextFlagNoSuggestions; //Control.SetPadding(25, Control.PaddingTop, Control.PaddingRight, Control.PaddingBottom); UpdateStrikeThrough(e.NewElement as LabelStriked); } } protected override void OnElementPropertyChanged(object sender, PropertyChangedEventArgs e) { base.OnElementPropertyChanged(sender, e); if (e.PropertyName == nameof(LabelStriked.IsStrikeThrough)) { UpdateStrikeThrough(sender as LabelStriked); } } private void UpdateStrikeThrough(LabelStriked label) { if (label?.IsStrikeThrough == true) { Control.PaintFlags |= PaintFlags.StrikeThruText; } else { Control.PaintFlags &= ~PaintFlags.StrikeThruText; } } } }
using Microsoft.VisualBasic; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using DataLayer; using Wpro.GSM.TelerikUI; using BusinessLayer; namespace Wpro.GSM.TelerikUI.adm { public partial class WebForm1 : System.Web.UI.Page { private SqlDataReader mdrDB; private SqlCommand mcmdDB; RightsModule rightMod = new RightsModule(); protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { RightsObject RightsObj = new RightsObject(); int user_level = 0; RightsObj = rightMod.checkRight("Responsibility"); if (RightsObj != null) { user_level = RightsObj.User_Level; hid_user_level.Value = user_level.ToString(); hid_Office.Value = Session["gsm_office_code"].ToString(); hid_Division.Value = Session["gsm_dir_code"].ToString(); hid_Unit.Value = Session["gsm_unit_code"].ToString(); } else { Response.Redirect("~/no_rights.aspx", false); } } } private string Fld2Str(string varString, bool boTrim = true, string stDefault = "") { string stRetVal = null; if (Information.IsDBNull(varString)) { stRetVal = stDefault; } else { if (Information.IsDate(varString)) { stRetVal = Strings.Format(varString, "dd MMM yyyy"); } else if (boTrim) { stRetVal = Strings.Trim(varString); } else { stRetVal = varString; } if (stRetVal == string.Empty) { stRetVal = stDefault; } } return stRetVal; } protected void btnExport_Click(System.Object sender, System.EventArgs e) { Response.Clear(); Response.Buffer = true; Response.AddHeader("Content-Disposition", "attachment;filename=Responsibility.xls"); Response.ContentType = "application/vnd.ms-excel"; Response.Write(GenHtmlTable()); Response.End(); } // export function private object GenHtmlTable() { AdministrationManager AM = new AdministrationManager(); StringBuilder sRet = default(StringBuilder); string stCurStaff = null; string stStaffName = null; string stFunctionalTitle = null; string stStfCntDate = null; string stResp = null; System.DateTime dtEndDate = default(System.DateTime); System.DateTime dtStfEndDate = default(System.DateTime); string stEndDate = null; string stStyle = null; string stStyle1 = null; int iStaffNo = 0; bool blCntrctEnd; var _chkExclStandardResp =Convert.ToBoolean(chkExclStandardResp.Value); var _chkInclStafEnd = Convert.ToBoolean(chkInclStafEnd.Value); var _chkInclInactive = Convert.ToBoolean(chkInclInactive.Value); var _chkShowResEndDate = Convert.ToBoolean(chkShowResEndDate.Value); mcmdDB = AM.Responsibility_lib_list_get( hid_Office.Value, hid_Division.Value, hid_Unit.Value, hid_staff_name.Value, hid_responsibility.Value, _chkExclStandardResp, _chkInclStafEnd, _chkInclInactive); using (mcmdDB) { mdrDB = mcmdDB.ExecuteReader(); } if (mdrDB.HasRows) { //divNoRecords.Visible = false; //qryResult.Visible = true; } else { //divNoRecords.Visible = true; //qryResult.Visible = false; } stCurStaff = null; sRet = new StringBuilder(); sRet.Append("<table class='tab_content' cellspacing='1' cellpadding='2' width='70%' border ='1'>"); sRet.Append("<tr class='tab_header2'>"); sRet.Append("<td>"); sRet.Append("<b>Office</b>"); sRet.Append("</td>"); sRet.Append("<td>"); sRet.Append("<b>Division</b>"); sRet.Append("</td>"); sRet.Append("<td>"); sRet.Append("<b>Unit</b>"); sRet.Append("</td>"); sRet.Append("<td>"); sRet.Append("<b>Staff Name</b>"); sRet.Append("</td>"); sRet.Append("<td>"); sRet.Append("<b>Post Title</b>"); sRet.Append("</td>"); sRet.Append("<td>"); sRet.Append("<b>Contract End Date</b>"); sRet.Append("</td>"); sRet.Append("<td>"); sRet.Append("<b>Responsibility</b>"); sRet.Append("</td>"); sRet.Append("<td>"); sRet.Append("<b>Responsibility End Date</b>"); sRet.Append("</td>"); sRet.Append("</tr>"); while (mdrDB.Read()) { stStaffName = Fld2Str(mdrDB["staff_name"].ToString()); stResp = Fld2Str(mdrDB["responsibility_name"].ToString()); stFunctionalTitle = Fld2Str(mdrDB["functional_title"].ToString()); if (Information.IsDBNull(mdrDB["resp_end_date"])) { stEndDate = "-"; stStyle = ""; } else { dtEndDate = !string.IsNullOrEmpty(mdrDB["resp_end_date"].ToString()) ? DateTime.Parse(mdrDB["resp_end_date"].ToString()) : DateTime.MinValue; if (_chkShowResEndDate) { stEndDate = Strings.Format(dtEndDate, "dd MMM yyyy"); } else { stEndDate = ""; } if (dtEndDate > DateAndTime.Now) { stStyle = ""; } else { stEndDate = Strings.Format(dtEndDate, "dd MMM yyyy"); stStyle = " style=color:#778899;"; } } if (Information.IsDBNull(mdrDB["contract_end_date"])) { stStfCntDate = "-"; stStyle1 = Constants.vbNullString; } else { dtStfEndDate = DateTime.Parse(mdrDB["contract_end_date"].ToString()); if (Convert.ToDateTime(dtStfEndDate) > DateAndTime.Now) { stStfCntDate = Strings.Format(dtStfEndDate, "dd MMM yyyy"); stStyle1 = ""; } else { stStfCntDate = Strings.Format(dtStfEndDate, "dd MMM yyyy"); stStyle1 = " style=color:#778899;"; stStyle = " style=color:#778899;"; } } if (Information.IsDBNull(mdrDB["contract_end_date"]) == false & Information.IsDBNull(mdrDB["resp_end_date"]) == false) { if (Convert.ToDateTime(dtEndDate) > Convert.ToDateTime(dtStfEndDate) & Convert.ToDateTime(dtStfEndDate) > DateAndTime.Now & DateAndTime.DateDiff(DateInterval.Day, Convert.ToDateTime(dtStfEndDate), Convert.ToDateTime(dtEndDate)) > 1) { stStyle = " style=color:red;"; } } if (string.IsNullOrEmpty(stStfCntDate)) { stStfCntDate = "-"; } sRet.Append("<tr class='tab_row' onMouseOver=\"this.className='highlight'\" onMouseOut=\"this.className='tab_row'\">"); sRet.Append("<td ").Append(stStyle1).Append(">"); if (stCurStaff == null | stCurStaff != stStaffName) { sRet.Append(Fld2Str(mdrDB["office_code"].ToString())).Append("</td><td ").Append(stStyle1).Append(">"); sRet.Append(Fld2Str(mdrDB["div_code"].ToString())).Append("</td><td ").Append(stStyle1).Append(">"); sRet.Append(Fld2Str(mdrDB["unit_code"].ToString())).Append("</td><td ").Append(stStyle1).Append(">"); sRet.Append(stStaffName).Append("</td><td ").Append(stStyle1).Append(">"); sRet.Append(stFunctionalTitle).Append("</td><td ").Append(stStyle1).Append(">"); sRet.Append(stStfCntDate); stCurStaff = stStaffName; iStaffNo += 1; } else { sRet.Append("&nbsp;</td><td>"); sRet.Append("&nbsp;</td><td>"); sRet.Append("&nbsp;</td><td>&nbsp;</td><td>"); sRet.Append("&nbsp;</td><td>&nbsp;"); } sRet.Append("</td><td").Append(stStyle).Append(">"); sRet.Append(stResp).Append("</td>"); sRet.Append("<td").Append(stStyle).Append(">").Append(stEndDate).Append("</td>"); sRet.Append("</tr>"); //ltRow.Text = strBuilder.ToString } mdrDB.Close(); mdrDB = null; mcmdDB.Connection.Close(); mcmdDB.Connection = null; sRet.Append("</table>"); return sRet.ToString(); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace NsWF { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void createJsonBtn_Click(object sender, EventArgs e) // coverts to Json { Person jPerson = new Person(); jPerson.firstName = firstNameTxt.Text; jPerson.lastName = lastNameTxt.Text; jPerson.contact.Add("phone", phoneTxt.Text); jPerson.contact.Add("email", emailTxt.Text); foreach (string friend in friendListBox.Items) { jPerson.Friends.Add(friend); } string newJson = Newtonsoft.Json.JsonConvert.SerializeObject(jPerson); MessageBox.Show(newJson); } private void desirialiseBtn_Click(object sender, EventArgs e) // converts to person class { string Json = jsonTxt.Text; Person person = new Person(); Newtonsoft.Json.JsonConvert.PopulateObject(Json, person); firstNameTxt.Text = person.firstName; lastNameTxt.Text = person.lastName; emailTxt.Text = person.contact["email"]; phoneTxt.Text = person.contact["phone"]; foreach (var friend in person.Friends) { friendListBox.Items.Add(friend); } } } }
using System.Collections.Generic; using System.Threading.Tasks; namespace Crawler { public interface ISimpleWebCrawler { Task<CrawlResult> PerformCrawlingAsync(IEnumerable<string> rootUrls); } }
using Sentry.Extensibility; using Sentry.Internal; namespace Sentry; /// <summary> /// Special HTTP message handler that can be used to propagate Sentry headers and other contextual information. /// </summary> public class SentryGraphQLHttpMessageHandler : SentryMessageHandler { private readonly IHub _hub; private readonly SentryOptions? _options; private readonly ISentryFailedRequestHandler? _failedRequestHandler; /// <summary> /// Constructs an instance of <see cref="SentryHttpMessageHandler"/>. /// </summary> /// <param name="innerHandler">An inner message handler to delegate calls to.</param> /// <param name="hub">The Sentry hub.</param> public SentryGraphQLHttpMessageHandler(HttpMessageHandler? innerHandler = default, IHub? hub = default) : this(hub, default, innerHandler) { } internal SentryGraphQLHttpMessageHandler(IHub? hub, SentryOptions? options, HttpMessageHandler? innerHandler = default, ISentryFailedRequestHandler? failedRequestHandler = null) : base(hub, options, innerHandler) { _hub = hub ?? HubAdapter.Instance; _options = options ?? _hub.GetSentryOptions(); _failedRequestHandler = failedRequestHandler; if (_options != null) { _failedRequestHandler ??= new SentryGraphQLHttpFailedRequestHandler(_hub, _options); } } /// <inheritdoc /> protected internal override ISpan? ProcessRequest(HttpRequestMessage request, string method, string url) { var content = GraphQLContentExtractor.ExtractRequestContentAsync(request, _options).Result; if (content is not { } graphQlRequestContent) { _options?.LogDebug("Unable to process non GraphQL request content"); return null; } request.SetFused(graphQlRequestContent); // Start a span that tracks this request // (may be null if transaction is not set on the scope) return _hub.GetSpan()?.StartChild( "http.client", $"{method} {url}" // e.g. "GET https://example.com" ); } /// <inheritdoc /> protected internal override void HandleResponse(HttpResponseMessage response, ISpan? span, string method, string url) { var graphqlInfo = response.RequestMessage?.GetFused<GraphQLRequestContent>(); var breadcrumbData = new Dictionary<string, string> { {"url", url}, {"method", method}, {"status_code", ((int) response.StatusCode).ToString()} }; AddIfExists(breadcrumbData, "request_body_size", response.RequestMessage?.Content?.Headers.ContentLength?.ToString()); #if NET5_0_OR_GREATER // Starting with .NET 5, the content and headers are guaranteed to not be null. AddIfExists(breadcrumbData, "response_body_size", response.Content.Headers.ContentLength?.ToString()); #else AddIfExists(breadcrumbData, "response_body_size", response.Content?.Headers.ContentLength?.ToString()); #endif AddIfExists(breadcrumbData, "operation_name", graphqlInfo?.OperationName); // The GraphQL operation name AddIfExists(breadcrumbData, "operation_type", graphqlInfo?.OperationType); // i.e. `query`, `mutation`, `subscription` _hub.AddBreadcrumb( string.Empty, graphqlInfo?.OperationType ?? "graphql.operation", "graphql", breadcrumbData ); // Create events for failed requests _failedRequestHandler?.HandleResponse(response); // This will handle unsuccessful status codes as well if (span is not null) { // TODO: See how we can determine the span status for a GraphQL request... span.Status = SpanStatusConverter.FromHttpStatusCode(response.StatusCode); // TODO: Don't do this if the span is errored span.Description = GetSpanDescriptionOrDefault(graphqlInfo, response.StatusCode) ?? span.Description; span.Finish(); } } private string? GetSpanDescriptionOrDefault(GraphQLRequestContent? graphqlInfo, HttpStatusCode statusCode) => string.Join(" ", graphqlInfo?.OperationNameOrFallback(), graphqlInfo?.OperationTypeOrFallback(), ((int)statusCode).ToString() ); private void AddIfExists(Dictionary<string, string> breadcrumbData, string key, string? value) { if (!string.IsNullOrEmpty(value)) { breadcrumbData[key] = value; } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; public class FloaterController : Projectile { protected bool hasPerched; protected bool isSlowing; protected float correctingForce = 5f; protected float speedBeforePerch; protected Vector2 velocityBeforePerch; protected float accelerationToSlowBeforePerch; protected float distanceBeforePerch = 2f; protected float distanceToStartSlowing; protected float timeToStayPerched = 0.5f; protected float minSpeed = 1.5f; protected Vector2 originalPos; protected float accelDive; //protected bool accelSet; protected bool isEnabled; protected GameObject player; protected bool isLeftToRight; protected bool isRightToLeft; protected bool isTopToBottom; protected bool isBottomToTop; bool canReverse; protected override void Start() { base.Start(); //accelerationX = DEFAULT_ACCELERATION_X; //accelerationY = DEFAULT_ACCELERATION_Y; player = GameObject.FindGameObjectWithTag("Player"); UpdateDistanceToStartSlowing(); SetPositionAsOriginalPosition(); SetDistanceBeforePerch(2f); distanceToStartSlowing = Mathf.Infinity; //velocityBeforePerch = new Vector2(-2.5f, 0); SetDirection(); SetSpeedBeforePerch(2f); SetAccelerationBeforePerch(5f); } protected override void FixedUpdate() { if (player == null) { player = GameObject.FindGameObjectWithTag("Player"); } if (!hasPerched) { if (!isSlowing && FindDistanceTraveled() >= distanceToStartSlowing) { StartCoroutine(StartSlowing()); } else if (!isSlowing){ MaintainVelocityBeforePerch(); } return; } base.FixedUpdate(); float accelX = correctingForce * Mathf.Cos(FindAngleToPlayer()); float accelY = correctingForce * Mathf.Sin(FindAngleToPlayer()); if (!canReverse) { PreventReverse(); } SetAcceleration(new Vector2(accelX, accelY)); } protected float FindDistanceTraveled() { //Debug.Log("Distance Traveled " + Mathf.Sqrt(Mathf.Pow(transform.position.x - originalPos.x, 2) + Mathf.Pow(transform.position.y - originalPos.y, 2))); return Mathf.Sqrt(Mathf.Pow(transform.position.x - originalPos.x, 2) + Mathf.Pow(transform.position.y - originalPos.y, 2)); } protected float FindAngleToPlayer() { Vector2 currentPlayerPosition = player.transform.position; return Mathf.Atan2((currentPlayerPosition.y - transform.position.y), (currentPlayerPosition.x - transform.position.x)); } protected IEnumerator StartSlowing() { isSlowing = true; //Debug.Log("Started slowing at " + FindDistanceTraveled()); while (Mathf.Abs(rb.velocity.x) > 0.01f || Mathf.Abs(rb.velocity.y) > 0.01f) { //Debug.Log(rb.velocity); if (rb.velocity.y > 0) { rb.AddForce(new Vector2(0, -rb.mass * accelerationToSlowBeforePerch)); } if (rb.velocity.y < 0) { rb.AddForce(new Vector2(0, rb.mass * accelerationToSlowBeforePerch)); } if (rb.velocity.x > 0) { rb.AddForce(new Vector2(-rb.mass * accelerationToSlowBeforePerch, 0)); } if (rb.velocity.x < 0) { rb.AddForce(new Vector2(rb.mass * accelerationToSlowBeforePerch, 0)); } yield return new WaitForFixedUpdate(); } //Debug.Log("MEH"); isSlowing = false; yield return new WaitForSeconds(timeToStayPerched); hasPerched = true; } public void SetCorrectingForce(float newCorrectingForce) { correctingForce = newCorrectingForce; } public void SetPlayer(GameObject newPlayer) { player = newPlayer; } /*public void SetDirection(string direction) { if (direction.Equals("TopToBottom")) { isVertical = true; isTopToBottom = true; } else if (direction.Equals("BottomToTop")) { isVertical = true; isTopToBottom = false; } else if (direction.Equals("LeftToRight")) { isVertical = false; isLeftToRight = true; } else { isVertical = false; isLeftToRight = false; } }*/ public void SetDistanceBeforePerch(float newDistance) { distanceBeforePerch = newDistance; MaintainVelocityBeforePerch(); UpdateDistanceToStartSlowing(); } public void SetVelocityBeforePerch() { if (isLeftToRight) { velocityBeforePerch = new Vector2(speedBeforePerch, 0); } else if (isBottomToTop) { velocityBeforePerch = new Vector2(0, speedBeforePerch); } else if (isRightToLeft) { velocityBeforePerch = new Vector2(-1 * speedBeforePerch, 0); } else if (isTopToBottom) { velocityBeforePerch = new Vector2(0, -1 * speedBeforePerch); } MaintainVelocityBeforePerch(); UpdateDistanceToStartSlowing(); } /*public void SetVelocityBeforePerch(Vector2 vel) { velocityBeforePerch = vel; MaintainVelocityBeforePerch(); UpdateDistanceToStartSlowing(); }*/ public void SetSpeedBeforePerch(float speed) { speedBeforePerch = speed; SetVelocityBeforePerch(); } public void SetAccelerationBeforePerch(float accel) { accelerationToSlowBeforePerch = accel; UpdateDistanceToStartSlowing(); } protected void SetAccelDive(float accel) { accelDive = accel; } /*public void SetAccelerationBeforePerch(Vector2 accel) { accelerationToSlowBeforePerch = accel; UpdateDistanceToStartSlowing(); }*/ public void MaintainVelocityBeforePerch() { //Debug.Log(rb.name); //Debug.Log(velocityBeforePerch); //rb = GetComponent<Rigidbody2D>(); rb.velocity = velocityBeforePerch; } protected void UpdateDistanceToStartSlowing() { /*float timeToStop = Mathf.Max(velocityBeforePerch.x / accelerationToSlowBeforePerch, velocityBeforePerch.y / accelerationToSlowBeforePerch); Debug.Log(timeToStop); float distanceTraveledWhileSlowingX = Mathf.Max(0, Mathf.Abs(velocityBeforePerch.x * timeToStop) - Mathf.Abs(0.5f * accelerationToSlowBeforePerch * timeToStop * timeToStop)); Debug.Log("Distance traveled while slowing x" + distanceTraveledWhileSlowingX); float distanceTraveledWhileSlowingY = Mathf.Max(0, Mathf.Abs(velocityBeforePerch.y * timeToStop) - Mathf.Abs(0.5f * accelerationToSlowBeforePerch * timeToStop * timeToStop)); Debug.Log("Distance traveled while slowing y" + distanceTraveledWhileSlowingY); float distanceTraveledWhileSlowing = Mathf.Sqrt(Mathf.Pow(distanceTraveledWhileSlowingX, 2) + Mathf.Pow(distanceTraveledWhileSlowingY, 2));*/ float timeToStop = speedBeforePerch / accelerationToSlowBeforePerch; //Debug.Log("Time to stop" + rb.name + timeToStop); float distanceTraveledWhileSlowing = (speedBeforePerch * timeToStop) - (0.5f * accelerationToSlowBeforePerch * Mathf.Pow(timeToStop, 2)); distanceToStartSlowing = Mathf.Max(0, distanceBeforePerch - distanceTraveledWhileSlowing); //Debug.Log(rb.name + " " + distanceToStartSlowing); //Debug.Log(distanceToStartSlowing); //Debug.Log("Distance to start slowing: " + distanceToStartSlowing); } protected void SetPositionAsOriginalPosition() { originalPos = transform.position; //Debug.Log(originalPos); } protected void ResetConditionals() { hasPerched = false; isSlowing = false; } protected void SetDirection() { float angleToPlayer = FindAngleToPlayer(); //Debug.Log(gameObject.name + " " + angleToPlayer); if (angleToPlayer <= Mathf.PI / 4 && angleToPlayer > -1 * Mathf.PI / 4) { isLeftToRight = true; } else if (angleToPlayer <= Mathf.PI * 3 / 4 && angleToPlayer > Mathf.PI / 4) { isBottomToTop = true; } else if (angleToPlayer <= -1 * Mathf.PI * 3 / 4 || angleToPlayer > Mathf.PI * 3 / 4) { isRightToLeft = true; } else { isTopToBottom = true; } UpdateDistanceToStartSlowing(); } public void SetCanReverse(bool canReverse) { this.canReverse = canReverse; } public void SetTimeToStayPerched(float time) { timeToStayPerched = time; } //It might be better to do this by keeping track of a maximum speed reached and prevent the ball from ever slowing down. ex: if leftToRight velocity will always have the max x velocity it reached. protected void PreventReverse() { if (isLeftToRight) { SetVelocity(new Vector2(Mathf.Max(minSpeed, rb.velocity.x), rb.velocity.y)); } else if (isBottomToTop) { SetVelocity(new Vector2(rb.velocity.x, Mathf.Max(minSpeed, rb.velocity.y))); } else if (isRightToLeft) { SetVelocity(new Vector2(Mathf.Min(-1 * minSpeed, rb.velocity.x), rb.velocity.y)); } else if (isTopToBottom) { SetVelocity(new Vector2(rb.velocity.x, Mathf.Min(-1 * minSpeed, rb.velocity.y))); } } }
/* * ClassName: tblAktenIntPosSet * Author: Blade * Date Created: 02/22/2011 * Description: Contains a list of tblAktenIntPos records */ using System.Data.SqlClient; using System.Data; using System.Collections; using System.Text; using MySql.Data.MySqlClient; using System; using System.Reflection; namespace HTB.Database { public class tblAktenIntPosSet { #region Property Declaration private ArrayList _lsttblAktenIntPos = new ArrayList(); public ArrayList tblAktenIntPosList { get { return _lsttblAktenIntPos; } set { _lsttblAktenIntPos = value; } } #endregion private DbConnection _con; #region Load Data public SqlDataReader GettblAktenIntPosDataReader(string psqlCommand, int connectToDatabase = DatabasePool.ConnectToHTB) { SqlDataReader _Results; _con = DatabasePool.GetConnection(psqlCommand, connectToDatabase); SqlCommand _cmd = new SqlCommand(psqlCommand, _con.Connection); _Results = _cmd.ExecuteReader(); return _Results; } public void LoadtblAktenIntPos(string psqlCommand) { LoadListFromDataReader(GettblAktenIntPosDataReader(psqlCommand)); } public void Load(String where, String order) { LoadListFromDataReader(GettblAktenIntPosDataReader("SELECT * FROM tblAktenIntPos " + (where != null ? " WHERE " + where : "") + (order != null ? " order by " + order : ""))); } public void LoadAktenIntPosByAktIntPosAkt(int aktIntPosAkt) { LoadListFromDataReader(GettblAktenIntPosDataReader("select * from tblAktenIntPos where AktIntPosAkt = " + aktIntPosAkt)); } private void LoadListFromDataReader(SqlDataReader dr) { _lsttblAktenIntPos.Clear(); RecordLoader.LoadRecordsFromDataReader( dr, tblAktenIntPosList, typeof(tblAktenIntPos), _con); } #endregion } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace tools { public class log { public static object locker = new object(); static System.IO.FileInfo file; static StreamWriter sw;static FileStream stream; static string ApplicationPath = Directory.GetCurrentDirectory().ToString(); static DirectoryInfo logDirectory = new DirectoryInfo(ApplicationPath + "\\Log"); public static void Debug(string msg) { string logmsg = string.Format("{0:yyyy年MM月dd日 HH:mm:ss:fffffff} {1}: {2}", DateTime.Now, "消息", msg); writeLine(logmsg); } public static void writeLine(string msg) { try { if (!logDirectory.Exists) { logDirectory.Create(); } if (file == null) { // System.Windows.Forms.MessageBox.Show(string.Format("c:\\{0:yyyy-MM-dd-HH:mm:ss}.log", DateTime.Now), "sss"); file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.Dispose(); } file.Refresh(); // System.Windows.Forms.MessageBox.Show(file.Length.ToString(), "ss"); if (!file.Exists) { file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.Dispose(); } if (file.Length > 1024 * 10240) { //System.Windows.Forms.MessageBox.Show("sa", "ss"); file = new FileInfo(string.Format(ApplicationPath + "\\Log\\{0:yyyy-MM-dd-HH-mm-ss}.txt", DateTime.Now)); sw = file.CreateText(); sw.WriteLine(msg); } else { sw = file.AppendText(); } sw.WriteLine(msg); sw.Flush(); // System.Windows.Forms.MessageBox.Show("sa","ss"); } catch (Exception e) { tools.log.Debug(e.ToString()); } finally{ sw.Close(); sw.Dispose(); } } } }
using System; using System.Collections.Generic; namespace Euler_Logic.Problems.AdventOfCode.Y2018 { public class Problem11 : AdventOfCodeBase { public override string ProblemName { get { return "Advent of Code 2018: 11"; } } public override string GetAnswer() { return Answer1(); } public override string GetAnswer2() { return Answer2(); } private string Answer1() { var grid = GetGrid(9110); var highest = FindHighest(grid); return highest.Item1 + "," + highest.Item2; } private string Answer2() { var grid = GetGrid(9110); var highest = FindHighestVaried(grid); return highest.Item1 + "," + highest.Item2 + "," + highest.Item3; } private Tuple<int, int> FindHighest(int[,] grid) { int highest = 0; int bestX = 0; int bestY = 0; for (int x = 0; x <= 297; x++) { for (int y = 0; y <= 297; y++) { int sum = 0; for (int xOffset = 0; xOffset <= 2; xOffset++) { for (int yOffset = 0; yOffset <= 2; yOffset++) { sum += grid[x + xOffset, y + yOffset]; } } if (sum > highest) { highest = sum; bestX = x + 1; bestY = y + 1; } } } return new Tuple<int, int>(bestX, bestY); } private Tuple<int, int, int> FindHighestVaried(int[,] grid) { int size = grid.GetUpperBound(0) + 1; var hash = new List<int[,]>(); hash.Add(grid); hash.Add(new int[size - 1, size - 1]); int bestValue = 0; int bestX = 0; int bestY = 0; int bestL = 0; for (int x = 0; x < size; x++) { for (int y = 0; y < size; y++) { if (hash[0][x, y] > bestValue) { bestValue = hash[0][x, y]; bestX = x + 1; bestY = y + 1; bestL = 1; } } } for (int x = 0; x < size - 1; x++) { for (int y = 0; y < size - 1; y++) { hash[1][x, y] = hash[0][x, y] + hash[0][x + 1, y] + hash[0][x, y + 1] + hash[0][x + 1, y + 1]; if (hash[1][x, y] > bestValue) { bestValue = hash[1][x, y]; bestX = x + 1; bestY = y + 1; bestL = 1; } } } for (int length = 3; length <= size; length++) { var next = new int[size - length + 1, size - length + 1]; for (int x = 0; x <= size - length; x++) { for (int y = 0; y <= size - length; y++) { next[x, y] = hash[1][x, y] + hash[1][x + 1, y + 1] - hash[0][x + 1, y + 1] + grid[x + length - 1, y] + grid[x, y + length - 1]; if (next[x, y] > bestValue) { bestValue = next[x, y]; bestX = x + 1; bestY = y + 1; bestL = length; } } } hash[0] = hash[1]; hash[1] = next; } return new Tuple<int, int, int>(bestX, bestY, bestL); } private int[,] GetGrid(int serialNumber) { var grid = new int[300, 300]; for (int x = 1; x <= 300; x++) { for (int y = 1; y <= 300; y++) { grid[x - 1, y - 1] = GetPower(x, y, serialNumber); } } return grid; } private int GetPower(int x, int y, int serialNumber) { var power = x + 10; power *= y; power += serialNumber; power *= x + 10; power = (power / 100) % 10; power -= 5; return power; } } }
using System; using SharpArch.Domain.DomainModel; namespace Profiling2.Domain.Prf.Events { /// <summary> /// A record of when an Event has been looked over and approved by a user. /// </summary> public class EventApproval : Entity { public virtual Event Event { get; set; } public virtual AdminUser AdminUser { get; set; } public virtual DateTime ApprovalDateTime { get; set; } public virtual string Notes { get; set; } } }
using Microsoft.Office.Interop; using Microsoft.Office.Interop.Excel; using System; using System.Collections; using System.Collections.Generic; using System.Data; using System.Data.OleDb; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading; using System.Windows.Forms; using Tricentis.TCAddOns; using Tricentis.TCAPIObjects.Objects; using DataTable = System.Data.DataTable; namespace TestSheetAddOn { public class TestSheetAddOn : TCAddOn { public override string UniqueName { get { return "Testsheet Helper"; } } } public class ExportTCtoExcel : TCAddOnTask { public override string Name => "Export Test Design model to Excel"; public override Type ApplicableType => typeof(TestSheet); //Check if it's a testcase folder not just any folder public override bool IsTaskPossible(TCObject obj) => true; public override bool RequiresChangeRights => true; public override TCObject Execute(TCObject objectToExecuteOn, TCAddOnTaskContext taskContext) { if (objectToExecuteOn is TestSheet) { //Excel information 1 int headerrow = 2; Microsoft.Office.Interop.Excel.Application oXL; try { oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); oXL.Visible = false; } catch { oXL = new Microsoft.Office.Interop.Excel.Application(); oXL.Visible = false; } TestSheet ts = (TestSheet)objectToExecuteOn; string shname = ts.DisplayedName; string[] headervalues = { }; int intcounter = 0; //Get Excel objects Workbook oWB = oXL.Workbooks.Add(); Worksheet oWS = oWB.Sheets.Add(); //oWS.Name = shname; //Find all the instances IEnumerable<TDElementWrapper> elementWrappers = TestsheetElementsHelper.GetElementsRecursively(ts); var instances = ts.Instances.Items.ToArray(); // int renamecounter = 1; int rowcountt = 0; //Write header rows int colcounter = 2; int headerrow_names = 1; oWS.Cells[headerrow_names, 1] = "Key"; oWS.Cells[headerrow_names, 2] = "Name"; oWS.Cells[headerrow_names, 3] = "Status"; oWS.Cells[headerrow_names, 4] = "Precondition"; oWS.Cells[headerrow_names, 5] = "Objective"; oWS.Cells[headerrow_names, 6] = "Folder"; oWS.Cells[headerrow_names, 7] = "Priority"; oWS.Cells[headerrow_names, 8] = "Component"; oWS.Cells[headerrow_names, 9] = "Labels"; oWS.Cells[headerrow_names, 10] = "Owner"; oWS.Cells[headerrow_names, 11] = "Estimated Time"; oWS.Cells[headerrow_names, 12] = "Coverage (Issues)"; oWS.Cells[headerrow_names, 13] = "Coverage (Pages)"; oWS.Cells[headerrow_names, 14] = "Test Script (Step-by-Step) - Step"; oWS.Cells[headerrow_names, 15] = "Test Script (Step-by-Step) - Test Data"; oWS.Cells[headerrow_names, 16] = "Test Script (Step-by-Step) - Expected Result"; oWS.Cells[headerrow_names, 17] = "Test Script (Plain Text))"; oWS.Cells[headerrow_names, 18] = "Test Script (BDD)"; //foreach (TDInstance tdheader in ts.Instances.Items) //{ // for (int i = 0; i < elementWrappers.Count(); i++) // { // TDElementWrapper ewvarheader = elementWrappers.ElementAt(i); // if (ewvarheader != null) // { // string path = ewvarheader.Path; // if (path.Contains('.')) // { // string[] patharray = path.Split('.'); // for (int j = 0; j < patharray.Length; j++) // { // oWS.Cells[headerrow + (j * 1), colcounter] = patharray[j]; // if (rowcountt < headerrow + (j * 1)) { rowcountt = headerrow + (j * 1); } // } // } // else // { // oWS.Cells[headerrow, colcounter] = path; // } // colcounter = colcounter + 1; // } // } // break; //} //Range oHeader = oWS.Range[oWS.Cells[headerrow, 2], oWS.Cells[rowcountt, colcounter-1]]; //int contentrow = rowcountt + 1; //Write rows -- Instances names int contentrow = headerrow; foreach (TDInstance tdi in ts.Instances.Items) { oWS.Cells[contentrow, 2] = tdi.DisplayedName; oWS.Cells[contentrow, 3] = "Approved"; oWS.Cells[contentrow, 7] = "High"; oWS.Cells[contentrow, 8] = "PCC"; oWS.Cells[contentrow, 9] = "Drop 1 Collection Strategies"; oWS.Cells[contentrow, 14] = tdi.DisplayedName; //oWS.Cells[contentrow, 4] = "\nPrecondition: \t" + tdi.Values.ElementAt(0).ValueInstance.DisplayedName +"\nProcess:\t"; oWS.Cells[contentrow, 4] = ts.Items.ElementAt(0).DisplayedName + "\n"+ts.Items.ElementAt(0).NonTDMItems.ElementAt(0).DisplayedName+" " + ts.Items.ElementAt(0).NonTDMItems.ElementAt(0).Items.ElementAt(0).Instances.Items.ElementAt(0).DisplayedName +"\n" + ts.Items.ElementAt(0).NonTDMItems.ElementAt(1).DisplayedName + " " + ts.Items.ElementAt(0).NonTDMItems.ElementAt(1).Items.ElementAt(0).Instances.Items.ElementAt(0).DisplayedName; oWS.Cells[contentrow, 16] = ts.Items.ElementAt(0).NonTDMItems.ElementAt(2).DisplayedName + " " + ts.Items.ElementAt(0).NonTDMItems.ElementAt(2).Items.ElementAt(0).Instances.Items.ElementAt(0).DisplayedName; //string values = null; //for (int i = 0; i < elementWrappers.Count(); i++) //{ // TDElementWrapper ewvar = elementWrappers.ElementAt(i); // if (ewvar != null) // { // tdi.Name += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ewvar); // string path = ewvar.Path; // values = ElementToValueMapper.GetInstanceValueStringForElement(tdi, ewvar); // } //} //oWS.Cells[contentrow, 4] = "\n"+values+"\n"; colcounter = 2; for (int i = 0; i < elementWrappers.Count(); i++) { TDElementWrapper ewvar = elementWrappers.ElementAt(i); if (ewvar != null) { tdi.Name += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ewvar); string path = ewvar.Path; oWS.Cells[contentrow, colcounter] = ElementToValueMapper.GetInstanceValueStringForElement(tdi, ewvar); colcounter = colcounter + 1; } } contentrow = contentrow + 1; } //Try to get the relationships //Format excel document oWS.Columns.AutoFit(); oWS.Columns.Font.Size = 11; oWS.Columns.Font.Name = "Calibri"; //Range myCell = oWS.Range[oWS.Cells[rowcountt+1, 2], oWS.Cells[rowcountt + 1, 2]]; //myCell.Activate(); //myCell.Application.ActiveWindow.FreezePanes = true; //oHeader.Columns.Font.Color = XlRgbColor.rgbWhite; //oHeader.Columns.Font.Bold = true; //oHeader.Columns.HorizontalAlignment = XlHAlign.xlHAlignCenter; //oHeader.Columns.Interior.Color = XlRgbColor.rgbDarkSlateGrey; //Range contents = oWS.Range[oWS.Cells[rowcountt+1, 1], oWS.Cells[contentrow - 1, colcounter-1]]; //contents.WrapText = true; //contents.Borders.LineStyle = XlLineStyle.xlContinuous; //contents.Borders.Weight = XlBorderWeight.xlThin; //contents.Borders.ColorIndex = XlColorIndex.xlColorIndexAutomatic; //Save document System.IO.Directory.CreateDirectory("C:\\Tosca_Projects\\Tosca_Exports"); oWB.SaveAs("C:\\Tosca_Projects\\Tosca_Exports\\"+ shname + "_TCD Extract " +" DEBUG "+ DateTime.Now.ToString("MMddyyyy_hhmmss"), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //Close Excel application oWB.Close(true); oXL.Quit(); //Release Excel objects Marshal.ReleaseComObject(oWS); Marshal.ReleaseComObject(oWB); Marshal.ReleaseComObject(oXL); Process.Start(@"C:\Tosca_Projects\Tosca_Exports\"); } return null; } } //public class ExportAttributetoExcel : TCAddOnTask //{ // public override string Name => "Export TD Attribute model to Excel"; // public override Type ApplicableType => typeof(TDAttribute); // //Check if it's a testcase folder not just any folder // public override bool IsTaskPossible(TCObject obj) => true; // public override bool RequiresChangeRights => true; // public override TCObject Execute(TCObject objectToExecuteOn, TCAddOnTaskContext taskContext) // { // if (objectToExecuteOn is TDAttribute) // { // //Excel information // int headerrow = 1; // Microsoft.Office.Interop.Excel.Application oXL; // try // { // oXL = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application"); // oXL.Visible = false; // } // catch // { // oXL = new Microsoft.Office.Interop.Excel.Application(); // oXL.Visible = false; // } // TDAttribute ts = (TDAttribute)objectToExecuteOn; // string shname = ts.DisplayedName; // string[] headervalues = { }; // int intcounter = 0; // //Get Excel objects // Workbook oWB = oXL.Workbooks.Add(); // Worksheet oWS = oWB.Sheets.Add(); // //oWS.Name = shname; // //Find all the instances // IEnumerable<TDElementWrapper> elementWrappers = TestsheetElementsHelper.GetAttrRecursively(ts); // var instances = ts.Instances.Items.ToArray(); // int renamecounter = 1; // int rowcountt = 0; // //Write header rows // int colcounter = 2; // oWS.Cells[headerrow, 1] = "Instances"; // foreach (TDInstance tdheader in ts.Instances.Items) // { // for (int i = 0; i < elementWrappers.Count(); i++) // { // TDElementWrapper ewvarheader = elementWrappers.ElementAt(i); // if (ewvarheader != null) // { // string path = ewvarheader.Path; // if (path.Contains('.')) // { // string[] patharray = path.Split('.'); // for (int j = 0; j < patharray.Length; j++) // { // oWS.Cells[headerrow + (j * 1), colcounter] = patharray[j]; // if (rowcountt < headerrow + (j * 1)) { rowcountt = headerrow + (j * 1); } // } // } // else // { // oWS.Cells[headerrow, colcounter] = path; // } // colcounter = colcounter + 1; // } // } // break; // } // Range oHeader = oWS.Range[oWS.Cells[headerrow, 1], oWS.Cells[rowcountt, colcounter - 1]]; // int contentrow = rowcountt + 1; // //Write rows -- Instances names // foreach (TDInstance tdi in ts.Instances.Items) // { // oWS.Cells[contentrow, 1] = tdi.DisplayedName; // colcounter = 2; // for (int i = 0; i < elementWrappers.Count(); i++) // { // TDElementWrapper ewvar = elementWrappers.ElementAt(i); // if (ewvar != null) // { // //tdi.Name += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ew); // string path = ewvar.Path; // oWS.Cells[contentrow, colcounter] = ElementToValueMapper.GetInstanceValueStringForElement(tdi, ewvar); // colcounter = colcounter + 1; // } // } // contentrow = contentrow + 1; // } // //Try to get the relationships // //Format excel document // oWS.Columns.AutoFit(); // oWS.Columns.Font.Size = 11; // oWS.Columns.Font.Name = "Calibri"; // Range myCell = oWS.Range[oWS.Cells[rowcountt + 1, 2], oWS.Cells[rowcountt + 1, 2]]; // myCell.Activate(); // myCell.Application.ActiveWindow.FreezePanes = true; // oHeader.Columns.Font.Color = XlRgbColor.rgbWhite; // oHeader.Columns.Font.Bold = true; // oHeader.Columns.HorizontalAlignment = XlHAlign.xlHAlignCenter; // oHeader.Columns.Interior.Color = XlRgbColor.rgbDarkSlateGrey; // Range contents = oWS.Range[oWS.Cells[rowcountt + 1, 1], oWS.Cells[contentrow - 1, colcounter - 1]]; // contents.WrapText = true; // contents.Borders.LineStyle = XlLineStyle.xlContinuous; // contents.Borders.Weight = XlBorderWeight.xlThin; // contents.Borders.ColorIndex = XlColorIndex.xlColorIndexAutomatic; // //Save document // System.IO.Directory.CreateDirectory("C:\\Tosca_Projects\\Tosca_Exports"); // oWB.SaveAs("C:\\Tosca_Projects\\Tosca_Exports\\" + shname + "_TCD Extract " + DateTime.Now.ToString("MMddyyyy_hhmmss"), Microsoft.Office.Interop.Excel.XlFileFormat.xlWorkbookDefault, Type.Missing, Type.Missing, // false, false, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, // Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); // //Close Excel application // oWB.Close(true); // oXL.Quit(); // //Release Excel objects // Marshal.ReleaseComObject(oWS); // Marshal.ReleaseComObject(oWB); // Marshal.ReleaseComObject(oXL); // Process.Start(@"C:\Tosca_Projects\Tosca_Exports\"); // } // return null; // } //} //public class RenameInstancesAddOn : TCAddOnTask //{ // public override Type ApplicableType // { // get { return typeof(TestSheet); } // } // public override TCObject Execute(TCObject objectToExecuteOn, TCAddOnTaskContext taskContext) // { // frmTDIName f = new frmTDIName(); // if (f.ShowDialog() == DialogResult.OK) // { // if (objectToExecuteOn is TestSheet) // { // TestSheet ts = (TestSheet)objectToExecuteOn; // List<TDInstanceNameComponent> components = TestsheetElementsHelper.Initialise(f.NameFormat); // IEnumerable<TDElementWrapper> elementWrappers = TestsheetElementsHelper.GetElementsRecursively(ts); // var instances = ts.Instances.Items.ToArray(); // int renamecounter = 1; // int errorCount = 0; // foreach (TDInstance tdi in ts.Instances.Items) // { // String oldName = tdi.Name; // String newName = ""; // try // { // tdi.Name = ""; // Clear old name // foreach (TDInstanceNameComponent comp in components) // { // if (comp.IsPath) // { // TDElementWrapper ew = // elementWrappers.FirstOrDefault( // e => e.Path.Equals(comp.Text, StringComparison.CurrentCultureIgnoreCase)); // if (ew != null) // { // //tdi.Name += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ew); // newName += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ew); // } // } // else // { // //tdi.Name += comp.Text; // newName += comp.Text; // } // } // //Loop to make sure that there are not continuous _ // while (newName.Contains("__")) // { // newName = newName.Replace("__", "_"); // } // //Check for the trailing character and omit it // if (newName.Substring(newName.Length - 1, 1) == "_") // { // newName = newName.Substring(0, newName.Length - 1); // } // //Check for name already exists // string newNamewithcount = ""; // if (instances.Any(instance => instance.Name == newName)) // { // newNamewithcount = newName + "_" + renamecounter.ToString("D3"); // while (instances.Any(instance => instance.Name == newNamewithcount)) // { // renamecounter++; // newNamewithcount = newName + "_" + renamecounter.ToString("D3"); // } // } // else // { // newNamewithcount = newName; // } // tdi.Name = newNamewithcount; // //recurssive function to check name // //string finalname = RecursiveSearch(ref newName, ref ts); // } // catch (Exception) // { // // Reset to old name // tdi.Name = oldName; // errorCount++; // } // } // if (errorCount > 0) // { // MessageBox.Show(errorCount.ToString() + " instances could not be renamed."); // } // } // } // return null; // } // public override string Name // { // get { return "Rename Instances"; } // } //} //public class RenameAttributesAddOn : TCAddOnTask //{ // public override Type ApplicableType // { // get { return typeof(TDAttribute); } // } // public override TCObject Execute(TCObject objectToExecuteOn, TCAddOnTaskContext taskContext) // { // frmTDIName f = new frmTDIName(); // if (f.ShowDialog() == DialogResult.OK) // { // if (objectToExecuteOn is TDAttribute) // { // TDAttribute ts = (TDAttribute)objectToExecuteOn; // List<TDInstanceNameComponent> components = TestsheetElementsHelper.Initialise(f.NameFormat); // IEnumerable<TDElementWrapper> elementWrappers = TestsheetElementsHelper.GetAttrRecursively(ts); // var instances = ts.Instances.Items.ToArray(); // int renamecounter = 1; // int errorCount = 0; // foreach (TDInstance tdi in ts.Instances.Items) // { // String oldName = tdi.Name; // String newName = ""; // try // { // tdi.Name = ""; // Clear old name // foreach (TDInstanceNameComponent comp in components) // { // if (comp.IsPath) // { // TDElementWrapper ew = // elementWrappers.FirstOrDefault( // e => e.Path.Equals(comp.Text, StringComparison.CurrentCultureIgnoreCase)); // if (ew != null) // { // //tdi.Name += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ew); // newName += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ew); // } // } // else // { // //tdi.Name += comp.Text; // newName += comp.Text; // } // } // //Loop to make sure that there are not continuous _ // while (newName.Contains("__")) // { // newName = newName.Replace("__", "_"); // } // //Check for the trailing character and omit it // if (newName.Substring(newName.Length - 1, 1) == "_") // { // newName = newName.Substring(0, newName.Length - 1); // } // //Check for name already exists // string newNamewithcount = ""; // if (instances.Any(instance => instance.Name == newName)) // { // newNamewithcount = newName + "_" + renamecounter.ToString("D3"); // while (instances.Any(instance => instance.Name == newNamewithcount)) // { // renamecounter++; // newNamewithcount = newName + "_" + renamecounter.ToString("D3"); // } // } // else // { // newNamewithcount = newName; // } // tdi.Name = newNamewithcount; // //recurssive function to check name // //string finalname = RecursiveSearch(ref newName, ref ts); // } // catch (Exception) // { // // Reset to old name // tdi.Name = oldName; // errorCount++; // } // } // if (errorCount > 0) // { // MessageBox.Show(errorCount.ToString() + " instances could not be renamed."); // } // } // } // return null; // } // public override string Name // { // get { return "Rename Attributes"; } // } //} //public class PopulateInstanceDescription : TCAddOnTask //{ // public override Type ApplicableType // { // get { return typeof(TestSheet); } // } // public override TCObject Execute(TCObject objectToExecuteOn, TCAddOnTaskContext taskContext) // { // if (objectToExecuteOn is TestSheet) // { // TestSheet ts = (TestSheet)objectToExecuteOn; // IEnumerable<TDElementWrapper> elementWrappers = TestsheetElementsHelper.GetElementsRecursively(ts); // var instances = ts.Instances.Items.ToArray(); // int errorCount = 0; // foreach (TDInstance tdi in ts.Instances.Items) // { // String desc = ""; // try // { // for (int i = 0; i < elementWrappers.Count(); i++) // { // TDElementWrapper ewvar = elementWrappers.ElementAt(i); // if (ewvar != null) // { // //tdi.Name += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ew); // desc += ElementToValueMapper.GetInstanceValueStringForElement(tdi, ewvar) + "_"; // } // } // //Loop to make sure that there are not continuous _ // while (desc.Contains("__")) // { // desc = desc.Replace("__", "_"); // } // //Check for the trailing character and omit it // if (desc.Substring(desc.Length - 1, 1) == "_") // { // desc = desc.Substring(0, desc.Length - 1); // } // tdi.Description = desc; // } // catch (Exception) // { // // Reset to empty description // tdi.Description = ""; // errorCount++; // } // } // if (errorCount > 0) // { // MessageBox.Show(errorCount.ToString() + " instance's description could not be renamed."); // } // } // return null; // } // public override string Name // { // get { return "Populate Instance Description"; } // } //} internal class TDInstanceNameComponent { private String _text; public String Text { get { return _text; } set { _text = value; } } private Boolean _isPath = false; public Boolean IsPath { get { return _isPath; } set { _isPath = value; } } public TDInstanceNameComponent(String text) { _text = text; } public TDInstanceNameComponent(String text, Boolean isPath) : this(text) { _isPath = isPath; } } internal static class TestsheetElementsHelper { public static List<TDInstanceNameComponent> Initialise(String rawFormat) { List<TDInstanceNameComponent> components = new List<TDInstanceNameComponent>(); String[] split = rawFormat.Split(']'); foreach (String s in split) { if (s.Contains('[')) { String[] subS = s.Split('['); components.Add(new TDInstanceNameComponent(subS[0])); components.Add(new TDInstanceNameComponent(subS[1], true)); } else { components.Add(new TDInstanceNameComponent(s)); } } return components; } public static IEnumerable<TDElementWrapper> GetElementsRecursively(TestSheet testSheet) { return GetElementsRecursively(testSheet.Items.Select(a => new TDElementWrapper { TDElement = a, ParentWrapper = null })); } public static IEnumerable<TDElementWrapper> GetAttrRecursively(TDAttribute tdattribute) { return GetElementsRecursively(tdattribute.Items.Select(a => new TDElementWrapper { TDElement = a, ParentWrapper = null })); } private static IEnumerable<TDElementWrapper> GetElementsRecursively(IEnumerable<TDElementWrapper> elements) { foreach (TDElementWrapper parentElement in elements) { yield return parentElement; IEnumerable<TDElementWrapper> children = GetElementsRecursively(parentElement.TDElement.Items.Select(a => new TDElementWrapper { TDElement = a, ParentWrapper = parentElement })); foreach (TDElementWrapper child in children) { yield return child; } TDClass referencedClass = (parentElement.TDElement as TDAttribute) == null ? null : (parentElement.TDElement as TDAttribute).ReferencedClass; if (referencedClass != null) { IEnumerable<TDElementWrapper> childrenInClass = GetElementsRecursively(referencedClass.Attributes.Select(a => new TDElementWrapper { TDElement = a, ParentWrapper = parentElement })); foreach (TDElementWrapper child in childrenInClass) { yield return child; } } } } } internal static class ExcelHelper { public static DataTable ReadExcelFile(String path, String sheetName) { OleDbConnection conn = null; DataTable dt = new DataTable(); try { conn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=1\""); OleDbCommand cmd = new OleDbCommand("Select * from [" + sheetName + "$]", conn); cmd.CommandType = CommandType.Text; OleDbDataAdapter adapt = new OleDbDataAdapter(cmd); conn.Open(); adapt.Fill(dt); } catch (Exception ex) { throw new Exception("Error reading Excel file", ex); } finally { if (conn != null) { conn.Close(); conn.Dispose(); } } return dt; } } }
using System; using Uintra.Core.Member.Models; using Uintra.Features.Links.Models; namespace Uintra.Features.Groups.Models { public class GroupViewModel { public Guid Id { get; set; } public bool HasImage { get; set; } public UintraLinkModel GroupUrl { get; set; } public string GroupImageUrl { get; set; } public string Title { get; set; } public string Description { get; set; } public MemberViewModel Creator { get; set; } public bool IsMember { get; set; } public int MembersCount { get; set; } public bool IsCreator { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; using System.Data; using System.Collections; namespace CRL.Order { /// <summary> /// 订单维护 /// </summary> public class OrderAction<TType> : BaseAction<TType, IOrder> where TType:class { /// <summary> /// 查询一个订单 /// </summary> public static TMain Query<TMain>(string orderId) where TMain : IOrder, new() { string table = Base.GetTableName(typeof(TMain)); DBExtend helper = dbHelper; TMain orderMain = helper.QueryItem<TMain>(b => b.OrderId == orderId); return orderMain; } /// <summary> /// 提交订单 /// </summary> /// <typeparam name="TMain"></typeparam> /// <returns></returns> public static bool SubmitOrder<TMain>(TMain order) where TMain : IOrder, new() { DBExtend helper = dbHelper; int id = helper.InsertFromObj(order); order.Id = id; return true; } /// <summary> /// 更改订单状态 /// </summary> /// <param name="order"></param> /// <param name="status"></param> /// <param name="remark"></param> /// <returns></returns> public static bool UpdateOrderStatus<TMain>(TMain order, int status, string remark) where TMain : IOrder, new() { if (remark.Length > 100) remark = remark.Substring(0, 100); ParameCollection c = new ParameCollection(); c["status"] = status; if (!string.IsNullOrEmpty(remark)) { c["remark"] = remark; } c["UpdateTime"] = DateTime.Now; //c["PayType"] = order.PayType; Update<TMain>(b => b.Id == order.Id, c); return true; } /// <summary> /// 取消订单 /// </summary> /// <param name="order"></param> /// <param name="remark"></param> /// <returns></returns> public static bool CancelOrder<TMain>(TMain order, string remark) where TMain : IOrder, new() { UpdateOrderStatus(order, (int)OrderStatus.已取消, remark); return true; } /// <summary> /// 确认订单 /// </summary> /// <param name="order"></param> /// <param name="remark"></param> /// <returns></returns> public static bool ConfirmOrder<TMain>(TMain order, string remark) where TMain : IOrder, new() { UpdateOrderStatus(order, (int)OrderStatus.已确认, remark); return true; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace UseFul.ClientApi.Dtos { public class SolicitacoesVagasDto { public int IdSolicitacao { get; set; } public int IdPessoa { get; set; } public int IdVeiculo { get; set; } public DateTime DtSolicitacao { get; set; } public string IdUser { get; set; } public DateTime DtInicio { get; set; } public bool Ativo { get; set; } public int Situacao { get; set; } public DateTime DtCancel { get; set; } public string UserCancel { get; set; } } }
using System.Collections.Generic; namespace Titan.Util { public class Cooldown { public static Dictionary<uint, Cooldown> Cooldowns = new Dictionary<uint, Cooldown>(); public string Reason; public bool Permanent; public Cooldown(uint penalty, string reason, bool permanent) { Reason = reason; Permanent = permanent; Cooldowns.Add(penalty, this); } public static implicit operator string(Cooldown cooldown) { return cooldown.Reason; } public static implicit operator uint(Cooldown cooldown) { foreach (var keyValue in Cooldowns) { if (keyValue.Value == cooldown) { return keyValue.Key; } } return 0; } public static implicit operator bool(Cooldown cooldown) { return cooldown.Permanent; } public static implicit operator Cooldown(uint penalty) { foreach (var keyValue in Cooldowns) { if (keyValue.Key == penalty) { return keyValue.Value; } } return null; } } }
public class Solution { public bool SearchMatrix(int[][] matrix, int target) { int m = matrix.Length, n = matrix[0].Length; int left = 0, right = m - 1, rowIdx; while (left + 1 < right) { int mid = (right - left) / 2 + left; if (matrix[mid][0] > target) { right = mid; } else if (matrix[mid][n-1] < target) { left = mid; } else { left = mid; right = mid; } } if (matrix[left][0] <= target && target <= matrix[left][n-1]) { rowIdx = left; } else if (matrix[right][0] <= target && target <= matrix[right][n-1]) { rowIdx = right; } else { return false; } left = 0; right = n - 1; while (left + 1 < right) { int mid = (right - left) / 2 + left; if (matrix[rowIdx][mid] == target) { return true; } else if (matrix[rowIdx][mid] > target) { right = mid; } else { left = mid; } } if (matrix[rowIdx][left] == target || matrix[rowIdx][right] == target) return true; return false; } }
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; /* * [23:43] Riccardoric: Bem vindo ao reverse the plague Obrigado testar nosso jogo! [23:44] Riccardoric: Nesse jogo é necessário ter cautela você é o governador de uma grande região que foi infectada por um vírus... [23:44] Riccardoric: sua missão é fazer com que o vírus mate o menos de pessoas possível até criar uma vacina, é uma tarefa difícil, será que você é capaz? [23:44] Riccardoric: barre fronteiras, coloque lockdown, trave navios e aviões. faça tudo na medida do necessário. [23:44] Riccardoric: está pronto para essa responsabilidade? */ public class Information : MonoBehaviour { public Queue<string> MyTexts; public TextMeshProUGUI MyTextBox; void Start() { MyTexts = new Queue<string>(); MyTexts.Enqueue("Welcome to Reverse The Plague" + "" + "" + " Thanks for testing our game."); MyTextBox.text = MyTexts.Dequeue(); MyTexts.Enqueue("In this game," + " you are the Ruler of a enormous Region that is infected by a dangerous virus." + " You really need to be cautious..."); MyTexts.Enqueue("Your goal is stop the virus that is infecting and killing all the citizens" + " of your region, until you don't find a cure."); MyTexts.Enqueue("Take actions, such as locking borders, establish a lockdown, close harbors and airports, " + " but measure your costs," + " it will affect your economies and population."); MyTexts.Enqueue("Can you take care of this?"); } // Update is called once per frame void Update() { if(Input.GetMouseButtonUp(0)) { if (MyTexts.Count != 0) MyTextBox.text = MyTexts.Dequeue(); Debug.Log("press"); } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using Kingdee.CAPP.Model; using Kingdee.CAPP.BLL; namespace Kingdee.CAPP.UI.ProcessDesign { public partial class AddProcessPlanningModuleFrm : BaseSkinForm { public AddProcessPlanningModuleFrm() { InitializeComponent(); } private ProcessPlanningModule _processPlanningMod; public ProcessPlanningModule ProcessPlanningMod { get { return _processPlanningMod; } set { _processPlanningMod = value; } } public AddProcessPlanningModuleFrm(ProcessPlanningModule processPlanningModle) { InitializeComponent(); this._processPlanningMod = processPlanningModle; } public Dictionary<string, ProcessPlanningModule> NewNodeNameDic { get; set; } private void btnClose_Click(object sender, EventArgs e) { this.DialogResult = DialogResult.Cancel; } private void btnAdd_Click(object sender, EventArgs e) { ProcessPlanningModule processPlanningModule = new ProcessPlanningModule(); processPlanningModule.BusinessId = Guid.NewGuid(); processPlanningModule.BType = BusinessType.Planning; processPlanningModule.Name = txtBusinessName.Text.Trim(); processPlanningModule.ParentNode = ProcessPlanningMod.ParentNode; processPlanningModule.ProcessPlanningModuleId = Guid.NewGuid(); try { int currentNode = ProcessPlanningModuleBLL.AddProcessPlanningModule(processPlanningModule); NewNodeNameDic = new Dictionary<string, ProcessPlanningModule>() { { txtBusinessName.Text.Trim(), processPlanningModule } }; this.DialogResult = DialogResult.OK; } catch (Exception ex) { MessageBox.Show(ex.Message); this.DialogResult = DialogResult.Cancel; } } private void txtBusinessName_KeyDown(object sender, KeyEventArgs e) { if ((int)e.KeyCode == 13) { e.SuppressKeyPress = true; } } } }
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq; // ReSharper disable ForeachCanBeConvertedToQueryUsingAnotherGetEnumerator // ReSharper disable InvertIf // ReSharper disable LoopCanBeConvertedToQuery // ReSharper disable MemberCanBePrivate.Global // ReSharper disable UseDeconstruction // ReSharper disable UseDeconstructionOnParameter // ReSharper disable once CheckNamespace namespace Microsoft.OpenApi.Models { //// https://swagger.io/docs/specification/data-models/ //// https://swagger.io/docs/specification/data-models/data-types/-> "String Formats" public static class OpenApiSchemaExtensions { public static bool HasDataTypeOfList(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsDataTypeOfList()); } public static bool HasFormatTypeOfUuid(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfUuid()); } public static bool HasFormatTypeOfDate(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfDate()); } public static bool HasFormatTypeOfTime(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfTime()); } public static bool HasFormatTypeOfTimestamp(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfTimestamp()); } public static bool HasFormatTypeOfDateTime(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfDateTime()); } public static bool HasFormatTypeOfByte(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfByte()); } public static bool HasFormatTypeOfInt32(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfInt32()); } public static bool HasFormatTypeOfInt64(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfInt64()); } public static bool HasFormatTypeOfEmail(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfEmail()); } public static bool HasFormatTypeOfUri(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.IsFormatTypeOfUri()); } public static bool HasFormatTypeFromSystemNamespace(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.IsFormatTypeOfUuid() || schema.IsFormatTypeOfDate() || schema.IsFormatTypeOfDateTime() || schema.IsFormatTypeOfTime() || schema.IsFormatTypeOfTimestamp() || schema.IsFormatTypeOfUri(); } public static bool HasFormatTypeFromSystemNamespace(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.HasFormatTypeFromSystemNamespace()); } public static bool HasDataTypeFromSystemCollectionGenericNamespace(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.IsDataTypeOfList(); } public static bool HasDataTypeFromSystemCollectionGenericNamespace(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.HasDataTypeFromSystemCollectionGenericNamespace()); } public static bool HasFormatTypeFromDataAnnotationsNamespace(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.IsFormatTypeOfEmail() || schema.IsFormatTypeOfUri() || schema.IsRuleValidationString() || schema.IsRuleValidationNumber(); } public static bool HasFormatTypeFromDataAnnotationsNamespace(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.HasFormatTypeFromDataAnnotationsNamespace()); } public static bool HasFormatType(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return !string.IsNullOrEmpty(schema.Format); } public static bool HasAnyProperties(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (schema.OneOf != null && schema.OneOf.Count == 1 && schema.OneOf.First().Properties.Count > 0) { return true; } return schema.Properties.Count > 0; } public static bool HasAnyPropertiesFormatTypeBinary(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (!schema.HasAnyProperties()) { return false; } foreach (var schemaProperty in schema.Properties) { if (schemaProperty.Value.IsFormatTypeOfBinary()) { return true; } } return false; } public static bool HasAnyPropertiesFormatTypeFromSystemNamespace(this OpenApiSchema schema) { return schema.HasAnyProperties() && schema.Properties.Any(x => x.Value.HasFormatTypeFromSystemNamespace()); } public static bool HasAnyPropertiesFormatTypeFromSystemNamespace(this OpenApiSchema schema, IDictionary<string, OpenApiSchema> componentSchemas) { if (!schema.HasAnyProperties()) { return false; } foreach (var schemaProperty in schema.Properties) { if (schemaProperty.Value.HasFormatTypeFromSystemNamespace()) { return true; } if (!schemaProperty.Value.IsObjectReferenceTypeDeclared()) { continue; } var childModelName = schemaProperty.Value.GetModelName(); if (string.IsNullOrEmpty(childModelName)) { continue; } var childSchema = componentSchemas.FirstOrDefault(x => x.Key == childModelName); if (string.IsNullOrEmpty(childSchema.Key)) { continue; } if (childSchema.Value.HasAnyPropertiesFormatTypeFromSystemNamespace(componentSchemas)) { return true; } } return false; } public static bool HasAnyPropertiesFormatFromSystemCollectionGenericNamespace(this OpenApiSchema schema, IDictionary<string, OpenApiSchema> componentSchemas) { if (!schema.HasAnyProperties()) { return false; } foreach (var schemaProperty in schema.Properties) { if (schemaProperty.Value.HasDataTypeFromSystemCollectionGenericNamespace()) { return true; } if (!schemaProperty.Value.IsObjectReferenceTypeDeclared()) { continue; } var childModelName = schemaProperty.Value.GetModelName(); if (string.IsNullOrEmpty(childModelName)) { continue; } var childSchema = componentSchemas.FirstOrDefault(x => x.Key == childModelName); if (string.IsNullOrEmpty(childSchema.Key)) { continue; } if (childSchema.Value.HasAnyPropertiesFormatFromSystemCollectionGenericNamespace(componentSchemas)) { return true; } } return false; } public static bool HasFormatTypeFromAspNetCoreHttpNamespace(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.IsFormatTypeOfBinary(); } public static bool HasFormatTypeFromAspNetCoreHttpNamespace(this IList<OpenApiSchema> schemas) { if (schemas == null) { throw new ArgumentNullException(nameof(schemas)); } return schemas.Any(x => x.HasFormatTypeFromAspNetCoreHttpNamespace()); } public static bool IsDataTypeOfList(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return !string.IsNullOrEmpty(schema.Type) && schema.Type.Equals(OpenApiDataTypeConstants.Array, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfUuid(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Uuid, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfDate(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Date, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfTime(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Time, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfTimestamp(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Timestamp, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfDateTime(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.DateTime, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfByte(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Byte, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfBinary(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Binary, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfInt32(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Int32, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfInt64(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Int64, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfEmail(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Email, StringComparison.OrdinalIgnoreCase); } public static bool IsFormatTypeOfUri(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.HasFormatType() && schema.Format.Equals(OpenApiFormatTypeConstants.Uri, StringComparison.OrdinalIgnoreCase); } public static bool IsRuleValidationString(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.MinLength != null || schema.MaxLength != null; } public static bool IsRuleValidationNumber(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.Minimum != null || schema.Maximum != null; } public static bool IsSimpleDataType(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (schema.Type == null) { return false; } var dataType = schema.GetDataType(); return string.Equals(dataType, OpenApiDataTypeConstants.Boolean, StringComparison.Ordinal) || string.Equals(dataType, "bool", StringComparison.Ordinal) || string.Equals(dataType, OpenApiDataTypeConstants.Integer, StringComparison.Ordinal) || string.Equals(dataType, "int", StringComparison.Ordinal) || string.Equals(dataType, "long", StringComparison.Ordinal) || string.Equals(dataType, "double", StringComparison.Ordinal) || string.Equals(dataType, "float", StringComparison.Ordinal) || string.Equals(dataType, OpenApiDataTypeConstants.Number, StringComparison.Ordinal) || string.Equals(dataType, OpenApiDataTypeConstants.String, StringComparison.Ordinal); } public static bool IsObjectReferenceTypeDeclared(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.Reference != null; } public static bool IsArrayReferenceTypeDeclared(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.Type == OpenApiDataTypeConstants.Array && schema.Items?.Reference != null; } public static bool IsItemsOfSimpleDataType(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.Items != null && schema.Items.IsSimpleDataType(); } public static bool IsSchemaEnum(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.Enum != null && schema.Enum.Any(); } public static bool IsSchemaEnumOrPropertyEnum(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } return schema.IsSchemaEnum() || (schema.Properties.Any(x => x.Value.Enum.Any()) && schema.Properties.Count == 1); } [SuppressMessage("Critical Code Smell", "S3776:Cognitive Complexity of methods should not be too high", Justification = "OK.")] public static bool IsSharedContract(this OpenApiSchema schema, OpenApiComponents openApiComponents) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (openApiComponents == null) { throw new ArgumentNullException(nameof(openApiComponents)); } var referencedSchemaSet = new List<Tuple<string, string>>(); foreach (var itemSchema in openApiComponents.Schemas.Values) { foreach (var itemPropertySchema in itemSchema.Properties.Values) { if (itemPropertySchema.Reference == null) { continue; } var schemaReference = itemPropertySchema.Reference.Id; if (!string.Equals(schema.Title, schemaReference, StringComparison.Ordinal) || itemPropertySchema.IsSchemaEnum()) { continue; } if (!referencedSchemaSet.Any(x => string.Equals(x.Item1, itemSchema.Title, StringComparison.Ordinal) && string.Equals(x.Item2, schemaReference, StringComparison.Ordinal))) { referencedSchemaSet.Add(Tuple.Create(itemSchema.Title, schemaReference)); } if (referencedSchemaSet.Any(x => !string.Equals(x.Item1, itemSchema.Title, StringComparison.Ordinal) && string.Equals(x.Item2, schemaReference, StringComparison.Ordinal))) { return true; } } } return false; } public static string GetModelName(this OpenApiSchema schema, bool ensureFirstCharacterToUpper = true) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (schema.AllOf.Count == 2 && (NameConstants.Pagination.Equals(schema.AllOf[0].Reference?.Id, StringComparison.OrdinalIgnoreCase) || NameConstants.Pagination.Equals(schema.AllOf[1].Reference?.Id, StringComparison.OrdinalIgnoreCase))) { if (!NameConstants.Pagination.Equals(schema.AllOf[0].Reference?.Id, StringComparison.OrdinalIgnoreCase)) { return schema.AllOf[0].GetModelName(); } if (!NameConstants.Pagination.Equals(schema.AllOf[1].Reference?.Id, StringComparison.OrdinalIgnoreCase)) { return schema.AllOf[1].GetModelName(); } } if (schema.Items == null && schema.Reference == null) { return string.Empty; } if (schema.Items != null && !OpenApiDataTypeConstants.Object.Equals(schema.Items.Type, StringComparison.Ordinal)) { return string.Empty; } if (ensureFirstCharacterToUpper) { return schema.Items == null ? schema.Reference.Id.EnsureFirstCharacterToUpper() : schema.Items.Reference.Id.EnsureFirstCharacterToUpper(); } return schema.Items == null ? schema.Reference.Id : schema.Items.Reference.Id; } public static string? GetModelType(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (schema.AllOf.Count == 2 && (NameConstants.Pagination.Equals(schema.AllOf[0].Reference?.Id, StringComparison.OrdinalIgnoreCase) || NameConstants.Pagination.Equals(schema.AllOf[1].Reference?.Id, StringComparison.OrdinalIgnoreCase))) { if (!NameConstants.Pagination.Equals(schema.AllOf[0].Reference?.Id, StringComparison.OrdinalIgnoreCase)) { return schema.AllOf[0].GetModelType(); } if (!NameConstants.Pagination.Equals(schema.AllOf[1].Reference?.Id, StringComparison.OrdinalIgnoreCase)) { return schema.AllOf[1].GetModelType(); } } return schema.Type; } public static string GetDataType(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } var dataType = schema.Type; switch (schema.Type) { case OpenApiDataTypeConstants.Number: return "double"; case OpenApiDataTypeConstants.Integer: return string.Equals(schema.Format, OpenApiFormatTypeConstants.Int64, StringComparison.Ordinal) ? "long" : "int"; case OpenApiDataTypeConstants.Boolean: return "bool"; case OpenApiDataTypeConstants.Array: return "Array"; } if (!string.IsNullOrEmpty(schema.Format)) { switch (schema.Format) { case OpenApiFormatTypeConstants.Uuid: return "Guid"; case OpenApiFormatTypeConstants.Date: case OpenApiFormatTypeConstants.Time: case OpenApiFormatTypeConstants.Timestamp: case OpenApiFormatTypeConstants.DateTime: return "DateTimeOffset"; case OpenApiFormatTypeConstants.Byte: return "string"; case OpenApiFormatTypeConstants.Binary: return "IFormFile"; case OpenApiFormatTypeConstants.Int32: return "int"; case OpenApiFormatTypeConstants.Int64: return "long"; case OpenApiFormatTypeConstants.Email: return "string"; case OpenApiFormatTypeConstants.Uri: return "Uri"; } } if (schema.Reference?.Id != null) { dataType = schema.Reference.Id; } else if (schema.OneOf != null && schema.OneOf.Count == 1 && schema.OneOf.First().Reference?.Id != null) { dataType = schema.OneOf.First().Reference.Id; } return string.Equals(dataType, OpenApiDataTypeConstants.String, StringComparison.Ordinal) ? dataType : dataType.EnsureFirstCharacterToUpper(); } public static string GetTitleFromPropertyByPropertyKey(this OpenApiSchema schema, string propertyKey) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (propertyKey == null) { throw new ArgumentNullException(nameof(propertyKey)); } foreach (var property in schema.Properties) { if (string.Equals(property.Key, propertyKey, StringComparison.Ordinal)) { return property.Value.Title; } } throw new ItemNotFoundException($"Can't find property title by property-key: {propertyKey}"); } public static Tuple<string, OpenApiSchema> GetEnumSchema(this OpenApiSchema schema) { if (schema == null) { throw new ArgumentNullException(nameof(schema)); } if (schema.Enum != null && schema.Enum.Any()) { return Tuple.Create(schema.Reference.Id, schema); } foreach (var schemaProperty in schema.Properties) { if (!schemaProperty.Value.Enum.Any()) { continue; } var enumName = schemaProperty.Value.Reference?.Id ?? schema.Reference.Id; return Tuple.Create(enumName, schemaProperty.Value); } throw new ItemNotFoundException("Schema does not contain an enum!"); } public static OpenApiSchema GetSchemaByModelName(this IDictionary<string, OpenApiSchema> componentSchemas, string modelName) => componentSchemas.First(x => x.Key.Equals(modelName, StringComparison.OrdinalIgnoreCase)).Value; } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.EntityFrameworkCore; using Predictr.Data; using Predictr.Models; using Predictr.ViewModels; namespace Predictr.Controllers { [RequireHttps] public class LeagueController : Controller { private readonly ApplicationDbContext _context; public LeagueController(ApplicationDbContext context) { _context = context; } // GET: Fixtures public IActionResult Index() { var predictions = _context.Predictions.Include("ApplicationUser").ToList(); VM_League vm = new VM_League(); IEnumerable<PlayerScore> scores = from p in predictions group p by p.ApplicationUser.UserName into g select new PlayerScore { Username = g.Key, TotalPoints = g.Sum(p => p.Points), FirstName = g.Select(f => f.ApplicationUser.FirstName).FirstOrDefault(), Surname = g.Select(f => f.ApplicationUser.Surname).FirstOrDefault(), Guid = g.Select(f => f.ApplicationUser.Id).FirstOrDefault() }; vm.PlayerScores = scores.ToList(); return View("Index", vm); } } }
using System; using System.Drawing; using MonoTouch.Foundation; using MonoTouch.UIKit; using System.Linq; using MonoTouch.CoreGraphics; namespace Screenmedia.IFTTT.JazzHands { public class FrameAnimation : Animation { public FrameAnimation(UIView view) : base(view) { } public override void Animate(int time) { if (KeyFrames.Count() <= 1) return; AnimationFrame animationFrame = AnimationFrameForTime(time); // Store the current transform CGAffineTransform tempTransform = View.Transform; // Reset rotation to 0 to avoid warping View.Transform = CGAffineTransform.MakeRotation(0); View.Frame = animationFrame.Frame; // Return to original transform View.Transform = tempTransform; } public override AnimationFrame FrameForTime(int time, AnimationKeyFrame startKeyFrame, AnimationKeyFrame endKeyFrame) { int startTime = startKeyFrame.Time; int endTime = endKeyFrame.Time; RectangleF startLocation = startKeyFrame.Frame; RectangleF endLocation = endKeyFrame.Frame; RectangleF frame = View.Frame; frame.Location = new PointF( TweenValueForStartTime(startTime, endTime, startLocation.GetMinX(), endLocation.GetMinX(), time), TweenValueForStartTime(startTime, endTime, startLocation.GetMinY(), endLocation.GetMinY(), time)); frame.Size = new SizeF(TweenValueForStartTime(startTime, endTime, startLocation.Width, endLocation.Width, time), TweenValueForStartTime(startTime, endTime, startLocation.Height, endLocation.Height, time)); AnimationFrame animationFrame = new AnimationFrame(); animationFrame.Frame = frame; return animationFrame; } } }
using Sudoku.Services.Business; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Sudoku.Models { public class FullBoard { public List<Cell> GameBoard{ get; set; } public int BoardNumber { get; set; } public PuzzleStatus Status { get; set; } public FullBoard() { GameBoard = new List<Cell>(); Status = PuzzleStatus.Normal; } } }
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml; using AlphaSolutions.SitecoreCms.ExtendedCRMProvider.Common; using CRMSecurityProvider.Caching; using CRMSecurityProvider.Configuration; using CRMSecurityProvider.Repository; using CRMSecurityProvider.Repository.V5; using CRMSecurityProvider.Utils; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Messages; using Sitecore.Diagnostics; namespace AlphaSolutions.SitecoreCms.ExtendedCRMProvider.Repository.V5 { class RoleRepositoryV5 : CRMSecurityProvider.Repository.V5.RoleRepositoryV5 { public RoleRepositoryV5(IOrganizationService crmService, IMarketingListToRoleConverterV5 marketingListToRoleConverter, IContactToUserConverterV5 contactToUserConverter, UserRepositoryBase userRepository, ICacheService cacheService) : base(crmService, marketingListToRoleConverter, contactToUserConverter, userRepository, cacheService) { } /// <summary> /// Method to get users in given Role. in CRM Marketing list. /// This method has been customized to support dynamic lists. /// </summary> /// <param name="roleName"></param> /// <returns></returns> public override string[] GetUsersInRole(string roleName) { //setting that disabled the dynamic list functionality. if (SitecoreUtility.GetSitecoreSetting<bool>("AlphaSolutions.ExtendedCRMProvider.Disable.DynamicLists", false)) { return base.GetUsersInRole(roleName); } Assert.ArgumentNotNull(roleName, "roleName"); ConditionalLog.Info(string.Format("GetUsersInRole({0}). Started.", roleName), this, TimerAction.Start, "getUsersInRole"); string text = base.CacheService.MembersCache.Get(roleName); if (text != null) { ConditionalLog.Info(string.Format("GetUsersInRole({0}). Finished (users have been retrieved from cache).", roleName), this, TimerAction.Stop, "getUsersInRole"); return text.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries); } // set up a query for the list to check type Microsoft.Xrm.Sdk.Query.ColumnSet columnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(new string[] { "listname", "query", "type" }); Microsoft.Xrm.Sdk.Query.QueryExpression query = new Microsoft.Xrm.Sdk.Query.QueryExpression(); query.ColumnSet = columnSet; Microsoft.Xrm.Sdk.Query.ConditionExpression listnameCondition = new Microsoft.Xrm.Sdk.Query.ConditionExpression(); listnameCondition.AttributeName = "listname"; listnameCondition.Operator = Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal; listnameCondition.Values.Add(roleName); Microsoft.Xrm.Sdk.Query.FilterExpression filterList = new Microsoft.Xrm.Sdk.Query.FilterExpression(); filterList.Conditions.Add(listnameCondition); filterList.FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And; query.EntityName = "list"; query.Criteria = filterList; // Execute the query Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest req = new Microsoft.Xrm.Sdk.Messages.RetrieveMultipleRequest(); req.Query = query; Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse res = (Microsoft.Xrm.Sdk.Messages.RetrieveMultipleResponse)this.OrganizationService.Execute(req); if (res != null && res.EntityCollection != null && res.EntityCollection.Entities.Count > 0) { Entity myList = res.EntityCollection.Entities[0]; if (myList.Attributes.Keys.Contains("query")) { // Define the fetch attributes. // Set the number of records per page to retrieve. int fetchCount = Settings.FetchThrottlingPageSize; // Initialize the page number. int pageNumber = 1; // Initialize the number of records. int recordCount = 0; // Specify the current paging cookie. For retrieving the first page, // pagingCookie should be null. string pagingCookie = null; //Convert fetchXML to Query Expression var xml = myList["query"].ToString(); HashSet<string> hashSet = new HashSet<string>(); try { while (true) { string xmlpaging = CreateXml(xml, pagingCookie, pageNumber, fetchCount, Settings.UniqueKeyProperty); Microsoft.Xrm.Sdk.Query.FetchExpression f = new Microsoft.Xrm.Sdk.Query.FetchExpression(xmlpaging); RetrieveMultipleRequest retrieveMultipleRequest = new RetrieveMultipleRequest(); retrieveMultipleRequest.Query = f; RetrieveMultipleResponse retrieveMultipleResponse = (RetrieveMultipleResponse)this.OrganizationService.Execute(retrieveMultipleRequest); if (retrieveMultipleResponse != null && retrieveMultipleResponse.EntityCollection != null) { ConditionalLog.Info(string.Format("GetUsersInRole({0}). Retrieved {1} users from CRM.", roleName, retrieveMultipleResponse.EntityCollection.Entities.Count), this, TimerAction.Tick, "getUsersInRole"); foreach (Entity current in retrieveMultipleResponse.EntityCollection.Entities) { try { base.CacheService.UserCache.Add(this.ContactToUserConverter.Convert(current)); hashSet.Add((string)current[Settings.UniqueKeyProperty]); } catch (Exception e) { ConditionalLog.Error(string.Format("GetUsersInRole({0}). Error in converting contact to user. Number of attributes gotten: {1}", current.LogicalName, current.Attributes.Count),e,this); } } // Check for morerecords, if it returns 1. if (retrieveMultipleResponse.EntityCollection.MoreRecords) { // Increment the page number to retrieve the next page. pageNumber++; } else { // If no more records in the result nodes, exit the loop. break; } pagingCookie = retrieveMultipleResponse.EntityCollection.PagingCookie; } } var ret = hashSet.ToArray<string>(); base.CacheService.MembersCache.Add(roleName, string.Join("|", ret)); return ret; } catch (System.Exception sourceException) { ConditionalLog.Error(string.Format("Couldn't get contacts of {0} marketing list from CRM.", roleName), sourceException, this); } } else { return base.GetUsersInRole(roleName); } } return new string[0]; } protected string CreateXml(string xml, string cookie, int page, int count, string returnattribute) { StringReader stringReader = new StringReader(xml); XmlTextReader reader = new XmlTextReader(stringReader); // Load document XmlDocument doc = new XmlDocument(); doc.Load(reader); return CreateXml(doc, cookie, page, count, returnattribute); } protected string CreateXml(XmlDocument doc, string cookie, int page, int count, string returnattribute) { XmlAttributeCollection attrs = doc.DocumentElement.Attributes; if (cookie != null) { XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie"); pagingAttr.Value = cookie; attrs.Append(pagingAttr); } XmlAttribute pageAttr = doc.CreateAttribute("page"); pageAttr.Value = System.Convert.ToString(page); attrs.Append(pageAttr); XmlAttribute countAttr = doc.CreateAttribute("count"); countAttr.Value = System.Convert.ToString(count); attrs.Append(countAttr); XmlNode n = doc.SelectSingleNode("//attribute"); XmlNode id = n.CloneNode(false); n.ParentNode.AppendChild(id); id.Attributes["name"].Value = returnattribute; StringBuilder sb = new StringBuilder(1024); StringWriter stringWriter = new StringWriter(sb); XmlTextWriter writer = new XmlTextWriter(stringWriter); doc.WriteTo(writer); writer.Close(); return sb.ToString(); } } }
using EddiCompanionAppService.Exceptions; using Newtonsoft.Json.Linq; using System; using Utilities; namespace EddiCompanionAppService.Endpoints { public class ProfileEndpoint : Endpoint { private const string PROFILE_URL = "/profile"; // We cache the profile to avoid spamming the service private JObject cachedProfileJson; private DateTime cachedProfileTimeStamp; private DateTime cachedProfileExpires => cachedProfileTimeStamp.AddSeconds(30); // Set up an event handler for data changes public event EndpointEventHandler ProfileUpdatedEvent; /// <summary> /// Contains information about the player's profile and commander /// </summary> /// <param name="forceRefresh"></param> /// <returns></returns> public JObject GetProfile(bool forceRefresh = false) { if ((!forceRefresh) && cachedProfileExpires > DateTime.UtcNow) { // return the cached version Logging.Debug($"{PROFILE_URL} endpoint queried too often. Returning cached data: ", cachedProfileJson); return cachedProfileJson; } try { Logging.Debug($"Getting {PROFILE_URL} data"); var result = GetEndpoint(PROFILE_URL); if ( result is null ) { return null; } if (!result.DeepEquals(cachedProfileJson)) { cachedProfileJson = result; cachedProfileTimeStamp = result["timestamp"]?.ToObject<DateTime?>() ?? DateTime.MinValue; Logging.Debug($"{PROFILE_URL} returned: ", cachedProfileJson); ProfileUpdatedEvent?.Invoke(this, new CompanionApiEndpointEventArgs(CompanionAppService.Instance.ServerURL(), cachedProfileJson, null, null, null)); } else { Logging.Debug($"{PROFILE_URL} returned, no change from prior cached data."); } } catch (EliteDangerousCompanionAppException ex) { // not Logging.Error as telemetry is getting spammed when the server is down Logging.Warn(ex.Message); } return cachedProfileJson; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace BearerTokenAuthenticationSample.Models { public class InstanceModel { public int Version { get; set; } public bool ShareSettings { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; namespace Euler_Logic.Problems.AdventOfCode.Y2022 { public class Problem21 : AdventOfCodeBase { public override string ProblemName => "Advent of Code 2022: 21"; public override string GetAnswer() { return GetAnswer(Input()).ToString(); } public override string GetAnswer2() { return GetAnswer2(Input()).ToString(); } private long GetAnswer(List<string> input) { var state = new State(); SetMonkeys(state, input); return Aggregate(state, "root", false); } private long GetAnswer2(List<string> input) { var state = new State(); SetMonkeys(state, input); state.Monkeys["humn"].HasNumber = false; Aggregate(state, "root", true); return WorkBackwards(state); } private long WorkBackwards(State state) { var root = state.Monkeys["root"]; var monkey1 = state.Monkeys[root.Monkey1]; var monkey2 = state.Monkeys[root.Monkey2]; if (!monkey1.HasNumber) { return WorkBackwards(state, monkey1.Name, monkey2.Number); } else { return WorkBackwards(state, monkey2.Name, monkey1.Number); } } private long WorkBackwards(State state, string name, long number) { var monkey = state.Monkeys[name]; var monkey1 = state.Monkeys[monkey.Monkey1]; var monkey2 = state.Monkeys[monkey.Monkey2]; var withNum = monkey1; var withoutNum = monkey2; if (monkey2.HasNumber) { withNum = monkey2; withoutNum = monkey1; } long num = 0; if (monkey.Operator == enumOperator.Divide || monkey.Operator == enumOperator.Subtract) { if (monkey1.HasNumber) { num = PerformOperator(monkey1.Number, number, monkey.Operator); } else { num = PerformOperatorReverse(monkey2.Number, number, monkey.Operator); } } else { num = PerformOperatorReverse(number, withNum.Number, monkey.Operator); } if (withoutNum.Name == "humn") { return num; } else { return WorkBackwards(state, withoutNum.Name, num); } } private long Aggregate(State state, string name, bool ignoreHuman) { if (name == "humn" && ignoreHuman) return 0; var monkey = state.Monkeys[name]; if (!monkey.HasNumber) { var num1 = Aggregate(state, monkey.Monkey1, ignoreHuman); var num2 = Aggregate(state, monkey.Monkey2, ignoreHuman); if (ignoreHuman) { var monkey1 = state.Monkeys[monkey.Monkey1]; var monkey2 = state.Monkeys[monkey.Monkey2]; if (!monkey1.HasNumber || !monkey2.HasNumber) { return 0; } } monkey.Number = PerformOperator(num1, num2, monkey.Operator); monkey.HasNumber = true; } return monkey.Number; } private void SetMonkeys(State state, List<string> input) { var monkeys = input.Select(line => { var monkey = new Monkey(); var split = line.Split(' '); monkey.Name = split[0].Replace(":", ""); if (split.Length == 2) { monkey.Number = Convert.ToInt64(split[1]); monkey.HasNumber = true; } else { monkey.Monkey1 = split[1]; monkey.Monkey2 = split[3]; monkey.Operator = GetOperator(split[2]); } return monkey; }); state.Monkeys = monkeys.ToDictionary(x => x.Name, x => x); } private long PerformOperator(long value1, long value2, enumOperator op) { switch (op) { case enumOperator.Add: return value1 + value2; case enumOperator.Subtract: return value1 - value2; case enumOperator.Multiply: return value1 * value2; case enumOperator.Divide: return value1 / value2; default: throw new NotImplementedException(); } } private long PerformOperatorReverse(long value1, long value2, enumOperator op) { switch (op) { case enumOperator.Add: return value1 - value2; case enumOperator.Subtract: return value1 + value2; case enumOperator.Multiply: return value1 / value2; case enumOperator.Divide: return value1 * value2; default: throw new NotImplementedException(); } } private enumOperator GetOperator(string text) { switch (text) { case "+": return enumOperator.Add; case "-": return enumOperator.Subtract; case "*": return enumOperator.Multiply; case "/": return enumOperator.Divide; default: throw new NotImplementedException(); } } private class State { public Dictionary<string, Monkey> Monkeys { get; set; } } private enum enumOperator { Add, Subtract, Multiply, Divide } private class Monkey { public string Name { get; set; } public bool HasNumber { get; set; } public long Number { get; set; } public string Monkey1 { get; set; } public string Monkey2 { get; set; } public enumOperator Operator { get; set; } } } }
using System.Collections; using System.Collections.Generic; using UnityEngine; [RequireComponent(typeof(Camera))] public class expendableCamControl : MonoBehaviour { private Camera m_cam; [SerializeField] private GameObject m_player; [SerializeField] private Vector3 m_offset; void Awake() { m_cam = this.gameObject.GetComponent<Camera>(); } // Start is called before the first frame update void Start() { } // Update is called once per frame void Update() { this.gameObject.transform.position = m_player.transform.position + m_offset; this.gameObject.transform.LookAt(m_player.transform); } }
using University.Data; using University.Service.Interface; using University.UI.Areas.Admin.Models; using University.UI.Controllers; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace IPSU.Web.Areas.Admin.Controllers { public class VideoController : BaseController { private IProductVideoService _productVideoService; private IProductService _productService; private ISubCategoryService _subCategoryService; public VideoController(IProductVideoService productVideoService, IProductService productService,ISubCategoryService subCategoryService) : base(productService) { _productVideoService = productVideoService; _productService = productService; _subCategoryService = subCategoryService; } // GET: Admin/Video public ActionResult Index() { return View(); } public ActionResult Video(string SearchString) { List<ProductVideoViewModel> productVideoViewModel = new List<ProductVideoViewModel>(); var res = _productVideoService.GetUserVideosList().ToList(); if (!String.IsNullOrEmpty(SearchString)) { res = res.Where(x => x.Title.ToLower().Contains(SearchString.ToLower())).ToList(); } foreach (var pvideo in res) { productVideoViewModel.Add(new ProductVideoViewModel{ Id = pvideo.Id, Title = pvideo.Title, Decription = pvideo.Decription, VideoURL = pvideo.VideoURL, ProductId=pvideo.ProductId, IsPaid=pvideo.IsPaid, VideoRate=pvideo.VideoRate, SubCatID=pvideo.SubcatId }); } if (!String.IsNullOrEmpty(SearchString)) { productVideoViewModel = productVideoViewModel.Where(x => x.Title.ToLower().Contains(SearchString.ToLower())).ToList(); } return View(productVideoViewModel); } } }
using System.Collections.Generic; using Tails_Of_Joy.Models; namespace Tails_Of_Joy.Repositories { public interface IAdoptionRepository { void Add(Adoption adoption); void Delete(int id); Adoption GetById(int id); List<Adoption> GetAllAdoptionsByUserProfileId(int id); List<Adoption> GetAllApprovedAdoptions(); List<Adoption> GetAllPendingAdoptions(); void Update(Adoption adoption); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Task2_ConvertToBinary { /// <summary> /// Class for work with user /// </summary> class Input { public uint UserInput { get; set; } /// <summary> /// Method reuests user input and saves it. /// </summary> public void getUserInput() { Console.WriteLine("Введите целое число:"); UserInput = uint.Parse(Console.ReadLine()); } } }
using BattleEngine.Actors; using BattleEngine.Utils; namespace BattleEngine.Engine { public class BattleTransform { private BattleObject _battleObject; private double _x; private double _y; private double _z; public BattleTransform(BattleObject battleObject) { _battleObject = battleObject; } public BattleObject target { get { return _battleObject; } } public void setFrom(BattleTransform transform) { _x = transform._x; _y = transform._y; _z = transform._z; } public void copyFrom(BattleTransform transform) { _x = transform._x; _y = transform._y; _z = transform._z; } public double positionDistance(BattleTransform transform) { var fromX = _x; var fromY = _y; var toX = transform.x; var toY = transform.y; var distance = Math2.distance(fromX, fromY, toX, toY); return distance; } public double positionDistanceTo(double x, double y) { var fromX = _x; var fromY = _y; var toX = x; var toY = y; var distance = Math2.distance(fromX, fromY, toX, toY); return distance; } public double distance(BattleTransform transform) { var fromX = _x; var fromY = _y; var fromZ = _z; var toX = transform.x; var toY = transform.y; var toZ = transform.z; var distance = Math2.distance3(fromX, fromY, fromZ, toX, toY, toZ); return distance; } public double distanceTo(double x, double y, double z) { var fromX = _x; var fromY = _y; var fromZ = _z; var toX = x; var toY = y; var toZ = z; var distance = Math2.distance3(fromX, fromY, fromZ, toX, toY, toZ); return distance; } public void setPosition(double x, double y) { _x = x; _y = y; } public void setFromPoint3(Point3 position) { _x = position.x; _y = position.y; _z = position.z; } public void setFromPoint(Point position) { _x = position.x; _y = position.y; } public double x { get { return _x; } set { _x = value; } } public double y { get { return _y; } set { _y = value; } } public double z { get { return _z; } set { _z = value; } } } }
using System; using System.Linq; namespace calc { public static class Input { public static bool CheckInput(string[] args) { var equalsCount = 0; // only one equal sign var variableCount = 0; // needs at least one variable var wasNumber = false; // checks if the previous argument was a number if (!isValidFirstArgument(args[0])) { //Assignment specifies first argument should be 'calc' throw new Exception(Errors.InvalidFirstArgument); } for (int i = 1; i < args.Length; i++) { if (args[i].Length == 1) { // e.g. * if (!IsValidCharacter(args[i][0])) { throw new Exception(Errors.InvalidCharacter); } if (args[i][0] == '=') { equalsCount++; if (i == args.Length - 1 || i == 0) { // when an equal sign is at the start or end of an equation throw new Exception(Errors.InvalidEqualPlacement); } } if (IsNumber(args[i][0]) && wasNumber) { throw new Exception(Errors.InvalidEquation); } if (IsNumber(args[i][0])) { wasNumber = true; } if (args[i][0] == 'X') { variableCount++; } if (IsOperator(args[i][0]) || args[i][0] == '=' || args[i][0] == '(' || args[i][0] == ')') { wasNumber = false; } } else { // e.g. -34X for (int j = 0; j < args[i].Length; j++) { if (!IsValidCharacter(args[i][j])) { throw new Exception(Errors.InvalidCharacter); } if (args[i][j] == 'X') { variableCount++; } if (IsNumber(args[i][j]) && !wasNumber) { // the current argument contains a number wasNumber = true; } } } } if (equalsCount != 1) { throw new Exception(Errors.IncorrectEqualSigns); } if (variableCount == 0) { throw new Exception(Errors.IncorrectVariables); } return true; } public static Equation[] ParseInput(string[] args) { Equation leftSide = new Equation(); var currentSide = new Equation(); var equals = false; var brackets = false; // check if brackets is open var bracketEquation = new Equation(); var bracketModifier = "1"; var bracketOperator = '*'; for (int i = 0; i < args.Length; i++) { if (equals) { leftSide = currentSide; currentSide = new Equation(); // switches side of the equation (current side is now right side) equals = false; // will no longer switch on loop } bool wasNumber = false; // check if argument is a number foreach (var c in args[i]) { if (c == '=') { equals = true; } else if (IsNumber(c) && !wasNumber) { wasNumber = true; } else if (IsOperator(c) && args[i].Length == 1) { // is a single operator and not a modifier operator ( - as opposed to -4X ) wasNumber = false; var operation = c; //Check to see if multiple operators existing concurrently if (i < args.Length - 1 && args[i+1].Length == 1 && IsUnaryOperator(args[i][0]) && IsUnaryOperator(args[i+1][0])) { operation = args[i][0] == args[i + 1][0] ? '+' : '-'; i++; if (i + 1 < args.Length - 1 && args[i + 1].Length == 1 && IsUnaryOperator(args[i + 1][0])) { operation = operation == args[i + 1][0] ? '+' : '-'; i++; } } if (brackets) { bracketEquation.Add(operation); } else { currentSide.Add(operation); } } else if (c == '(') { wasNumber = false; brackets = true; bracketEquation = new Equation(); //renew variable incase of multiple brackets } else if (c == ')') { // close bracket if (i + 1 < args.Length && IsMultiDivide(args[i + 1][0])) { bracketModifier = args[i + 2]; bracketOperator = args[i + 1][0]; i += 2; // skip the next two arguments as you add them to the bracket } wasNumber = false; brackets = false; currentSide.Add(bracketEquation, bracketModifier, bracketOperator); } } if (wasNumber) { if (brackets) { bracketEquation.Add(args[i]); } else if (i < args.Length-1 && args[i + 1][0] == '(') { // next character is an open bracket bracketModifier = args[i]; } else { currentSide.Add(args[i]); } } } return new []{ leftSide, currentSide}; } private static bool isValidFirstArgument(String s){ return s.Equals("calc"); } private static bool IsUnaryOperator(char c) { return "+-".Contains(c); } private static bool IsOperator(char c) { return "+-*/%".Contains(c); } private static bool IsMultiDivide(char c) { return "*/%".Contains(c); } private static bool IsNumber(char c) { return "0123456789X".Contains(c); } private static bool IsValidCharacter(char c) { return "0123456789+-*/%()=X".Contains(c); } } }
/* * Создано в SharpDevelop. * Пользователь: vlunev * Дата: 03.06.2016 * Время: 15:29 */ using System; using System.Text.RegularExpressions; using System.IO; namespace Worker { /// <summary> /// Класс содержит настройки переименования для ListItemClass /// </summary> public class CRename { public int iOption_HowRename; //Тип переименования public bool bOption_AddDesign; //Флаг, добавления обозначения в новое имя файла public bool bOption_AddName; //Флаг, добавления наименования в новое имя файла public bool bOption_AddList; //Флаг, добавления номера листа в новое имя файла public string UserText; //Текст задаваемый пользователем при выборе RENAME_USER private readonly ListItemClass _lic; public const int RENAME_NO = 1; public const int RENAME_CLASSIC = 2; public const int RENAME_USER = 3; public CRename(ListItemClass LIC) { this._lic = LIC; this.iOption_HowRename = RENAME_CLASSIC; this.bOption_AddName = true; this.bOption_AddDesign = true; this.bOption_AddList = false; this.UserText = ""; } public string GetNewFilename() { string NEWfilename; string filename; string formatFilename; if (iOption_HowRename == RENAME_NO) { filename = Path.GetFileName(_lic.RasterFilename); return filename; } if (iOption_HowRename == RENAME_USER) { filename = UserText; if (filename == "") filename = Path.GetFileNameWithoutExtension(_lic.RasterFilename); filename = filename.MultiReplace('_', Path.GetInvalidFileNameChars()); filename = filename.MultiReplace('_', new char[] {'\\', '/', ':', '*', '?'}); filename = filename.Replace('\n', ' '); //Окончание, формирование полного имени файла filename = filename + Path.GetExtension(_lic.RasterFilename); return filename; } if (iOption_HowRename == RENAME_CLASSIC) { //выбор, это многострачный документ или нет //решение принимается на основании флага добавления листа if (_lic.currentDrawingType != null) { formatFilename = bOption_AddList ? _lic.currentDrawingType.FormatFilenameMultipleSheets : _lic.currentDrawingType.FormatFilenameSingleSheet; } else { //это если рамка не будет распознана, по дефолту formatFilename = bOption_AddList ? "{Обозначение} - {Наименование}. Лист {Лист}" : "{Обозначение} - {Наименование}"; } //если Наименование или обозначение не показано то шаблон формирования имени особый if ((!bOption_AddDesign) && (!bOption_AddName)) { formatFilename = bOption_AddList ? Path.GetFileNameWithoutExtension(_lic.RasterFilename) + ". Лист {Лист}" : Path.GetFileNameWithoutExtension(_lic.RasterFilename); } if ((bOption_AddDesign) && (!bOption_AddName)) { formatFilename = bOption_AddList ? "{Обозначение}. Лист {Лист}" : "{Обозначение}"; } if ((!bOption_AddDesign) && (bOption_AddName)) { formatFilename = bOption_AddList ? "{Наименование}. Лист {Лист}" : "{Наименование}"; } //формирование имени файла на основе формата NEWfilename = Regex.Replace(formatFilename, @"\{(.*?)\}", delegate (Match m) { string tmp = m.Value.DeleteEdge(); string txt = ""; if ((tmp == "Обозначение") && bOption_AddDesign) txt = _lic.mapFields.TryGetValueDefault(tmp, ""); if ((tmp == "Наименование") && bOption_AddName) txt = _lic.mapFields.TryGetValueDefault(tmp, ""); if ((tmp == "Лист") && bOption_AddList) txt = _lic.mapFields.TryGetValueDefault(tmp, ""); return (txt.MultiContains("<", ">")) ? "" : txt; //если не содержаться элементы <нет> } ); //удаление запрещённых символов NEWfilename = NEWfilename.MultiReplace('_', Path.GetInvalidFileNameChars()); NEWfilename = NEWfilename.MultiReplace('_', new char[] {'\\', '/', ':', '*', '?'}); NEWfilename = NEWfilename.Replace('\n', ' '); //формирование нового имени без пути и без расширения if (NEWfilename == "") NEWfilename = Path.GetFileNameWithoutExtension(_lic.RasterFilename); //Окончание, формирование полного имени файла filename = NEWfilename + Path.GetExtension(_lic.RasterFilename); return filename; } return ""; } public string GetNewFilenameWithPath(string sPath) //sPath - путь к файлу, без разница есть в конце \ или нет { string normalizePath, fullFN, filename; int i = 0; normalizePath = sPath.TrimEnd('\\'); filename = GetNewFilename(); fullFN = normalizePath + "\\" + filename; while (File.Exists(fullFN) && i < (int.MaxValue - 2)) { var digits = i.ToString("D4"); fullFN = normalizePath + "\\" + Path.GetFileNameWithoutExtension(filename) + "_" + digits + Path.GetExtension(filename); i++; } return File.Exists(fullFN) ? "" : fullFN; } } }
/* * Factory that builds roles based on raw manual string. * What a horrible way to do this! * Copyright (c) Yulo Leake 2016 */ using System; namespace Deadwood.Model.Factories { class RawRoleFactory : IRoleFactory { // Singleton Constructor private static IRoleFactory instance = null; public static IRoleFactory mInstance { get { if (instance == null) { instance = new RawRoleFactory(); } return instance; } } private RawRoleFactory() { } // Interface Methods public Role CreateExtraRole(string name) { string desc = null; int rank = 0; switch (name) { // Roles at Train Station case "Crusty Prospector": desc = "Aww, peaches!"; rank = 1; break; case "Dragged by Train": desc = "Omgeezers!"; rank = 1; break; case "Preacher with Bag": desc = "The Lord will provide."; rank = 2; break; case "Cyrus the Gunfighter": desc = "Git to fightin' or git away!"; rank = 4; break; // Roles at Secret Hideout case "Clumsy Pit Fighter": desc = "Hit me!"; rank = 1; break; case "Thug with Knife": desc = "Meet Suzy, my murderin' knife."; rank = 2; break; case "Dangerous Tom": desc = "There's two ways we can do this...."; rank = 3; break; case "Penny, who is lost": desc = "Oh, wow! for I am lost!"; rank = 4; break; // Roles at Church case "Dead Man": desc = "...."; rank = 1; break; case "Crying Woman": desc = "Oh, the humanity!"; rank = 2; break; // Roles at Hotel case "Sleeping Drunkard": desc = "Zzzzzzz...Whiskey!"; rank = 1; break; case "Faro Player": desc = "Hit me!"; rank = 1; break; case "Falls from Balcony": desc = "Arrrgghh!"; rank = 2; break; case "Australian Bartender": desc = "What'll it be, mate?"; rank = 3; break; // Roles at Main Street case "Railroad Worker": desc = "Hit me!"; rank = 1; break; case "Falls off Roof": desc = "Aaaaiiiigggghh!"; rank = 2; break; case "Woman in Black Dress": desc = "Well, I'll be!"; rank = 2; break; case "Mayor McGinty": desc = "People of Deadwood!"; rank = 4; break; // Roles at Jail case "Prisoner In Cell": desc = "Zzzzzzz...Whiskey!"; rank = 2; break; case "Feller in Irons": desc = "Ah kilt the wrong man!"; rank = 3; break; // Roles at General Store case "Man in Overalls": desc = "Looks like a storm's comin' in."; rank = 1; break; case "Mister Keach": desc = "Howdy, stranger."; rank = 3; break; // Roles at Ranch case "Shot in Leg": desc = "Ow! Me Leg!"; rank = 1; break; case "Saucy Fred": desc = "That's what she said."; rank = 2; break; case "Man Under Horse": desc = "A little help here!"; rank = 3; break; // Roles at Bank case "Suspicious Gentleman": desc = "Can you be more specific?"; rank = 2; break; case "Flustered Teller": desc = "Would you like a large bill, sir?"; rank = 3; break; // Roles at Saloon case "Reluctant Farmer": desc = "I ain't so sure about that!"; rank = 1; break; case "Woman in Red Dress": desc = "Come up and see me!"; rank = 2; break; default: // TODO: throw exception break; } return new Role(name, desc, rank); } public Role CreateStarringRole(string name) { string desc = null; int rank = 0; switch (name) { // Scene "Evil Wears a Hat" case "Defrocked Priest": desc = "Look out below!"; rank = 2; break; case "Marshal Canfield": desc = "Hold fast!"; rank = 3; break; case "One-Eyed Man": desc = "Balderdash"; rank = 4; break; // Scene "Law and the Old West" case "Rug Merchant": desc = "Don't leave my store!"; rank = 1; break; case "Banker": desc = "Trust me."; rank = 2; break; case "Talking Mule": desc = "Nice work, Johnny!"; rank = 4; break; // Scene "The Life and Times of John Skywater" case "Auctioneer": desc = "Going once!"; rank = 5; break; case "General Custer": desc = "Go West!"; rank = 6; break; // Scene "My Years on the Prairie" case "Drunk": desc = "Where's Willard?"; rank = 3; break; case "Librarian": desc = "Shhhhh!"; rank = 4; break; case "Man with Hay": desc = "Hey!"; rank = 6; break; // Scene "Buffalo Bill: The Lost Years" case "Hollering Boy": desc = "Over here, mister!"; rank = 2; break; case "Drink Farmer": desc = "Git outta me barn!"; rank = 3; break; case "Meek Little Sarah": desc = "He's so cute!"; rank = 5; break; // Scene "Square Deal City" case "Squaking Boy": desc = "I'll say!"; rank = 2; break; case "Pharaoh Imhotep": desc = "Attack, soldiers!"; rank = 4; break; case "Aunt Martha": desc = "You got nothin'!"; rank = 6; break; // Scene "Davy Crockett: A Drunkard's Tale" case "The Duck": desc = "Waaaak!"; rank = 4; break; case "His Brother": desc = "Waaaaaaaak!"; rank = 6; break; // Scene "The Way the West Was Run" case "Town Drunk": desc = "Even me!"; rank = 2; break; case "Squinting Miner": desc = "Sure we can!"; rank = 4; break; case "Poltergeist": desc = "Wooooo!"; rank = 5; break; // Scene "Down in the Valley" case "Angry Barber": desc = "Hold him still!"; rank = 1; break; case "Woman with Board": desc = "Nonsense, Frank!"; rank = 3; break; case "Man in Fire": desc = "It burns!"; rank = 5; break; // Scene "Ol' Shooter and Little Doll" case "Sleeping Man": desc = "Snnkkk snnkk snnkk."; rank = 1; break; case "Man with Pig": desc = "Tally-Hooo!"; rank = 2; break; case "Shooter": desc = "Where's my britches?"; rank = 4; break; // Scene "The Robbers of Trains" case "Buster": desc = "One two three go!"; rank = 1; break; case "Man Reading Paper": desc = "Ouchie!"; rank = 4; break; case "Fat Pete": desc = "Nick kick, boss!"; rank = 5; break; // Scene "Beyond the Pail: Life without Lactose" case "Martin": desc = "Have you tried soy cheese?"; rank = 6; break; // Scene "A Man Called 'Cow'" case "Preacher": desc = "My word!"; rank = 3; break; case "Amused Witness": desc = "Tee hee hee!"; rank = 6; break; // Scene "Taffy Commercial" case "Curious girl": desc = "Are you sure?"; rank = 3; break; case "Ghost of Plato": desc = "It happened to me!"; rank = 4; break; // Scene "Gum Commercial" case "Surprised Bison": desc = "Mmrrrrrph!"; rank = 2; break; case "Man with Horn": desc = "Ta daaaa!"; rank = 4; break; // Scene "Jesse James: Man of Action" case "Shot in Back": desc = "Arrrggh!"; rank = 2; break; case "Shot in Leg": desc = "Ooh, lordy!"; rank = 4; break; case "Leaps into Cake": desc = "Dangit, Jesse!"; rank = 5; break; // Scene "Disaster at Flying J" case "Piano Player": desc = "It's a nocturne!"; rank = 2; break; case "Man in Turban": desc = "My stars!"; rank = 3; break; case "Falls on Hoe": desc = "Ow!"; rank = 4; break; // Scene "Shakespear in Lubbock" case "Falls from Tree": desc = "What ho!"; rank = 1; break; case "Laughing Woman": desc = "Tis to laugh!"; rank = 3; break; case "Man with Whistle": desc = "Tweeeeet!"; rank = 4; break; // Scene "Go West, You!" case "Ex-Convict": desc = "Never again!"; rank = 4; break; case "Man with Onion": desc = "Fresh Onions!"; rank = 6; break; // Scene "The Life and Times of John Skywater" case "Staggering Man": desc = "You never know!"; rank = 3; break; case "Woman with Beer": desc = "Howdy, stranger!"; rank = 5; break; case "Marcie": desc = "Welcome home!"; rank = 6; break; // Scene "Gun! The Musical" case "Looks like Elvis": desc = "Thankyouverymuch."; rank = 4; break; case "Singing Dead Man": desc = "Yeah!"; rank = 5; break; case "Apothecary": desc = "Such drugs I have."; rank = 6; break; // Scene "Humor at the Expense of Others" case "Jailer": desc = "You there!"; rank = 2; break; case "Mephistopheles": desc = "Be not afraid!"; rank = 4; break; case "Breaks a Window": desc = "Oops!"; rank = 5; break; // Scene "The Search for Maggie White" case "Film Critic": desc = "Implausible!"; rank = 5; break; case "Hobo with Bat": desc = "Nice house!"; rank = 6; break; // Scene "Picante Sauce Commercial" case "Bewhisker'd Cowpoke": desc = "Oh, sweet Lord!"; rank = 3; break; case "Dog": desc = "Wurf!"; rank = 6; break; // Scene "Jesse James: Man of Action" case "Shot in Head": desc = "Arrrgh!"; rank = 1; break; case "Leaps Out of Cake": desc = "Oh, for Pete's sake!"; rank = 4; break; case "Shot Three Times": desc = "Ow! Ow! Ow!"; rank = 6; break; // Scene "One False Step for Mankind" case "Flustered Man": desc = "Well, I never!"; rank = 1; break; case "Space Monkey": desc = "Ook!"; rank = 2; break; case "Cowbot Dan": desc = "Bzzzzzt!"; rank = 5; break; // Scene "Thirteen the Hard Way" case "Man in Poncho": desc = "Howdy, Jones!"; rank = 1; break; case "Ecstatic Housewife": desc = "This is fine!"; rank = 3; break; case "Isaac": desc = "The mail!"; rank = 5; break; // Scene "How They Get Milk" case "Cow": desc = "Moo."; rank = 2; break; case "St. Clement of Alexandria": desc = "Peace be with you, child!"; rank = 3; break; case "Josie": desc = "Yikes!"; rank = 4; break; // Scene "My Years on the Prairie" case "Willard": desc = "Ain't that a sight?"; rank = 2; break; case "Leprechaun": desc = "Begorrah!"; rank = 3; break; case "Startled Ox": desc = "Mrr?"; rank = 5; break; // Scene "Davy Crockett: A Drunkard's Tale" case "Voice of God": desc = "Grab hold, son!"; rank = 2; break; case "Hands of God": desc = "!"; rank = 3; break; case "Jack Kemp": desc = "America!"; rank = 4; break; // Scene "Czechs in the Sonora" case "Opice (Monkey)": desc = "Ukk! (Ook)!"; rank = 5; break; case "Man with Gun": desc = "Hold it right there!"; rank = 6; break; // Scene "Swing 'em Wide" case "Thrifty Mike": desc = "Call!"; rank = 1; break; case "Sober Physician": desc = "Raise!"; rank = 3; break; case "Man on Floor": desc = "Fold!"; rank = 5; break; // Scene "Swing 'em Wide" ?? case "Liberated Nun": desc = "Let me have it!"; rank = 3; break; case "Witch Doctor": desc = "Oogie Boogie!"; rank = 5; break; case "Voice of Reason": desc = "Come on, now!"; rank = 6; break; // Scene "Trials of the First Pioneers" case "Burning Man": desc = "Make it stop!"; rank = 2; break; case "Cheese Vendor": desc = "Opa!"; rank = 4; break; case "Hit with Table": desc = "Ow! A table?"; rank = 5; break; // Scene "How the Grinch Stole Texas" case "Detective": desc = "I have a hunch."; rank = 3; break; case "File Clerk": desc = "My stapler!"; rank = 4; break; case "Cindy Lou": desc = "Dear Lord!"; rank = 5; break; // Scene "J. Robert Lucky, Man of Substance" case "Man with Rope": desc = "Look out below!"; rank = 1; break; case "Svetlana": desc = "Says who?"; rank = 2; break; case "Accidental Victim": desc = "Ow! My spine!"; rank = 5; break; // Scene "Thirteen the Hard Way" case "Very Wet Man": desc = "Sheesh!"; rank = 2; break; case "Dejected Housewife": desc = "Its time had come."; rank = 4; break; case "Man with Box": desc = "Progress!"; rank = 5; break; // Scene "How They Get Milk" case "Marksman": desc = "Pull!"; rank = 4; break; case "Postal Worker": desc = "It's about time!"; rank = 5; break; case "A Horse": desc = "Yes Sir!"; rank = 6; break; // Scene "Breakin' in Trick Ponies" case "Fraternity Pledge": desc = "Beer me!"; rank = 2; break; case "Man with Sword": desc = "None shall pass!"; rank = 6; break; // Scene "Custer's Other Stands" case "Farmer": desc = "Git off a that!"; rank = 2; break; case "Exploding Horse": desc = "Boom!"; rank = 4; break; case "Jack": desc = "Here we go again!"; rank = 6; break; default: // TODO: throw exception break; } return new Role(name, desc, rank); } } }
using System; using System.Threading; using System.Threading.Tasks; namespace Piovra.Data; public interface IUnitOfWork : IDisposable, IAsyncDisposable { Task<int> Commit(CancellationToken cancellationToken = default); }
using Database; using Microsoft.Extensions.Configuration; using System; using System.Collections.Generic; using System.Configuration; namespace TestDBCalls { class Program { static void Main(string[] args) { } } }
using UnityEngine; [CreateAssetMenu(fileName = "Buildable", menuName = "MS49/Buildable/Buildable Fog", order = 1)] public class BuildableFog : BuildableBase { public override bool isValidLocation(World world, Position pos, Rotation rotation) { return !world.isCoveredByFog(pos); } public override void placeIntoWorld(World world, BuildAreaHighlighter highlight, Position pos, Rotation rotation) { world.placeFog(pos); } }
// Dynamic Programming /** * Definition for a binary tree node. * public class TreeNode { * public int val; * public TreeNode left; * public TreeNode right; * public TreeNode(int x) { val = x; } * } */ public class Solution { public IList<TreeNode> GenerateTrees(int n) { List<List<TreeNode>> results = new List<List<TreeNode>>(); results.Add(new List<TreeNode>()); if (n == 0) { return results[0]; } results[0].Add(null); for (int i = 1; i < n+1; i++) { // fill up the results list List<TreeNode> temp = new List<TreeNode>(); // initialize results[i] for (int j = 1; j <= i; j++) { // when j is the root of the tree foreach (TreeNode leftNode in results[j-1]) { foreach (TreeNode rightNode in results[i-j]) { TreeNode root = new TreeNode(j); root.left = leftNode; root.right = clone(rightNode, j); temp.Add(root); } } } results.Add(temp); } return results[n]; } public TreeNode clone(TreeNode node, int offset) { if (node == null) { return null; } TreeNode newNode = new TreeNode(node.val + offset); newNode.left = clone(node.left, offset); newNode.right = clone(node.right, offset); return newNode; } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using ZY.OA.IBLL; using ZY.OA.Model; using ZY.OA.Model.Enum; using ZY.OA.Model.SearchModel; namespace ZY.OA.UI.PortalNew.Controllers { public class RoleInfoController : BaseController { public IRoleInfoService RoleInfoService { get; set; } public ActionResult Index() { return View(); } //获取角色信息 public ActionResult GetRoleInfo() { int pageIndex= Request["page"] == null ? 1 : int.Parse(Request["page"]); int pageSize = Request["rows"] == null ? 10 : int.Parse(Request["rows"]); int total = 0; string RoleName = Request["RoleName"]; string Remark = Request["Remark"]; RoleSearchParms roleSearchParms = new RoleSearchParms { pageIndex = pageIndex, pageSize = pageSize, total = total, RoleName= RoleName, Remark= Remark }; //获取搜索后的数据 var roleInfoList= RoleInfoService.GetPageEntityBySearch(roleSearchParms); var temp = from r in roleInfoList select new { ID=r.ID, RoleName=r.RoleName, SubTime =r.SubTime, ModfiedOn =r.ModfiedOn, Remark=r.Remark }; return Json(new {rows=temp, total=roleSearchParms.total },JsonRequestBehavior.AllowGet); } public ActionResult AddRoleInfo() { return View(); } //添加角色信息 [HttpPost] public ActionResult AddRoleInfo(RoleInfo roleInfo) { if (!string.IsNullOrEmpty(roleInfo.RoleName)) { short delFlag = (short)DelFlagEnum.Normal; roleInfo.SubTime = DateTime.Now; roleInfo.ModfiedOn = DateTime.Now; roleInfo.DelFlag = delFlag; RoleInfo role = RoleInfoService.Add(roleInfo); if (role != null) { return Content("ok"); } else { return Content("no"); } } else { return Content("no"); } } //展示要修改的角色信息 public ActionResult EditRoleInfo() { int id = int.Parse(Request["ID"]); var RoleInfo = RoleInfoService.GetEntities(r => r.ID == id).FirstOrDefault(); if (RoleInfo != null) { ViewBag.RoleInfo = RoleInfo; } return View(); } //修改角色 public ActionResult EditRole(RoleInfo role) { short delFlag = (short)DelFlagEnum.Normal; if (!string.IsNullOrEmpty(role.RoleName)&& !string.IsNullOrEmpty(role.Remark)) { role.ModfiedOn = DateTime.Now; role.DelFlag = delFlag; if (RoleInfoService.Update(role)) { return Content("ok"); } } return Content("no"); } //根据ID删除角色信息 public ActionResult DeleteRoleById() { string IdList = Request["IdList"]; List<int> ids = new List<int>(); if (!string.IsNullOrEmpty(IdList)) { string[] idList = IdList.Split(','); foreach (var id in idList) { ids.Add(int.Parse(id)); } if (RoleInfoService.DeleteListBylogical(ids)) { return Content("ok"); } } return Content("no"); } } }
using System.Threading.Tasks; using System.Web.Http; using Appmon.Dashboard.Models; using Newtonsoft.Json; namespace Appmon.Dashboard.Controllers { public class HealthCheckController : ApiController { public HealthCheckResults Get() { return (HealthCheckResults)JsonConvert.DeserializeObject(DocumentService.GetResult("DependencyHealthResultsCollection"), typeof(HealthCheckResults)); } } }
using System; using System.Xml.Serialization; using Newtonsoft.Json; namespace NeuroLinker.Models { /// <summary> /// Anime information entry for the user`s anime list /// </summary> [Serializable] [XmlRoot("anime")] public class UserListAnime { #region Properties /// <summary> /// Indicate if the user is rewatching the show or not /// </summary> [XmlElement(ElementName = "my_rewatching")] [JsonProperty(PropertyName = "my_rewatching")] public string MyRewatching { get; set; } /// <summary> /// The current rewatch episode /// </summary> [XmlElement(ElementName = "my_rewatching_ep")] [JsonProperty(PropertyName = "my_rewatching_episodes")] public int RewatchingEpisode { get; set; } /// <summary> /// The last time the user list entry was updated /// </summary> [XmlElement(ElementName = "my_last_updated")] [JsonProperty(PropertyName = "last_update")] public string LastUpdated { get; set; } /// <summary> /// The user`s Id /// </summary> [XmlElement(ElementName = "my_id")] [JsonProperty(PropertyName = "my_id")] public int MyId { get; set; } /// <summary> /// The number of episodes the user has watched /// </summary> [XmlElement(ElementName = "my_watched_episodes")] [JsonProperty(PropertyName = "watched_episodes")] public int WatchedEpisodes { get; set; } /// <summary> /// The date when the user started watching the show /// </summary> [XmlElement(ElementName = "my_start_date")] [JsonProperty(PropertyName = "my_start_date")] public string MyStartDate { get; set; } /// <summary> /// The date when the user finished watching the show /// </summary> [XmlElement(ElementName = "my_finish_date")] [JsonProperty(PropertyName = "my_finish_date")] public string MyFinishDate { get; set; } /// <summary> /// The date when the series finished screening /// </summary> [XmlElement(ElementName = "series_end")] [JsonProperty(PropertyName = "series_end")] public string SeriesEnd { get; set; } /// <summary> /// URL to the anime`s poster /// </summary> [XmlElement(ElementName = "series_image")] [JsonProperty(PropertyName = "series_image")] public string SeriesImage { get; set; } /// <summary> /// Score the user assigned to the anime /// </summary> [XmlElement(ElementName = "my_score")] [JsonProperty(PropertyName = "my_score")] public int MyScore { get; set; } /// <summary> /// The user`s watch status for the show /// </summary> [XmlElement(ElementName = "my_status")] [JsonProperty(PropertyName = "my_status")] public int MyStatus { get; set; } /// <summary> /// Tags the user has assigned to the show /// </summary> [XmlElement(ElementName = "my_tags")] [JsonProperty(PropertyName = "my_tags")] public string MyTags { get; set; } /// <summary> /// Number of episodes the series has /// </summary> [XmlElement(ElementName = "series_episodes")] [JsonProperty(PropertyName = "series_episodes")] public int SeriesEpisodes { get; set; } /// <summary> /// Synonyms for the series /// </summary> [XmlElement(ElementName = "series_synonyms")] [JsonProperty(PropertyName = "series_synonyms")] public string SeriesSynonyms { get; set; } /// <summary> /// The type of the series (eg TV) /// </summary> [XmlElement(ElementName = "series_type")] [JsonProperty(PropertyName = "series_type")] public int SeriesType { get; set; } /// <summary> /// The Mal Id for the show /// </summary> [XmlElement(ElementName = "series_animedb_id")] [JsonProperty(PropertyName = "series_id")] public int SeriesId { get; set; } /// <summary> /// The series screening status /// </summary> [XmlElement(ElementName = "series_status")] [JsonProperty(PropertyName = "series_status")] public int SeriesStatus { get; set; } /// <summary> /// Date when the series started screening /// </summary> [XmlElement(ElementName = "series_start")] [JsonProperty(PropertyName = "series_start")] public string SeriesStart { get; set; } /// <summary> /// The series title /// </summary> [XmlElement(ElementName = "series_title")] [JsonProperty(PropertyName = "series_title")] public string SeriesTitle { get; set; } #endregion } }
using System; using System.Windows.Input; using TripLog.Models; using TripLog.Services; using Xamarin.Forms; namespace TripLog.ViewModels { public class DetailPageViewModel : ViewModelBase { private TripLogEntry entry; public TripLogEntry Entry { get { return entry; } set { if (value != entry) { entry = value; NotifyPropertyChanged(nameof(Entry)); } } } private ICommand backCommand; public ICommand BackCommand { get { if(backCommand == null) { backCommand = new Command(BackProcedure); } return backCommand; } } private readonly ITripLogNavigation tripLogNavigation; public DetailPageViewModel(ITripLogNavigation tripLogNavigation) { this.tripLogNavigation = tripLogNavigation; } public void Init(TripLogEntry entry) { this.Entry = entry; } private void BackProcedure() { this.tripLogNavigation.PopAsync(); } } }
using UnityEngine; using System.Collections; public class Layers { public const int Block = 10; public const int Missile = 11; public const int BluTeam = 9; public const int RedTeam = 8; }
using UnityEngine; using System.Collections; public class CheckPoint : MonoBehaviour { //Variables private PlayerStates playerStates; private SaveSystem saveManager; //private PlayerPrefs save; void Awake() { playerStates = GameObject.FindWithTag("Player").GetComponent<PlayerStates>(); saveManager = GameObject.Find ("GameManager").GetComponent<SaveSystem>(); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } //on Trigger Enter void OnTriggerEnter(Collider other) { //Player Enters Checkpoint if(other.tag == "Player") { Debug.Log ("Player Hits Checkpoint!"); Save (); } else { } } void Save() { saveManager.Save(playerStates.getCurrHP(), playerStates.getPlayerPosX (), playerStates.getPlayerPosY (), playerStates.getPlayerPosZ (), playerStates.getCanteenUses()); Debug.Log("Saving... Player Pos: " + playerStates.getPlayerPosX() + " / " + playerStates.getPlayerPosY () + " / " + playerStates.getPlayerPosZ() + " HP: " + playerStates.getCurrHP()); } void Load() { saveManager.Load (); } }
using System; using System.Diagnostics; using System.IO; using Microsoft.VisualStudio.TestTools.UnitTesting; using ZipLib.Enums; using ZipLib.Ext; namespace MSNetZipTests { [TestClass] public class BasicTests { [TestMethod] public void CanRun_MSNetTest_True() { Assert.IsTrue(true); /* Sanity check to make sure test framework is working */ } [TestMethod] public void CanGzipFile_Test01_True() { /* Arrange */ var sutFilePath = Path.Combine(Environment.CurrentDirectory, TestConstants.INPUT_FILE_01_PATH); var sutOutputFilePath = Path.Combine(Environment.CurrentDirectory, TestConstants.OUTPUT_FILE_01_PATH); var gotInput = new FileInfo(sutFilePath); var got = new FileInfo(sutOutputFilePath); /* Act */ Trace.WriteLine("File already exists:{0}", got.Exists.ToString()); got = gotInput.Compress(got, 60000); /* Assert */ Trace.WriteLine("File created:{0}", got?.FullName); Assert.IsTrue(got.Exists, $"{TestConstants.CANNOT_FIND_FILE_MSG} {got.FullName}"); } } }
using System; using System.ComponentModel.DataAnnotations; namespace com.Sconit.Entity.CUST { [Serializable] public partial class ProductLineMap : EntityBase { #region O/R Mapping Properties [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "ProductLineMap_SAPProductLine", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string SAPProductLine { get; set; } [Required(AllowEmptyStrings = false, ErrorMessageResourceName = "Errors_Common_FieldRequired", ErrorMessageResourceType = typeof(Resources.SYS.ErrorMessage))] [Display(Name = "ProductLineMap_ProductLine", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string ProductLine { get; set; } [Display(Name = "ProductLineMap_CabLocation", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string CabLocation { get; set; } [Display(Name = "ProductLineMap_ChassisLocation", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string ChassisLocation { get; set; } [Display(Name = "ProductLineMap_VanLocation", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string VanLocation { get; set; } [Display(Name = "ProductLineMap_CabFlow", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string CabFlow { get; set; } [Display(Name = "ProductLineMap_ChassisFlow", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string ChassisFlow { get; set; } [Display(Name = "ProductLineMap_ChassisSapLocation", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string ChassisSapLocation { get; set; } [Display(Name = "ProductLineMap_VanSapLocation", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string VanSapLocation { get; set; } [Display(Name = "ProductLineMap_PowerFlow", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string PowerFlow { get; set; } [Display(Name = "ProductLineMap_TransmissionFlow", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string TransmissionFlow { get; set; } [Display(Name = "ProductLineMap_TireFlow", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string TireFlow { get; set; } [Display(Name = "ProductLineMap_SaddleFlow", ResourceType = typeof(Resources.CUST.ProductLineMap))] public string SaddleFlow { get; set; } #endregion public override int GetHashCode() { if (SAPProductLine != null) { return SAPProductLine.GetHashCode(); } else { return base.GetHashCode(); } } public override bool Equals(object obj) { ProductLineMap another = obj as ProductLineMap; if (another == null) { return false; } else { return (this.SAPProductLine == another.SAPProductLine); } } } }
// Copyright (c) 2020, mParticle, Inc // // 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 // // https://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; using System.Collections.Generic; using System.Text; using Xunit; namespace MP.Json.Validation.Test { public class StringTests { [Fact] public void StringFormatTest() { var schema = SimpleSchema("format", "unknown"); Assert.True(schema.IsValid); Assert.True(schema.Validate("xyz")); Assert.True(schema.Validate(123)); Assert.False(SimpleSchema("format", 1).IsValid); Assert.False(SimpleSchema("format", MPJson.Array()).IsValid); } [Fact] public void StringMaxLengthTest() { var schema = SimpleSchema("maxLength", 3); Assert.True(schema.IsValid); Assert.True(schema.Validate("")); Assert.True(schema.Validate("ab")); Assert.True(schema.Validate("abc")); Assert.False(schema.Validate("abcd")); Assert.True(schema.Validate(0)); Assert.False(SimpleSchema("maxLength", 1.5).IsValid); Assert.False(SimpleSchema("maxLength", "1").IsValid); Assert.False(SimpleSchema("maxLength", MPJson.Array()).IsValid); } [Fact] public void StringMinLengthTest() { var schema = SimpleSchema("minLength", 3); Assert.True(schema.IsValid); Assert.False(schema.Validate("")); Assert.False(schema.Validate("ab")); Assert.True(schema.Validate("abc")); Assert.True(schema.Validate("abcd")); Assert.True(schema.Validate(0)); Assert.False(SimpleSchema("minLength", 1.5).IsValid); Assert.False(SimpleSchema("minLength", "1").IsValid); Assert.False(SimpleSchema("minLength", MPJson.Array()).IsValid); } [Fact] public void StringPatternTest() { var schema = SimpleSchema("pattern", @"\d+"); Assert.True(schema.IsValid); Assert.True(schema.Validate(0)); Assert.True(schema.Validate("1")); Assert.True(schema.Validate("12")); Assert.False(schema.Validate("")); Assert.False(SimpleSchema("pattern", 1.5).IsValid); Assert.False(SimpleSchema("pattern", MPJson.Array()).IsValid); } #region Helpers MPSchema SimpleSchema(string keyword, MPJson json) { return new MPSchema(MPJson.Object(MPJson.Property(keyword, json))); } #endregion } }
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading.Tasks; namespace SoftwareAuthKeyLoader { internal static class Network { public static IPAddress ParseIpAddress(string ipAddress) { return IPAddress.Parse(ipAddress); } public static int ParseUdpPort(string udpPort) { int udpPortNumber = int.Parse(udpPort); if (udpPortNumber >= 1 && udpPortNumber <= 65535) { return udpPortNumber; } else { throw new ArgumentOutOfRangeException("udpPortNumber"); } } public static int ParseTimeout(string timeout) { int timeoutValue = int.Parse(timeout); if (timeoutValue > 0) { return timeoutValue; } else { throw new ArgumentOutOfRangeException("timeout"); } } public static byte[] QueryRadio(byte[] toRadio) { string ipAddress = Settings.IpAddress.ToString(); int udpPort = Settings.UdpPort; int timeout = Settings.Timeout; Output.DebugLine("ip address: {0}, udp port: {1}, receive timeout: {2}", ipAddress, udpPort, timeout); using (UdpClient udpClient = new UdpClient(ipAddress, udpPort)) { Output.DebugLine("sending {0} bytes to radio - {1}", toRadio.Length, BitConverter.ToString(toRadio)); udpClient.Client.ReceiveTimeout = timeout; udpClient.Send(toRadio, toRadio.Length); IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Any, 0); byte[] fromRadio = udpClient.Receive(ref remoteEndPoint); Output.DebugLine("received {0} bytes from radio - {1}", fromRadio.Length, BitConverter.ToString(fromRadio)); return fromRadio; } } } }
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Flipcards.DataAccess; using FlipCards.Models; namespace Flipcards { public partial class EditCardForm : MaterialSkin.Controls.MaterialForm { private readonly CardModel _model; public EditCardForm(CardModel model) { InitializeComponent(); _model = model; promptTextBox.Text = model.Prompt; answerTextBox.Text = model.Answer; } private void cancelButton_Click(object sender, EventArgs e) { Close(); } private void okButton_Click(object sender, EventArgs e) { CardModel updatedModel = new CardModel(); updatedModel.Prompt = promptTextBox.Text; updatedModel.Answer = answerTextBox.Text; updatedModel.Id = _model.Id; if (promptTextBox.Text.Length > 0 || answerTextBox.Text.Length > 0) { GlobalConfig.Connection.UpdateCard(updatedModel); Close(); } else { MessageBox.Show("Please complete all fields"); } } private void EditCardForm_Load(object sender, EventArgs e) { } } }
namespace BDTest.Attributes; internal class EnumOrderAttribute : Attribute { internal readonly int Order; internal EnumOrderAttribute(int order) { Order = order; } }
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public abstract class ActorState<Data> : BaseState where Data : ActorStateData { protected Data data; public ActorState(Data characterData) : base(characterData.StateM) { data = characterData; } public override void FixedUpdate() { if (!stateManager.IsPaused) UpdatePhysics(); } /// <summary> /// Physics Update, Called From ActorState FixedUpdate /// </summary> protected virtual void UpdatePhysics() { } }
namespace DesignPatterns.Creational.Builder { public class CoffeeAssembly { public void Assemble(CoffeeBuilder coffeeBuilder) { coffeeBuilder.Flavor(); coffeeBuilder.Milk(); coffeeBuilder.Size(); coffeeBuilder.Sweetener(); } } }
using Mono.Options; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using VerbiLib.ParserV1; using VerbiLib.Phraser; namespace VerbiConsole { class Program { static void Main(string[] args) { new Program(args); } //============================================================================== public Program(string[] args) { // these variables will be set when the command line is parsed var showHelp = false; var number = 40; var template = "MAIN"; var verbose = false; string optOutFile = null; // these are the available options, not that they set the variables var options = new OptionSet { { "n|number=", $"Number of phrases to generate. Default is {number}", (int x) => number = x }, { "t|template=", $"Specific template to generate. Default is {template}", x => template = x }, { "h|help", "show this message and exit", x => showHelp = x != null }, { "v", "increase debug message verbosity", x => verbose = (x != null) }, { "o|output=", "output file. Default is STDOUT", x => optOutFile = x }, }; List<string> extra; try { // parse the command line extra = options.Parse(args); } catch (OptionException e) { // output some error message ccc("Error parsing command line arguments."); ccc(e.Message); ccc("Try `--help' for more information."); return; } if (showHelp) { ccc("Usage: thing.exe [OPTIONS] somefile.phrasi"); ccc(" Make sure u also have .verbi and .paroli in that directory"); options.WriteOptionDescriptions(Console.Out); return; } var filename = extra.FirstOrDefault(); //------------------------------------------------------------------------------------------------------------- if (verbose) ccc($"ARGZ: n={number}, t={template}, filename={filename}"); PhraseBuilder _phraseBuilder = CompilePhraseReaderFromThisVerbiFile(filename, verbose); if (_phraseBuilder == null) { ccc("Error creating phrase builder"); return; } // after everything is successfully loaded, redirect STDOUT to optOutFile if that option was set StreamWriter swOutFile = null; if (optOutFile != null) { FileStream fs = new FileStream(optOutFile, FileMode.Create); //TextWriter tmp = Console.Out; swOutFile = new StreamWriter(fs); Console.SetOut(swOutFile); } for (int i = 0; i < number; i++) { var test = _phraseBuilder.GeneratePhrase(template); ccc(test); } if (swOutFile != null) { swOutFile.Flush(); swOutFile.Close(); } } private PhraseBuilder CompilePhraseReaderFromThisVerbiFile(string filename, bool isVerbose) { if (filename == null) return NullWithErrorMessage("Must specify a .phrasi file as the first argument"); if (!File.Exists(filename)) return NullWithErrorMessage($"Invalid argument: file '{filename}' does not exist"); if (Path.GetExtension(filename).ToLower() != ".phrasi") return NullWithErrorMessage($"The first argument must be a .phrasi file"); var dirname = Path.GetDirectoryName(filename); if (string.IsNullOrEmpty(dirname)) dirname = "."; var allFilesVerbi = Directory.GetFiles(dirname, "*.verbi"); var allFilesParoli = Directory.GetFiles(dirname, "*.paroli"); var filenameVerbi = allFilesVerbi.FirstOrDefault(); var filenameParoli = allFilesParoli.FirstOrDefault(); var filenamePhrasiCommon = Path.Combine(dirname, "common.phrasi"); if (!File.Exists(filenamePhrasiCommon)) filenamePhrasiCommon = null; if (filenameVerbi == null) return NullWithErrorMessage($"no .verbi file was found in this directory ('{dirname}')"); if (filenameParoli == null) return NullWithErrorMessage($"no .paroli file was found in this directory ('{dirname}')"); if (isVerbose) ccc($@"Neccessary files found: - {Path.GetFileName(filenameVerbi)} - {Path.GetFileName(filenameParoli)} - {Path.GetFileName(filename)} "); ParoliStructure myParoli; VerbiStructure myVerbi; PhrasiStructure phraseTree, phraseTreeCommons = null; try { myParoli = ParoliParser.ParseEverything(File.ReadAllText(filenameParoli)); } catch (VerbiSyntaxException ex) { ccc($"Error in file '{filenameParoli}', Line:{ex.Position.Line}, Col:{ex.Position.Column}, Error: {ex.Message}"); return null; } try { myVerbi = VerbiParser.ParseEverything(File.ReadAllText(filenameVerbi)); } catch (VerbiSyntaxException ex) { ccc($"Error in file '{filenameVerbi}', Line:{ex.Position.Line}, Col:{ex.Position.Column}, Error: {ex.Message}"); return null; } try { phraseTree = PhrasiParser.ParseEverything(File.ReadAllText(filename)); } catch (VerbiSyntaxException ex) { ccc($"Error in file '{filename}', Line:{ex.Position.Line}, Col:{ex.Position.Column}, Error: {ex.Message}"); return null; } //if (verbose) // ccc(phraseTree.ToStringDeep()); var _phraseBuilder = new PhraseBuilder(phraseTree, myVerbi, myParoli); if (filenamePhrasiCommon != null) { try { phraseTreeCommons = PhrasiParser.ParseEverything(File.ReadAllText(filenamePhrasiCommon)); } catch (VerbiSyntaxException ex) { ccc($"Error in file '{filename}', Line:{ex.Position.Line}, Col:{ex.Position.Column}, Error: {ex.Message}"); return null; } } var _phraseBuilder = new PhraseBuilder(phraseTree, myVerbi, myParoli); if (phraseTreeCommons != null) phraseTree.MergeWith(phraseTreeCommons); _phraseBuilder.IsVerbose = isVerbose; return _phraseBuilder; } private PhraseBuilder NullWithErrorMessage(string message) { ccc(message); return null; } private void ccc(string message) { //Debug.WriteLine(message); Console.WriteLine(message); } } }
using System; using System.Drawing; using System.Windows.Forms; using System.IO; namespace FileBackupper { public partial class frmPreferences : Form { public frmPreferences() { InitializeComponent(); rbYes.CheckedChanged += new EventHandler(RadioButtonsOverwr_CheckedChanged); rbNo.CheckedChanged += new EventHandler(RadioButtonsOverwr_CheckedChanged); rbDateFormat1.CheckedChanged += new EventHandler(RadioButtonsDateF_CheckedChanged); rbDateFormat1.CheckedChanged += new EventHandler(RadioButtonsDateF_CheckedChanged); try { FileOps.RadioButtonsFix(Properties.Settings.Default.Overwrite, rbYes, rbNo); FileOps.RadioButtonsFix(Properties.Settings.Default.DateYYYY, rbDateFormat1, rbDateFormat2); FileOps.ToggleEnable(Properties.Settings.Default.IncludeDate, new ButtonBase[] { rbDateFormat1, rbDateFormat2, chkDateFirst }); FileOps.CheckBoxFix(Properties.Settings.Default.IncludeDate, chkIncludeDate); FileOps.CheckBoxFix(Properties.Settings.Default.DateFirst, chkDateFirst); } catch (Exception) { MessageBox.Show("App.config has been modified incorrectly.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } txtFolderName.Text = Properties.Settings.Default.DefaultFolderName; } protected override bool ProcessDialogKey(Keys keyData) { if (ModifierKeys == Keys.None && keyData == Keys.Escape) { Close(); } return base.ProcessDialogKey(keyData); } private void RadioButtonsOverwr_CheckedChanged(object sender, EventArgs e) { RadioButton radioButton = sender as RadioButton; Properties.Settings.Default.Overwrite = rbYes.Checked; Properties.Settings.Default.Save(); } private void btnClose_Click(object sender, EventArgs e) { Close(); } private void btnSaveFolderName_Click(object sender, EventArgs e) { if (txtFolderName.Text.IndexOfAny(Path.GetInvalidFileNameChars()) == -1) { Properties.Settings.Default.DefaultFolderName = txtFolderName.Text.Trim(); Properties.Settings.Default.Save(); txtFolderName.BackColor = Color.LightGreen; txtFolderName.ForeColor = Color.Black; } else { txtFolderName.ForeColor = Color.Red; MessageBox.Show("A filename cannot contain any of the following characters: \\ / : * ? \" < > | ", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } } private void chkIncludeDate_CheckedChanged(object sender, EventArgs e) { Properties.Settings.Default.IncludeDate = chkIncludeDate.Checked; Properties.Settings.Default.Save(); FileOps.ToggleEnable(Properties.Settings.Default.IncludeDate, new ButtonBase[] { rbDateFormat1, rbDateFormat2, chkDateFirst }); } private void chkDateFirst_CheckedChanged(object sender, EventArgs e) { Properties.Settings.Default.DateFirst = chkDateFirst.Checked; Properties.Settings.Default.Save(); } private void rbDateFormat1_MouseHover(object sender, EventArgs e) { ttipShort.SetToolTip(rbDateFormat1, DateTime.Now.ToString("yyyy-MM-dd")); } private void rbDateFormat2_MouseHover(object sender, EventArgs e) { ttipShort.SetToolTip(rbDateFormat2, DateTime.Now.ToString("yy-MM-dd")); } private void chkDateFirst_MouseHover(object sender, EventArgs e) { ttipLong.SetToolTip(chkDateFirst, $"Checked: {DateTime.Now.ToString("yyyy-MM-dd")} YourFolderName" + $"\n\n Unchecked: YourFolderName {DateTime.Now.ToString("yyyy-MM-dd")}"); } private void RadioButtonsDateF_CheckedChanged(object sender, EventArgs e) { RadioButton radioButton = sender as RadioButton; if (rbDateFormat1.Checked) { Properties.Settings.Default.DateFormat = "yyyy-MM-dd"; } else { Properties.Settings.Default.DateFormat = "yy-MM-dd"; } Properties.Settings.Default.DateYYYY = rbDateFormat1.Checked; Properties.Settings.Default.Save(); } } }
using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using lsc.Dal; using lsc.Model; namespace lsc.Bll { public class UserAnswerBll { public async Task<int> AddAsync(UserAnswer userAnswer) { return await UserAnswerDal.Ins.AddAsync(userAnswer); } public async Task<List<UserAnswer>> GetList(int logId) { return await UserAnswerDal.Ins.GetList(logId); } public async Task<UserAnswer> GetByIdAsync(int id) { return await UserAnswerDal.Ins.GetByIdAsync(id); } public async Task<bool> UpdateAsync(UserAnswer userAnswer) { return await UserAnswerDal.Ins.UpdateAsync(userAnswer); } } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.IO; using System.Text; using LitJson; public class JsonData { public eMsgID MsgID; public virtual byte[] Pack() { return new []{(byte)MsgID}; } public JsonData(eMsgID id) { MsgID = id; } } /* { "objects": [ { "obj1": { "lightmapIndex": 0, "offsetX": -0.2, "offsetY": 0.4, "scaleX": 0.5, "scaleY": 0.6 } }, { "obj2": { "lightmapIndex": 0, "offsetX": -0.2, "offsetY": 0.4, "scaleX": 0.5, "scaleY": 0.6 } } ] } */ public class LightmapSTJsonData : JsonData { public Dictionary<string, Tuple<int, Vector4>> STDict = new Dictionary<string, Tuple<int, Vector4>>(); public LightmapSTJsonData(MeshRenderer[] meshRenderers,eMsgID id) : base(id) { foreach (var mesh in meshRenderers) { if(STDict.ContainsKey(mesh.gameObject.name)) Debug.Log("Same Name: " + mesh.gameObject.name); STDict.Add(mesh.gameObject.name, new Tuple<int, Vector4>(mesh.lightmapIndex, mesh.lightmapScaleOffset)); } } static void LightmapST2Json(JsonWriter writer, int index, Vector4 st) { writer.WriteObjectStart(); writer.WritePropertyName("lightmapIndex"); writer.Write(index); writer.WritePropertyName("scaleX"); writer.Write(st.x); writer.WritePropertyName("scaleY"); writer.Write(st.y); writer.WritePropertyName("offsetX"); writer.Write(st.z); writer.WritePropertyName("offsetY"); writer.Write(st.w); writer.WriteObjectEnd(); // Camera.main. } public override byte[] Pack() { StringBuilder sb = new StringBuilder(); JsonWriter writer = new JsonWriter(sb); writer.WriteObjectStart(); //writer.WritePropertyName("objects"); // writer.WriteArrayStart(); foreach (var st in STDict) { // writer.WriteObjectStart(); writer.WritePropertyName(st.Key); LightmapST2Json(writer, st.Value.Item1, st.Value.Item2); // writer.WriteObjectEnd(); } // writer.WriteArrayEnd(); writer.WriteObjectEnd(); var jsonStr = sb.ToString(); byte[] jsonBytes = Encoding.UTF8.GetBytes(jsonStr); FileStream file = new FileStream("d:/lightmapST.json", FileMode.Create); file.Write(jsonBytes, 0, jsonBytes.Length); if (file != null) { file.Close(); } return jsonBytes; } } /// /// { /// "lightmap"=[ /// { /// "index"=0, /// "base64""dsl;ifunjiawevy" /// }, /// { /// "index"=1, /// "base64""dsl;ifunjiawevy" /// } /// ] /// } public class LightmapArrayJsonData : JsonData { public LightmapArrayJsonData(eMsgID id) : base(id) { } public override byte[] Pack() { StringBuilder sb = new StringBuilder(); JsonWriter writer = new JsonWriter(sb); writer.WriteObjectStart(); writer.WritePropertyName("lightmap"); writer.WriteArrayStart(); for (int i = 0; i < LightmapSettings.lightmaps.Length; ++i) { writer.WriteObjectStart(); writer.WritePropertyName("index"); writer.Write(i.ToString()); writer.WritePropertyName("base64"); // writer.Write(Convert.ToBase64String(Baker.ExtractLightmapBytes(LightmapSettings.lightmaps[i].lightmapColor))); writer.Write(Convert.ToBase64String(Baker.ExtractLightmapBytes(Baker.Instance.LightmapData[i]))); writer.WriteObjectEnd(); } writer.WriteArrayEnd(); writer.WriteObjectEnd(); var jsonStr = sb.ToString(); return Encoding.UTF8.GetBytes(jsonStr); } } public class RadianceData { public UInt16 Header; public UInt16 Width; public UInt16 Height; byte[] mRawData; public RadianceData(UInt16 width , UInt16 height , byte[] rawData) { Width = width; Height = height; mRawData = rawData; } public RadianceData(UInt16 header, UInt16 width, UInt16 height, byte[] rawData) { Header = header; Width = width; Height = height; mRawData = rawData; } public byte[] packedData { get { byte[] headerBytes = BitConverter.GetBytes(Header); byte[] newData = new byte[headerBytes.Length + mRawData.Length]; LCRS.Log("======================================== header length: " + headerBytes.Length + ", #$34F: " + Header); Array.Copy(headerBytes, newData, headerBytes.Length); Array.Copy(mRawData, 0, newData, headerBytes.Length, mRawData.Length); return newData; } } public byte[] rawData { get { return mRawData; } } } public class AttributeData { public byte[] RawData; public AttributeData(byte[] rawData) { RawData = rawData; } } public class CloudSocket { Queue<AttributeData> mAttributeDataList = new Queue<AttributeData>(); Queue<RadianceData> mRadianceDataList = new Queue<RadianceData>(); Queue<JsonData> mJsonDataList = new Queue<JsonData>(); public RadianceData DequeueRadianceData() { if (mRadianceDataList.Count > 0) { return mRadianceDataList.Dequeue(); } return null; } public AttributeData DequeueAttributeData() { if (mAttributeDataList.Count > 0) { return mAttributeDataList.Dequeue(); } return null; } public void EnqueueRadianceData(RadianceData dataBytes) { mRadianceDataList.Enqueue(dataBytes); } public void EnqueueAttributeData(AttributeData dataBytes) { mAttributeDataList.Enqueue(dataBytes); } public void EnqueueJsonData(JsonData dataBytes) { mJsonDataList.Enqueue(dataBytes); } public JsonData DequeueJsonData() { if (mJsonDataList.Count > 0) { return mJsonDataList.Dequeue(); } return null; } }
using HomeAutomation.Model.DoorSwitchReading; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using HomeAutomation.DAL; namespace HomeAutomation.DAL.DoorSwitch { public class DoorSwitch { static List<DoorSwitchDTO> _doorSwitchItems; static DoorSwitch _instance; public static DoorSwitch Singleton() { if (_instance == null) { _instance = new DoorSwitch(); } if (_doorSwitchItems == null) { _doorSwitchItems = new List<DoorSwitchDTO>(); } return _instance; } private DoorSwitch() { } public List<DoorSwitchDTO> GetReadings() { return _doorSwitchItems; //using (var db = new HomeAutomation.DAL.HomeAutomationEntities()) //{ // var query = (from item in db.SensorReadings // join dss in db.DoorSwitchSensors on item.Id equals dss.SensorReadingID // join sr in db.Sensors on item.SensorID equals sr.Id // select (new DoorSwitchDTO { ReadingDateTime = item.ReadingDateTime })).ToList(); // return query; //} } public void InsertReading(DoorSwitchDTO item) { _doorSwitchItems.Add(item); } } }
using FifthBot.Resources.Datatypes; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.IO; using System.Text; namespace FifthBot.Resources.Helpers { public static class HelperMethods { public static void LoadSettings() { string JSON = ""; string settingsLocation = @"C:\discordbots\FifthBot\FifthBot\Data\Settings.json"; if (!File.Exists(settingsLocation)) { settingsLocation = @"FifthBot/Data/ReleaseSettings.json"; } using (var fileStream = new FileStream(settingsLocation, FileMode.Open, FileAccess.Read)) using (var ReadSettings = new StreamReader(fileStream)) { JSON = ReadSettings.ReadToEnd(); } JsonConvert.DeserializeObject<Setting>(JSON); } } }
using Alabo.Data.Things.Orders.Domain.Entities; using Alabo.Data.Things.Orders.ResultModel; using Alabo.Domains.Repositories; using System.Collections.Generic; namespace Alabo.Data.Things.Orders.Domain.Repositories { /// <summary> /// 分润订单 /// </summary> public interface IShareOrderRepository : IRepository<ShareOrder, long> { /// <summary> /// 获取s the un handled identifier list. /// </summary> IList<long> GetUnHandledIdList(); /// <summary> /// Errors the order. /// </summary> /// <param name="shareOrderId">The share order identifier.</param> /// <param name="message">The message.</param> void ErrorOrder(long shareOrderId, string message); /// <summary> /// 更新成功 /// </summary> /// <param name="shareOrderId"></param> void SuccessOrder(long shareOrderId); /// <summary> /// 获取s the single native. /// </summary> /// <param name="shareOrderId">The share order identifier.</param> ShareOrder GetSingleNative(long shareOrderId); /// <summary> /// 更新分润执行结果 /// 价格类型的分润结果 /// </summary> /// <param name="resultList">The result list.</param> void UpdatePriceTaskResult(IEnumerable<ShareResult> resultList); /// <summary> /// 更新分润模块执行次数 /// </summary> /// <param name="shareOrderId">The share order identifier.</param> /// <param name="count">The count.</param> void UpdateExcuteCount(long shareOrderId, long count); /// <summary> /// 执行分润执行结果 /// </summary> /// <param name="resultList">The result list.</param> void UpdateUpgradeTaskResult(IEnumerable<UserGradeChangeResult> resultList); /// <summary> /// 根据EntityIds 获取分润订单 /// </summary> /// <param name="EntityIds"></param> List<ShareOrder> GetList(List<long> EntityIds); } }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Diagnostics; using System.Threading; using System.Timers; using System.IO; using RakNet; namespace SwigTestApp { class TestMain { static void Main(string[] args) { if (!File.Exists("RakNet.dll")) { Console.WriteLine("The SWIG build of the DLL has not been copied to the executable directory\nCopy from Swig/SwigWindowsCSharpSample/SwigTestApp/bin/X86/Debug/RakNet.dll to\nSwigWindowsCSharpSample/SwigTestApp/bin/Debug/RakNet.dll\nPress enter to quit."); Console.Read(); return; } try { RakString dllCallTest = new RakString(); } catch (Exception e) { Console.WriteLine("DLL issue\nAdd SwigOutput/CplusDLLIncludes/RakNetWrap.cxx to the project\nDLL_Swig/RakNet.sln and rebuild.\nPress enter to quit."); Console.Read(); return; } Packet testPacket; int loopNumber; BitStream stringTestSendBitStream = new BitStream(); BitStream rakStringTestSendBitStream = new BitStream(); BitStream receiveBitStream = new BitStream(); String holdingString; TimeSpan startTimeSpan; RakString rakStringTest = new RakString(); RakPeerInterface testClient = RakPeer.GetInstance(); testClient.Startup(1, new SocketDescriptor(60000, "127.0.0.1"), 1); RakPeerInterface testServer = RakPeer.GetInstance(); testServer.Startup(1, new SocketDescriptor(60001, "127.0.0.1"), 1); testServer.SetMaximumIncomingConnections(1); Console.WriteLine("Send and receive loop using BitStream.\nBitStream read done into RakString"); testClient.Connect("127.0.0.1", 60001, "", 0); String sendString = "The test string"; stringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); stringTestSendBitStream.Write(sendString); RakString testRakString = new RakString("Test RakString"); rakStringTestSendBitStream.Write((byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM); rakStringTestSendBitStream.Write(testRakString); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(rakStringTest); Console.WriteLine("Loop number: " + loopNumber + "\nData: " + rakStringTest.C_String()); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); testClient.Send(rakStringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } Console.WriteLine("String send and receive loop using BitStream.\nBitStream read done into String"); SystemAddress[] remoteSystems; ushort numberOfSystems=1; testServer.GetConnectionList(out remoteSystems, ref numberOfSystems); startTimeSpan = (DateTime.UtcNow - new DateTime(1970, 1, 1)); loopNumber = 0; while (startTimeSpan.TotalSeconds + 5 > (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds) { testPacket = testServer.Receive(); if (testPacket != null && testPacket.data[0] == (byte)DefaultMessageIDTypes.ID_USER_PACKET_ENUM) { receiveBitStream.Reset(); receiveBitStream.Write(testPacket.data, testPacket.length); receiveBitStream.IgnoreBytes(1); receiveBitStream.Read(out holdingString); Console.WriteLine("Loop number: " + loopNumber + "\nData: " + holdingString); } testServer.DeallocatePacket(testPacket); loopNumber++; System.Threading.Thread.Sleep(50); SystemAddress sa = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; testClient.Send(stringTestSendBitStream, PacketPriority.LOW_PRIORITY, PacketReliability.RELIABLE_ORDERED, (char)0, new AddressOrGUID(new SystemAddress("127.0.0.1", 60001)), false); } //If RakString is not freed before program exit it will crash rakStringTest.Dispose(); testRakString.Dispose(); RakPeer.DestroyInstance(testClient); RakPeer.DestroyInstance(testServer); Console.WriteLine("Demo complete. Press Enter."); Console.Read(); } } #if AUTOPATCHERMYSQLTESTS private static int TestAutoPatcherClient() { //Stick the restarter path here String restarterPath = "C:\\Rak4\\Samples\\AutopatcherClientRestarter\\Debug\\AutopatcherClientRestarter.exe"; TestCB transferCallback = new TestCB(); Console.Write("A simple client interface for the advanced autopatcher.\n"); Console.Write("Use DirectoryDeltaTransfer for a simpler version of an autopatcher.\n"); Console.Write("Difficulty: Intermediate\n\n"); Console.Write("Client starting..."); SystemAddress serverAddress = RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS; AutopatcherClient autopatcherClient = new AutopatcherClient(); FileListTransfer fileListTransfer = new FileListTransfer(); autopatcherClient.SetFileListTransferPlugin(fileListTransfer); RakPeerInterface rakPeer; rakPeer = RakPeerInterface.GetInstance(); SocketDescriptor socketDescriptor = new SocketDescriptor(0, null); rakPeer.Startup(1, socketDescriptor, 1); // Plugin will send us downloading progress notifications if a file is split to fit under the MTU 10 or more times rakPeer.SetSplitMessageProgressInterval(10); rakPeer.AttachPlugin(autopatcherClient); rakPeer.AttachPlugin(fileListTransfer); Console.Write("started\n"); String buff; Console.Write("Enter server IP: "); buff = Console.ReadLine(); if (buff == "") buff = "127.0.0.1"; rakPeer.Connect(buff, 60000, null, 0); Console.Write("Connecting...\n"); String appDir; Console.Write("Enter application directory: "); appDir = Console.ReadLine(); if (appDir == "") { appDir = "C:/temp2"; } String appName; Console.Write("Enter application name: "); appName = Console.ReadLine(); if (appName == "") appName = "TestApp"; bool patchImmediately = false; if (patchImmediately == false) Console.Write("Hit 'q' to quit, 'p' to patch, 'c' to cancel the patch. 'r' to reconnect. 'd' to disconnect.\n"); else Console.Write("Hit 'q' to quit, 'c' to cancel the patch.\n"); char ch; Packet p; while (true) { p = rakPeer.Receive(); while (p != null) { if (p.data[0] == (byte)DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION) Console.Write("ID_DISCONNECTION_NOTIFICATION\n"); else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_CONNECTION_LOST) Console.Write("ID_CONNECTION_LOST\n"); else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_CONNECTION_REQUEST_ACCEPTED) { Console.Write("ID_CONNECTION_REQUEST_ACCEPTED\n"); serverAddress = p.systemAddress; } else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_CONNECTION_ATTEMPT_FAILED) Console.Write("ID_CONNECTION_ATTEMPT_FAILED\n"); else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR) { //String buff; //BitStream temp = new BitStream(p.data, p.length, false); //temp.IgnoreBits(8); //StringCompressor.Instance().DecodeString(buff, 256, temp); //Console.Write("ID_AUTOPATCHER_REPOSITORY_FATAL_ERROR\n"); //Console.Write("%s\n", buff); } else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_AUTOPATCHER_FINISHED) Console.Write("ID_AUTOPATCHER_FINISHED\n"); else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_AUTOPATCHER_RESTART_APPLICATION) Console.Write("Launch \"AutopatcherClientRestarter.exe autopatcherRestart.txt\"\nQuit this application immediately after to unlock files.\n"); rakPeer.DeallocatePacket(p); p = rakPeer.Receive(); } if (Console.KeyAvailable) ch = Console.ReadKey().KeyChar; else ch = (char)0; if (ch == 'q') break; else if (ch == 'r') { rakPeer.Connect(buff, 60000, null, 0); } else if (ch == 'd') { rakPeer.CloseConnection(serverAddress, true); } else if (ch == 'p' || (serverAddress != RakNet.RakNet.UNASSIGNED_SYSTEM_ADDRESS && patchImmediately == true)) { patchImmediately = false; String lastUpdateDate; String restartFile; restartFile = appDir; restartFile += "/autopatcherRestart.txt"; // Console.Write("Enter last update date (only newer updates retrieved) or nothing to get all updates\n"); // lastUpdateDate = Console.ReadLine(); lastUpdateDate = ""; if (autopatcherClient.PatchApplication(appName, appDir, lastUpdateDate, serverAddress, transferCallback, restartFile, restarterPath)) { Console.Write("Patching process starting.\n"); } else { Console.Write("Failed to start patching.\n"); } } else if (ch == 'c') { autopatcherClient.Clear(); Console.Write("Autopatcher cleared.\n"); } Thread.Sleep(30); } // Dereference so the destructor doesn't crash autopatcherClient.SetFileListTransferPlugin(null); rakPeer.Shutdown(500, 0); RakPeerInterface.DestroyInstance(rakPeer); return 1; } private static void TestAutoPatcherServer() { TimeSpan startTimeSpan; // Avoids the Error: Got a packet bigger than 'max_allowed_packet' bytes Console.Write("Important: Requires that you first set the DB schema and the max packet size on the server.\n"); Console.Write("See DependentExtensions/AutopatcherMySQLRepository/readme.txt\n"); Console.Write("Server starting... "); AutopatcherServer autopatcherServer = new AutopatcherServer(); FLP_Printf progressIndicator = new FLP_Printf(); FileListTransfer fileListTransfer = new FileListTransfer(); // So only one thread runs per connection, we create an array of connection objects, and tell the autopatcher server to use one thread per item const int sqlConnectionObjectCount = 4; AutopatcherMySQLRepository[] connectionObject = new AutopatcherMySQLRepository[sqlConnectionObjectCount]; AutopatcherRepositoryInterface[] connectionObjectAddresses = new AutopatcherRepositoryInterface[sqlConnectionObjectCount]; for (int i = 0; i < sqlConnectionObjectCount; i++) { connectionObject[i] = new AutopatcherMySQLRepository(); connectionObjectAddresses[i] = connectionObject[i]; } fileListTransfer.SetCallback(progressIndicator); autopatcherServer.SetFileListTransferPlugin(fileListTransfer); RakPeerInterface rakPeer; rakPeer = RakPeerInterface.GetInstance(); SocketDescriptor socketDescriptor = new SocketDescriptor((ushort)LISTEN_PORT, null); rakPeer.Startup(8, socketDescriptor, 1); rakPeer.SetMaximumIncomingConnections(MAX_INCOMING_CONNECTIONS); rakPeer.AttachPlugin(autopatcherServer); rakPeer.AttachPlugin(fileListTransfer); Console.Write("started.\n"); Console.Write("Enter database password:\n"); String password; String username = "root"; password = Console.ReadLine(); if (password == "") password = "aaaa"; string db; Console.Write("Enter DB schema: "); // To create the schema, go to the command line client and type create schema autopatcher; // You also have to add // max_allowed_packet=128M // Where 128 is the maximum size file in megabytes you'll ever add // to MySQL\MySQL Server 5.1\my.ini in the [mysqld] section // Be sure to restart the service after doing so db = Console.ReadLine(); ; if (db == "") db = "autopatcher"; for (int conIdx = 0; conIdx < sqlConnectionObjectCount; conIdx++) { if (!connectionObject[conIdx].Connect("localhost", username, password, db, 0, null, 0)) { Console.Write("Database connection failed.\n"); return; } } Console.Write("Database connection suceeded.\n"); Console.Write("Starting threads\n"); autopatcherServer.StartThreads(sqlConnectionObjectCount, connectionObjectAddresses); Console.Write("System ready for connections\n"); Console.Write("(D)rop database\n(C)reate database.\n(A)dd application\n(U)pdate revision.\n(R)emove application\n(Q)uit\n"); char ch; Packet p; while (true) { p = rakPeer.Receive(); while (p != null) { if (p.data[0] == (byte)DefaultMessageIDTypes.ID_NEW_INCOMING_CONNECTION) Console.Write("ID_NEW_INCOMING_CONNECTION\n"); else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_DISCONNECTION_NOTIFICATION) Console.Write("ID_DISCONNECTION_NOTIFICATION\n"); else if (p.data[0] == (byte)DefaultMessageIDTypes.ID_CONNECTION_LOST) Console.Write("ID_CONNECTION_LOST\n"); rakPeer.DeallocatePacket(p); p = rakPeer.Receive(); } if (Console.KeyAvailable) { ch = Console.ReadKey().KeyChar; if (ch == 'q') break; else if (ch == 'c') { if (connectionObject[0].CreateAutopatcherTables() == false) Console.Write("Error: %s\n", connectionObject[0].GetLastError()); else Console.Write("Created\n"); } else if (ch == 'd') { if (connectionObject[0].DestroyAutopatcherTables() == false) Console.Write("Error: %s\n", connectionObject[0].GetLastError()); else Console.Write("Destroyed\n"); } else if (ch == 'a') { Console.Write("Enter application name to add: "); string appName; appName = Console.ReadLine(); ; if (appName == "") appName = "TestApp"; if (connectionObject[0].AddApplication(appName, username) == false) Console.Write("Error: %s\n", connectionObject[0].GetLastError()); else Console.Write("Done\n"); } else if (ch == 'r') { Console.Write("Enter application name to remove: "); string appName; appName = Console.ReadLine(); ; if (appName == "") appName = "TestApp"; if (connectionObject[0].RemoveApplication(appName) == false) Console.Write("Error: %s\n", connectionObject[0].GetLastError()); else Console.Write("Done\n"); } else if (ch == 'u') { Console.Write("Enter application name: "); string appName; appName = Console.ReadLine(); ; if (appName == "") appName = "TestApp"; Console.Write("Enter application directory: "); string appDir; appDir = Console.ReadLine(); ; if (appDir == "") appDir = "C:/temp"; if (connectionObject[0].UpdateApplicationFiles(appName, appDir, username, progressIndicator) == false) { Console.Write("Error: %s\n", connectionObject[0].GetLastError()); } else { Console.Write("Update success.\n"); } } } Thread.Sleep(30); } RakPeerInterface.DestroyInstance(rakPeer); } #endif }
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.IO; namespace Pair_Programming_Exercises { class Program { struct ValuePair { public string Title; public string Contents; public ValuePair(string TitleInput, string ContentsInput) { this.Title = TitleInput; this.Contents = ContentsInput; } } static void Main(string[] args) { AuthorCRUD(); ArticleCRUD(); } private static void AuthorCRUD() { //Check if The File Exists //bool a = File.Exists(@"C:\Users\Orte7\Desktop\Pair Programming Exercises\Pair Programming Exercises\bin\Debug\author.csv" bool fileExists = File.Exists("author.csv"); Console.WriteLine("File Exists: " + fileExists); Thread.Sleep(500); File.WriteAllText("author.csv", "0,Bill,Bill@Here.com"); //Check if The File Contains Bill, Bill@Here.com //FileStream fileContents = File.Open("author.csv", FileMode.Open); string fileContents = string.Join("", File.ReadAllLines("author.csv")); bool containsTest = fileContents.Contains("0,Bill,Bill@Here.com"); Console.WriteLine("File Contains 'Bill, Bill@Here.com': " + containsTest); Thread.Sleep(500); //Add 'Sue' to Author Table //StreamWriter fileWriter = new StreamWriter("author.csv") using (StreamWriter fileWriter = new StreamWriter("author.csv", true)) { fileWriter.WriteLine("1,Sue,Sue@Here.com"); fileWriter.Close(); } Console.WriteLine("Sue Added to Authors Table: Complete"); Thread.Sleep(500); //Add 10 Other Authors to Table string[] authors = new string[] { "Bob", "John", "Mike", "Steve", "Luke", "Tom", "Jerry", "Tim", "Fateh", "Rafi" }; int index = 2; using (StreamWriter fileWriter = new StreamWriter("author.csv", true)) { foreach (string author in authors) { fileWriter.WriteLine(index + "," + author + ", " + author + "@Here.com"); Console.WriteLine(author + " added to File: Complete"); Thread.Sleep(50); index += 1; } fileWriter.Close(); } //Read CSV Records and Print Emails Console.WriteLine("CSV File Records:"); //string[] fileContentsArray = File.ReadAllLines("author.csv"); //foreach (string item in fileContentsArray) //{ // Console.WriteLine(item.Split(',')[1]); // Thread.Sleep(50); //} Dictionary<string, string> keyValues = new Dictionary<string, string>(); foreach (string item in File.ReadAllLines("author.csv")) { keyValues.Add(item.Split(',')[1], item.Split(',')[2].Trim()); } foreach (KeyValuePair<string, string> item in keyValues) { Console.WriteLine(item.Value); } //Change Bills Email keyValues["Bill"] = "NotBill@Here.com"; Console.WriteLine("Changing Bills Email: Complete"); //Remove Sue keyValues.Remove("Sue"); Console.WriteLine("Removing Sue From Data"); File.WriteAllText("author.csv", string.Empty); index = 0; string contents = ""; foreach (KeyValuePair<string, string> item in keyValues) { contents += index + "," + item.Key + "," + item.Value + Environment.NewLine; index += 1; } //string contents = String.Join(Environment.NewLine, keyValues.Select(d =>d.Key + ", " + d.Value)); File.WriteAllText("author.csv", contents); Console.WriteLine("File Rewritten: Complete"); Console.WriteLine("Exiting in 5 Seconds"); Thread.Sleep(5000); } private static void ArticleCRUD() { //Check if The File Exists bool fileExists = File.Exists("article.csv"); Console.WriteLine("File Exists: " + fileExists); if (!fileExists) { File.Create("article.csv"); Console.WriteLine("File Created"); } Thread.Sleep(50); //CSV file Contains 'Rattlesnakes, I hate snakes' string fileContents = string.Join("", File.ReadAllLines("article.csv")); if (fileContents.Contains("Rattlesnakes, I hate snakes")) { Console.WriteLine("File Contains Rattlesnakes: True"); } else { File.WriteAllText("article.csv", "4,Rattlesnakes,I hate snakes"); } //Print Article List List<Tuple<string, ValuePair>> keyValues = new List<Tuple<string, ValuePair>>(); foreach (string item in File.ReadAllLines("article.csv")) { Tuple<string, ValuePair> pair = new Tuple<string, ValuePair>(); keyValues.Add(new Tuple<item.Split(',')[0], new ValuePair(item.Split(',')[1], item.Split(',')[2])>); } foreach (KeyValuePair<string, ValuePair> item in keyValues) { Console.WriteLine(item.Value.Title + ", " + item.Value.Contents); } //Add Article Kittnes Are Fuzzy keyValues.Add("4", new ValuePair("Kittens", "Kittens are Fuzzy")); Thread.Sleep(10000); } } }